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.Generic;
19 using System.Globalization;
20 using System.Diagnostics;
25 /// Tokenizer for C# source code.
28 public class Tokenizer : yyParser.yyInput
32 public readonly T Token;
33 public KeywordEntry<T> Next;
34 public readonly char[] Value;
36 public KeywordEntry (string value, T token)
38 this.Value = value.ToCharArray ();
43 sealed class IdentifiersComparer : IEqualityComparer<char[]>
47 public IdentifiersComparer (int length)
52 public bool Equals (char[] x, char[] y)
54 for (int i = 0; i < length; ++i)
61 public int GetHashCode (char[] obj)
64 for (int i = 0; i < length; ++i)
65 h = (h << 5) - h + obj [i];
72 // This class has to be used in the parser only, it reuses token
73 // details after each parse
75 public class LocatedToken
80 static LocatedToken[] buffer;
83 private LocatedToken ()
87 public static LocatedToken Create (int row, int column)
89 return Create (null, row, column);
92 public static LocatedToken Create (string value, int row, int column)
95 // TODO: I am not very happy about the logic but it's the best
96 // what I could come up with for now.
97 // Ideally we should be using just tiny buffer (256 elements) which
98 // is enough to hold all details for currect stack and recycle elements
99 // poped from the stack but there is a trick needed to recycle
103 if (pos >= buffer.Length) {
104 entry = new LocatedToken ();
106 entry = buffer [pos];
108 entry = new LocatedToken ();
109 buffer [pos] = entry;
116 entry.column = column;
121 // Used for token not required by expression evaluator
123 [Conditional ("FULL_AST")]
124 public static void CreateOptional (int row, int col, ref object token)
126 token = Create (row, col);
129 public static void Initialize ()
132 buffer = new LocatedToken [10000];
136 public Location Location {
137 get { return new Location (row, column); }
140 public string Value {
141 get { return value; }
145 enum PreprocessorDirective
151 If = 3 | RequiresArgument,
153 Elif = 5 | RequiresArgument,
155 Define = 7 | RequiresArgument,
156 Undef = 8 | RequiresArgument,
159 Pragma = 11 | CustomArgumentsParsing,
162 CustomArgumentsParsing = 1 << 10,
163 RequiresArgument = 1 << 11
166 SeekableStreamReader reader;
168 CompilationUnit file_name;
169 CompilerContext context;
177 bool handle_get_set = false;
178 bool handle_remove_add = false;
179 bool handle_where = false;
180 bool handle_typeof = false;
181 bool lambda_arguments_parsing;
182 Location current_comment_location = Location.Null;
183 List<Location> escaped_identifiers;
184 int parsing_generic_less_than;
187 // Used mainly for parser optimizations. Some expressions for instance
188 // can appear only in block (including initializer, base initializer)
191 public int parsing_block;
192 internal bool query_parsing;
195 // When parsing type only, useful for ambiguous nullable types
197 public int parsing_type;
200 // Set when parsing generic declaration (type or method header)
202 public bool parsing_generic_declaration;
205 // The value indicates that we have not reach any declaration or
208 public int parsing_declaration;
211 // The special character to inject on streams to trigger the EXPRESSION_PARSE
212 // token to be returned. It just happens to be a Unicode character that
213 // would never be part of a program (can not be an identifier).
215 // This character is only tested just before the tokenizer is about to report
216 // an error; So on the regular operation mode, this addition will have no
217 // impact on the tokenizer's performance.
220 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
221 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
222 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
225 // XML documentation buffer. The save point is used to divide
226 // comments on types and comments on members.
228 StringBuilder xml_comment_buffer;
231 // See comment on XmlCommentState enumeration.
233 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
236 // Whether tokens have been seen on this line
238 bool tokens_seen = false;
241 // Set to true once the GENERATE_COMPLETION token has bee
242 // returned. This helps produce one GENERATE_COMPLETION,
243 // as many COMPLETE_COMPLETION as necessary to complete the
244 // AST tree and one final EOF.
249 // Whether a token has been seen on the file
250 // This is needed because `define' is not allowed to be used
251 // after a token has been seen.
253 bool any_token_seen = false;
255 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
257 public bool PropertyParsing {
258 get { return handle_get_set; }
259 set { handle_get_set = value; }
262 public bool EventParsing {
263 get { return handle_remove_add; }
264 set { handle_remove_add = value; }
267 public bool ConstraintsParsing {
268 get { return handle_where; }
269 set { handle_where = value; }
272 public bool TypeOfParsing {
273 get { return handle_typeof; }
274 set { handle_typeof = value; }
278 get { return tab_size; }
279 set { tab_size = value; }
282 public XmlCommentState doc_state {
283 get { return xml_doc_state; }
285 if (value == XmlCommentState.Allowed) {
286 check_incorrect_doc_comment ();
287 reset_doc_comment ();
289 xml_doc_state = value;
294 // This is used to trigger completion generation on the parser
295 public bool CompleteOnEOF;
297 void AddEscapedIdentifier (Location loc)
299 if (escaped_identifiers == null)
300 escaped_identifiers = new List<Location> ();
302 escaped_identifiers.Add (loc);
305 public bool IsEscapedIdentifier (MemberName name)
307 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
313 static KeywordEntry<int>[][] keywords;
314 static KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
315 static Dictionary<string, object> keyword_strings; // TODO: HashSet
316 static NumberStyles styles;
317 static NumberFormatInfo csharp_format_info;
320 static readonly char[] pragma_warning = "warning".ToCharArray ();
321 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
322 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
323 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
326 // Values for the associated token returned
328 internal int putback_char; // Used by repl only
334 const int TAKING = 1;
335 const int ELSE_SEEN = 4;
336 const int PARENT_TAKING = 8;
337 const int REGION = 16;
340 // pre-processor if stack state:
344 static System.Text.StringBuilder string_builder;
346 const int max_id_size = 512;
347 static char [] id_builder = new char [max_id_size];
349 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
351 const int max_number_size = 512;
352 static char [] number_builder = new char [max_number_size];
353 static int number_pos;
355 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
364 // This is used when the tokenizer needs to save
365 // the current position as it needs to do some parsing
366 // on its own to deamiguate a token in behalf of the
369 Stack<Position> position_stack = new Stack<Position> (2);
377 public int putback_char;
378 public int previous_col;
379 public Stack<int> ifstack;
380 public int parsing_generic_less_than;
381 public int current_token;
384 public Position (Tokenizer t)
386 position = t.reader.Position;
388 ref_line = t.ref_line;
391 putback_char = t.putback_char;
392 previous_col = t.previous_col;
393 if (t.ifstack != null && t.ifstack.Count != 0) {
394 // There is no simple way to clone Stack<T> all
395 // methods reverse the order
396 var clone = t.ifstack.ToArray ();
397 Array.Reverse (clone);
398 ifstack = new Stack<int> (clone);
400 parsing_generic_less_than = t.parsing_generic_less_than;
401 current_token = t.current_token;
406 public void PushPosition ()
408 position_stack.Push (new Position (this));
411 public void PopPosition ()
413 Position p = position_stack.Pop ();
415 reader.Position = p.position;
416 ref_line = p.ref_line;
420 putback_char = p.putback_char;
421 previous_col = p.previous_col;
423 parsing_generic_less_than = p.parsing_generic_less_than;
424 current_token = p.current_token;
428 // Do not reset the position, ignore it.
429 public void DiscardPosition ()
431 position_stack.Pop ();
434 static void AddKeyword (string kw, int token)
436 keyword_strings.Add (kw, null);
438 AddKeyword (keywords, kw, token);
441 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
443 AddKeyword (keywords_preprocessor, kw, directive);
446 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
448 int length = kw.Length;
449 if (keywords[length] == null) {
450 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
453 int char_index = kw[0] - '_';
454 var kwe = keywords[length][char_index];
456 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
460 while (kwe.Next != null) {
464 kwe.Next = new KeywordEntry<T> (kw, token);
467 static void InitTokens ()
469 keyword_strings = new Dictionary<string, object> ();
471 // 11 is the length of the longest keyword for now
472 keywords = new KeywordEntry<int> [11] [];
474 AddKeyword ("__arglist", Token.ARGLIST);
475 AddKeyword ("abstract", Token.ABSTRACT);
476 AddKeyword ("as", Token.AS);
477 AddKeyword ("add", Token.ADD);
478 AddKeyword ("base", Token.BASE);
479 AddKeyword ("bool", Token.BOOL);
480 AddKeyword ("break", Token.BREAK);
481 AddKeyword ("byte", Token.BYTE);
482 AddKeyword ("case", Token.CASE);
483 AddKeyword ("catch", Token.CATCH);
484 AddKeyword ("char", Token.CHAR);
485 AddKeyword ("checked", Token.CHECKED);
486 AddKeyword ("class", Token.CLASS);
487 AddKeyword ("const", Token.CONST);
488 AddKeyword ("continue", Token.CONTINUE);
489 AddKeyword ("decimal", Token.DECIMAL);
490 AddKeyword ("default", Token.DEFAULT);
491 AddKeyword ("delegate", Token.DELEGATE);
492 AddKeyword ("do", Token.DO);
493 AddKeyword ("double", Token.DOUBLE);
494 AddKeyword ("else", Token.ELSE);
495 AddKeyword ("enum", Token.ENUM);
496 AddKeyword ("event", Token.EVENT);
497 AddKeyword ("explicit", Token.EXPLICIT);
498 AddKeyword ("extern", Token.EXTERN);
499 AddKeyword ("false", Token.FALSE);
500 AddKeyword ("finally", Token.FINALLY);
501 AddKeyword ("fixed", Token.FIXED);
502 AddKeyword ("float", Token.FLOAT);
503 AddKeyword ("for", Token.FOR);
504 AddKeyword ("foreach", Token.FOREACH);
505 AddKeyword ("goto", Token.GOTO);
506 AddKeyword ("get", Token.GET);
507 AddKeyword ("if", Token.IF);
508 AddKeyword ("implicit", Token.IMPLICIT);
509 AddKeyword ("in", Token.IN);
510 AddKeyword ("int", Token.INT);
511 AddKeyword ("interface", Token.INTERFACE);
512 AddKeyword ("internal", Token.INTERNAL);
513 AddKeyword ("is", Token.IS);
514 AddKeyword ("lock", Token.LOCK);
515 AddKeyword ("long", Token.LONG);
516 AddKeyword ("namespace", Token.NAMESPACE);
517 AddKeyword ("new", Token.NEW);
518 AddKeyword ("null", Token.NULL);
519 AddKeyword ("object", Token.OBJECT);
520 AddKeyword ("operator", Token.OPERATOR);
521 AddKeyword ("out", Token.OUT);
522 AddKeyword ("override", Token.OVERRIDE);
523 AddKeyword ("params", Token.PARAMS);
524 AddKeyword ("private", Token.PRIVATE);
525 AddKeyword ("protected", Token.PROTECTED);
526 AddKeyword ("public", Token.PUBLIC);
527 AddKeyword ("readonly", Token.READONLY);
528 AddKeyword ("ref", Token.REF);
529 AddKeyword ("remove", Token.REMOVE);
530 AddKeyword ("return", Token.RETURN);
531 AddKeyword ("sbyte", Token.SBYTE);
532 AddKeyword ("sealed", Token.SEALED);
533 AddKeyword ("set", Token.SET);
534 AddKeyword ("short", Token.SHORT);
535 AddKeyword ("sizeof", Token.SIZEOF);
536 AddKeyword ("stackalloc", Token.STACKALLOC);
537 AddKeyword ("static", Token.STATIC);
538 AddKeyword ("string", Token.STRING);
539 AddKeyword ("struct", Token.STRUCT);
540 AddKeyword ("switch", Token.SWITCH);
541 AddKeyword ("this", Token.THIS);
542 AddKeyword ("throw", Token.THROW);
543 AddKeyword ("true", Token.TRUE);
544 AddKeyword ("try", Token.TRY);
545 AddKeyword ("typeof", Token.TYPEOF);
546 AddKeyword ("uint", Token.UINT);
547 AddKeyword ("ulong", Token.ULONG);
548 AddKeyword ("unchecked", Token.UNCHECKED);
549 AddKeyword ("unsafe", Token.UNSAFE);
550 AddKeyword ("ushort", Token.USHORT);
551 AddKeyword ("using", Token.USING);
552 AddKeyword ("virtual", Token.VIRTUAL);
553 AddKeyword ("void", Token.VOID);
554 AddKeyword ("volatile", Token.VOLATILE);
555 AddKeyword ("while", Token.WHILE);
556 AddKeyword ("partial", Token.PARTIAL);
557 AddKeyword ("where", Token.WHERE);
558 AddKeyword ("async", Token.ASYNC);
561 AddKeyword ("from", Token.FROM);
562 AddKeyword ("join", Token.JOIN);
563 AddKeyword ("on", Token.ON);
564 AddKeyword ("equals", Token.EQUALS);
565 AddKeyword ("select", Token.SELECT);
566 AddKeyword ("group", Token.GROUP);
567 AddKeyword ("by", Token.BY);
568 AddKeyword ("let", Token.LET);
569 AddKeyword ("orderby", Token.ORDERBY);
570 AddKeyword ("ascending", Token.ASCENDING);
571 AddKeyword ("descending", Token.DESCENDING);
572 AddKeyword ("into", Token.INTO);
574 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
576 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
577 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
578 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
579 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
580 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
581 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
582 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
583 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
584 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
585 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
586 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
587 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
596 csharp_format_info = NumberFormatInfo.InvariantInfo;
597 styles = NumberStyles.Float;
599 string_builder = new System.Text.StringBuilder ();
602 int GetKeyword (char[] id, int id_len)
605 // Keywords are stored in an array of arrays grouped by their
606 // length and then by the first character
608 if (id_len >= keywords.Length || keywords [id_len] == null)
611 int first_index = id [0] - '_';
612 if (first_index > 'z' - '_')
615 var kwe = keywords [id_len] [first_index];
622 for (int i = 1; i < id_len; ++i) {
623 if (id [i] != kwe.Value [i]) {
629 } while (res == 0 && kwe != null);
643 if (!handle_remove_add)
647 if (parsing_declaration == 0)
648 res = Token.EXTERN_ALIAS;
651 if (peek_token () == Token.COLON) {
653 res = Token.DEFAULT_COLON;
657 if (!handle_where && !query_parsing)
662 // A query expression is any expression that starts with `from identifier'
663 // followed by any token except ; , =
665 if (!query_parsing) {
666 if (lambda_arguments_parsing) {
672 // HACK: to disable generics micro-parser, because PushPosition does not
673 // store identifiers array
674 parsing_generic_less_than = 1;
676 case Token.IDENTIFIER:
688 next_token = xtoken ();
689 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
692 res = Token.FROM_FIRST;
693 query_parsing = true;
694 if (RootContext.Version <= LanguageVersion.ISO_2)
695 Report.FeatureIsNotAvailable (Location, "query expressions");
698 Expression.Error_VoidInvalidInTheContext (Location, Report);
702 // HACK: A token is not a keyword so we need to restore identifiers buffer
703 // which has been overwritten before we grabbed the identifier
704 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
718 case Token.ASCENDING:
719 case Token.DESCENDING:
726 case Token.NAMESPACE:
727 // TODO: some explanation needed
728 check_incorrect_doc_comment ();
732 if (parsing_block > 0) {
737 // Save current position and parse next token.
740 next_token = token ();
741 bool ok = (next_token == Token.CLASS) ||
742 (next_token == Token.STRUCT) ||
743 (next_token == Token.INTERFACE) ||
744 (next_token == Token.VOID);
749 if (next_token == Token.VOID) {
750 if (RootContext.Version == LanguageVersion.ISO_1 ||
751 RootContext.Version == LanguageVersion.ISO_2)
752 Report.FeatureIsNotAvailable (Location, "partial methods");
753 } else if (RootContext.Version == LanguageVersion.ISO_1)
754 Report.FeatureIsNotAvailable (Location, "partial types");
759 if (next_token < Token.LAST_KEYWORD) {
760 Report.Error (267, Location,
761 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
769 if (parsing_block > 0 || RootContext.Version != LanguageVersion.Future) {
779 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
782 // Keywords are stored in an array of arrays grouped by their
783 // length and then by the first character
785 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
786 return PreprocessorDirective.Invalid;
788 int first_index = id[0] - '_';
789 if (first_index > 'z' - '_')
790 return PreprocessorDirective.Invalid;
792 var kwe = keywords_preprocessor[id_len][first_index];
794 return PreprocessorDirective.Invalid;
796 PreprocessorDirective res = PreprocessorDirective.Invalid;
799 for (int i = 1; i < id_len; ++i) {
800 if (id[i] != kwe.Value[i]) {
806 } while (res == PreprocessorDirective.Invalid && kwe != null);
811 public Location Location {
813 return new Location (ref_line, hidden ? -1 : col);
817 public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
819 this.ref_name = file;
820 this.file_name = file;
826 xml_comment_buffer = new StringBuilder ();
828 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
834 // FIXME: This could be `Location.Push' but we have to
835 // find out why the MS compiler allows this
837 Mono.CSharp.Location.Push (file, file);
840 static bool is_identifier_start_character (int c)
842 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
845 static bool is_identifier_part_character (char c)
847 if (c >= 'a' && c <= 'z')
850 if (c >= 'A' && c <= 'Z')
853 if (c == '_' || (c >= '0' && c <= '9'))
859 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
862 public static bool IsKeyword (string s)
864 return keyword_strings.ContainsKey (s);
868 // Open parens micro parser. Detects both lambda and cast ambiguity.
870 int TokenizeOpenParens ()
875 int bracket_level = 0;
876 bool is_type = false;
877 bool can_be_type = false;
880 ptoken = current_token;
883 switch (current_token) {
884 case Token.CLOSE_PARENS:
888 // Expression inside parens is lambda, (int i) =>
890 if (current_token == Token.ARROW)
891 return Token.OPEN_PARENS_LAMBDA;
894 // Expression inside parens is single type, (int[])
897 return Token.OPEN_PARENS_CAST;
900 // Expression is possible cast, look at next token, (T)null
903 switch (current_token) {
904 case Token.OPEN_PARENS:
907 case Token.IDENTIFIER:
921 case Token.UNCHECKED:
926 // These can be part of a member access
940 return Token.OPEN_PARENS_CAST;
943 return Token.OPEN_PARENS;
946 case Token.DOUBLE_COLON:
947 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
952 case Token.IDENTIFIER:
955 if (bracket_level == 0) {
961 case Token.OP_GENERICS_LT:
963 case Token.DOUBLE_COLON:
965 if (bracket_level == 0)
969 can_be_type = is_type = false;
989 if (bracket_level == 0)
994 if (bracket_level == 0) {
996 can_be_type = is_type = false;
1000 case Token.OP_GENERICS_LT:
1001 case Token.OPEN_BRACKET:
1002 if (bracket_level++ == 0)
1006 case Token.OP_GENERICS_GT:
1007 case Token.CLOSE_BRACKET:
1011 case Token.INTERR_NULLABLE:
1013 if (bracket_level == 0)
1019 can_be_type = is_type = false;
1023 return Token.OPEN_PARENS;
1028 public static bool IsValidIdentifier (string s)
1030 if (s == null || s.Length == 0)
1033 if (!is_identifier_start_character (s [0]))
1036 for (int i = 1; i < s.Length; i ++)
1037 if (! is_identifier_part_character (s [i]))
1043 bool parse_less_than ()
1046 int the_token = token ();
1047 if (the_token == Token.OPEN_BRACKET) {
1049 the_token = token ();
1050 } while (the_token != Token.CLOSE_BRACKET);
1051 the_token = token ();
1052 } else if (the_token == Token.IN || the_token == Token.OUT) {
1053 the_token = token ();
1055 switch (the_token) {
1056 case Token.IDENTIFIER:
1074 case Token.OP_GENERICS_GT:
1081 the_token = token ();
1083 if (the_token == Token.OP_GENERICS_GT)
1085 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1087 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1089 else if (the_token == Token.OP_GENERICS_LT) {
1090 if (!parse_less_than ())
1093 } else if (the_token == Token.OPEN_BRACKET) {
1095 the_token = token ();
1096 if (the_token == Token.CLOSE_BRACKET)
1098 else if (the_token == Token.COMMA)
1099 goto rank_specifiers;
1106 bool parse_generic_dimension (out int dimension)
1111 int the_token = token ();
1112 if (the_token == Token.OP_GENERICS_GT)
1114 else if (the_token == Token.COMMA) {
1122 public int peek_token ()
1127 the_token = token ();
1134 // Tonizes `?' using custom disambiguous rules to return one
1135 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1137 // Tricky expression look like:
1139 // Foo ? a = x ? b : c;
1141 int TokenizePossibleNullableType ()
1143 if (parsing_block == 0 || parsing_type > 0)
1144 return Token.INTERR_NULLABLE;
1146 int d = peek_char ();
1149 return Token.OP_COALESCING;
1152 switch (current_token) {
1153 case Token.CLOSE_PARENS:
1158 return Token.INTERR;
1162 if (d == ',' || d == ';' || d == '>')
1163 return Token.INTERR_NULLABLE;
1164 if (d == '*' || (d >= '0' && d <= '9'))
1165 return Token.INTERR;
1169 current_token = Token.NONE;
1171 switch (xtoken ()) {
1178 next_token = Token.INTERR;
1181 case Token.SEMICOLON:
1183 case Token.CLOSE_PARENS:
1184 case Token.OPEN_BRACKET:
1185 case Token.OP_GENERICS_GT:
1186 next_token = Token.INTERR_NULLABLE;
1194 if (next_token == -1) {
1195 switch (xtoken ()) {
1197 case Token.SEMICOLON:
1198 case Token.OPEN_BRACE:
1199 case Token.CLOSE_PARENS:
1201 next_token = Token.INTERR_NULLABLE;
1205 next_token = Token.INTERR;
1213 // All shorcuts failed, do it hard way
1215 while ((ntoken = xtoken ()) != Token.EOF) {
1216 if (ntoken == Token.SEMICOLON)
1219 if (ntoken == Token.COLON) {
1220 if (++colons == interrs)
1225 if (ntoken == Token.INTERR) {
1231 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1240 bool decimal_digits (int c)
1243 bool seen_digits = false;
1246 if (number_pos == max_number_size)
1247 Error_NumericConstantTooLong ();
1248 number_builder [number_pos++] = (char) c;
1252 // We use peek_char2, because decimal_digits needs to do a
1253 // 2-character look-ahead (5.ToString for example).
1255 while ((d = peek_char2 ()) != -1){
1256 if (d >= '0' && d <= '9'){
1257 if (number_pos == max_number_size)
1258 Error_NumericConstantTooLong ();
1259 number_builder [number_pos++] = (char) d;
1269 static bool is_hex (int e)
1271 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1274 static TypeCode real_type_suffix (int c)
1278 return TypeCode.Single;
1280 return TypeCode.Double;
1282 return TypeCode.Decimal;
1284 return TypeCode.Empty;
1288 int integer_type_suffix (ulong ul, int c)
1290 bool is_unsigned = false;
1291 bool is_long = false;
1294 bool scanning = true;
1307 // if we have not seen anything in between
1308 // report this error
1310 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1330 if (is_long && is_unsigned){
1331 val = new ULongLiteral (ul, Location);
1332 return Token.LITERAL;
1336 // uint if possible, or ulong else.
1338 if ((ul & 0xffffffff00000000) == 0)
1339 val = new UIntLiteral ((uint) ul, Location);
1341 val = new ULongLiteral (ul, Location);
1342 } else if (is_long){
1343 // long if possible, ulong otherwise
1344 if ((ul & 0x8000000000000000) != 0)
1345 val = new ULongLiteral (ul, Location);
1347 val = new LongLiteral ((long) ul, Location);
1349 // int, uint, long or ulong in that order
1350 if ((ul & 0xffffffff00000000) == 0){
1351 uint ui = (uint) ul;
1353 if ((ui & 0x80000000) != 0)
1354 val = new UIntLiteral (ui, Location);
1356 val = new IntLiteral ((int) ui, Location);
1358 if ((ul & 0x8000000000000000) != 0)
1359 val = new ULongLiteral (ul, Location);
1361 val = new LongLiteral ((long) ul, Location);
1364 return Token.LITERAL;
1368 // given `c' as the next char in the input decide whether
1369 // we need to convert to a special type, and then choose
1370 // the best representation for the integer
1372 int adjust_int (int c)
1375 if (number_pos > 9){
1376 ulong ul = (uint) (number_builder [0] - '0');
1378 for (int i = 1; i < number_pos; i++){
1379 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1381 return integer_type_suffix (ul, c);
1383 uint ui = (uint) (number_builder [0] - '0');
1385 for (int i = 1; i < number_pos; i++){
1386 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1388 return integer_type_suffix (ui, c);
1390 } catch (OverflowException) {
1391 Error_NumericConstantTooLong ();
1392 val = new IntLiteral (0, Location);
1393 return Token.LITERAL;
1395 catch (FormatException) {
1396 Report.Error (1013, Location, "Invalid number");
1397 val = new IntLiteral (0, Location);
1398 return Token.LITERAL;
1402 int adjust_real (TypeCode t)
1404 string s = new String (number_builder, 0, number_pos);
1405 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1408 case TypeCode.Decimal:
1410 val = new DecimalLiteral (decimal.Parse (s, styles, csharp_format_info), Location);
1411 } catch (OverflowException) {
1412 val = new DecimalLiteral (0, Location);
1413 Report.Error (594, Location, error_details, "decimal");
1416 case TypeCode.Single:
1418 val = new FloatLiteral (float.Parse (s, styles, csharp_format_info), Location);
1419 } catch (OverflowException) {
1420 val = new FloatLiteral (0, Location);
1421 Report.Error (594, Location, error_details, "float");
1426 val = new DoubleLiteral (double.Parse (s, styles, csharp_format_info), Location);
1427 } catch (OverflowException) {
1428 val = new DoubleLiteral (0, Location);
1429 Report.Error (594, Location, error_details, "double");
1434 return Token.LITERAL;
1443 while ((d = peek_char ()) != -1){
1445 number_builder [number_pos++] = (char) d;
1451 string s = new String (number_builder, 0, number_pos);
1453 if (number_pos <= 8)
1454 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1456 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1457 } catch (OverflowException){
1458 Error_NumericConstantTooLong ();
1459 val = new IntLiteral (0, Location);
1460 return Token.LITERAL;
1462 catch (FormatException) {
1463 Report.Error (1013, Location, "Invalid number");
1464 val = new IntLiteral (0, Location);
1465 return Token.LITERAL;
1468 return integer_type_suffix (ul, peek_char ());
1472 // Invoked if we know we have .digits or digits
1474 int is_number (int c)
1476 bool is_real = false;
1480 if (c >= '0' && c <= '9'){
1482 int peek = peek_char ();
1484 if (peek == 'x' || peek == 'X')
1485 return handle_hex ();
1492 // We need to handle the case of
1493 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1496 if (decimal_digits ('.')){
1502 return adjust_int (-1);
1506 if (c == 'e' || c == 'E'){
1508 if (number_pos == max_number_size)
1509 Error_NumericConstantTooLong ();
1510 number_builder [number_pos++] = 'e';
1514 if (number_pos == max_number_size)
1515 Error_NumericConstantTooLong ();
1516 number_builder [number_pos++] = '+';
1518 } else if (c == '-') {
1519 if (number_pos == max_number_size)
1520 Error_NumericConstantTooLong ();
1521 number_builder [number_pos++] = '-';
1524 if (number_pos == max_number_size)
1525 Error_NumericConstantTooLong ();
1526 number_builder [number_pos++] = '+';
1533 var type = real_type_suffix (c);
1534 if (type == TypeCode.Empty && !is_real){
1536 return adjust_int (c);
1541 if (type == TypeCode.Empty){
1546 return adjust_real (type);
1548 throw new Exception ("Is Number should never reach this point");
1552 // Accepts exactly count (4 or 8) hex, no more no less
1554 int getHex (int count, out int surrogate, out bool error)
1559 int top = count != -1 ? count : 4;
1564 for (i = 0; i < top; i++){
1567 if (c >= '0' && c <= '9')
1568 c = (int) c - (int) '0';
1569 else if (c >= 'A' && c <= 'F')
1570 c = (int) c - (int) 'A' + 10;
1571 else if (c >= 'a' && c <= 'f')
1572 c = (int) c - (int) 'a' + 10;
1578 total = (total * 16) + c;
1580 int p = peek_char ();
1583 if (!is_hex ((char)p))
1589 if (total > 0x0010FFFF) {
1594 if (total >= 0x00010000) {
1595 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1596 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1603 int escape (int c, out int surrogate)
1639 v = getHex (-1, out surrogate, out error);
1645 return EscapeUnicode (d, out surrogate);
1648 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1657 int EscapeUnicode (int ch, out int surrogate)
1661 ch = getHex (8, out surrogate, out error);
1663 ch = getHex (4, out surrogate, out error);
1667 Report.Error (1009, Location, "Unrecognized escape sequence");
1675 if (putback_char != -1) {
1688 void advance_line ()
1698 if (putback_char == -1)
1699 putback_char = reader.Read ();
1700 return putback_char;
1705 if (putback_char != -1)
1706 return putback_char;
1707 return reader.Peek ();
1710 void putback (int c)
1712 if (putback_char != -1){
1713 Console.WriteLine ("Col: " + col);
1714 Console.WriteLine ("Row: " + line);
1715 Console.WriteLine ("Name: " + ref_name.Name);
1716 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1717 throw new Exception ("This should not happen putback on putback");
1719 if (c == '\n' || col == 0) {
1720 // It won't happen though.
1730 public bool advance ()
1732 return peek_char () != -1 || CompleteOnEOF;
1735 public Object Value {
1741 public Object value ()
1748 current_token = xtoken ();
1749 return current_token;
1752 int TokenizePreprocessorIdentifier (out int c)
1754 // skip over white space
1757 } while (c == '\r' || c == ' ' || c == '\t');
1761 while (c != -1 && c >= 'a' && c <= 'z') {
1762 id_builder[pos++] = (char) c;
1765 int peek = peek_char ();
1766 if (peek == 'U' || peek == 'u') {
1768 c = EscapeUnicode (c, out surrogate);
1769 if (surrogate != 0) {
1770 if (is_identifier_part_character ((char) c)) {
1771 id_builder[pos++] = (char) c;
1782 PreprocessorDirective get_cmd_arg (out string arg)
1786 tokens_seen = false;
1789 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1791 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1794 // skip over white space
1795 while (c == '\r' || c == ' ' || c == '\t')
1798 static_cmd_arg.Length = 0;
1799 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1801 while (c != -1 && c != '\n' && c != '\r') {
1802 if (c == '\\' && has_identifier_argument >= 0) {
1803 if (has_identifier_argument != 0) {
1804 has_identifier_argument = 1;
1806 int peek = peek_char ();
1807 if (peek == 'U' || peek == 'u') {
1809 c = EscapeUnicode (c, out surrogate);
1810 if (surrogate != 0) {
1811 if (is_identifier_part_character ((char) c))
1812 static_cmd_arg.Append ((char) c);
1817 has_identifier_argument = -1;
1820 static_cmd_arg.Append ((char) c);
1824 if (static_cmd_arg.Length != 0) {
1825 arg = static_cmd_arg.ToString ();
1827 // Eat any trailing whitespaces and single-line comments
1828 if (arg.IndexOf ("//") != -1) {
1829 arg = arg.Substring (0, arg.IndexOf ("//"));
1832 arg = arg.Trim (simple_whitespaces);
1839 // Handles the #line directive
1841 bool PreProcessLine (string arg)
1843 if (arg.Length == 0)
1846 if (arg == "default"){
1848 ref_name = file_name;
1850 Location.Push (file_name, ref_name);
1852 } else if (arg == "hidden"){
1860 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1861 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1864 char [] quotes = { '\"' };
1866 string name = arg.Substring (pos). Trim (quotes);
1867 ref_name = Location.LookupFile (file_name, name);
1868 file_name.AddFile (ref_name);
1870 Location.Push (file_name, ref_name);
1872 ref_line = System.Int32.Parse (arg);
1883 // Handles #define and #undef
1885 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1887 if (ident.Length == 0 || ident == "true" || ident == "false"){
1888 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1892 if (ident.IndexOfAny (simple_whitespaces) != -1){
1893 Error_EndLineExpected ();
1897 if (!is_identifier_start_character (ident [0]))
1898 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1900 foreach (char c in ident.Substring (1)){
1901 if (!is_identifier_part_character (c)){
1902 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1907 if (!caller_is_taking)
1914 if (RootContext.IsConditionalDefined (ident))
1917 file_name.AddDefine (ident);
1922 file_name.AddUndefine (ident);
1926 byte read_hex (out bool error)
1929 int c = get_char ();
1931 if ((c >= '0') && (c <= '9'))
1932 total = (int) c - (int) '0';
1933 else if ((c >= 'A') && (c <= 'F'))
1934 total = (int) c - (int) 'A' + 10;
1935 else if ((c >= 'a') && (c <= 'f'))
1936 total = (int) c - (int) 'a' + 10;
1945 if ((c >= '0') && (c <= '9'))
1946 total += (int) c - (int) '0';
1947 else if ((c >= 'A') && (c <= 'F'))
1948 total += (int) c - (int) 'A' + 10;
1949 else if ((c >= 'a') && (c <= 'f'))
1950 total += (int) c - (int) 'a' + 10;
1957 return (byte) total;
1961 // Parses #pragma checksum
1963 bool ParsePragmaChecksum ()
1966 // The syntax is ` "foo.txt" "{guid}" "hash"'
1968 int c = get_char ();
1973 string_builder.Length = 0;
1974 while (c != -1 && c != '\n') {
1981 string_builder.Append ((char) c);
1984 if (string_builder.Length == 0) {
1985 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
1988 // TODO: Any white-spaces count
1992 SourceFile file = Location.LookupFile (file_name, string_builder.ToString ());
1994 if (get_char () != '"' || get_char () != '{')
1998 byte[] guid_bytes = new byte [16];
2001 for (; i < 4; i++) {
2002 guid_bytes [i] = read_hex (out error);
2007 if (get_char () != '-')
2010 for (; i < 10; i++) {
2011 guid_bytes [i] = read_hex (out error);
2015 guid_bytes [i++] = read_hex (out error);
2019 if (get_char () != '-')
2023 for (; i < 16; i++) {
2024 guid_bytes [i] = read_hex (out error);
2029 if (get_char () != '}' || get_char () != '"')
2032 // TODO: Any white-spaces count
2037 if (get_char () != '"')
2040 // Any length of checksum
2041 List<byte> checksum_bytes = new List<byte> (16);
2044 while (c != '"' && c != -1) {
2045 checksum_bytes.Add (read_hex (out error));
2053 ReadSingleLineComment ();
2054 } else if (get_char () != '"') {
2058 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2059 ref_name.AutoGenerated = true;
2063 bool IsTokenIdentifierEqual (char[] identifier)
2065 for (int i = 0; i < identifier.Length; ++i) {
2066 if (identifier[i] != id_builder[i])
2073 int TokenizePragmaNumber (ref int c)
2079 if (c >= '0' && c <= '9') {
2081 uint ui = (uint) (number_builder[0] - '0');
2084 for (int i = 1; i < number_pos; i++) {
2085 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2089 } catch (OverflowException) {
2090 Error_NumericConstantTooLong ();
2097 // skip over white space
2098 while (c == '\r' || c == ' ' || c == '\t')
2105 // skip over white space
2106 while (c == '\r' || c == ' ' || c == '\t')
2111 ReadSingleLineComment ();
2113 Report.Warning (1692, 1, Location, "Invalid number");
2115 // Read everything till the end of the line or file
2118 } while (c != -1 && c != '\n');
2125 void ReadSingleLineComment ()
2127 if (peek_char () != '/')
2128 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2130 // Read everything till the end of the line or file
2134 } while (c != -1 && c != '\n');
2138 /// Handles #pragma directive
2140 void ParsePragmaDirective (string arg)
2143 int length = TokenizePreprocessorIdentifier (out c);
2144 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2145 length = TokenizePreprocessorIdentifier (out c);
2148 // #pragma warning disable
2149 // #pragma warning restore
2151 if (length == pragma_warning_disable.Length) {
2152 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2153 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2154 // skip over white space
2155 while (c == '\r' || c == ' ' || c == '\t')
2160 if (c == '\n' || c == '/') {
2162 ReadSingleLineComment ();
2165 // Disable/Restore all warnings
2168 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2170 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2174 // Disable/Restore a warning or group of warnings
2178 code = TokenizePragmaNumber (ref c);
2181 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2183 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2186 } while (code >= 0 && c != '\n');
2193 Report.Warning (1634, 1, Location, "Expected disable or restore");
2200 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2201 if (c != ' ' || !ParsePragmaChecksum ()) {
2202 Report.Warning (1695, 1, Location,
2203 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2209 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2212 bool eval_val (string s)
2219 return file_name.IsConditionalDefined (s);
2222 bool pp_primary (ref string s)
2231 s = s.Substring (1);
2232 bool val = pp_expr (ref s, false);
2233 if (s.Length > 0 && s [0] == ')'){
2234 s = s.Substring (1);
2237 Error_InvalidDirective ();
2241 if (is_identifier_start_character (c)){
2247 if (is_identifier_part_character (c)){
2251 bool v = eval_val (s.Substring (0, j));
2252 s = s.Substring (j);
2255 bool vv = eval_val (s);
2260 Error_InvalidDirective ();
2264 bool pp_unary (ref string s)
2271 if (len > 1 && s [1] == '='){
2272 Error_InvalidDirective ();
2275 s = s.Substring (1);
2276 return ! pp_primary (ref s);
2278 return pp_primary (ref s);
2280 Error_InvalidDirective ();
2285 bool pp_eq (ref string s)
2287 bool va = pp_unary (ref s);
2293 if (len > 2 && s [1] == '='){
2294 s = s.Substring (2);
2295 return va == pp_unary (ref s);
2297 Error_InvalidDirective ();
2300 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2301 s = s.Substring (2);
2303 return va != pp_unary (ref s);
2312 bool pp_and (ref string s)
2314 bool va = pp_eq (ref s);
2320 if (len > 2 && s [1] == '&'){
2321 s = s.Substring (2);
2322 return (va & pp_and (ref s));
2324 Error_InvalidDirective ();
2333 // Evaluates an expression for `#if' or `#elif'
2335 bool pp_expr (ref string s, bool isTerm)
2337 bool va = pp_and (ref s);
2344 if (len > 2 && s [1] == '|'){
2345 s = s.Substring (2);
2346 return va | pp_expr (ref s, isTerm);
2348 Error_InvalidDirective ();
2353 Error_EndLineExpected ();
2361 bool eval (string s)
2363 bool v = pp_expr (ref s, true);
2372 void Error_NumericConstantTooLong ()
2374 Report.Error (1021, Location, "Integral constant is too large");
2377 void Error_InvalidDirective ()
2379 Report.Error (1517, Location, "Invalid preprocessor directive");
2382 void Error_UnexpectedDirective (string extra)
2386 "Unexpected processor directive ({0})", extra);
2389 void Error_TokensSeen ()
2391 Report.Error (1032, Location,
2392 "Cannot define or undefine preprocessor symbols after first token in file");
2395 void Eror_WrongPreprocessorLocation ()
2397 Report.Error (1040, Location,
2398 "Preprocessor directives must appear as the first non-whitespace character on a line");
2401 void Error_EndLineExpected ()
2403 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2407 // if true, then the code continues processing the code
2408 // if false, the code stays in a loop until another directive is
2410 // When caller_is_taking is false we ignore all directives except the ones
2411 // which can help us to identify where the #if block ends
2412 bool ParsePreprocessingDirective (bool caller_is_taking)
2415 bool region_directive = false;
2417 var directive = get_cmd_arg (out arg);
2420 // The first group of pre-processing instructions is always processed
2422 switch (directive) {
2423 case PreprocessorDirective.Region:
2424 region_directive = true;
2426 goto case PreprocessorDirective.If;
2428 case PreprocessorDirective.Endregion:
2429 if (ifstack == null || ifstack.Count == 0){
2430 Error_UnexpectedDirective ("no #region for this #endregion");
2433 int pop = ifstack.Pop ();
2435 if ((pop & REGION) == 0)
2436 Report.Error (1027, Location, "Expected `#endif' directive");
2438 return caller_is_taking;
2440 case PreprocessorDirective.If:
2441 if (ifstack == null)
2442 ifstack = new Stack<int> (2);
2444 int flags = region_directive ? REGION : 0;
2445 if (ifstack.Count == 0){
2446 flags |= PARENT_TAKING;
2448 int state = ifstack.Peek ();
2449 if ((state & TAKING) != 0) {
2450 flags |= PARENT_TAKING;
2454 if (caller_is_taking && eval (arg)) {
2455 ifstack.Push (flags | TAKING);
2458 ifstack.Push (flags);
2461 case PreprocessorDirective.Endif:
2462 if (ifstack == null || ifstack.Count == 0){
2463 Error_UnexpectedDirective ("no #if for this #endif");
2466 pop = ifstack.Pop ();
2468 if ((pop & REGION) != 0)
2469 Report.Error (1038, Location, "#endregion directive expected");
2471 if (arg.Length != 0) {
2472 Error_EndLineExpected ();
2475 if (ifstack.Count == 0)
2478 int state = ifstack.Peek ();
2479 return (state & TAKING) != 0;
2482 case PreprocessorDirective.Elif:
2483 if (ifstack == null || ifstack.Count == 0){
2484 Error_UnexpectedDirective ("no #if for this #elif");
2487 int state = ifstack.Pop ();
2489 if ((state & REGION) != 0) {
2490 Report.Error (1038, Location, "#endregion directive expected");
2494 if ((state & ELSE_SEEN) != 0){
2495 Error_UnexpectedDirective ("#elif not valid after #else");
2499 if ((state & TAKING) != 0) {
2504 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2505 ifstack.Push (state | TAKING);
2509 ifstack.Push (state);
2513 case PreprocessorDirective.Else:
2514 if (ifstack == null || ifstack.Count == 0){
2515 Error_UnexpectedDirective ("no #if for this #else");
2518 int state = ifstack.Peek ();
2520 if ((state & REGION) != 0) {
2521 Report.Error (1038, Location, "#endregion directive expected");
2525 if ((state & ELSE_SEEN) != 0){
2526 Error_UnexpectedDirective ("#else within #else");
2532 if (arg.Length != 0) {
2533 Error_EndLineExpected ();
2538 if ((state & PARENT_TAKING) != 0) {
2539 ret = (state & TAKING) == 0;
2547 ifstack.Push (state | ELSE_SEEN);
2551 case PreprocessorDirective.Define:
2552 if (any_token_seen){
2553 Error_TokensSeen ();
2554 return caller_is_taking;
2556 PreProcessDefinition (true, arg, caller_is_taking);
2557 return caller_is_taking;
2559 case PreprocessorDirective.Undef:
2560 if (any_token_seen){
2561 Error_TokensSeen ();
2562 return caller_is_taking;
2564 PreProcessDefinition (false, arg, caller_is_taking);
2565 return caller_is_taking;
2567 case PreprocessorDirective.Invalid:
2568 Report.Error (1024, Location, "Wrong preprocessor directive");
2573 // These are only processed if we are in a `taking' block
2575 if (!caller_is_taking)
2579 case PreprocessorDirective.Error:
2580 Report.Error (1029, Location, "#error: '{0}'", arg);
2583 case PreprocessorDirective.Warning:
2584 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2587 case PreprocessorDirective.Pragma:
2588 if (RootContext.Version == LanguageVersion.ISO_1) {
2589 Report.FeatureIsNotAvailable (Location, "#pragma");
2592 ParsePragmaDirective (arg);
2595 case PreprocessorDirective.Line:
2596 if (!PreProcessLine (arg))
2599 "The line number specified for #line directive is missing or invalid");
2600 return caller_is_taking;
2603 throw new NotImplementedException (directive.ToString ());
2606 private int consume_string (bool quoted)
2609 string_builder.Length = 0;
2614 if (quoted && peek_char () == '"') {
2615 string_builder.Append ((char) c);
2620 val = new StringLiteral (string_builder.ToString (), Location);
2621 return Token.LITERAL;
2626 Report.Error (1010, Location, "Newline in constant");
2627 } else if (c == '\\' && !quoted) {
2629 c = escape (c, out surrogate);
2632 if (surrogate != 0) {
2633 string_builder.Append ((char) c);
2636 } else if (c == -1) {
2637 Report.Error (1039, Location, "Unterminated string literal");
2641 string_builder.Append ((char) c);
2645 private int consume_identifier (int s)
2647 int res = consume_identifier (s, false);
2649 if (doc_state == XmlCommentState.Allowed)
2650 doc_state = XmlCommentState.NotAllowed;
2655 int consume_identifier (int c, bool quoted)
2658 // This method is very performance sensitive. It accounts
2659 // for approximately 25% of all parser time
2667 c = escape (c, out surrogate);
2668 if (surrogate != 0) {
2669 id_builder [pos++] = (char) c;
2674 id_builder [pos++] = (char) c;
2680 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2681 id_builder [pos++] = (char) c;
2688 c = escape (c, out surrogate);
2689 if (surrogate != 0) {
2690 if (is_identifier_part_character ((char) c))
2691 id_builder[pos++] = (char) c;
2697 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2698 id_builder [pos++] = (char) c;
2705 } catch (IndexOutOfRangeException) {
2706 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2714 // Optimization: avoids doing the keyword lookup
2715 // on uppercase letters
2717 if (id_builder [0] >= '_' && !quoted) {
2718 int keyword = GetKeyword (id_builder, pos);
2719 if (keyword != -1) {
2720 val = LocatedToken.Create (null, ref_line, column);
2726 // Keep identifiers in an array of hashtables to avoid needless
2729 var identifiers_group = identifiers [pos];
2731 if (identifiers_group != null) {
2732 if (identifiers_group.TryGetValue (id_builder, out s)) {
2733 val = LocatedToken.Create (s, ref_line, column);
2735 AddEscapedIdentifier (((LocatedToken) val).Location);
2736 return Token.IDENTIFIER;
2739 // TODO: this should be number of files dependant
2740 // corlib compilation peaks at 1000 and System.Core at 150
2741 int capacity = pos > 20 ? 10 : 100;
2742 identifiers_group = new Dictionary<char[],string> (capacity, new IdentifiersComparer (pos));
2743 identifiers [pos] = identifiers_group;
2746 char [] chars = new char [pos];
2747 Array.Copy (id_builder, chars, pos);
2749 s = new string (id_builder, 0, pos);
2750 identifiers_group.Add (chars, s);
2752 val = LocatedToken.Create (s, ref_line, column);
2754 AddEscapedIdentifier (((LocatedToken) val).Location);
2756 return Token.IDENTIFIER;
2759 public int xtoken ()
2763 // Whether we have seen comments on the current line
2764 bool comments_seen = false;
2765 while ((c = get_char ()) != -1) {
2768 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2776 case 0xFEFF: // Ignore BOM anywhere in the file
2779 /* This is required for compatibility with .NET
2781 if (peek_char () == 0xBB) {
2784 if (get_char () == 0xBF)
2791 if (peek_char () != '\n')
2796 any_token_seen |= tokens_seen;
2797 tokens_seen = false;
2798 comments_seen = false;
2803 return consume_identifier (c);
2806 val = LocatedToken.Create (ref_line, col);
2807 return Token.OPEN_BRACE;
2809 val = LocatedToken.Create (ref_line, col);
2810 return Token.CLOSE_BRACE;
2812 // To block doccomment inside attribute declaration.
2813 if (doc_state == XmlCommentState.Allowed)
2814 doc_state = XmlCommentState.NotAllowed;
2816 val = LocatedToken.Create (ref_line, col);
2818 if (parsing_block == 0 || lambda_arguments_parsing)
2819 return Token.OPEN_BRACKET;
2821 int next = peek_char ();
2825 return Token.OPEN_BRACKET;
2833 next = peek_token ();
2834 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2835 return Token.OPEN_BRACKET;
2837 return Token.OPEN_BRACKET_EXPR;
2839 return Token.OPEN_BRACKET_EXPR;
2842 LocatedToken.CreateOptional (ref_line, col, ref val);
2843 return Token.CLOSE_BRACKET;
2845 val = LocatedToken.Create (ref_line, col);
2847 // An expression versions of parens can appear in block context only
2849 if (parsing_block != 0 && !lambda_arguments_parsing) {
2852 // Optmize most common case where we know that parens
2855 switch (current_token) {
2856 case Token.IDENTIFIER:
2864 case Token.DELEGATE:
2865 case Token.OP_GENERICS_GT:
2866 return Token.OPEN_PARENS;
2869 // Optimize using peek
2870 int xx = peek_char ();
2877 return Token.OPEN_PARENS;
2880 lambda_arguments_parsing = true;
2882 d = TokenizeOpenParens ();
2884 lambda_arguments_parsing = false;
2888 return Token.OPEN_PARENS;
2890 LocatedToken.CreateOptional (ref_line, col, ref val);
2891 return Token.CLOSE_PARENS;
2893 LocatedToken.CreateOptional (ref_line, col, ref val);
2896 LocatedToken.CreateOptional (ref_line, col, ref val);
2897 return Token.SEMICOLON;
2899 val = LocatedToken.Create (ref_line, col);
2902 val = LocatedToken.Create (ref_line, col);
2903 return TokenizePossibleNullableType ();
2905 val = LocatedToken.Create (ref_line, col);
2906 if (parsing_generic_less_than++ > 0)
2907 return Token.OP_GENERICS_LT;
2909 return TokenizeLessThan ();
2912 val = LocatedToken.Create (ref_line, col);
2920 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2921 parsing_generic_less_than--;
2922 return Token.OP_GENERICS_GT;
2931 return Token.OP_SHIFT_RIGHT_ASSIGN;
2933 return Token.OP_SHIFT_RIGHT;
2939 val = LocatedToken.Create (ref_line, col);
2943 } else if (d == '=') {
2944 d = Token.OP_ADD_ASSIGN;
2952 val = LocatedToken.Create (ref_line, col);
2956 } else if (d == '=')
2957 d = Token.OP_SUB_ASSIGN;
2967 val = LocatedToken.Create (ref_line, col);
2968 if (peek_char () == '='){
2975 val = LocatedToken.Create (ref_line, col);
2986 return Token.ASSIGN;
2989 val = LocatedToken.Create (ref_line, col);
2993 return Token.OP_AND;
2997 return Token.OP_AND_ASSIGN;
2999 return Token.BITWISE_AND;
3002 val = LocatedToken.Create (ref_line, col);
3010 return Token.OP_OR_ASSIGN;
3012 return Token.BITWISE_OR;
3015 val = LocatedToken.Create (ref_line, col);
3016 if (peek_char () == '='){
3018 return Token.OP_MULT_ASSIGN;
3025 val = LocatedToken.Create (ref_line, col);
3027 return Token.OP_DIV_ASSIGN;
3030 // Handle double-slash comments.
3033 if (RootContext.Documentation != null && peek_char () == '/') {
3035 // Don't allow ////.
3036 if ((d = peek_char ()) != '/') {
3037 update_comment_location ();
3038 if (doc_state == XmlCommentState.Allowed)
3039 handle_one_line_xml_comment ();
3040 else if (doc_state == XmlCommentState.NotAllowed)
3041 warn_incorrect_doc_comment ();
3044 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
3046 any_token_seen |= tokens_seen;
3047 tokens_seen = false;
3048 comments_seen = false;
3050 } else if (d == '*'){
3052 bool docAppend = false;
3053 if (RootContext.Documentation != null && peek_char () == '*') {
3055 update_comment_location ();
3056 // But when it is /**/, just do nothing.
3057 if (peek_char () == '/') {
3061 if (doc_state == XmlCommentState.Allowed)
3063 else if (doc_state == XmlCommentState.NotAllowed)
3064 warn_incorrect_doc_comment ();
3067 int current_comment_start = 0;
3069 current_comment_start = xml_comment_buffer.Length;
3070 xml_comment_buffer.Append (Environment.NewLine);
3073 while ((d = get_char ()) != -1){
3074 if (d == '*' && peek_char () == '/'){
3076 comments_seen = true;
3080 xml_comment_buffer.Append ((char) d);
3083 any_token_seen |= tokens_seen;
3084 tokens_seen = false;
3086 // Reset 'comments_seen' just to be consistent.
3087 // It doesn't matter either way, here.
3089 comments_seen = false;
3093 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3096 update_formatted_doc_comment (current_comment_start);
3099 val = LocatedToken.Create (ref_line, col);
3103 val = LocatedToken.Create (ref_line, col);
3104 if (peek_char () == '='){
3106 return Token.OP_MOD_ASSIGN;
3108 return Token.PERCENT;
3111 val = LocatedToken.Create (ref_line, col);
3112 if (peek_char () == '='){
3114 return Token.OP_XOR_ASSIGN;
3116 return Token.CARRET;
3119 val = LocatedToken.Create (ref_line, col);
3120 if (peek_char () == ':') {
3122 return Token.DOUBLE_COLON;
3126 case '0': case '1': case '2': case '3': case '4':
3127 case '5': case '6': case '7': case '8': case '9':
3129 return is_number (c);
3131 case '\n': // white space
3132 any_token_seen |= tokens_seen;
3133 tokens_seen = false;
3134 comments_seen = false;
3140 if (d >= '0' && d <= '9')
3141 return is_number (c);
3143 LocatedToken.CreateOptional (ref_line, col, ref val);
3147 if (tokens_seen || comments_seen) {
3148 Eror_WrongPreprocessorLocation ();
3152 if (ParsePreprocessingDirective (true))
3155 bool directive_expected = false;
3156 while ((c = get_char ()) != -1) {
3158 directive_expected = true;
3159 } else if (!directive_expected) {
3160 // TODO: Implement comment support for disabled code and uncomment this code
3162 // Eror_WrongPreprocessorLocation ();
3163 // return Token.ERROR;
3168 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
3172 if (ParsePreprocessingDirective (false))
3175 directive_expected = false;
3179 tokens_seen = false;
3186 return consume_string (false);
3189 return TokenizeBackslash ();
3195 return consume_string (true);
3198 if (is_identifier_start_character (c)){
3199 return consume_identifier (c, true);
3202 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3205 case EvalStatementParserCharacter:
3206 return Token.EVAL_STATEMENT_PARSER;
3207 case EvalCompilationUnitParserCharacter:
3208 return Token.EVAL_COMPILATION_UNIT_PARSER;
3209 case EvalUsingDeclarationsParserCharacter:
3210 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3213 if (is_identifier_start_character (c)) {
3215 return consume_identifier (c);
3218 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3223 return Token.COMPLETE_COMPLETION;
3226 return Token.GENERATE_COMPLETION;
3233 int TokenizeBackslash ()
3235 int c = get_char ();
3238 val = new CharLiteral ((char) c, Location);
3239 Report.Error (1011, Location, "Empty character literal");
3240 return Token.LITERAL;
3243 if (c == '\r' || c == '\n') {
3244 Report.Error (1010, Location, "Newline in constant");
3249 c = escape (c, out d);
3253 throw new NotImplementedException ();
3255 val = new CharLiteral ((char) c, Location);
3259 Report.Error (1012, Location, "Too many characters in character literal");
3261 // Try to recover, read until newline or next "'"
3262 while ((c = get_char ()) != -1) {
3263 if (c == '\n' || c == '\'')
3268 return Token.LITERAL;
3271 int TokenizeLessThan ()
3274 if (handle_typeof) {
3276 if (parse_generic_dimension (out d)) {
3279 return Token.GENERIC_DIMENSION;
3284 // Save current position and parse next token.
3286 if (parse_less_than ()) {
3287 if (parsing_generic_declaration && token () != Token.DOT) {
3288 d = Token.OP_GENERICS_LT_DECL;
3290 d = Token.OP_GENERICS_LT;
3297 parsing_generic_less_than = 0;
3306 return Token.OP_SHIFT_LEFT_ASSIGN;
3308 return Token.OP_SHIFT_LEFT;
3319 // Handles one line xml comment
3321 private void handle_one_line_xml_comment ()
3324 while ((c = peek_char ()) == ' ')
3325 get_char (); // skip heading whitespaces.
3326 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3327 xml_comment_buffer.Append ((char) get_char ());
3329 if (c == '\r' || c == '\n')
3330 xml_comment_buffer.Append (Environment.NewLine);
3334 // Remove heading "*" in Javadoc-like xml documentation.
3336 private void update_formatted_doc_comment (int current_comment_start)
3338 int length = xml_comment_buffer.Length - current_comment_start;
3339 string [] lines = xml_comment_buffer.ToString (
3340 current_comment_start,
3341 length).Replace ("\r", "").Split ('\n');
3343 // The first line starts with /**, thus it is not target
3344 // for the format check.
3345 for (int i = 1; i < lines.Length; i++) {
3346 string s = lines [i];
3347 int idx = s.IndexOf ('*');
3350 if (i < lines.Length - 1)
3354 head = s.Substring (0, idx);
3355 foreach (char c in head)
3358 lines [i] = s.Substring (idx + 1);
3360 xml_comment_buffer.Remove (current_comment_start, length);
3361 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3365 // Updates current comment location.
3367 private void update_comment_location ()
3369 if (current_comment_location.IsNull) {
3370 // "-2" is for heading "//" or "/*"
3371 current_comment_location =
3372 new Location (ref_line, hidden ? -1 : col - 2);
3377 // Checks if there was incorrect doc comments and raise
3380 public void check_incorrect_doc_comment ()
3382 if (xml_comment_buffer.Length > 0)
3383 warn_incorrect_doc_comment ();
3387 // Raises a warning when tokenizer found incorrect doccomment
3390 private void warn_incorrect_doc_comment ()
3392 if (doc_state != XmlCommentState.Error) {
3393 doc_state = XmlCommentState.Error;
3394 // in csc, it is 'XML comment is not placed on
3395 // a valid language element'. But that does not
3397 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3402 // Consumes the saved xml comment lines (if any)
3403 // as for current target member or type.
3405 public string consume_doc_comment ()
3407 if (xml_comment_buffer.Length > 0) {
3408 string ret = xml_comment_buffer.ToString ();
3409 reset_doc_comment ();
3416 get { return context.Report; }
3419 void reset_doc_comment ()
3421 xml_comment_buffer.Length = 0;
3422 current_comment_location = Location.Null;
3425 public void cleanup ()
3427 if (ifstack != null && ifstack.Count >= 1) {
3428 int state = ifstack.Pop ();
3429 if ((state & REGION) != 0)
3430 Report.Error (1038, Location, "#endregion directive expected");
3432 Report.Error (1027, Location, "Expected `#endif' directive");
3438 // Indicates whether it accepts XML documentation or not.
3440 public enum XmlCommentState {
3441 // comment is allowed in this state.
3443 // comment is not allowed in this state.
3445 // once comments appeared when it is NotAllowed, then the
3446 // state is changed to it, until the state is changed to