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;
18 using System.Globalization;
19 using System.Diagnostics;
24 /// Tokenizer for C# source code.
27 public class Tokenizer : yyParser.yyInput
31 public readonly T Token;
32 public KeywordEntry<T> Next;
33 public readonly char[] Value;
35 public KeywordEntry (string value, T token)
37 this.Value = value.ToCharArray ();
42 sealed class IdentifiersComparer : IEqualityComparer<char[]>
46 public IdentifiersComparer (int length)
51 public bool Equals (char[] x, char[] y)
53 for (int i = 0; i < length; ++i)
60 public int GetHashCode (char[] obj)
63 for (int i = 0; i < length; ++i)
64 h = (h << 5) - h + obj [i];
71 // This class has to be used in the parser only, it reuses token
72 // details after each parse
74 public class LocatedToken
79 static LocatedToken[] buffer;
82 private LocatedToken ()
86 public static LocatedToken Create (int row, int column)
88 return Create (null, row, column);
91 public static LocatedToken Create (string value, int row, int column)
94 // TODO: I am not very happy about the logic but it's the best
95 // what I could come up with for now.
96 // Ideally we should be using just tiny buffer (256 elements) which
97 // is enough to hold all details for currect stack and recycle elements
98 // poped from the stack but there is a trick needed to recycle
102 if (pos >= buffer.Length) {
103 entry = new LocatedToken ();
105 entry = buffer [pos];
107 entry = new LocatedToken ();
108 buffer [pos] = entry;
115 entry.column = column;
120 // Used for token not required by expression evaluator
122 [Conditional ("FULL_AST")]
123 public static void CreateOptional (int row, int col, ref object token)
125 token = Create (row, col);
128 public static void Initialize ()
131 buffer = new LocatedToken [10000];
135 public Location Location {
136 get { return new Location (row, column); }
139 public string Value {
140 get { return value; }
144 enum PreprocessorDirective
150 If = 3 | RequiresArgument,
152 Elif = 5 | RequiresArgument,
154 Define = 7 | RequiresArgument,
155 Undef = 8 | RequiresArgument,
158 Pragma = 11 | CustomArgumentsParsing,
161 CustomArgumentsParsing = 1 << 10,
162 RequiresArgument = 1 << 11
165 SeekableStreamReader reader;
167 CompilationUnit file_name;
168 CompilerContext context;
176 bool handle_get_set = false;
177 bool handle_remove_add = false;
178 bool handle_where = false;
179 bool handle_typeof = false;
180 bool lambda_arguments_parsing;
181 Location current_comment_location = Location.Null;
182 List<Location> escaped_identifiers;
183 int parsing_generic_less_than;
186 // Used mainly for parser optimizations. Some expressions for instance
187 // can appear only in block (including initializer, base initializer)
190 public int parsing_block;
191 internal bool query_parsing;
194 // When parsing type only, useful for ambiguous nullable types
196 public int parsing_type;
199 // Set when parsing generic declaration (type or method header)
201 public bool parsing_generic_declaration;
204 // The value indicates that we have not reach any declaration or
207 public int parsing_declaration;
210 // The special character to inject on streams to trigger the EXPRESSION_PARSE
211 // token to be returned. It just happens to be a Unicode character that
212 // would never be part of a program (can not be an identifier).
214 // This character is only tested just before the tokenizer is about to report
215 // an error; So on the regular operation mode, this addition will have no
216 // impact on the tokenizer's performance.
219 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
220 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
221 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
224 // XML documentation buffer. The save point is used to divide
225 // comments on types and comments on members.
227 StringBuilder xml_comment_buffer;
230 // See comment on XmlCommentState enumeration.
232 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
235 // Whether tokens have been seen on this line
237 bool tokens_seen = false;
240 // Set to true once the GENERATE_COMPLETION token has bee
241 // returned. This helps produce one GENERATE_COMPLETION,
242 // as many COMPLETE_COMPLETION as necessary to complete the
243 // AST tree and one final EOF.
248 // Whether a token has been seen on the file
249 // This is needed because `define' is not allowed to be used
250 // after a token has been seen.
252 bool any_token_seen = false;
254 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
256 public bool PropertyParsing {
257 get { return handle_get_set; }
258 set { handle_get_set = value; }
261 public bool EventParsing {
262 get { return handle_remove_add; }
263 set { handle_remove_add = value; }
266 public bool ConstraintsParsing {
267 get { return handle_where; }
268 set { handle_where = value; }
271 public bool TypeOfParsing {
272 get { return handle_typeof; }
273 set { handle_typeof = value; }
277 get { return tab_size; }
278 set { tab_size = value; }
281 public XmlCommentState doc_state {
282 get { return xml_doc_state; }
284 if (value == XmlCommentState.Allowed) {
285 check_incorrect_doc_comment ();
286 reset_doc_comment ();
288 xml_doc_state = value;
293 // This is used to trigger completion generation on the parser
294 public bool CompleteOnEOF;
296 void AddEscapedIdentifier (Location loc)
298 if (escaped_identifiers == null)
299 escaped_identifiers = new List<Location> ();
301 escaped_identifiers.Add (loc);
304 public bool IsEscapedIdentifier (MemberName name)
306 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
312 static KeywordEntry<int>[][] keywords;
313 static KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
314 static Dictionary<string, object> keyword_strings; // TODO: HashSet
315 static NumberStyles styles;
316 static NumberFormatInfo csharp_format_info;
319 static readonly char[] pragma_warning = "warning".ToCharArray ();
320 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
321 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
322 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
325 // Values for the associated token returned
327 internal int putback_char; // Used by repl only
333 const int TAKING = 1;
334 const int ELSE_SEEN = 4;
335 const int PARENT_TAKING = 8;
336 const int REGION = 16;
339 // pre-processor if stack state:
343 static System.Text.StringBuilder string_builder;
345 const int max_id_size = 512;
346 static char [] id_builder = new char [max_id_size];
348 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
350 const int max_number_size = 512;
351 static char [] number_builder = new char [max_number_size];
352 static int number_pos;
354 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
363 // This is used when the tokenizer needs to save
364 // the current position as it needs to do some parsing
365 // on its own to deamiguate a token in behalf of the
368 Stack<Position> position_stack = new Stack<Position> (2);
376 public int putback_char;
377 public int previous_col;
378 public Stack<int> ifstack;
379 public int parsing_generic_less_than;
380 public int current_token;
383 public Position (Tokenizer t)
385 position = t.reader.Position;
387 ref_line = t.ref_line;
390 putback_char = t.putback_char;
391 previous_col = t.previous_col;
392 if (t.ifstack != null && t.ifstack.Count != 0) {
393 // There is no simple way to clone Stack<T> all
394 // methods reverse the order
395 var clone = t.ifstack.ToArray ();
396 Array.Reverse (clone);
397 ifstack = new Stack<int> (clone);
399 parsing_generic_less_than = t.parsing_generic_less_than;
400 current_token = t.current_token;
405 public void PushPosition ()
407 position_stack.Push (new Position (this));
410 public void PopPosition ()
412 Position p = position_stack.Pop ();
414 reader.Position = p.position;
415 ref_line = p.ref_line;
419 putback_char = p.putback_char;
420 previous_col = p.previous_col;
422 parsing_generic_less_than = p.parsing_generic_less_than;
423 current_token = p.current_token;
427 // Do not reset the position, ignore it.
428 public void DiscardPosition ()
430 position_stack.Pop ();
433 static void AddKeyword (string kw, int token)
435 keyword_strings.Add (kw, null);
437 AddKeyword (keywords, kw, token);
440 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
442 AddKeyword (keywords_preprocessor, kw, directive);
445 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
447 int length = kw.Length;
448 if (keywords[length] == null) {
449 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
452 int char_index = kw[0] - '_';
453 var kwe = keywords[length][char_index];
455 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
459 while (kwe.Next != null) {
463 kwe.Next = new KeywordEntry<T> (kw, token);
466 static void InitTokens ()
468 keyword_strings = new Dictionary<string, object> ();
470 // 11 is the length of the longest keyword for now
471 keywords = new KeywordEntry<int> [11] [];
473 AddKeyword ("__arglist", Token.ARGLIST);
474 AddKeyword ("abstract", Token.ABSTRACT);
475 AddKeyword ("as", Token.AS);
476 AddKeyword ("add", Token.ADD);
477 AddKeyword ("base", Token.BASE);
478 AddKeyword ("bool", Token.BOOL);
479 AddKeyword ("break", Token.BREAK);
480 AddKeyword ("byte", Token.BYTE);
481 AddKeyword ("case", Token.CASE);
482 AddKeyword ("catch", Token.CATCH);
483 AddKeyword ("char", Token.CHAR);
484 AddKeyword ("checked", Token.CHECKED);
485 AddKeyword ("class", Token.CLASS);
486 AddKeyword ("const", Token.CONST);
487 AddKeyword ("continue", Token.CONTINUE);
488 AddKeyword ("decimal", Token.DECIMAL);
489 AddKeyword ("default", Token.DEFAULT);
490 AddKeyword ("delegate", Token.DELEGATE);
491 AddKeyword ("do", Token.DO);
492 AddKeyword ("double", Token.DOUBLE);
493 AddKeyword ("else", Token.ELSE);
494 AddKeyword ("enum", Token.ENUM);
495 AddKeyword ("event", Token.EVENT);
496 AddKeyword ("explicit", Token.EXPLICIT);
497 AddKeyword ("extern", Token.EXTERN);
498 AddKeyword ("false", Token.FALSE);
499 AddKeyword ("finally", Token.FINALLY);
500 AddKeyword ("fixed", Token.FIXED);
501 AddKeyword ("float", Token.FLOAT);
502 AddKeyword ("for", Token.FOR);
503 AddKeyword ("foreach", Token.FOREACH);
504 AddKeyword ("goto", Token.GOTO);
505 AddKeyword ("get", Token.GET);
506 AddKeyword ("if", Token.IF);
507 AddKeyword ("implicit", Token.IMPLICIT);
508 AddKeyword ("in", Token.IN);
509 AddKeyword ("int", Token.INT);
510 AddKeyword ("interface", Token.INTERFACE);
511 AddKeyword ("internal", Token.INTERNAL);
512 AddKeyword ("is", Token.IS);
513 AddKeyword ("lock", Token.LOCK);
514 AddKeyword ("long", Token.LONG);
515 AddKeyword ("namespace", Token.NAMESPACE);
516 AddKeyword ("new", Token.NEW);
517 AddKeyword ("null", Token.NULL);
518 AddKeyword ("object", Token.OBJECT);
519 AddKeyword ("operator", Token.OPERATOR);
520 AddKeyword ("out", Token.OUT);
521 AddKeyword ("override", Token.OVERRIDE);
522 AddKeyword ("params", Token.PARAMS);
523 AddKeyword ("private", Token.PRIVATE);
524 AddKeyword ("protected", Token.PROTECTED);
525 AddKeyword ("public", Token.PUBLIC);
526 AddKeyword ("readonly", Token.READONLY);
527 AddKeyword ("ref", Token.REF);
528 AddKeyword ("remove", Token.REMOVE);
529 AddKeyword ("return", Token.RETURN);
530 AddKeyword ("sbyte", Token.SBYTE);
531 AddKeyword ("sealed", Token.SEALED);
532 AddKeyword ("set", Token.SET);
533 AddKeyword ("short", Token.SHORT);
534 AddKeyword ("sizeof", Token.SIZEOF);
535 AddKeyword ("stackalloc", Token.STACKALLOC);
536 AddKeyword ("static", Token.STATIC);
537 AddKeyword ("string", Token.STRING);
538 AddKeyword ("struct", Token.STRUCT);
539 AddKeyword ("switch", Token.SWITCH);
540 AddKeyword ("this", Token.THIS);
541 AddKeyword ("throw", Token.THROW);
542 AddKeyword ("true", Token.TRUE);
543 AddKeyword ("try", Token.TRY);
544 AddKeyword ("typeof", Token.TYPEOF);
545 AddKeyword ("uint", Token.UINT);
546 AddKeyword ("ulong", Token.ULONG);
547 AddKeyword ("unchecked", Token.UNCHECKED);
548 AddKeyword ("unsafe", Token.UNSAFE);
549 AddKeyword ("ushort", Token.USHORT);
550 AddKeyword ("using", Token.USING);
551 AddKeyword ("virtual", Token.VIRTUAL);
552 AddKeyword ("void", Token.VOID);
553 AddKeyword ("volatile", Token.VOLATILE);
554 AddKeyword ("while", Token.WHILE);
555 AddKeyword ("partial", Token.PARTIAL);
556 AddKeyword ("where", Token.WHERE);
557 AddKeyword ("async", Token.ASYNC);
560 AddKeyword ("from", Token.FROM);
561 AddKeyword ("join", Token.JOIN);
562 AddKeyword ("on", Token.ON);
563 AddKeyword ("equals", Token.EQUALS);
564 AddKeyword ("select", Token.SELECT);
565 AddKeyword ("group", Token.GROUP);
566 AddKeyword ("by", Token.BY);
567 AddKeyword ("let", Token.LET);
568 AddKeyword ("orderby", Token.ORDERBY);
569 AddKeyword ("ascending", Token.ASCENDING);
570 AddKeyword ("descending", Token.DESCENDING);
571 AddKeyword ("into", Token.INTO);
573 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
575 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
576 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
577 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
578 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
579 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
580 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
581 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
582 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
583 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
584 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
585 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
586 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
595 csharp_format_info = NumberFormatInfo.InvariantInfo;
596 styles = NumberStyles.Float;
598 string_builder = new System.Text.StringBuilder ();
601 int GetKeyword (char[] id, int id_len)
604 // Keywords are stored in an array of arrays grouped by their
605 // length and then by the first character
607 if (id_len >= keywords.Length || keywords [id_len] == null)
610 int first_index = id [0] - '_';
611 if (first_index > 'z' - '_')
614 var kwe = keywords [id_len] [first_index];
621 for (int i = 1; i < id_len; ++i) {
622 if (id [i] != kwe.Value [i]) {
628 } while (res == 0 && kwe != null);
642 if (!handle_remove_add)
646 if (parsing_declaration == 0)
647 res = Token.EXTERN_ALIAS;
650 if (peek_token () == Token.COLON) {
652 res = Token.DEFAULT_COLON;
656 if (!handle_where && !query_parsing)
661 // A query expression is any expression that starts with `from identifier'
662 // followed by any token except ; , =
664 if (!query_parsing) {
665 if (lambda_arguments_parsing) {
671 // HACK: to disable generics micro-parser, because PushPosition does not
672 // store identifiers array
673 parsing_generic_less_than = 1;
675 case Token.IDENTIFIER:
687 next_token = xtoken ();
688 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
691 res = Token.FROM_FIRST;
692 query_parsing = true;
693 if (RootContext.Version <= LanguageVersion.ISO_2)
694 Report.FeatureIsNotAvailable (Location, "query expressions");
697 Expression.Error_VoidInvalidInTheContext (Location, Report);
701 // HACK: A token is not a keyword so we need to restore identifiers buffer
702 // which has been overwritten before we grabbed the identifier
703 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
717 case Token.ASCENDING:
718 case Token.DESCENDING:
725 case Token.NAMESPACE:
726 // TODO: some explanation needed
727 check_incorrect_doc_comment ();
731 if (parsing_block > 0) {
736 // Save current position and parse next token.
739 next_token = token ();
740 bool ok = (next_token == Token.CLASS) ||
741 (next_token == Token.STRUCT) ||
742 (next_token == Token.INTERFACE) ||
743 (next_token == Token.VOID);
748 if (next_token == Token.VOID) {
749 if (RootContext.Version == LanguageVersion.ISO_1 ||
750 RootContext.Version == LanguageVersion.ISO_2)
751 Report.FeatureIsNotAvailable (Location, "partial methods");
752 } else if (RootContext.Version == LanguageVersion.ISO_1)
753 Report.FeatureIsNotAvailable (Location, "partial types");
758 if (next_token < Token.LAST_KEYWORD) {
759 Report.Error (267, Location,
760 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
768 if (parsing_block > 0 || RootContext.Version != LanguageVersion.Future) {
778 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
781 // Keywords are stored in an array of arrays grouped by their
782 // length and then by the first character
784 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
785 return PreprocessorDirective.Invalid;
787 int first_index = id[0] - '_';
788 if (first_index > 'z' - '_')
789 return PreprocessorDirective.Invalid;
791 var kwe = keywords_preprocessor[id_len][first_index];
793 return PreprocessorDirective.Invalid;
795 PreprocessorDirective res = PreprocessorDirective.Invalid;
798 for (int i = 1; i < id_len; ++i) {
799 if (id[i] != kwe.Value[i]) {
805 } while (res == PreprocessorDirective.Invalid && kwe != null);
810 public Location Location {
812 return new Location (ref_line, hidden ? -1 : col);
816 public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
818 this.ref_name = file;
819 this.file_name = file;
825 xml_comment_buffer = new StringBuilder ();
827 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
833 // FIXME: This could be `Location.Push' but we have to
834 // find out why the MS compiler allows this
836 Mono.CSharp.Location.Push (file, file);
839 static bool is_identifier_start_character (int c)
841 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
844 static bool is_identifier_part_character (char c)
846 if (c >= 'a' && c <= 'z')
849 if (c >= 'A' && c <= 'Z')
852 if (c == '_' || (c >= '0' && c <= '9'))
858 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
861 public static bool IsKeyword (string s)
863 return keyword_strings.ContainsKey (s);
867 // Open parens micro parser. Detects both lambda and cast ambiguity.
869 int TokenizeOpenParens ()
874 int bracket_level = 0;
875 bool is_type = false;
876 bool can_be_type = false;
879 ptoken = current_token;
882 switch (current_token) {
883 case Token.CLOSE_PARENS:
887 // Expression inside parens is lambda, (int i) =>
889 if (current_token == Token.ARROW)
890 return Token.OPEN_PARENS_LAMBDA;
893 // Expression inside parens is single type, (int[])
896 return Token.OPEN_PARENS_CAST;
899 // Expression is possible cast, look at next token, (T)null
902 switch (current_token) {
903 case Token.OPEN_PARENS:
906 case Token.IDENTIFIER:
920 case Token.UNCHECKED:
925 // These can be part of a member access
939 return Token.OPEN_PARENS_CAST;
942 return Token.OPEN_PARENS;
945 case Token.DOUBLE_COLON:
946 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
951 case Token.IDENTIFIER:
954 if (bracket_level == 0) {
960 case Token.OP_GENERICS_LT:
962 case Token.DOUBLE_COLON:
964 if (bracket_level == 0)
968 can_be_type = is_type = false;
988 if (bracket_level == 0)
993 if (bracket_level == 0) {
995 can_be_type = is_type = false;
999 case Token.OP_GENERICS_LT:
1000 case Token.OPEN_BRACKET:
1001 if (bracket_level++ == 0)
1005 case Token.OP_GENERICS_GT:
1006 case Token.CLOSE_BRACKET:
1010 case Token.INTERR_NULLABLE:
1012 if (bracket_level == 0)
1018 can_be_type = is_type = false;
1022 return Token.OPEN_PARENS;
1027 public static bool IsValidIdentifier (string s)
1029 if (s == null || s.Length == 0)
1032 if (!is_identifier_start_character (s [0]))
1035 for (int i = 1; i < s.Length; i ++)
1036 if (! is_identifier_part_character (s [i]))
1042 bool parse_less_than ()
1045 int the_token = token ();
1046 if (the_token == Token.OPEN_BRACKET) {
1048 the_token = token ();
1049 } while (the_token != Token.CLOSE_BRACKET);
1050 the_token = token ();
1051 } else if (the_token == Token.IN || the_token == Token.OUT) {
1052 the_token = token ();
1054 switch (the_token) {
1055 case Token.IDENTIFIER:
1073 case Token.OP_GENERICS_GT:
1080 the_token = token ();
1082 if (the_token == Token.OP_GENERICS_GT)
1084 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1086 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1088 else if (the_token == Token.OP_GENERICS_LT) {
1089 if (!parse_less_than ())
1092 } else if (the_token == Token.OPEN_BRACKET) {
1094 the_token = token ();
1095 if (the_token == Token.CLOSE_BRACKET)
1097 else if (the_token == Token.COMMA)
1098 goto rank_specifiers;
1105 bool parse_generic_dimension (out int dimension)
1110 int the_token = token ();
1111 if (the_token == Token.OP_GENERICS_GT)
1113 else if (the_token == Token.COMMA) {
1121 public int peek_token ()
1126 the_token = token ();
1133 // Tonizes `?' using custom disambiguous rules to return one
1134 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1136 // Tricky expression look like:
1138 // Foo ? a = x ? b : c;
1140 int TokenizePossibleNullableType ()
1142 if (parsing_block == 0 || parsing_type > 0)
1143 return Token.INTERR_NULLABLE;
1145 int d = peek_char ();
1148 return Token.OP_COALESCING;
1151 switch (current_token) {
1152 case Token.CLOSE_PARENS:
1157 return Token.INTERR;
1161 if (d == ',' || d == ';' || d == '>')
1162 return Token.INTERR_NULLABLE;
1163 if (d == '*' || (d >= '0' && d <= '9'))
1164 return Token.INTERR;
1168 current_token = Token.NONE;
1170 switch (xtoken ()) {
1177 next_token = Token.INTERR;
1180 case Token.SEMICOLON:
1182 case Token.CLOSE_PARENS:
1183 case Token.OPEN_BRACKET:
1184 case Token.OP_GENERICS_GT:
1185 next_token = Token.INTERR_NULLABLE;
1193 if (next_token == -1) {
1194 switch (xtoken ()) {
1196 case Token.SEMICOLON:
1197 case Token.OPEN_BRACE:
1198 case Token.CLOSE_PARENS:
1200 next_token = Token.INTERR_NULLABLE;
1204 next_token = Token.INTERR;
1212 // All shorcuts failed, do it hard way
1214 while ((ntoken = xtoken ()) != Token.EOF) {
1215 if (ntoken == Token.SEMICOLON)
1218 if (ntoken == Token.COLON) {
1219 if (++colons == interrs)
1224 if (ntoken == Token.INTERR) {
1230 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1239 bool decimal_digits (int c)
1242 bool seen_digits = false;
1245 if (number_pos == max_number_size)
1246 Error_NumericConstantTooLong ();
1247 number_builder [number_pos++] = (char) c;
1251 // We use peek_char2, because decimal_digits needs to do a
1252 // 2-character look-ahead (5.ToString for example).
1254 while ((d = peek_char2 ()) != -1){
1255 if (d >= '0' && d <= '9'){
1256 if (number_pos == max_number_size)
1257 Error_NumericConstantTooLong ();
1258 number_builder [number_pos++] = (char) d;
1268 static bool is_hex (int e)
1270 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1273 static TypeCode real_type_suffix (int c)
1277 return TypeCode.Single;
1279 return TypeCode.Double;
1281 return TypeCode.Decimal;
1283 return TypeCode.Empty;
1287 int integer_type_suffix (ulong ul, int c)
1289 bool is_unsigned = false;
1290 bool is_long = false;
1293 bool scanning = true;
1306 // if we have not seen anything in between
1307 // report this error
1309 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1329 if (is_long && is_unsigned){
1330 val = new ULongLiteral (ul, Location);
1331 return Token.LITERAL;
1335 // uint if possible, or ulong else.
1337 if ((ul & 0xffffffff00000000) == 0)
1338 val = new UIntLiteral ((uint) ul, Location);
1340 val = new ULongLiteral (ul, Location);
1341 } else if (is_long){
1342 // long if possible, ulong otherwise
1343 if ((ul & 0x8000000000000000) != 0)
1344 val = new ULongLiteral (ul, Location);
1346 val = new LongLiteral ((long) ul, Location);
1348 // int, uint, long or ulong in that order
1349 if ((ul & 0xffffffff00000000) == 0){
1350 uint ui = (uint) ul;
1352 if ((ui & 0x80000000) != 0)
1353 val = new UIntLiteral (ui, Location);
1355 val = new IntLiteral ((int) ui, Location);
1357 if ((ul & 0x8000000000000000) != 0)
1358 val = new ULongLiteral (ul, Location);
1360 val = new LongLiteral ((long) ul, Location);
1363 return Token.LITERAL;
1367 // given `c' as the next char in the input decide whether
1368 // we need to convert to a special type, and then choose
1369 // the best representation for the integer
1371 int adjust_int (int c)
1374 if (number_pos > 9){
1375 ulong ul = (uint) (number_builder [0] - '0');
1377 for (int i = 1; i < number_pos; i++){
1378 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1380 return integer_type_suffix (ul, c);
1382 uint ui = (uint) (number_builder [0] - '0');
1384 for (int i = 1; i < number_pos; i++){
1385 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1387 return integer_type_suffix (ui, c);
1389 } catch (OverflowException) {
1390 Error_NumericConstantTooLong ();
1391 val = new IntLiteral (0, Location);
1392 return Token.LITERAL;
1394 catch (FormatException) {
1395 Report.Error (1013, Location, "Invalid number");
1396 val = new IntLiteral (0, Location);
1397 return Token.LITERAL;
1401 int adjust_real (TypeCode t)
1403 string s = new String (number_builder, 0, number_pos);
1404 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1407 case TypeCode.Decimal:
1409 val = new DecimalLiteral (decimal.Parse (s, styles, csharp_format_info), Location);
1410 } catch (OverflowException) {
1411 val = new DecimalLiteral (0, Location);
1412 Report.Error (594, Location, error_details, "decimal");
1415 case TypeCode.Single:
1417 val = new FloatLiteral (float.Parse (s, styles, csharp_format_info), Location);
1418 } catch (OverflowException) {
1419 val = new FloatLiteral (0, Location);
1420 Report.Error (594, Location, error_details, "float");
1425 val = new DoubleLiteral (double.Parse (s, styles, csharp_format_info), Location);
1426 } catch (OverflowException) {
1427 val = new DoubleLiteral (0, Location);
1428 Report.Error (594, Location, error_details, "double");
1433 return Token.LITERAL;
1442 while ((d = peek_char ()) != -1){
1444 number_builder [number_pos++] = (char) d;
1450 string s = new String (number_builder, 0, number_pos);
1452 if (number_pos <= 8)
1453 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1455 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1456 } catch (OverflowException){
1457 Error_NumericConstantTooLong ();
1458 val = new IntLiteral (0, Location);
1459 return Token.LITERAL;
1461 catch (FormatException) {
1462 Report.Error (1013, Location, "Invalid number");
1463 val = new IntLiteral (0, Location);
1464 return Token.LITERAL;
1467 return integer_type_suffix (ul, peek_char ());
1471 // Invoked if we know we have .digits or digits
1473 int is_number (int c)
1475 bool is_real = false;
1479 if (c >= '0' && c <= '9'){
1481 int peek = peek_char ();
1483 if (peek == 'x' || peek == 'X')
1484 return handle_hex ();
1491 // We need to handle the case of
1492 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1495 if (decimal_digits ('.')){
1501 return adjust_int (-1);
1505 if (c == 'e' || c == 'E'){
1507 if (number_pos == max_number_size)
1508 Error_NumericConstantTooLong ();
1509 number_builder [number_pos++] = 'e';
1513 if (number_pos == max_number_size)
1514 Error_NumericConstantTooLong ();
1515 number_builder [number_pos++] = '+';
1517 } else if (c == '-') {
1518 if (number_pos == max_number_size)
1519 Error_NumericConstantTooLong ();
1520 number_builder [number_pos++] = '-';
1523 if (number_pos == max_number_size)
1524 Error_NumericConstantTooLong ();
1525 number_builder [number_pos++] = '+';
1532 var type = real_type_suffix (c);
1533 if (type == TypeCode.Empty && !is_real){
1535 return adjust_int (c);
1540 if (type == TypeCode.Empty){
1545 return adjust_real (type);
1547 throw new Exception ("Is Number should never reach this point");
1551 // Accepts exactly count (4 or 8) hex, no more no less
1553 int getHex (int count, out int surrogate, out bool error)
1558 int top = count != -1 ? count : 4;
1563 for (i = 0; i < top; i++){
1566 if (c >= '0' && c <= '9')
1567 c = (int) c - (int) '0';
1568 else if (c >= 'A' && c <= 'F')
1569 c = (int) c - (int) 'A' + 10;
1570 else if (c >= 'a' && c <= 'f')
1571 c = (int) c - (int) 'a' + 10;
1577 total = (total * 16) + c;
1579 int p = peek_char ();
1582 if (!is_hex ((char)p))
1588 if (total > 0x0010FFFF) {
1593 if (total >= 0x00010000) {
1594 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1595 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1602 int escape (int c, out int surrogate)
1638 v = getHex (-1, out surrogate, out error);
1644 return EscapeUnicode (d, out surrogate);
1647 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1656 int EscapeUnicode (int ch, out int surrogate)
1660 ch = getHex (8, out surrogate, out error);
1662 ch = getHex (4, out surrogate, out error);
1666 Report.Error (1009, Location, "Unrecognized escape sequence");
1674 if (putback_char != -1) {
1687 void advance_line ()
1697 if (putback_char == -1)
1698 putback_char = reader.Read ();
1699 return putback_char;
1704 if (putback_char != -1)
1705 return putback_char;
1706 return reader.Peek ();
1709 void putback (int c)
1711 if (putback_char != -1){
1712 Console.WriteLine ("Col: " + col);
1713 Console.WriteLine ("Row: " + line);
1714 Console.WriteLine ("Name: " + ref_name.Name);
1715 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1716 throw new Exception ("This should not happen putback on putback");
1718 if (c == '\n' || col == 0) {
1719 // It won't happen though.
1729 public bool advance ()
1731 return peek_char () != -1 || CompleteOnEOF;
1734 public Object Value {
1740 public Object value ()
1747 current_token = xtoken ();
1748 return current_token;
1751 int TokenizePreprocessorIdentifier (out int c)
1753 // skip over white space
1756 } while (c == '\r' || c == ' ' || c == '\t');
1760 while (c != -1 && c >= 'a' && c <= 'z') {
1761 id_builder[pos++] = (char) c;
1764 int peek = peek_char ();
1765 if (peek == 'U' || peek == 'u') {
1767 c = EscapeUnicode (c, out surrogate);
1768 if (surrogate != 0) {
1769 if (is_identifier_part_character ((char) c)) {
1770 id_builder[pos++] = (char) c;
1781 PreprocessorDirective get_cmd_arg (out string arg)
1785 tokens_seen = false;
1788 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1790 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1793 // skip over white space
1794 while (c == '\r' || c == ' ' || c == '\t')
1797 static_cmd_arg.Length = 0;
1798 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1800 while (c != -1 && c != '\n' && c != '\r') {
1801 if (c == '\\' && has_identifier_argument >= 0) {
1802 if (has_identifier_argument != 0) {
1803 has_identifier_argument = 1;
1805 int peek = peek_char ();
1806 if (peek == 'U' || peek == 'u') {
1808 c = EscapeUnicode (c, out surrogate);
1809 if (surrogate != 0) {
1810 if (is_identifier_part_character ((char) c))
1811 static_cmd_arg.Append ((char) c);
1816 has_identifier_argument = -1;
1819 static_cmd_arg.Append ((char) c);
1823 if (static_cmd_arg.Length != 0) {
1824 arg = static_cmd_arg.ToString ();
1826 // Eat any trailing whitespaces and single-line comments
1827 if (arg.IndexOf ("//") != -1) {
1828 arg = arg.Substring (0, arg.IndexOf ("//"));
1831 arg = arg.Trim (simple_whitespaces);
1838 // Handles the #line directive
1840 bool PreProcessLine (string arg)
1842 if (arg.Length == 0)
1845 if (arg == "default"){
1847 ref_name = file_name;
1849 Location.Push (file_name, ref_name);
1851 } else if (arg == "hidden"){
1859 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1860 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1863 char [] quotes = { '\"' };
1865 string name = arg.Substring (pos). Trim (quotes);
1866 ref_name = Location.LookupFile (file_name, name);
1867 file_name.AddFile (ref_name);
1869 Location.Push (file_name, ref_name);
1871 ref_line = System.Int32.Parse (arg);
1882 // Handles #define and #undef
1884 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1886 if (ident.Length == 0 || ident == "true" || ident == "false"){
1887 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1891 if (ident.IndexOfAny (simple_whitespaces) != -1){
1892 Error_EndLineExpected ();
1896 if (!is_identifier_start_character (ident [0]))
1897 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1899 foreach (char c in ident.Substring (1)){
1900 if (!is_identifier_part_character (c)){
1901 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1906 if (!caller_is_taking)
1913 if (RootContext.IsConditionalDefined (ident))
1916 file_name.AddDefine (ident);
1921 file_name.AddUndefine (ident);
1925 byte read_hex (out bool error)
1928 int c = get_char ();
1930 if ((c >= '0') && (c <= '9'))
1931 total = (int) c - (int) '0';
1932 else if ((c >= 'A') && (c <= 'F'))
1933 total = (int) c - (int) 'A' + 10;
1934 else if ((c >= 'a') && (c <= 'f'))
1935 total = (int) c - (int) 'a' + 10;
1944 if ((c >= '0') && (c <= '9'))
1945 total += (int) c - (int) '0';
1946 else if ((c >= 'A') && (c <= 'F'))
1947 total += (int) c - (int) 'A' + 10;
1948 else if ((c >= 'a') && (c <= 'f'))
1949 total += (int) c - (int) 'a' + 10;
1956 return (byte) total;
1960 // Parses #pragma checksum
1962 bool ParsePragmaChecksum ()
1965 // The syntax is ` "foo.txt" "{guid}" "hash"'
1967 int c = get_char ();
1972 string_builder.Length = 0;
1973 while (c != -1 && c != '\n') {
1980 string_builder.Append ((char) c);
1983 if (string_builder.Length == 0) {
1984 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
1987 // TODO: Any white-spaces count
1991 SourceFile file = Location.LookupFile (file_name, string_builder.ToString ());
1993 if (get_char () != '"' || get_char () != '{')
1997 byte[] guid_bytes = new byte [16];
2000 for (; i < 4; i++) {
2001 guid_bytes [i] = read_hex (out error);
2006 if (get_char () != '-')
2009 for (; i < 10; i++) {
2010 guid_bytes [i] = read_hex (out error);
2014 guid_bytes [i++] = read_hex (out error);
2018 if (get_char () != '-')
2022 for (; i < 16; i++) {
2023 guid_bytes [i] = read_hex (out error);
2028 if (get_char () != '}' || get_char () != '"')
2031 // TODO: Any white-spaces count
2036 if (get_char () != '"')
2039 // Any length of checksum
2040 List<byte> checksum_bytes = new List<byte> (16);
2043 while (c != '"' && c != -1) {
2044 checksum_bytes.Add (read_hex (out error));
2052 ReadSingleLineComment ();
2053 } else if (get_char () != '"') {
2057 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2058 ref_name.AutoGenerated = true;
2062 bool IsTokenIdentifierEqual (char[] identifier)
2064 for (int i = 0; i < identifier.Length; ++i) {
2065 if (identifier[i] != id_builder[i])
2072 int TokenizePragmaNumber (ref int c)
2078 if (c >= '0' && c <= '9') {
2080 uint ui = (uint) (number_builder[0] - '0');
2083 for (int i = 1; i < number_pos; i++) {
2084 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2088 } catch (OverflowException) {
2089 Error_NumericConstantTooLong ();
2096 // skip over white space
2097 while (c == '\r' || c == ' ' || c == '\t')
2104 // skip over white space
2105 while (c == '\r' || c == ' ' || c == '\t')
2110 ReadSingleLineComment ();
2112 Report.Warning (1692, 1, Location, "Invalid number");
2114 // Read everything till the end of the line or file
2117 } while (c != -1 && c != '\n');
2124 void ReadSingleLineComment ()
2126 if (peek_char () != '/')
2127 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2129 // Read everything till the end of the line or file
2133 } while (c != -1 && c != '\n');
2137 /// Handles #pragma directive
2139 void ParsePragmaDirective (string arg)
2142 int length = TokenizePreprocessorIdentifier (out c);
2143 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2144 length = TokenizePreprocessorIdentifier (out c);
2147 // #pragma warning disable
2148 // #pragma warning restore
2150 if (length == pragma_warning_disable.Length) {
2151 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2152 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2153 // skip over white space
2154 while (c == '\r' || c == ' ' || c == '\t')
2159 if (c == '\n' || c == '/') {
2161 ReadSingleLineComment ();
2164 // Disable/Restore all warnings
2167 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2169 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2173 // Disable/Restore a warning or group of warnings
2177 code = TokenizePragmaNumber (ref c);
2180 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2182 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2185 } while (code >= 0 && c != '\n' && c != -1);
2192 Report.Warning (1634, 1, Location, "Expected disable or restore");
2199 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2200 if (c != ' ' || !ParsePragmaChecksum ()) {
2201 Report.Warning (1695, 1, Location,
2202 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2208 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2211 bool eval_val (string s)
2218 return file_name.IsConditionalDefined (s);
2221 bool pp_primary (ref string s)
2230 s = s.Substring (1);
2231 bool val = pp_expr (ref s, false);
2232 if (s.Length > 0 && s [0] == ')'){
2233 s = s.Substring (1);
2236 Error_InvalidDirective ();
2240 if (is_identifier_start_character (c)){
2246 if (is_identifier_part_character (c)){
2250 bool v = eval_val (s.Substring (0, j));
2251 s = s.Substring (j);
2254 bool vv = eval_val (s);
2259 Error_InvalidDirective ();
2263 bool pp_unary (ref string s)
2270 if (len > 1 && s [1] == '='){
2271 Error_InvalidDirective ();
2274 s = s.Substring (1);
2275 return ! pp_primary (ref s);
2277 return pp_primary (ref s);
2279 Error_InvalidDirective ();
2284 bool pp_eq (ref string s)
2286 bool va = pp_unary (ref s);
2292 if (len > 2 && s [1] == '='){
2293 s = s.Substring (2);
2294 return va == pp_unary (ref s);
2296 Error_InvalidDirective ();
2299 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2300 s = s.Substring (2);
2302 return va != pp_unary (ref s);
2311 bool pp_and (ref string s)
2313 bool va = pp_eq (ref s);
2319 if (len > 2 && s [1] == '&'){
2320 s = s.Substring (2);
2321 return (va & pp_and (ref s));
2323 Error_InvalidDirective ();
2332 // Evaluates an expression for `#if' or `#elif'
2334 bool pp_expr (ref string s, bool isTerm)
2336 bool va = pp_and (ref s);
2343 if (len > 2 && s [1] == '|'){
2344 s = s.Substring (2);
2345 return va | pp_expr (ref s, isTerm);
2347 Error_InvalidDirective ();
2352 Error_EndLineExpected ();
2360 bool eval (string s)
2362 bool v = pp_expr (ref s, true);
2371 void Error_NumericConstantTooLong ()
2373 Report.Error (1021, Location, "Integral constant is too large");
2376 void Error_InvalidDirective ()
2378 Report.Error (1517, Location, "Invalid preprocessor directive");
2381 void Error_UnexpectedDirective (string extra)
2385 "Unexpected processor directive ({0})", extra);
2388 void Error_TokensSeen ()
2390 Report.Error (1032, Location,
2391 "Cannot define or undefine preprocessor symbols after first token in file");
2394 void Eror_WrongPreprocessorLocation ()
2396 Report.Error (1040, Location,
2397 "Preprocessor directives must appear as the first non-whitespace character on a line");
2400 void Error_EndLineExpected ()
2402 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2406 // if true, then the code continues processing the code
2407 // if false, the code stays in a loop until another directive is
2409 // When caller_is_taking is false we ignore all directives except the ones
2410 // which can help us to identify where the #if block ends
2411 bool ParsePreprocessingDirective (bool caller_is_taking)
2414 bool region_directive = false;
2416 var directive = get_cmd_arg (out arg);
2419 // The first group of pre-processing instructions is always processed
2421 switch (directive) {
2422 case PreprocessorDirective.Region:
2423 region_directive = true;
2425 goto case PreprocessorDirective.If;
2427 case PreprocessorDirective.Endregion:
2428 if (ifstack == null || ifstack.Count == 0){
2429 Error_UnexpectedDirective ("no #region for this #endregion");
2432 int pop = ifstack.Pop ();
2434 if ((pop & REGION) == 0)
2435 Report.Error (1027, Location, "Expected `#endif' directive");
2437 return caller_is_taking;
2439 case PreprocessorDirective.If:
2440 if (ifstack == null)
2441 ifstack = new Stack<int> (2);
2443 int flags = region_directive ? REGION : 0;
2444 if (ifstack.Count == 0){
2445 flags |= PARENT_TAKING;
2447 int state = ifstack.Peek ();
2448 if ((state & TAKING) != 0) {
2449 flags |= PARENT_TAKING;
2453 if (caller_is_taking && eval (arg)) {
2454 ifstack.Push (flags | TAKING);
2457 ifstack.Push (flags);
2460 case PreprocessorDirective.Endif:
2461 if (ifstack == null || ifstack.Count == 0){
2462 Error_UnexpectedDirective ("no #if for this #endif");
2465 pop = ifstack.Pop ();
2467 if ((pop & REGION) != 0)
2468 Report.Error (1038, Location, "#endregion directive expected");
2470 if (arg.Length != 0) {
2471 Error_EndLineExpected ();
2474 if (ifstack.Count == 0)
2477 int state = ifstack.Peek ();
2478 return (state & TAKING) != 0;
2481 case PreprocessorDirective.Elif:
2482 if (ifstack == null || ifstack.Count == 0){
2483 Error_UnexpectedDirective ("no #if for this #elif");
2486 int state = ifstack.Pop ();
2488 if ((state & REGION) != 0) {
2489 Report.Error (1038, Location, "#endregion directive expected");
2493 if ((state & ELSE_SEEN) != 0){
2494 Error_UnexpectedDirective ("#elif not valid after #else");
2498 if ((state & TAKING) != 0) {
2503 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2504 ifstack.Push (state | TAKING);
2508 ifstack.Push (state);
2512 case PreprocessorDirective.Else:
2513 if (ifstack == null || ifstack.Count == 0){
2514 Error_UnexpectedDirective ("no #if for this #else");
2517 int state = ifstack.Peek ();
2519 if ((state & REGION) != 0) {
2520 Report.Error (1038, Location, "#endregion directive expected");
2524 if ((state & ELSE_SEEN) != 0){
2525 Error_UnexpectedDirective ("#else within #else");
2531 if (arg.Length != 0) {
2532 Error_EndLineExpected ();
2537 if ((state & PARENT_TAKING) != 0) {
2538 ret = (state & TAKING) == 0;
2546 ifstack.Push (state | ELSE_SEEN);
2550 case PreprocessorDirective.Define:
2551 if (any_token_seen){
2552 Error_TokensSeen ();
2553 return caller_is_taking;
2555 PreProcessDefinition (true, arg, caller_is_taking);
2556 return caller_is_taking;
2558 case PreprocessorDirective.Undef:
2559 if (any_token_seen){
2560 Error_TokensSeen ();
2561 return caller_is_taking;
2563 PreProcessDefinition (false, arg, caller_is_taking);
2564 return caller_is_taking;
2566 case PreprocessorDirective.Invalid:
2567 Report.Error (1024, Location, "Wrong preprocessor directive");
2572 // These are only processed if we are in a `taking' block
2574 if (!caller_is_taking)
2578 case PreprocessorDirective.Error:
2579 Report.Error (1029, Location, "#error: '{0}'", arg);
2582 case PreprocessorDirective.Warning:
2583 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2586 case PreprocessorDirective.Pragma:
2587 if (RootContext.Version == LanguageVersion.ISO_1) {
2588 Report.FeatureIsNotAvailable (Location, "#pragma");
2591 ParsePragmaDirective (arg);
2594 case PreprocessorDirective.Line:
2595 if (!PreProcessLine (arg))
2598 "The line number specified for #line directive is missing or invalid");
2599 return caller_is_taking;
2602 throw new NotImplementedException (directive.ToString ());
2605 private int consume_string (bool quoted)
2608 string_builder.Length = 0;
2613 if (quoted && peek_char () == '"') {
2614 string_builder.Append ((char) c);
2619 val = new StringLiteral (string_builder.ToString (), Location);
2620 return Token.LITERAL;
2625 Report.Error (1010, Location, "Newline in constant");
2626 } else if (c == '\\' && !quoted) {
2628 c = escape (c, out surrogate);
2631 if (surrogate != 0) {
2632 string_builder.Append ((char) c);
2635 } else if (c == -1) {
2636 Report.Error (1039, Location, "Unterminated string literal");
2640 string_builder.Append ((char) c);
2644 private int consume_identifier (int s)
2646 int res = consume_identifier (s, false);
2648 if (doc_state == XmlCommentState.Allowed)
2649 doc_state = XmlCommentState.NotAllowed;
2654 int consume_identifier (int c, bool quoted)
2657 // This method is very performance sensitive. It accounts
2658 // for approximately 25% of all parser time
2666 c = escape (c, out surrogate);
2667 if (surrogate != 0) {
2668 id_builder [pos++] = (char) c;
2673 id_builder [pos++] = (char) c;
2679 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2680 id_builder [pos++] = (char) c;
2687 c = escape (c, out surrogate);
2688 if (surrogate != 0) {
2689 if (is_identifier_part_character ((char) c))
2690 id_builder[pos++] = (char) c;
2696 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2697 id_builder [pos++] = (char) c;
2704 } catch (IndexOutOfRangeException) {
2705 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2713 // Optimization: avoids doing the keyword lookup
2714 // on uppercase letters
2716 if (id_builder [0] >= '_' && !quoted) {
2717 int keyword = GetKeyword (id_builder, pos);
2718 if (keyword != -1) {
2719 val = LocatedToken.Create (null, ref_line, column);
2725 // Keep identifiers in an array of hashtables to avoid needless
2728 var identifiers_group = identifiers [pos];
2730 if (identifiers_group != null) {
2731 if (identifiers_group.TryGetValue (id_builder, out s)) {
2732 val = LocatedToken.Create (s, ref_line, column);
2734 AddEscapedIdentifier (((LocatedToken) val).Location);
2735 return Token.IDENTIFIER;
2738 // TODO: this should be number of files dependant
2739 // corlib compilation peaks at 1000 and System.Core at 150
2740 int capacity = pos > 20 ? 10 : 100;
2741 identifiers_group = new Dictionary<char[],string> (capacity, new IdentifiersComparer (pos));
2742 identifiers [pos] = identifiers_group;
2745 char [] chars = new char [pos];
2746 Array.Copy (id_builder, chars, pos);
2748 s = new string (id_builder, 0, pos);
2749 identifiers_group.Add (chars, s);
2751 val = LocatedToken.Create (s, ref_line, column);
2753 AddEscapedIdentifier (((LocatedToken) val).Location);
2755 return Token.IDENTIFIER;
2758 public int xtoken ()
2762 // Whether we have seen comments on the current line
2763 bool comments_seen = false;
2764 while ((c = get_char ()) != -1) {
2767 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2775 case 0xFEFF: // Ignore BOM anywhere in the file
2778 /* This is required for compatibility with .NET
2780 if (peek_char () == 0xBB) {
2783 if (get_char () == 0xBF)
2790 if (peek_char () != '\n')
2795 any_token_seen |= tokens_seen;
2796 tokens_seen = false;
2797 comments_seen = false;
2802 return consume_identifier (c);
2805 val = LocatedToken.Create (ref_line, col);
2806 return Token.OPEN_BRACE;
2808 val = LocatedToken.Create (ref_line, col);
2809 return Token.CLOSE_BRACE;
2811 // To block doccomment inside attribute declaration.
2812 if (doc_state == XmlCommentState.Allowed)
2813 doc_state = XmlCommentState.NotAllowed;
2815 val = LocatedToken.Create (ref_line, col);
2817 if (parsing_block == 0 || lambda_arguments_parsing)
2818 return Token.OPEN_BRACKET;
2820 int next = peek_char ();
2824 return Token.OPEN_BRACKET;
2832 next = peek_token ();
2833 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2834 return Token.OPEN_BRACKET;
2836 return Token.OPEN_BRACKET_EXPR;
2838 return Token.OPEN_BRACKET_EXPR;
2841 LocatedToken.CreateOptional (ref_line, col, ref val);
2842 return Token.CLOSE_BRACKET;
2844 val = LocatedToken.Create (ref_line, col);
2846 // An expression versions of parens can appear in block context only
2848 if (parsing_block != 0 && !lambda_arguments_parsing) {
2851 // Optmize most common case where we know that parens
2854 switch (current_token) {
2855 case Token.IDENTIFIER:
2863 case Token.DELEGATE:
2864 case Token.OP_GENERICS_GT:
2865 return Token.OPEN_PARENS;
2868 // Optimize using peek
2869 int xx = peek_char ();
2876 return Token.OPEN_PARENS;
2879 lambda_arguments_parsing = true;
2881 d = TokenizeOpenParens ();
2883 lambda_arguments_parsing = false;
2887 return Token.OPEN_PARENS;
2889 LocatedToken.CreateOptional (ref_line, col, ref val);
2890 return Token.CLOSE_PARENS;
2892 LocatedToken.CreateOptional (ref_line, col, ref val);
2895 LocatedToken.CreateOptional (ref_line, col, ref val);
2896 return Token.SEMICOLON;
2898 val = LocatedToken.Create (ref_line, col);
2901 val = LocatedToken.Create (ref_line, col);
2902 return TokenizePossibleNullableType ();
2904 val = LocatedToken.Create (ref_line, col);
2905 if (parsing_generic_less_than++ > 0)
2906 return Token.OP_GENERICS_LT;
2908 return TokenizeLessThan ();
2911 val = LocatedToken.Create (ref_line, col);
2919 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2920 parsing_generic_less_than--;
2921 return Token.OP_GENERICS_GT;
2930 return Token.OP_SHIFT_RIGHT_ASSIGN;
2932 return Token.OP_SHIFT_RIGHT;
2938 val = LocatedToken.Create (ref_line, col);
2942 } else if (d == '=') {
2943 d = Token.OP_ADD_ASSIGN;
2951 val = LocatedToken.Create (ref_line, col);
2955 } else if (d == '=')
2956 d = Token.OP_SUB_ASSIGN;
2966 val = LocatedToken.Create (ref_line, col);
2967 if (peek_char () == '='){
2974 val = LocatedToken.Create (ref_line, col);
2985 return Token.ASSIGN;
2988 val = LocatedToken.Create (ref_line, col);
2992 return Token.OP_AND;
2996 return Token.OP_AND_ASSIGN;
2998 return Token.BITWISE_AND;
3001 val = LocatedToken.Create (ref_line, col);
3009 return Token.OP_OR_ASSIGN;
3011 return Token.BITWISE_OR;
3014 val = LocatedToken.Create (ref_line, col);
3015 if (peek_char () == '='){
3017 return Token.OP_MULT_ASSIGN;
3024 val = LocatedToken.Create (ref_line, col);
3026 return Token.OP_DIV_ASSIGN;
3029 // Handle double-slash comments.
3032 if (RootContext.Documentation != null && peek_char () == '/') {
3034 // Don't allow ////.
3035 if ((d = peek_char ()) != '/') {
3036 update_comment_location ();
3037 if (doc_state == XmlCommentState.Allowed)
3038 handle_one_line_xml_comment ();
3039 else if (doc_state == XmlCommentState.NotAllowed)
3040 warn_incorrect_doc_comment ();
3043 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
3045 any_token_seen |= tokens_seen;
3046 tokens_seen = false;
3047 comments_seen = false;
3049 } else if (d == '*'){
3051 bool docAppend = false;
3052 if (RootContext.Documentation != null && peek_char () == '*') {
3054 update_comment_location ();
3055 // But when it is /**/, just do nothing.
3056 if (peek_char () == '/') {
3060 if (doc_state == XmlCommentState.Allowed)
3062 else if (doc_state == XmlCommentState.NotAllowed)
3063 warn_incorrect_doc_comment ();
3066 int current_comment_start = 0;
3068 current_comment_start = xml_comment_buffer.Length;
3069 xml_comment_buffer.Append (Environment.NewLine);
3072 while ((d = get_char ()) != -1){
3073 if (d == '*' && peek_char () == '/'){
3075 comments_seen = true;
3079 xml_comment_buffer.Append ((char) d);
3082 any_token_seen |= tokens_seen;
3083 tokens_seen = false;
3085 // Reset 'comments_seen' just to be consistent.
3086 // It doesn't matter either way, here.
3088 comments_seen = false;
3092 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3095 update_formatted_doc_comment (current_comment_start);
3098 val = LocatedToken.Create (ref_line, col);
3102 val = LocatedToken.Create (ref_line, col);
3103 if (peek_char () == '='){
3105 return Token.OP_MOD_ASSIGN;
3107 return Token.PERCENT;
3110 val = LocatedToken.Create (ref_line, col);
3111 if (peek_char () == '='){
3113 return Token.OP_XOR_ASSIGN;
3115 return Token.CARRET;
3118 val = LocatedToken.Create (ref_line, col);
3119 if (peek_char () == ':') {
3121 return Token.DOUBLE_COLON;
3125 case '0': case '1': case '2': case '3': case '4':
3126 case '5': case '6': case '7': case '8': case '9':
3128 return is_number (c);
3130 case '\n': // white space
3131 any_token_seen |= tokens_seen;
3132 tokens_seen = false;
3133 comments_seen = false;
3139 if (d >= '0' && d <= '9')
3140 return is_number (c);
3142 LocatedToken.CreateOptional (ref_line, col, ref val);
3146 if (tokens_seen || comments_seen) {
3147 Eror_WrongPreprocessorLocation ();
3151 if (ParsePreprocessingDirective (true))
3154 bool directive_expected = false;
3155 while ((c = get_char ()) != -1) {
3157 directive_expected = true;
3158 } else if (!directive_expected) {
3159 // TODO: Implement comment support for disabled code and uncomment this code
3161 // Eror_WrongPreprocessorLocation ();
3162 // return Token.ERROR;
3167 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
3171 if (ParsePreprocessingDirective (false))
3174 directive_expected = false;
3178 tokens_seen = false;
3185 return consume_string (false);
3188 return TokenizeBackslash ();
3194 return consume_string (true);
3197 if (is_identifier_start_character (c)){
3198 return consume_identifier (c, true);
3201 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3204 case EvalStatementParserCharacter:
3205 return Token.EVAL_STATEMENT_PARSER;
3206 case EvalCompilationUnitParserCharacter:
3207 return Token.EVAL_COMPILATION_UNIT_PARSER;
3208 case EvalUsingDeclarationsParserCharacter:
3209 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3212 if (is_identifier_start_character (c)) {
3214 return consume_identifier (c);
3217 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3222 return Token.COMPLETE_COMPLETION;
3225 return Token.GENERATE_COMPLETION;
3232 int TokenizeBackslash ()
3234 int c = get_char ();
3237 val = new CharLiteral ((char) c, Location);
3238 Report.Error (1011, Location, "Empty character literal");
3239 return Token.LITERAL;
3242 if (c == '\r' || c == '\n') {
3243 Report.Error (1010, Location, "Newline in constant");
3248 c = escape (c, out d);
3252 throw new NotImplementedException ();
3254 val = new CharLiteral ((char) c, Location);
3258 Report.Error (1012, Location, "Too many characters in character literal");
3260 // Try to recover, read until newline or next "'"
3261 while ((c = get_char ()) != -1) {
3262 if (c == '\n' || c == '\'')
3267 return Token.LITERAL;
3270 int TokenizeLessThan ()
3273 if (handle_typeof) {
3275 if (parse_generic_dimension (out d)) {
3278 return Token.GENERIC_DIMENSION;
3283 // Save current position and parse next token.
3285 if (parse_less_than ()) {
3286 if (parsing_generic_declaration && token () != Token.DOT) {
3287 d = Token.OP_GENERICS_LT_DECL;
3289 d = Token.OP_GENERICS_LT;
3296 parsing_generic_less_than = 0;
3305 return Token.OP_SHIFT_LEFT_ASSIGN;
3307 return Token.OP_SHIFT_LEFT;
3318 // Handles one line xml comment
3320 private void handle_one_line_xml_comment ()
3323 while ((c = peek_char ()) == ' ')
3324 get_char (); // skip heading whitespaces.
3325 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3326 xml_comment_buffer.Append ((char) get_char ());
3328 if (c == '\r' || c == '\n')
3329 xml_comment_buffer.Append (Environment.NewLine);
3333 // Remove heading "*" in Javadoc-like xml documentation.
3335 private void update_formatted_doc_comment (int current_comment_start)
3337 int length = xml_comment_buffer.Length - current_comment_start;
3338 string [] lines = xml_comment_buffer.ToString (
3339 current_comment_start,
3340 length).Replace ("\r", "").Split ('\n');
3342 // The first line starts with /**, thus it is not target
3343 // for the format check.
3344 for (int i = 1; i < lines.Length; i++) {
3345 string s = lines [i];
3346 int idx = s.IndexOf ('*');
3349 if (i < lines.Length - 1)
3353 head = s.Substring (0, idx);
3354 foreach (char c in head)
3357 lines [i] = s.Substring (idx + 1);
3359 xml_comment_buffer.Remove (current_comment_start, length);
3360 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3364 // Updates current comment location.
3366 private void update_comment_location ()
3368 if (current_comment_location.IsNull) {
3369 // "-2" is for heading "//" or "/*"
3370 current_comment_location =
3371 new Location (ref_line, hidden ? -1 : col - 2);
3376 // Checks if there was incorrect doc comments and raise
3379 public void check_incorrect_doc_comment ()
3381 if (xml_comment_buffer.Length > 0)
3382 warn_incorrect_doc_comment ();
3386 // Raises a warning when tokenizer found incorrect doccomment
3389 private void warn_incorrect_doc_comment ()
3391 if (doc_state != XmlCommentState.Error) {
3392 doc_state = XmlCommentState.Error;
3393 // in csc, it is 'XML comment is not placed on
3394 // a valid language element'. But that does not
3396 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3401 // Consumes the saved xml comment lines (if any)
3402 // as for current target member or type.
3404 public string consume_doc_comment ()
3406 if (xml_comment_buffer.Length > 0) {
3407 string ret = xml_comment_buffer.ToString ();
3408 reset_doc_comment ();
3415 get { return context.Report; }
3418 void reset_doc_comment ()
3420 xml_comment_buffer.Length = 0;
3421 current_comment_location = Location.Null;
3424 public void cleanup ()
3426 if (ifstack != null && ifstack.Count >= 1) {
3427 int state = ifstack.Pop ();
3428 if ((state & REGION) != 0)
3429 Report.Error (1038, Location, "#endregion directive expected");
3431 Report.Error (1027, Location, "Expected `#endif' directive");
3437 // Indicates whether it accepts XML documentation or not.
3439 public enum XmlCommentState {
3440 // comment is allowed in this state.
3442 // comment is not allowed in this state.
3444 // once comments appeared when it is NotAllowed, then the
3445 // state is changed to it, until the state is changed to