2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 // This also implements the preprocessor
5 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
17 using System.Collections;
19 using System.Globalization;
20 using System.Reflection;
25 /// Tokenizer for C# source code.
28 public class Tokenizer : yyParser.yyInput
32 public readonly int Token;
33 public KeywordEntry Next;
34 public readonly char[] Value;
36 public KeywordEntry (string value, int token)
38 this.Value = value.ToCharArray ();
43 SeekableStreamReader reader;
45 CompilationUnit file_name;
52 bool handle_get_set = false;
53 bool handle_remove_add = false;
54 bool handle_where = false;
55 bool handle_typeof = false;
56 bool lambda_arguments_parsing;
57 Location current_comment_location = Location.Null;
58 ArrayList escaped_identifiers;
59 int parsing_generic_less_than;
62 // Used mainly for parser optimizations. Some expressions for instance
63 // can appear only in block (including initializer, base initializer)
66 public int parsing_block;
67 internal bool query_parsing;
70 // When parsing type only, useful for ambiguous nullable types
72 public int parsing_type;
75 // Set when parsing generic declaration (type or method header)
77 public bool parsing_generic_declaration;
80 // The value indicates that we have not reach any declaration or
83 public int parsing_declaration;
86 // The special character to inject on streams to trigger the EXPRESSION_PARSE
87 // token to be returned. It just happens to be a Unicode character that
88 // would never be part of a program (can not be an identifier).
90 // This character is only tested just before the tokenizer is about to report
91 // an error; So on the regular operation mode, this addition will have no
92 // impact on the tokenizer's performance.
95 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
96 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
97 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
100 // XML documentation buffer. The save point is used to divide
101 // comments on types and comments on members.
103 StringBuilder xml_comment_buffer;
106 // See comment on XmlCommentState enumeration.
108 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
111 // Whether tokens have been seen on this line
113 bool tokens_seen = false;
116 // Whether a token has been seen on the file
117 // This is needed because `define' is not allowed to be used
118 // after a token has been seen.
120 bool any_token_seen = false;
122 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
124 public bool PropertyParsing {
125 get { return handle_get_set; }
126 set { handle_get_set = value; }
129 public bool EventParsing {
130 get { return handle_remove_add; }
131 set { handle_remove_add = value; }
134 public bool ConstraintsParsing {
135 get { return handle_where; }
136 set { handle_where = value; }
139 public bool TypeOfParsing {
140 get { return handle_typeof; }
141 set { handle_typeof = value; }
144 public XmlCommentState doc_state {
145 get { return xml_doc_state; }
147 if (value == XmlCommentState.Allowed) {
148 check_incorrect_doc_comment ();
149 reset_doc_comment ();
151 xml_doc_state = value;
155 void AddEscapedIdentifier (LocatedToken lt)
157 if (escaped_identifiers == null)
158 escaped_identifiers = new ArrayList ();
160 escaped_identifiers.Add (lt);
163 public bool IsEscapedIdentifier (Location loc)
165 if (escaped_identifiers != null) {
166 foreach (LocatedToken lt in escaped_identifiers)
167 if (lt.Location.Equals (loc))
177 static KeywordEntry[][] keywords;
178 static Hashtable keyword_strings;
179 static NumberStyles styles;
180 static NumberFormatInfo csharp_format_info;
183 // Values for the associated token returned
185 internal int putback_char; // Used by repl only
191 const int TAKING = 1;
192 const int ELSE_SEEN = 4;
193 const int PARENT_TAKING = 8;
194 const int REGION = 16;
197 // pre-processor if stack state:
201 static System.Text.StringBuilder string_builder;
203 const int max_id_size = 512;
204 static char [] id_builder = new char [max_id_size];
206 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
208 const int max_number_size = 512;
209 static char [] number_builder = new char [max_number_size];
210 static int number_pos;
213 // Details about the error encoutered by the tokenizer
215 string error_details;
217 public string error {
219 return error_details;
230 // This is used when the tokenizer needs to save
231 // the current position as it needs to do some parsing
232 // on its own to deamiguate a token in behalf of the
235 Stack position_stack = new Stack (2);
242 public int putback_char;
243 public int previous_col;
244 public Stack ifstack;
245 public int parsing_generic_less_than;
246 public int current_token;
248 public Position (Tokenizer t)
250 position = t.reader.Position;
252 ref_line = t.ref_line;
255 putback_char = t.putback_char;
256 previous_col = t.previous_col;
257 if (t.ifstack != null && t.ifstack.Count != 0)
258 ifstack = (Stack)t.ifstack.Clone ();
259 parsing_generic_less_than = t.parsing_generic_less_than;
260 current_token = t.current_token;
264 public void PushPosition ()
266 position_stack.Push (new Position (this));
269 public void PopPosition ()
271 Position p = (Position) position_stack.Pop ();
273 reader.Position = p.position;
274 ref_line = p.ref_line;
278 putback_char = p.putback_char;
279 previous_col = p.previous_col;
281 parsing_generic_less_than = p.parsing_generic_less_than;
282 current_token = p.current_token;
285 // Do not reset the position, ignore it.
286 public void DiscardPosition ()
288 position_stack.Pop ();
291 static void AddKeyword (string kw, int token)
293 keyword_strings.Add (kw, kw);
295 int length = kw.Length;
296 if (keywords [length] == null) {
297 keywords [length] = new KeywordEntry ['z' - '_' + 1];
300 int char_index = kw [0] - '_';
301 KeywordEntry kwe = keywords [length] [char_index];
303 keywords [length] [char_index] = new KeywordEntry (kw, token);
307 while (kwe.Next != null) {
311 kwe.Next = new KeywordEntry (kw, token);
314 static void InitTokens ()
316 keyword_strings = new Hashtable ();
318 // 11 is the length of the longest keyword for now
319 keywords = new KeywordEntry [11] [];
321 AddKeyword ("__arglist", Token.ARGLIST);
322 AddKeyword ("abstract", Token.ABSTRACT);
323 AddKeyword ("as", Token.AS);
324 AddKeyword ("add", Token.ADD);
325 AddKeyword ("base", Token.BASE);
326 AddKeyword ("bool", Token.BOOL);
327 AddKeyword ("break", Token.BREAK);
328 AddKeyword ("byte", Token.BYTE);
329 AddKeyword ("case", Token.CASE);
330 AddKeyword ("catch", Token.CATCH);
331 AddKeyword ("char", Token.CHAR);
332 AddKeyword ("checked", Token.CHECKED);
333 AddKeyword ("class", Token.CLASS);
334 AddKeyword ("const", Token.CONST);
335 AddKeyword ("continue", Token.CONTINUE);
336 AddKeyword ("decimal", Token.DECIMAL);
337 AddKeyword ("default", Token.DEFAULT);
338 AddKeyword ("delegate", Token.DELEGATE);
339 AddKeyword ("do", Token.DO);
340 AddKeyword ("double", Token.DOUBLE);
341 AddKeyword ("else", Token.ELSE);
342 AddKeyword ("enum", Token.ENUM);
343 AddKeyword ("event", Token.EVENT);
344 AddKeyword ("explicit", Token.EXPLICIT);
345 AddKeyword ("extern", Token.EXTERN);
346 AddKeyword ("false", Token.FALSE);
347 AddKeyword ("finally", Token.FINALLY);
348 AddKeyword ("fixed", Token.FIXED);
349 AddKeyword ("float", Token.FLOAT);
350 AddKeyword ("for", Token.FOR);
351 AddKeyword ("foreach", Token.FOREACH);
352 AddKeyword ("goto", Token.GOTO);
353 AddKeyword ("get", Token.GET);
354 AddKeyword ("if", Token.IF);
355 AddKeyword ("implicit", Token.IMPLICIT);
356 AddKeyword ("in", Token.IN);
357 AddKeyword ("int", Token.INT);
358 AddKeyword ("interface", Token.INTERFACE);
359 AddKeyword ("internal", Token.INTERNAL);
360 AddKeyword ("is", Token.IS);
361 AddKeyword ("lock", Token.LOCK);
362 AddKeyword ("long", Token.LONG);
363 AddKeyword ("namespace", Token.NAMESPACE);
364 AddKeyword ("new", Token.NEW);
365 AddKeyword ("null", Token.NULL);
366 AddKeyword ("object", Token.OBJECT);
367 AddKeyword ("operator", Token.OPERATOR);
368 AddKeyword ("out", Token.OUT);
369 AddKeyword ("override", Token.OVERRIDE);
370 AddKeyword ("params", Token.PARAMS);
371 AddKeyword ("private", Token.PRIVATE);
372 AddKeyword ("protected", Token.PROTECTED);
373 AddKeyword ("public", Token.PUBLIC);
374 AddKeyword ("readonly", Token.READONLY);
375 AddKeyword ("ref", Token.REF);
376 AddKeyword ("remove", Token.REMOVE);
377 AddKeyword ("return", Token.RETURN);
378 AddKeyword ("sbyte", Token.SBYTE);
379 AddKeyword ("sealed", Token.SEALED);
380 AddKeyword ("set", Token.SET);
381 AddKeyword ("short", Token.SHORT);
382 AddKeyword ("sizeof", Token.SIZEOF);
383 AddKeyword ("stackalloc", Token.STACKALLOC);
384 AddKeyword ("static", Token.STATIC);
385 AddKeyword ("string", Token.STRING);
386 AddKeyword ("struct", Token.STRUCT);
387 AddKeyword ("switch", Token.SWITCH);
388 AddKeyword ("this", Token.THIS);
389 AddKeyword ("throw", Token.THROW);
390 AddKeyword ("true", Token.TRUE);
391 AddKeyword ("try", Token.TRY);
392 AddKeyword ("typeof", Token.TYPEOF);
393 AddKeyword ("uint", Token.UINT);
394 AddKeyword ("ulong", Token.ULONG);
395 AddKeyword ("unchecked", Token.UNCHECKED);
396 AddKeyword ("unsafe", Token.UNSAFE);
397 AddKeyword ("ushort", Token.USHORT);
398 AddKeyword ("using", Token.USING);
399 AddKeyword ("virtual", Token.VIRTUAL);
400 AddKeyword ("void", Token.VOID);
401 AddKeyword ("volatile", Token.VOLATILE);
402 AddKeyword ("while", Token.WHILE);
403 AddKeyword ("partial", Token.PARTIAL);
404 AddKeyword ("where", Token.WHERE);
407 AddKeyword ("from", Token.FROM);
408 AddKeyword ("join", Token.JOIN);
409 AddKeyword ("on", Token.ON);
410 AddKeyword ("equals", Token.EQUALS);
411 AddKeyword ("select", Token.SELECT);
412 AddKeyword ("group", Token.GROUP);
413 AddKeyword ("by", Token.BY);
414 AddKeyword ("let", Token.LET);
415 AddKeyword ("orderby", Token.ORDERBY);
416 AddKeyword ("ascending", Token.ASCENDING);
417 AddKeyword ("descending", Token.DESCENDING);
418 AddKeyword ("into", Token.INTO);
427 csharp_format_info = NumberFormatInfo.InvariantInfo;
428 styles = NumberStyles.Float;
430 string_builder = new System.Text.StringBuilder ();
433 int GetKeyword (char[] id, int id_len)
436 // Keywords are stored in an array of arrays grouped by their
437 // length and then by the first character
439 if (id_len >= keywords.Length || keywords [id_len] == null)
442 int first_index = id [0] - '_';
443 if (first_index > 'z')
446 KeywordEntry kwe = keywords [id_len] [first_index];
453 for (int i = 1; i < id_len; ++i) {
454 if (id [i] != kwe.Value [i]) {
460 } while (kwe != null && res == 0);
474 if (!handle_remove_add)
478 if (parsing_declaration == 0)
479 res = Token.EXTERN_ALIAS;
482 if (peek_token () == Token.COLON) {
484 res = Token.DEFAULT_COLON;
488 if (!handle_where && !query_parsing)
493 // A query expression is any expression that starts with `from identifier'
494 // followed by any token except ; , =
496 if (!query_parsing) {
497 if (lambda_arguments_parsing) {
503 // HACK: to disable generics micro-parser, because PushPosition does not
504 // store identifiers array
505 parsing_generic_less_than = 1;
507 case Token.IDENTIFIER:
519 next_token = xtoken ();
520 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
523 res = Token.FROM_FIRST;
524 query_parsing = true;
525 if (RootContext.Version <= LanguageVersion.ISO_2)
526 Report.FeatureIsNotAvailable (Location, "query expressions");
529 Expression.Error_VoidInvalidInTheContext (Location);
533 // HACK: A token is not a keyword so we need to restore identifiers buffer
534 // which has been overwritten before we grabbed the identifier
535 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
549 case Token.ASCENDING:
550 case Token.DESCENDING:
557 case Token.NAMESPACE:
558 // TODO: some explanation needed
559 check_incorrect_doc_comment ();
563 if (parsing_block > 0) {
568 // Save current position and parse next token.
571 next_token = token ();
572 bool ok = (next_token == Token.CLASS) ||
573 (next_token == Token.STRUCT) ||
574 (next_token == Token.INTERFACE) ||
575 (next_token == Token.VOID);
580 if (next_token == Token.VOID) {
581 if (RootContext.Version == LanguageVersion.ISO_1 ||
582 RootContext.Version == LanguageVersion.ISO_2)
583 Report.FeatureIsNotAvailable (Location, "partial methods");
584 } else if (RootContext.Version == LanguageVersion.ISO_1)
585 Report.FeatureIsNotAvailable (Location, "partial types");
590 if (next_token < Token.LAST_KEYWORD) {
591 Report.Error (267, Location,
592 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
603 public Location Location {
605 return new Location (ref_line, hidden ? -1 : col);
609 public Tokenizer (SeekableStreamReader input, CompilationUnit file)
611 this.ref_name = file;
612 this.file_name = file;
617 xml_comment_buffer = new StringBuilder ();
620 // FIXME: This could be `Location.Push' but we have to
621 // find out why the MS compiler allows this
623 Mono.CSharp.Location.Push (file, file);
626 static bool is_identifier_start_character (int c)
628 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
631 static bool is_identifier_part_character (char c)
633 if (c >= 'a' && c <= 'z')
636 if (c >= 'A' && c <= 'Z')
639 if (c == '_' || (c >= '0' && c <= '9'))
645 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
648 public static bool IsKeyword (string s)
650 return keyword_strings [s] != null;
654 // Open parens micro parser. Detects both lambda and cast ambiguity.
657 int TokenizeOpenParens ()
662 int bracket_level = 0;
663 bool is_type = false;
664 bool can_be_type = false;
667 ptoken = current_token;
670 switch (current_token) {
671 case Token.CLOSE_PARENS:
675 // Expression inside parens is lambda, (int i) =>
677 if (current_token == Token.ARROW) {
678 if (RootContext.Version <= LanguageVersion.ISO_2)
679 Report.FeatureIsNotAvailable (Location, "lambda expressions");
681 return Token.OPEN_PARENS_LAMBDA;
685 // Expression inside parens is single type, (int[])
688 return Token.OPEN_PARENS_CAST;
691 // Expression is possible cast, look at next token, (T)null
694 switch (current_token) {
695 case Token.OPEN_PARENS:
698 case Token.IDENTIFIER:
699 case Token.LITERAL_INTEGER:
700 case Token.LITERAL_FLOAT:
701 case Token.LITERAL_DOUBLE:
702 case Token.LITERAL_DECIMAL:
703 case Token.LITERAL_CHARACTER:
704 case Token.LITERAL_STRING:
717 case Token.UNCHECKED:
722 // These can be part of a member access
736 return Token.OPEN_PARENS_CAST;
739 return Token.OPEN_PARENS;
742 case Token.DOUBLE_COLON:
743 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
748 case Token.IDENTIFIER:
751 case Token.OP_GENERICS_LT:
753 case Token.DOUBLE_COLON:
755 if (bracket_level == 0)
759 can_be_type = is_type = false;
779 if (bracket_level == 0)
784 if (bracket_level == 0) {
786 can_be_type = is_type = false;
790 case Token.OP_GENERICS_LT:
791 case Token.OPEN_BRACKET:
792 if (bracket_level++ == 0)
796 case Token.OP_GENERICS_GT:
797 case Token.CLOSE_BRACKET:
801 case Token.INTERR_NULLABLE:
803 if (bracket_level == 0)
809 can_be_type = is_type = false;
813 return Token.OPEN_PARENS;
818 public static bool IsValidIdentifier (string s)
820 if (s == null || s.Length == 0)
823 if (!is_identifier_start_character (s [0]))
826 for (int i = 1; i < s.Length; i ++)
827 if (! is_identifier_part_character (s [i]))
833 bool parse_less_than ()
836 int the_token = token ();
837 if (the_token == Token.OPEN_BRACKET) {
839 the_token = token ();
840 } while (the_token != Token.CLOSE_BRACKET);
841 the_token = token ();
842 } else if (the_token == Token.IN || the_token == Token.OUT) {
843 the_token = token ();
846 case Token.IDENTIFIER:
864 case Token.OP_GENERICS_GT:
871 the_token = token ();
873 if (the_token == Token.OP_GENERICS_GT)
875 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
877 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
879 else if (the_token == Token.OP_GENERICS_LT) {
880 if (!parse_less_than ())
883 } else if (the_token == Token.OPEN_BRACKET) {
885 the_token = token ();
886 if (the_token == Token.CLOSE_BRACKET)
888 else if (the_token == Token.COMMA)
889 goto rank_specifiers;
896 bool parse_generic_dimension (out int dimension)
901 int the_token = token ();
902 if (the_token == Token.OP_GENERICS_GT)
904 else if (the_token == Token.COMMA) {
912 public int peek_token ()
917 the_token = token ();
924 // Tonizes `?' using custom disambiguous rules to return one
925 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
927 // Tricky expression look like:
929 // Foo ? a = x ? b : c;
931 int TokenizePossibleNullableType ()
933 if (parsing_block == 0 || parsing_type > 0)
934 return Token.INTERR_NULLABLE;
936 int d = peek_char ();
939 return Token.OP_COALESCING;
942 switch (current_token) {
943 case Token.CLOSE_PARENS:
947 case Token.LITERAL_INTEGER:
948 case Token.LITERAL_STRING:
953 if (d == ',' || d == ';' || d == '>')
954 return Token.INTERR_NULLABLE;
955 if (d == '*' || (d >= '0' && d <= '9'))
960 current_token = Token.NONE;
963 case Token.LITERAL_INTEGER:
964 case Token.LITERAL_STRING:
965 case Token.LITERAL_CHARACTER:
966 case Token.LITERAL_DECIMAL:
967 case Token.LITERAL_DOUBLE:
968 case Token.LITERAL_FLOAT:
974 next_token = Token.INTERR;
977 case Token.SEMICOLON:
979 case Token.CLOSE_PARENS:
980 case Token.OPEN_BRACKET:
981 case Token.OP_GENERICS_GT:
982 next_token = Token.INTERR_NULLABLE;
990 if (next_token == -1) {
993 case Token.SEMICOLON:
994 case Token.OPEN_BRACE:
995 case Token.CLOSE_PARENS:
997 next_token = Token.INTERR_NULLABLE;
1001 next_token = Token.INTERR;
1009 // All shorcuts failed, do it hard way
1011 while ((ntoken = xtoken ()) != Token.EOF) {
1012 if (ntoken == Token.SEMICOLON)
1015 if (ntoken == Token.COLON) {
1016 if (++colons == interrs)
1021 if (ntoken == Token.INTERR) {
1027 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1036 bool decimal_digits (int c)
1039 bool seen_digits = false;
1042 if (number_pos == max_number_size)
1043 Error_NumericConstantTooLong ();
1044 number_builder [number_pos++] = (char) c;
1048 // We use peek_char2, because decimal_digits needs to do a
1049 // 2-character look-ahead (5.ToString for example).
1051 while ((d = peek_char2 ()) != -1){
1052 if (d >= '0' && d <= '9'){
1053 if (number_pos == max_number_size)
1054 Error_NumericConstantTooLong ();
1055 number_builder [number_pos++] = (char) d;
1065 static bool is_hex (int e)
1067 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1070 static int real_type_suffix (int c)
1076 t = Token.LITERAL_FLOAT;
1079 t = Token.LITERAL_DOUBLE;
1082 t= Token.LITERAL_DECIMAL;
1090 int integer_type_suffix (ulong ul, int c)
1092 bool is_unsigned = false;
1093 bool is_long = false;
1096 bool scanning = true;
1109 // if we have not seen anything in between
1110 // report this error
1112 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1115 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1116 // work around that.
1140 if (is_long && is_unsigned){
1142 return Token.LITERAL_INTEGER;
1143 } else if (is_unsigned){
1144 // uint if possible, or ulong else.
1146 if ((ul & 0xffffffff00000000) == 0)
1150 } else if (is_long){
1151 // long if possible, ulong otherwise
1152 if ((ul & 0x8000000000000000) != 0)
1157 // int, uint, long or ulong in that order
1158 if ((ul & 0xffffffff00000000) == 0){
1159 uint ui = (uint) ul;
1161 if ((ui & 0x80000000) != 0)
1166 if ((ul & 0x8000000000000000) != 0)
1172 return Token.LITERAL_INTEGER;
1176 // given `c' as the next char in the input decide whether
1177 // we need to convert to a special type, and then choose
1178 // the best representation for the integer
1180 int adjust_int (int c)
1183 if (number_pos > 9){
1184 ulong ul = (uint) (number_builder [0] - '0');
1186 for (int i = 1; i < number_pos; i++){
1187 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1189 return integer_type_suffix (ul, c);
1191 uint ui = (uint) (number_builder [0] - '0');
1193 for (int i = 1; i < number_pos; i++){
1194 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1196 return integer_type_suffix (ui, c);
1198 } catch (OverflowException) {
1199 error_details = "Integral constant is too large";
1200 Report.Error (1021, Location, error_details);
1202 return Token.LITERAL_INTEGER;
1204 catch (FormatException) {
1205 Report.Error (1013, Location, "Invalid number");
1207 return Token.LITERAL_INTEGER;
1211 int adjust_real (int t)
1213 string s = new String (number_builder, 0, number_pos);
1214 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1217 case Token.LITERAL_DECIMAL:
1219 val = System.Decimal.Parse (s, styles, csharp_format_info);
1220 } catch (OverflowException) {
1222 Report.Error (594, Location, error_details, "decimal");
1225 case Token.LITERAL_FLOAT:
1227 val = float.Parse (s, styles, csharp_format_info);
1228 } catch (OverflowException) {
1230 Report.Error (594, Location, error_details, "float");
1234 case Token.LITERAL_DOUBLE:
1236 t = Token.LITERAL_DOUBLE;
1238 val = System.Double.Parse (s, styles, csharp_format_info);
1239 } catch (OverflowException) {
1241 Report.Error (594, Location, error_details, "double");
1254 while ((d = peek_char ()) != -1){
1256 number_builder [number_pos++] = (char) d;
1262 string s = new String (number_builder, 0, number_pos);
1264 if (number_pos <= 8)
1265 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1267 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1268 } catch (OverflowException){
1269 error_details = "Integral constant is too large";
1270 Report.Error (1021, Location, error_details);
1272 return Token.LITERAL_INTEGER;
1274 catch (FormatException) {
1275 Report.Error (1013, Location, "Invalid number");
1277 return Token.LITERAL_INTEGER;
1280 return integer_type_suffix (ul, peek_char ());
1284 // Invoked if we know we have .digits or digits
1286 int is_number (int c)
1288 bool is_real = false;
1293 if (c >= '0' && c <= '9'){
1295 int peek = peek_char ();
1297 if (peek == 'x' || peek == 'X')
1298 return handle_hex ();
1305 // We need to handle the case of
1306 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1309 if (decimal_digits ('.')){
1315 return adjust_int (-1);
1319 if (c == 'e' || c == 'E'){
1321 if (number_pos == max_number_size)
1322 Error_NumericConstantTooLong ();
1323 number_builder [number_pos++] = 'e';
1327 if (number_pos == max_number_size)
1328 Error_NumericConstantTooLong ();
1329 number_builder [number_pos++] = '+';
1331 } else if (c == '-') {
1332 if (number_pos == max_number_size)
1333 Error_NumericConstantTooLong ();
1334 number_builder [number_pos++] = '-';
1337 if (number_pos == max_number_size)
1338 Error_NumericConstantTooLong ();
1339 number_builder [number_pos++] = '+';
1346 type = real_type_suffix (c);
1347 if (type == Token.NONE && !is_real){
1349 return adjust_int (c);
1353 if (type == Token.NONE){
1358 return adjust_real (type);
1360 Console.WriteLine ("This should not be reached");
1361 throw new Exception ("Is Number should never reach this point");
1365 // Accepts exactly count (4 or 8) hex, no more no less
1367 int getHex (int count, out int surrogate, out bool error)
1372 int top = count != -1 ? count : 4;
1377 for (i = 0; i < top; i++){
1380 if (c >= '0' && c <= '9')
1381 c = (int) c - (int) '0';
1382 else if (c >= 'A' && c <= 'F')
1383 c = (int) c - (int) 'A' + 10;
1384 else if (c >= 'a' && c <= 'f')
1385 c = (int) c - (int) 'a' + 10;
1391 total = (total * 16) + c;
1393 int p = peek_char ();
1396 if (!is_hex ((char)p))
1402 if (total > 0x0010FFFF) {
1407 if (total >= 0x00010000) {
1408 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1409 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1416 int escape (int c, out int surrogate)
1452 v = getHex (-1, out surrogate, out error);
1458 return EscapeUnicode (d, out surrogate);
1461 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1470 int EscapeUnicode (int ch, out int surrogate)
1474 ch = getHex (8, out surrogate, out error);
1476 ch = getHex (4, out surrogate, out error);
1480 Report.Error (1009, Location, "Unrecognized escape sequence");
1488 if (putback_char != -1) {
1501 void advance_line ()
1511 if (putback_char == -1)
1512 putback_char = reader.Read ();
1513 return putback_char;
1518 if (putback_char != -1)
1519 return putback_char;
1520 return reader.Peek ();
1523 void putback (int c)
1525 if (putback_char != -1){
1526 Console.WriteLine ("Col: " + col);
1527 Console.WriteLine ("Row: " + line);
1528 Console.WriteLine ("Name: " + ref_name.Name);
1529 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1530 throw new Exception ("This should not happen putback on putback");
1532 if (c == '\n' || col == 0) {
1533 // It won't happen though.
1543 public bool advance ()
1545 return peek_char () != -1;
1548 public Object Value {
1554 public Object value ()
1561 current_token = xtoken ();
1562 return current_token;
1565 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1567 void get_cmd_arg (out string cmd, out string arg)
1571 tokens_seen = false;
1574 // skip over white space
1577 } while (c == '\r' || c == ' ' || c == '\t');
1579 static_cmd_arg.Length = 0;
1580 while (c != -1 && is_identifier_part_character ((char)c)) {
1581 static_cmd_arg.Append ((char)c);
1584 int peek = peek_char ();
1585 if (peek == 'U' || peek == 'u') {
1587 c = EscapeUnicode (c, out surrogate);
1588 if (surrogate != 0) {
1589 if (is_identifier_part_character ((char) c))
1590 static_cmd_arg.Append ((char) c);
1597 cmd = static_cmd_arg.ToString ();
1599 // skip over white space
1600 while (c == '\r' || c == ' ' || c == '\t')
1603 static_cmd_arg.Length = 0;
1604 int has_identifier_argument = 0;
1606 while (c != -1 && c != '\n' && c != '\r') {
1607 if (c == '\\' && has_identifier_argument >= 0) {
1608 if (has_identifier_argument != 0 || (cmd == "define" || cmd == "if" || cmd == "elif" || cmd == "undef")) {
1609 has_identifier_argument = 1;
1611 int peek = peek_char ();
1612 if (peek == 'U' || peek == 'u') {
1614 c = EscapeUnicode (c, out surrogate);
1615 if (surrogate != 0) {
1616 if (is_identifier_part_character ((char) c))
1617 static_cmd_arg.Append ((char) c);
1622 has_identifier_argument = -1;
1625 static_cmd_arg.Append ((char) c);
1629 if (static_cmd_arg.Length != 0)
1630 arg = static_cmd_arg.ToString ();
1634 // Handles the #line directive
1636 bool PreProcessLine (string arg)
1638 if (arg.Length == 0)
1641 if (arg == "default"){
1643 ref_name = file_name;
1645 Location.Push (file_name, ref_name);
1647 } else if (arg == "hidden"){
1655 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1656 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1659 char [] quotes = { '\"' };
1661 string name = arg.Substring (pos). Trim (quotes);
1662 ref_name = Location.LookupFile (file_name, name);
1663 file_name.AddFile (ref_name);
1665 Location.Push (file_name, ref_name);
1667 ref_line = System.Int32.Parse (arg);
1678 // Handles #define and #undef
1680 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1682 if (ident.Length == 0 || ident == "true" || ident == "false"){
1683 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1687 if (ident.IndexOfAny (simple_whitespaces) != -1){
1688 Error_EndLineExpected ();
1692 if (!is_identifier_start_character (ident [0]))
1693 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1695 foreach (char c in ident.Substring (1)){
1696 if (!is_identifier_part_character (c)){
1697 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1702 if (!caller_is_taking)
1709 if (RootContext.IsConditionalDefined (ident))
1712 file_name.AddDefine (ident);
1717 file_name.AddUndefine (ident);
1721 static byte read_hex (string arg, int pos, out bool error)
1728 if ((c >= '0') && (c <= '9'))
1729 total = (int) c - (int) '0';
1730 else if ((c >= 'A') && (c <= 'F'))
1731 total = (int) c - (int) 'A' + 10;
1732 else if ((c >= 'a') && (c <= 'f'))
1733 total = (int) c - (int) 'a' + 10;
1742 if ((c >= '0') && (c <= '9'))
1743 total += (int) c - (int) '0';
1744 else if ((c >= 'A') && (c <= 'F'))
1745 total += (int) c - (int) 'A' + 10;
1746 else if ((c >= 'a') && (c <= 'f'))
1747 total += (int) c - (int) 'a' + 10;
1753 return (byte) total;
1757 /// Handles #pragma checksum
1759 bool PreProcessPragmaChecksum (string arg)
1761 if ((arg [0] != ' ') && (arg [0] != '\t'))
1764 arg = arg.Trim (simple_whitespaces);
1765 if ((arg.Length < 2) || (arg [0] != '"'))
1768 StringBuilder file_sb = new StringBuilder ();
1772 while ((ch = arg [pos++]) != '"') {
1773 if (pos >= arg.Length)
1777 if (pos+1 >= arg.Length)
1782 file_sb.Append (ch);
1785 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1788 arg = arg.Substring (pos).Trim (simple_whitespaces);
1789 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1790 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1791 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1795 byte[] guid_bytes = new byte [16];
1797 for (int i = 0; i < 4; i++) {
1798 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1802 for (int i = 0; i < 2; i++) {
1803 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1806 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1809 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1814 for (int i = 0; i < 6; i++) {
1815 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1820 arg = arg.Substring (40).Trim (simple_whitespaces);
1821 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1824 byte[] checksum_bytes = new byte [16];
1825 for (int i = 0; i < 16; i++) {
1826 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1831 arg = arg.Substring (34).Trim (simple_whitespaces);
1835 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1836 file.SetChecksum (guid_bytes, checksum_bytes);
1837 ref_name.AutoGenerated = true;
1842 /// Handles #pragma directive
1844 void PreProcessPragma (string arg)
1846 const string warning = "warning";
1847 const string w_disable = "warning disable";
1848 const string w_restore = "warning restore";
1849 const string checksum = "checksum";
1851 if (arg == w_disable) {
1852 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1856 if (arg == w_restore) {
1857 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1861 if (arg.StartsWith (w_disable)) {
1862 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1863 foreach (int code in codes) {
1865 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1870 if (arg.StartsWith (w_restore)) {
1871 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1872 Hashtable w_table = Report.warning_ignore_table;
1873 foreach (int code in codes) {
1874 if (w_table != null && w_table.Contains (code))
1875 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1876 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1881 if (arg.StartsWith (warning)) {
1882 Report.Warning (1634, 1, Location, "Expected disable or restore");
1886 if (arg.StartsWith (checksum)) {
1887 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1888 Warning_InvalidPragmaChecksum ();
1892 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1895 int[] ParseNumbers (string text)
1897 string[] string_array = text.Split (',');
1898 int[] values = new int [string_array.Length];
1900 foreach (string string_code in string_array) {
1902 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1904 catch (FormatException) {
1905 Report.Warning (1692, 1, Location, "Invalid number");
1911 bool eval_val (string s)
1918 return file_name.IsConditionalDefined (s);
1921 bool pp_primary (ref string s)
1930 s = s.Substring (1);
1931 bool val = pp_expr (ref s, false);
1932 if (s.Length > 0 && s [0] == ')'){
1933 s = s.Substring (1);
1936 Error_InvalidDirective ();
1940 if (is_identifier_start_character (c)){
1946 if (is_identifier_part_character (c)){
1950 bool v = eval_val (s.Substring (0, j));
1951 s = s.Substring (j);
1954 bool vv = eval_val (s);
1959 Error_InvalidDirective ();
1963 bool pp_unary (ref string s)
1970 if (len > 1 && s [1] == '='){
1971 Error_InvalidDirective ();
1974 s = s.Substring (1);
1975 return ! pp_primary (ref s);
1977 return pp_primary (ref s);
1979 Error_InvalidDirective ();
1984 bool pp_eq (ref string s)
1986 bool va = pp_unary (ref s);
1992 if (len > 2 && s [1] == '='){
1993 s = s.Substring (2);
1994 return va == pp_unary (ref s);
1996 Error_InvalidDirective ();
1999 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2000 s = s.Substring (2);
2002 return va != pp_unary (ref s);
2011 bool pp_and (ref string s)
2013 bool va = pp_eq (ref s);
2019 if (len > 2 && s [1] == '&'){
2020 s = s.Substring (2);
2021 return (va & pp_and (ref s));
2023 Error_InvalidDirective ();
2032 // Evaluates an expression for `#if' or `#elif'
2034 bool pp_expr (ref string s, bool isTerm)
2036 bool va = pp_and (ref s);
2043 if (len > 2 && s [1] == '|'){
2044 s = s.Substring (2);
2045 return va | pp_expr (ref s, isTerm);
2047 Error_InvalidDirective ();
2052 Error_EndLineExpected ();
2060 bool eval (string s)
2062 bool v = pp_expr (ref s, true);
2071 void Error_NumericConstantTooLong ()
2073 Report.Error (1021, Location, "Numeric constant too long");
2076 void Error_InvalidDirective ()
2078 Report.Error (1517, Location, "Invalid preprocessor directive");
2081 void Error_UnexpectedDirective (string extra)
2085 "Unexpected processor directive ({0})", extra);
2088 void Error_TokensSeen ()
2090 Report.Error (1032, Location,
2091 "Cannot define or undefine preprocessor symbols after first token in file");
2094 void Eror_WrongPreprocessorLocation ()
2096 Report.Error (1040, Location,
2097 "Preprocessor directives must appear as the first non-whitespace character on a line");
2100 void Error_EndLineExpected ()
2102 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2105 void Warning_InvalidPragmaChecksum ()
2107 Report.Warning (1695, 1, Location,
2108 "Invalid #pragma checksum syntax; should be " +
2109 "#pragma checksum \"filename\" " +
2110 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2113 // if true, then the code continues processing the code
2114 // if false, the code stays in a loop until another directive is
2116 // When caller_is_taking is false we ignore all directives except the ones
2117 // which can help us to identify where the #if block ends
2118 bool handle_preprocessing_directive (bool caller_is_taking)
2121 bool region_directive = false;
2123 get_cmd_arg (out cmd, out arg);
2125 // Eat any trailing whitespaces and single-line comments
2126 if (arg.IndexOf ("//") != -1)
2127 arg = arg.Substring (0, arg.IndexOf ("//"));
2128 arg = arg.Trim (simple_whitespaces);
2131 // The first group of pre-processing instructions is always processed
2135 region_directive = true;
2140 if (ifstack == null || ifstack.Count == 0){
2141 Error_UnexpectedDirective ("no #region for this #endregion");
2144 int pop = (int) ifstack.Pop ();
2146 if ((pop & REGION) == 0)
2147 Report.Error (1027, Location, "Expected `#endif' directive");
2149 return caller_is_taking;
2152 if (ifstack == null)
2153 ifstack = new Stack (2);
2155 int flags = region_directive ? REGION : 0;
2156 if (ifstack.Count == 0){
2157 flags |= PARENT_TAKING;
2159 int state = (int) ifstack.Peek ();
2160 if ((state & TAKING) != 0) {
2161 flags |= PARENT_TAKING;
2165 if (caller_is_taking && eval (arg)) {
2166 ifstack.Push (flags | TAKING);
2169 ifstack.Push (flags);
2173 if (ifstack == null || ifstack.Count == 0){
2174 Error_UnexpectedDirective ("no #if for this #endif");
2177 pop = (int) ifstack.Pop ();
2179 if ((pop & REGION) != 0)
2180 Report.Error (1038, Location, "#endregion directive expected");
2182 if (arg.Length != 0) {
2183 Error_EndLineExpected ();
2186 if (ifstack.Count == 0)
2189 int state = (int) ifstack.Peek ();
2190 return (state & TAKING) != 0;
2194 if (ifstack == null || ifstack.Count == 0){
2195 Error_UnexpectedDirective ("no #if for this #elif");
2198 int state = (int) ifstack.Pop ();
2200 if ((state & REGION) != 0) {
2201 Report.Error (1038, Location, "#endregion directive expected");
2205 if ((state & ELSE_SEEN) != 0){
2206 Error_UnexpectedDirective ("#elif not valid after #else");
2210 if ((state & TAKING) != 0) {
2215 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2216 ifstack.Push (state | TAKING);
2220 ifstack.Push (state);
2225 if (ifstack == null || ifstack.Count == 0){
2226 Error_UnexpectedDirective ("no #if for this #else");
2229 int state = (int) ifstack.Peek ();
2231 if ((state & REGION) != 0) {
2232 Report.Error (1038, Location, "#endregion directive expected");
2236 if ((state & ELSE_SEEN) != 0){
2237 Error_UnexpectedDirective ("#else within #else");
2243 if (arg.Length != 0) {
2244 Error_EndLineExpected ();
2249 if ((state & PARENT_TAKING) != 0) {
2250 ret = (state & TAKING) == 0;
2258 ifstack.Push (state | ELSE_SEEN);
2263 if (any_token_seen){
2264 Error_TokensSeen ();
2265 return caller_is_taking;
2267 PreProcessDefinition (true, arg, caller_is_taking);
2268 return caller_is_taking;
2271 if (any_token_seen){
2272 Error_TokensSeen ();
2273 return caller_is_taking;
2275 PreProcessDefinition (false, arg, caller_is_taking);
2276 return caller_is_taking;
2280 // These are only processed if we are in a `taking' block
2282 if (!caller_is_taking)
2287 Report.Error (1029, Location, "#error: '{0}'", arg);
2291 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2295 if (RootContext.Version == LanguageVersion.ISO_1) {
2296 Report.FeatureIsNotAvailable (Location, "#pragma");
2300 PreProcessPragma (arg);
2304 if (!PreProcessLine (arg))
2307 "The line number specified for #line directive is missing or invalid");
2308 return caller_is_taking;
2311 Report.Error (1024, Location, "Wrong preprocessor directive");
2316 private int consume_string (bool quoted)
2319 string_builder.Length = 0;
2321 while ((c = get_char ()) != -1){
2323 if (quoted && peek_char () == '"'){
2324 string_builder.Append ((char) c);
2328 val = string_builder.ToString ();
2329 return Token.LITERAL_STRING;
2335 Report.Error (1010, Location, "Newline in constant");
2340 c = escape (c, out surrogate);
2343 if (surrogate != 0) {
2344 string_builder.Append ((char) c);
2348 string_builder.Append ((char) c);
2351 Report.Error (1039, Location, "Unterminated string literal");
2355 private int consume_identifier (int s)
2357 int res = consume_identifier (s, false);
2359 if (doc_state == XmlCommentState.Allowed)
2360 doc_state = XmlCommentState.NotAllowed;
2365 private int consume_identifier (int c, bool quoted)
2371 c = escape (c, out surrogate);
2372 if (surrogate != 0) {
2373 id_builder [pos++] = (char) c;
2378 id_builder [pos++] = (char) c;
2379 Location loc = Location;
2381 while ((c = get_char ()) != -1) {
2383 if (is_identifier_part_character ((char) c)){
2384 if (pos == max_id_size){
2385 Report.Error (645, loc, "Identifier too long (limit is 512 chars)");
2389 id_builder [pos++] = (char) c;
2390 } else if (c == '\\') {
2392 c = escape (c, out surrogate);
2393 if (surrogate != 0) {
2394 if (is_identifier_part_character ((char) c))
2395 id_builder [pos++] = (char) c;
2406 // Optimization: avoids doing the keyword lookup
2407 // on uppercase letters
2409 if (id_builder [0] >= '_' && !quoted) {
2410 int keyword = GetKeyword (id_builder, pos);
2411 if (keyword != -1) {
2412 // TODO: No need to store location for keyword, required location cleanup
2419 // Keep identifiers in an array of hashtables to avoid needless
2422 CharArrayHashtable identifiers_group = identifiers [pos];
2423 if (identifiers_group != null) {
2424 val = identifiers_group [id_builder];
2426 val = new LocatedToken (loc, (string) val);
2428 AddEscapedIdentifier ((LocatedToken) val);
2429 return Token.IDENTIFIER;
2432 identifiers_group = new CharArrayHashtable (pos);
2433 identifiers [pos] = identifiers_group;
2436 char [] chars = new char [pos];
2437 Array.Copy (id_builder, chars, pos);
2439 val = new String (id_builder, 0, pos);
2440 identifiers_group.Add (chars, val);
2442 if (RootContext.Version == LanguageVersion.ISO_1) {
2443 for (int i = 1; i < chars.Length; i += 3) {
2444 if (chars [i] == '_' && (chars [i - 1] == '_' || chars [i + 1] == '_')) {
2445 Report.Error (1638, loc,
2446 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2451 val = new LocatedToken (loc, (string) val);
2453 AddEscapedIdentifier ((LocatedToken) val);
2454 return Token.IDENTIFIER;
2457 public int xtoken ()
2461 // Whether we have seen comments on the current line
2462 bool comments_seen = false;
2463 while ((c = get_char ()) != -1) {
2466 col = ((col + 8) / 8) * 8;
2474 case 0xFEFF: // Ignore BOM anywhere in the file
2477 /* This is required for compatibility with .NET
2479 if (peek_char () == 0xBB) {
2482 if (get_char () == 0xBF)
2489 if (peek_char () != '\n')
2494 any_token_seen |= tokens_seen;
2495 tokens_seen = false;
2496 comments_seen = false;
2501 return consume_identifier (c);
2505 return Token.OPEN_BRACE;
2508 return Token.CLOSE_BRACE;
2510 // To block doccomment inside attribute declaration.
2511 if (doc_state == XmlCommentState.Allowed)
2512 doc_state = XmlCommentState.NotAllowed;
2513 return Token.OPEN_BRACKET;
2515 return Token.CLOSE_BRACKET;
2519 // An expression versions of parens can appear in block context only
2521 if (parsing_block != 0 && !lambda_arguments_parsing) {
2524 // Optmize most common case where we know that parens
2527 switch (current_token) {
2528 case Token.IDENTIFIER:
2536 case Token.DELEGATE:
2537 case Token.OP_GENERICS_GT:
2538 return Token.OPEN_PARENS;
2541 // Optimize using peek
2542 int xx = peek_char ();
2549 return Token.OPEN_PARENS;
2552 lambda_arguments_parsing = true;
2554 d = TokenizeOpenParens ();
2556 lambda_arguments_parsing = false;
2560 return Token.OPEN_PARENS;
2562 return Token.CLOSE_PARENS;
2566 return Token.SEMICOLON;
2570 return TokenizePossibleNullableType ();
2572 if (parsing_generic_less_than++ > 0)
2573 return Token.OP_GENERICS_LT;
2575 return TokenizeLessThan ();
2585 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2586 parsing_generic_less_than--;
2587 return Token.OP_GENERICS_GT;
2596 return Token.OP_SHIFT_RIGHT_ASSIGN;
2598 return Token.OP_SHIFT_RIGHT;
2607 } else if (d == '=') {
2608 d = Token.OP_ADD_ASSIGN;
2619 } else if (d == '=')
2620 d = Token.OP_SUB_ASSIGN;
2630 if (peek_char () == '='){
2647 return Token.ASSIGN;
2653 return Token.OP_AND;
2657 return Token.OP_AND_ASSIGN;
2659 return Token.BITWISE_AND;
2669 return Token.OP_OR_ASSIGN;
2671 return Token.BITWISE_OR;
2674 if (peek_char () == '='){
2676 return Token.OP_MULT_ASSIGN;
2685 return Token.OP_DIV_ASSIGN;
2688 // Handle double-slash comments.
2691 if (RootContext.Documentation != null && peek_char () == '/') {
2693 // Don't allow ////.
2694 if ((d = peek_char ()) != '/') {
2695 update_comment_location ();
2696 if (doc_state == XmlCommentState.Allowed)
2697 handle_one_line_xml_comment ();
2698 else if (doc_state == XmlCommentState.NotAllowed)
2699 warn_incorrect_doc_comment ();
2702 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2704 any_token_seen |= tokens_seen;
2705 tokens_seen = false;
2706 comments_seen = false;
2708 } else if (d == '*'){
2710 bool docAppend = false;
2711 if (RootContext.Documentation != null && peek_char () == '*') {
2713 update_comment_location ();
2714 // But when it is /**/, just do nothing.
2715 if (peek_char () == '/') {
2719 if (doc_state == XmlCommentState.Allowed)
2721 else if (doc_state == XmlCommentState.NotAllowed)
2722 warn_incorrect_doc_comment ();
2725 int current_comment_start = 0;
2727 current_comment_start = xml_comment_buffer.Length;
2728 xml_comment_buffer.Append (Environment.NewLine);
2731 while ((d = get_char ()) != -1){
2732 if (d == '*' && peek_char () == '/'){
2734 comments_seen = true;
2738 xml_comment_buffer.Append ((char) d);
2741 any_token_seen |= tokens_seen;
2742 tokens_seen = false;
2744 // Reset 'comments_seen' just to be consistent.
2745 // It doesn't matter either way, here.
2747 comments_seen = false;
2751 Report.Error (1035, Location, "End-of-file found, '*/' expected");
2754 update_formatted_doc_comment (current_comment_start);
2760 if (peek_char () == '='){
2762 return Token.OP_MOD_ASSIGN;
2764 return Token.PERCENT;
2767 if (peek_char () == '='){
2769 return Token.OP_XOR_ASSIGN;
2771 return Token.CARRET;
2774 if (peek_char () == ':') {
2776 return Token.DOUBLE_COLON;
2780 case '0': case '1': case '2': case '3': case '4':
2781 case '5': case '6': case '7': case '8': case '9':
2783 return is_number (c);
2785 case '\n': // white space
2786 any_token_seen |= tokens_seen;
2787 tokens_seen = false;
2788 comments_seen = false;
2794 if (d >= '0' && d <= '9')
2795 return is_number (c);
2799 if (tokens_seen || comments_seen) {
2800 Eror_WrongPreprocessorLocation ();
2804 if (handle_preprocessing_directive (true))
2807 bool directive_expected = false;
2808 while ((c = get_char ()) != -1) {
2810 directive_expected = true;
2811 } else if (!directive_expected) {
2812 // TODO: Implement comment support for disabled code and uncomment this code
2814 // Eror_WrongPreprocessorLocation ();
2815 // return Token.ERROR;
2820 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2824 if (handle_preprocessing_directive (false))
2827 directive_expected = false;
2831 tokens_seen = false;
2838 return consume_string (false);
2841 return TokenizeBackslash ();
2847 return consume_string (true);
2850 if (is_identifier_start_character (c)){
2851 return consume_identifier (c, true);
2854 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2857 case EvalStatementParserCharacter:
2858 return Token.EVAL_STATEMENT_PARSER;
2859 case EvalCompilationUnitParserCharacter:
2860 return Token.EVAL_COMPILATION_UNIT_PARSER;
2861 case EvalUsingDeclarationsParserCharacter:
2862 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2865 if (is_identifier_start_character (c)) {
2867 return consume_identifier (c);
2870 error_details = ((char)c).ToString ();
2877 int TokenizeBackslash ()
2879 int c = get_char ();
2882 error_details = "Empty character literal";
2883 Report.Error (1011, Location, error_details);
2886 if (c == '\r' || c == '\n') {
2887 Report.Error (1010, Location, "Newline in constant");
2892 c = escape (c, out d);
2896 throw new NotImplementedException ();
2902 Report.Error (1012, Location, "Too many characters in character literal");
2904 // Try to recover, read until newline or next "'"
2905 while ((c = get_char ()) != -1) {
2906 if (c == '\n' || c == '\'')
2912 return Token.LITERAL_CHARACTER;
2915 int TokenizeLessThan ()
2918 if (handle_typeof) {
2920 if (parse_generic_dimension (out d)) {
2923 return Token.GENERIC_DIMENSION;
2928 // Save current position and parse next token.
2930 if (parse_less_than ()) {
2931 if (parsing_generic_declaration && token () != Token.DOT) {
2932 d = Token.OP_GENERICS_LT_DECL;
2934 d = Token.OP_GENERICS_LT;
2941 parsing_generic_less_than = 0;
2950 return Token.OP_SHIFT_LEFT_ASSIGN;
2952 return Token.OP_SHIFT_LEFT;
2963 // Handles one line xml comment
2965 private void handle_one_line_xml_comment ()
2968 while ((c = peek_char ()) == ' ')
2969 get_char (); // skip heading whitespaces.
2970 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2971 xml_comment_buffer.Append ((char) get_char ());
2973 if (c == '\r' || c == '\n')
2974 xml_comment_buffer.Append (Environment.NewLine);
2978 // Remove heading "*" in Javadoc-like xml documentation.
2980 private void update_formatted_doc_comment (int current_comment_start)
2982 int length = xml_comment_buffer.Length - current_comment_start;
2983 string [] lines = xml_comment_buffer.ToString (
2984 current_comment_start,
2985 length).Replace ("\r", "").Split ('\n');
2987 // The first line starts with /**, thus it is not target
2988 // for the format check.
2989 for (int i = 1; i < lines.Length; i++) {
2990 string s = lines [i];
2991 int idx = s.IndexOf ('*');
2994 if (i < lines.Length - 1)
2998 head = s.Substring (0, idx);
2999 foreach (char c in head)
3002 lines [i] = s.Substring (idx + 1);
3004 xml_comment_buffer.Remove (current_comment_start, length);
3005 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3009 // Updates current comment location.
3011 private void update_comment_location ()
3013 if (current_comment_location.IsNull) {
3014 // "-2" is for heading "//" or "/*"
3015 current_comment_location =
3016 new Location (ref_line, hidden ? -1 : col - 2);
3021 // Checks if there was incorrect doc comments and raise
3024 public void check_incorrect_doc_comment ()
3026 if (xml_comment_buffer.Length > 0)
3027 warn_incorrect_doc_comment ();
3031 // Raises a warning when tokenizer found incorrect doccomment
3034 private void warn_incorrect_doc_comment ()
3036 if (doc_state != XmlCommentState.Error) {
3037 doc_state = XmlCommentState.Error;
3038 // in csc, it is 'XML comment is not placed on
3039 // a valid language element'. But that does not
3041 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3046 // Consumes the saved xml comment lines (if any)
3047 // as for current target member or type.
3049 public string consume_doc_comment ()
3051 if (xml_comment_buffer.Length > 0) {
3052 string ret = xml_comment_buffer.ToString ();
3053 reset_doc_comment ();
3059 void reset_doc_comment ()
3061 xml_comment_buffer.Length = 0;
3062 current_comment_location = Location.Null;
3065 public void cleanup ()
3067 if (ifstack != null && ifstack.Count >= 1) {
3068 int state = (int) ifstack.Pop ();
3069 if ((state & REGION) != 0)
3070 Report.Error (1038, Location, "#endregion directive expected");
3072 Report.Error (1027, Location, "Expected `#endif' directive");
3078 // Indicates whether it accepts XML documentation or not.
3080 public enum XmlCommentState {
3081 // comment is allowed in this state.
3083 // comment is not allowed in this state.
3085 // once comments appeared when it is NotAllowed, then the
3086 // state is changed to it, until the state is changed to