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@gmail.com)
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
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
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 = new LocatedToken[0];
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, Location loc)
93 return Create (value, loc.Row, loc.Column);
96 public static LocatedToken Create (string value, int row, int column)
99 // TODO: I am not very happy about the logic but it's the best
100 // what I could come up with for now.
101 // Ideally we should be using just tiny buffer (256 elements) which
102 // is enough to hold all details for currect stack and recycle elements
103 // poped from the stack but there is a trick needed to recycle
107 if (pos >= buffer.Length) {
108 entry = new LocatedToken ();
110 entry = buffer [pos];
112 entry = new LocatedToken ();
113 buffer [pos] = entry;
120 entry.column = column;
125 // Used for token not required by expression evaluator
127 [Conditional ("FULL_AST")]
128 public static void CreateOptional (int row, int col, ref object token)
130 token = Create (row, col);
133 public static void Initialize ()
136 if (buffer.Length == 0)
137 buffer = new LocatedToken [15000];
142 public Location Location {
143 get { return new Location (row, column); }
146 public string Value {
147 get { return value; }
151 public enum PreprocessorDirective
157 If = 3 | RequiresArgument,
159 Elif = 5 | RequiresArgument,
161 Define = 7 | RequiresArgument,
162 Undef = 8 | RequiresArgument,
165 Pragma = 11 | CustomArgumentsParsing,
166 Line = 12 | CustomArgumentsParsing,
168 CustomArgumentsParsing = 1 << 10,
169 RequiresArgument = 1 << 11
172 readonly SeekableStreamReader reader;
173 readonly CompilationSourceFile source_file;
174 readonly CompilerContext context;
176 SourceFile current_source;
177 Location hidden_block_start;
183 readonly int tab_size;
184 bool handle_get_set = false;
185 bool handle_remove_add = false;
186 bool handle_where = false;
187 bool handle_typeof = false;
188 bool lambda_arguments_parsing;
189 List<Location> escaped_identifiers;
190 int parsing_generic_less_than;
191 readonly bool doc_processing;
194 // Used mainly for parser optimizations. Some expressions for instance
195 // can appear only in block (including initializer, base initializer)
198 public int parsing_block;
199 internal bool query_parsing;
202 // When parsing type only, useful for ambiguous nullable types
204 public int parsing_type;
207 // Set when parsing generic declaration (type or method header)
209 public bool parsing_generic_declaration;
210 public bool parsing_generic_declaration_doc;
213 // The value indicates that we have not reach any declaration or
216 public int parsing_declaration;
218 public bool parsing_attribute_section;
220 public bool parsing_modifiers;
223 // The special characters to inject on streams to run the unit parser
224 // in the special expression mode. Using private characters from
225 // Plane Sixteen (U+100000 to U+10FFFD)
227 // This character is only tested just before the tokenizer is about to report
228 // an error; So on the regular operation mode, this addition will have no
229 // impact on the tokenizer's performance.
232 public const int EvalStatementParserCharacter = 0x100000;
233 public const int EvalCompilationUnitParserCharacter = 0x100001;
234 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
235 public const int DocumentationXref = 0x100003;
238 // XML documentation buffer. The save point is used to divide
239 // comments on types and comments on members.
241 StringBuilder xml_comment_buffer;
244 // See comment on XmlCommentState enumeration.
246 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
249 // Whether tokens have been seen on this line
251 bool tokens_seen = false;
254 // Set to true once the GENERATE_COMPLETION token has bee
255 // returned. This helps produce one GENERATE_COMPLETION,
256 // as many COMPLETE_COMPLETION as necessary to complete the
257 // AST tree and one final EOF.
262 // Whether a token has been seen on the file
263 // This is needed because `define' is not allowed to be used
264 // after a token has been seen.
271 static readonly KeywordEntry<int>[][] keywords;
272 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
273 static readonly HashSet<string> keyword_strings;
274 static readonly NumberStyles styles;
275 static readonly NumberFormatInfo csharp_format_info;
278 static readonly char[] pragma_warning = "warning".ToCharArray ();
279 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
280 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
281 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
282 static readonly char[] line_hidden = "hidden".ToCharArray ();
283 static readonly char[] line_default = "default".ToCharArray ();
285 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
287 public bool PropertyParsing {
288 get { return handle_get_set; }
289 set { handle_get_set = value; }
292 public bool EventParsing {
293 get { return handle_remove_add; }
294 set { handle_remove_add = value; }
297 public bool ConstraintsParsing {
298 get { return handle_where; }
299 set { handle_where = value; }
302 public bool TypeOfParsing {
303 get { return handle_typeof; }
304 set { handle_typeof = value; }
307 public XmlCommentState doc_state {
308 get { return xml_doc_state; }
310 if (value == XmlCommentState.Allowed) {
311 check_incorrect_doc_comment ();
312 reset_doc_comment ();
314 xml_doc_state = value;
319 // This is used to trigger completion generation on the parser
320 public bool CompleteOnEOF;
322 void AddEscapedIdentifier (Location loc)
324 if (escaped_identifiers == null)
325 escaped_identifiers = new List<Location> ();
327 escaped_identifiers.Add (loc);
330 public bool IsEscapedIdentifier (ATypeNameExpression name)
332 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
336 // Values for the associated token returned
338 internal int putback_char; // Used by repl only
344 const int TAKING = 1;
345 const int ELSE_SEEN = 4;
346 const int PARENT_TAKING = 8;
347 const int REGION = 16;
350 // pre-processor if stack state:
354 const int max_id_size = 512;
355 const int max_number_size = 512;
358 readonly char [] id_builder = new char [max_id_size];
360 Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
362 char [] number_builder = new char [max_number_size];
365 char[] value_builder = new char[256];
367 static readonly char [] id_builder = new char [max_id_size];
369 static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
371 static char [] number_builder = new char [max_number_size];
372 static int number_pos;
374 static char[] value_builder = new char[256];
384 // This is used when the tokenizer needs to save
385 // the current position as it needs to do some parsing
386 // on its own to deamiguate a token in behalf of the
389 Stack<Position> position_stack = new Stack<Position> (2);
396 public Location hidden;
397 public int putback_char;
398 public int previous_col;
399 public Stack<int> ifstack;
400 public int parsing_generic_less_than;
401 public int current_token;
404 public Position (Tokenizer t)
406 position = t.reader.Position;
408 ref_line = t.ref_line;
410 hidden = t.hidden_block_start;
411 putback_char = t.putback_char;
412 previous_col = t.previous_col;
413 if (t.ifstack != null && t.ifstack.Count != 0) {
414 // There is no simple way to clone Stack<T> all
415 // methods reverse the order
416 var clone = t.ifstack.ToArray ();
417 Array.Reverse (clone);
418 ifstack = new Stack<int> (clone);
420 parsing_generic_less_than = t.parsing_generic_less_than;
421 current_token = t.current_token;
426 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file)
428 this.source_file = file;
429 this.context = file.Compiler;
430 this.current_source = file.SourceFile;
436 xml_comment_buffer = new StringBuilder ();
437 doc_processing = context.Settings.DocumentationFile != null;
439 tab_size = context.Settings.TabSize;
441 Mono.CSharp.Location.Push (current_source);
444 public void PushPosition ()
446 position_stack.Push (new Position (this));
449 public void PopPosition ()
451 Position p = position_stack.Pop ();
453 reader.Position = p.position;
454 ref_line = p.ref_line;
457 hidden_block_start = p.hidden;
458 putback_char = p.putback_char;
459 previous_col = p.previous_col;
461 parsing_generic_less_than = p.parsing_generic_less_than;
462 current_token = p.current_token;
466 // Do not reset the position, ignore it.
467 public void DiscardPosition ()
469 position_stack.Pop ();
472 static void AddKeyword (string kw, int token)
474 keyword_strings.Add (kw);
476 AddKeyword (keywords, kw, token);
479 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
481 AddKeyword (keywords_preprocessor, kw, directive);
484 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
486 int length = kw.Length;
487 if (keywords[length] == null) {
488 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
491 int char_index = kw[0] - '_';
492 var kwe = keywords[length][char_index];
494 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
498 while (kwe.Next != null) {
502 kwe.Next = new KeywordEntry<T> (kw, token);
510 keyword_strings = new HashSet<string> ();
512 // 11 is the length of the longest keyword for now
513 keywords = new KeywordEntry<int>[11][];
515 AddKeyword ("__arglist", Token.ARGLIST);
516 AddKeyword ("__makeref", Token.MAKEREF);
517 AddKeyword ("__reftype", Token.REFTYPE);
518 AddKeyword ("__refvalue", Token.REFVALUE);
519 AddKeyword ("abstract", Token.ABSTRACT);
520 AddKeyword ("as", Token.AS);
521 AddKeyword ("add", Token.ADD);
522 AddKeyword ("base", Token.BASE);
523 AddKeyword ("bool", Token.BOOL);
524 AddKeyword ("break", Token.BREAK);
525 AddKeyword ("byte", Token.BYTE);
526 AddKeyword ("case", Token.CASE);
527 AddKeyword ("catch", Token.CATCH);
528 AddKeyword ("char", Token.CHAR);
529 AddKeyword ("checked", Token.CHECKED);
530 AddKeyword ("class", Token.CLASS);
531 AddKeyword ("const", Token.CONST);
532 AddKeyword ("continue", Token.CONTINUE);
533 AddKeyword ("decimal", Token.DECIMAL);
534 AddKeyword ("default", Token.DEFAULT);
535 AddKeyword ("delegate", Token.DELEGATE);
536 AddKeyword ("do", Token.DO);
537 AddKeyword ("double", Token.DOUBLE);
538 AddKeyword ("else", Token.ELSE);
539 AddKeyword ("enum", Token.ENUM);
540 AddKeyword ("event", Token.EVENT);
541 AddKeyword ("explicit", Token.EXPLICIT);
542 AddKeyword ("extern", Token.EXTERN);
543 AddKeyword ("false", Token.FALSE);
544 AddKeyword ("finally", Token.FINALLY);
545 AddKeyword ("fixed", Token.FIXED);
546 AddKeyword ("float", Token.FLOAT);
547 AddKeyword ("for", Token.FOR);
548 AddKeyword ("foreach", Token.FOREACH);
549 AddKeyword ("goto", Token.GOTO);
550 AddKeyword ("get", Token.GET);
551 AddKeyword ("if", Token.IF);
552 AddKeyword ("implicit", Token.IMPLICIT);
553 AddKeyword ("in", Token.IN);
554 AddKeyword ("int", Token.INT);
555 AddKeyword ("interface", Token.INTERFACE);
556 AddKeyword ("internal", Token.INTERNAL);
557 AddKeyword ("is", Token.IS);
558 AddKeyword ("lock", Token.LOCK);
559 AddKeyword ("long", Token.LONG);
560 AddKeyword ("namespace", Token.NAMESPACE);
561 AddKeyword ("new", Token.NEW);
562 AddKeyword ("null", Token.NULL);
563 AddKeyword ("object", Token.OBJECT);
564 AddKeyword ("operator", Token.OPERATOR);
565 AddKeyword ("out", Token.OUT);
566 AddKeyword ("override", Token.OVERRIDE);
567 AddKeyword ("params", Token.PARAMS);
568 AddKeyword ("private", Token.PRIVATE);
569 AddKeyword ("protected", Token.PROTECTED);
570 AddKeyword ("public", Token.PUBLIC);
571 AddKeyword ("readonly", Token.READONLY);
572 AddKeyword ("ref", Token.REF);
573 AddKeyword ("remove", Token.REMOVE);
574 AddKeyword ("return", Token.RETURN);
575 AddKeyword ("sbyte", Token.SBYTE);
576 AddKeyword ("sealed", Token.SEALED);
577 AddKeyword ("set", Token.SET);
578 AddKeyword ("short", Token.SHORT);
579 AddKeyword ("sizeof", Token.SIZEOF);
580 AddKeyword ("stackalloc", Token.STACKALLOC);
581 AddKeyword ("static", Token.STATIC);
582 AddKeyword ("string", Token.STRING);
583 AddKeyword ("struct", Token.STRUCT);
584 AddKeyword ("switch", Token.SWITCH);
585 AddKeyword ("this", Token.THIS);
586 AddKeyword ("throw", Token.THROW);
587 AddKeyword ("true", Token.TRUE);
588 AddKeyword ("try", Token.TRY);
589 AddKeyword ("typeof", Token.TYPEOF);
590 AddKeyword ("uint", Token.UINT);
591 AddKeyword ("ulong", Token.ULONG);
592 AddKeyword ("unchecked", Token.UNCHECKED);
593 AddKeyword ("unsafe", Token.UNSAFE);
594 AddKeyword ("ushort", Token.USHORT);
595 AddKeyword ("using", Token.USING);
596 AddKeyword ("virtual", Token.VIRTUAL);
597 AddKeyword ("void", Token.VOID);
598 AddKeyword ("volatile", Token.VOLATILE);
599 AddKeyword ("while", Token.WHILE);
600 AddKeyword ("partial", Token.PARTIAL);
601 AddKeyword ("where", Token.WHERE);
604 AddKeyword ("from", Token.FROM);
605 AddKeyword ("join", Token.JOIN);
606 AddKeyword ("on", Token.ON);
607 AddKeyword ("equals", Token.EQUALS);
608 AddKeyword ("select", Token.SELECT);
609 AddKeyword ("group", Token.GROUP);
610 AddKeyword ("by", Token.BY);
611 AddKeyword ("let", Token.LET);
612 AddKeyword ("orderby", Token.ORDERBY);
613 AddKeyword ("ascending", Token.ASCENDING);
614 AddKeyword ("descending", Token.DESCENDING);
615 AddKeyword ("into", Token.INTO);
617 // Contextual async keywords
618 AddKeyword ("async", Token.ASYNC);
619 AddKeyword ("await", Token.AWAIT);
621 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
623 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
624 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
625 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
626 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
627 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
628 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
629 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
630 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
631 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
632 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
633 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
634 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
636 csharp_format_info = NumberFormatInfo.InvariantInfo;
637 styles = NumberStyles.Float;
640 int GetKeyword (char[] id, int id_len)
643 // Keywords are stored in an array of arrays grouped by their
644 // length and then by the first character
646 if (id_len >= keywords.Length || keywords [id_len] == null)
649 int first_index = id [0] - '_';
650 if (first_index > 'z' - '_')
653 var kwe = keywords [id_len] [first_index];
660 for (int i = 1; i < id_len; ++i) {
661 if (id [i] != kwe.Value [i]) {
667 } while (res == 0 && kwe != null);
681 if (!handle_remove_add)
685 if (parsing_declaration == 0)
686 res = Token.EXTERN_ALIAS;
689 if (peek_token () == Token.COLON) {
691 res = Token.DEFAULT_COLON;
695 if (!handle_where && !query_parsing)
700 // A query expression is any expression that starts with `from identifier'
701 // followed by any token except ; , =
703 if (!query_parsing) {
704 if (lambda_arguments_parsing) {
710 // HACK: to disable generics micro-parser, because PushPosition does not
711 // store identifiers array
712 parsing_generic_less_than = 1;
714 case Token.IDENTIFIER:
726 next_token = xtoken ();
727 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
730 res = Token.FROM_FIRST;
731 query_parsing = true;
732 if (context.Settings.Version <= LanguageVersion.ISO_2)
733 Report.FeatureIsNotAvailable (context, Location, "query expressions");
736 Expression.Error_VoidInvalidInTheContext (Location, Report);
740 // HACK: A token is not a keyword so we need to restore identifiers buffer
741 // which has been overwritten before we grabbed the identifier
742 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
756 case Token.ASCENDING:
757 case Token.DESCENDING:
764 case Token.NAMESPACE:
765 // TODO: some explanation needed
766 check_incorrect_doc_comment ();
770 if (parsing_block > 0) {
775 // Save current position and parse next token.
778 next_token = token ();
779 bool ok = (next_token == Token.CLASS) ||
780 (next_token == Token.STRUCT) ||
781 (next_token == Token.INTERFACE) ||
782 (next_token == Token.VOID);
787 if (next_token == Token.VOID) {
788 if (context.Settings.Version <= LanguageVersion.ISO_2)
789 Report.FeatureIsNotAvailable (context, Location, "partial methods");
790 } else if (context.Settings.Version == LanguageVersion.ISO_1)
791 Report.FeatureIsNotAvailable (context, Location, "partial types");
796 if (next_token < Token.LAST_KEYWORD) {
797 Report.Error (267, Location,
798 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
806 if (parsing_modifiers) {
808 // Skip attributes section or constructor called async
810 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
815 } else if (parsing_block > 0) {
816 switch (peek_token ()) {
818 case Token.OPEN_PARENS_LAMBDA:
821 case Token.IDENTIFIER:
824 if (xtoken () != Token.ARROW)
837 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
838 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
844 if (parsing_block == 0)
854 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
857 // Keywords are stored in an array of arrays grouped by their
858 // length and then by the first character
860 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
861 return PreprocessorDirective.Invalid;
863 int first_index = id[0] - '_';
864 if (first_index > 'z' - '_')
865 return PreprocessorDirective.Invalid;
867 var kwe = keywords_preprocessor[id_len][first_index];
869 return PreprocessorDirective.Invalid;
871 PreprocessorDirective res = PreprocessorDirective.Invalid;
874 for (int i = 1; i < id_len; ++i) {
875 if (id[i] != kwe.Value[i]) {
881 } while (res == PreprocessorDirective.Invalid && kwe != null);
886 public Location Location {
888 return new Location (ref_line, col);
892 static bool is_identifier_start_character (int c)
894 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
897 static bool is_identifier_part_character (char c)
899 if (c >= 'a' && c <= 'z')
902 if (c >= 'A' && c <= 'Z')
905 if (c == '_' || (c >= '0' && c <= '9'))
911 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
914 public static bool IsKeyword (string s)
916 return keyword_strings.Contains (s);
920 // Open parens micro parser. Detects both lambda and cast ambiguity.
922 int TokenizeOpenParens ()
927 int bracket_level = 0;
928 bool is_type = false;
929 bool can_be_type = false;
932 ptoken = current_token;
935 switch (current_token) {
936 case Token.CLOSE_PARENS:
940 // Expression inside parens is lambda, (int i) =>
942 if (current_token == Token.ARROW)
943 return Token.OPEN_PARENS_LAMBDA;
946 // Expression inside parens is single type, (int[])
949 return Token.OPEN_PARENS_CAST;
952 // Expression is possible cast, look at next token, (T)null
955 switch (current_token) {
956 case Token.OPEN_PARENS:
959 case Token.IDENTIFIER:
973 case Token.UNCHECKED:
979 // These can be part of a member access
993 return Token.OPEN_PARENS_CAST;
996 return Token.OPEN_PARENS;
999 case Token.DOUBLE_COLON:
1000 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1005 case Token.IDENTIFIER:
1008 if (bracket_level == 0) {
1014 case Token.OP_GENERICS_LT:
1016 case Token.DOUBLE_COLON:
1018 if (bracket_level == 0)
1022 can_be_type = is_type = false;
1042 if (bracket_level == 0)
1047 if (bracket_level == 0) {
1048 bracket_level = 100;
1049 can_be_type = is_type = false;
1053 case Token.OP_GENERICS_LT:
1054 case Token.OPEN_BRACKET:
1055 if (bracket_level++ == 0)
1059 case Token.OP_GENERICS_GT:
1060 case Token.CLOSE_BRACKET:
1064 case Token.INTERR_NULLABLE:
1066 if (bracket_level == 0)
1072 can_be_type = is_type = false;
1076 return Token.OPEN_PARENS;
1081 public static bool IsValidIdentifier (string s)
1083 if (s == null || s.Length == 0)
1086 if (!is_identifier_start_character (s [0]))
1089 for (int i = 1; i < s.Length; i ++)
1090 if (! is_identifier_part_character (s [i]))
1096 bool parse_less_than ()
1099 int the_token = token ();
1100 if (the_token == Token.OPEN_BRACKET) {
1102 the_token = token ();
1103 } while (the_token != Token.CLOSE_BRACKET);
1104 the_token = token ();
1105 } else if (the_token == Token.IN || the_token == Token.OUT) {
1106 the_token = token ();
1108 switch (the_token) {
1109 case Token.IDENTIFIER:
1127 case Token.OP_GENERICS_GT:
1136 the_token = token ();
1138 if (the_token == Token.OP_GENERICS_GT)
1140 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1142 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1144 else if (the_token == Token.OP_GENERICS_LT) {
1145 if (!parse_less_than ())
1148 } else if (the_token == Token.OPEN_BRACKET) {
1150 the_token = token ();
1151 if (the_token == Token.CLOSE_BRACKET)
1153 else if (the_token == Token.COMMA)
1154 goto rank_specifiers;
1161 bool parse_generic_dimension (out int dimension)
1166 int the_token = token ();
1167 if (the_token == Token.OP_GENERICS_GT)
1169 else if (the_token == Token.COMMA) {
1177 public int peek_token ()
1182 the_token = token ();
1189 // Tonizes `?' using custom disambiguous rules to return one
1190 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1192 // Tricky expression look like:
1194 // Foo ? a = x ? b : c;
1196 int TokenizePossibleNullableType ()
1198 if (parsing_block == 0 || parsing_type > 0)
1199 return Token.INTERR_NULLABLE;
1201 int d = peek_char ();
1204 return Token.OP_COALESCING;
1207 switch (current_token) {
1208 case Token.CLOSE_PARENS:
1213 return Token.INTERR;
1217 if (d == ',' || d == ';' || d == '>')
1218 return Token.INTERR_NULLABLE;
1219 if (d == '*' || (d >= '0' && d <= '9'))
1220 return Token.INTERR;
1224 current_token = Token.NONE;
1226 switch (xtoken ()) {
1233 next_token = Token.INTERR;
1236 case Token.SEMICOLON:
1238 case Token.CLOSE_PARENS:
1239 case Token.OPEN_BRACKET:
1240 case Token.OP_GENERICS_GT:
1242 next_token = Token.INTERR_NULLABLE;
1250 if (next_token == -1) {
1251 switch (xtoken ()) {
1253 case Token.SEMICOLON:
1254 case Token.OPEN_BRACE:
1255 case Token.CLOSE_PARENS:
1257 next_token = Token.INTERR_NULLABLE;
1261 next_token = Token.INTERR;
1269 // All shorcuts failed, do it hard way
1271 while ((ntoken = xtoken ()) != Token.EOF) {
1272 if (ntoken == Token.SEMICOLON)
1275 if (ntoken == Token.COLON) {
1276 if (++colons == interrs)
1281 if (ntoken == Token.INTERR) {
1287 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1296 bool decimal_digits (int c)
1299 bool seen_digits = false;
1302 if (number_pos == max_number_size)
1303 Error_NumericConstantTooLong ();
1304 number_builder [number_pos++] = (char) c;
1308 // We use peek_char2, because decimal_digits needs to do a
1309 // 2-character look-ahead (5.ToString for example).
1311 while ((d = peek_char2 ()) != -1){
1312 if (d >= '0' && d <= '9'){
1313 if (number_pos == max_number_size)
1314 Error_NumericConstantTooLong ();
1315 number_builder [number_pos++] = (char) d;
1325 static bool is_hex (int e)
1327 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1330 static TypeCode real_type_suffix (int c)
1334 return TypeCode.Single;
1336 return TypeCode.Double;
1338 return TypeCode.Decimal;
1340 return TypeCode.Empty;
1344 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1346 bool is_unsigned = false;
1347 bool is_long = false;
1350 bool scanning = true;
1363 // if we have not seen anything in between
1364 // report this error
1366 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1386 if (is_long && is_unsigned){
1387 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1391 // uint if possible, or ulong else.
1393 if ((ul & 0xffffffff00000000) == 0)
1394 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1396 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1397 } else if (is_long){
1398 // long if possible, ulong otherwise
1399 if ((ul & 0x8000000000000000) != 0)
1400 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1402 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1404 // int, uint, long or ulong in that order
1405 if ((ul & 0xffffffff00000000) == 0){
1406 uint ui = (uint) ul;
1408 if ((ui & 0x80000000) != 0)
1409 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1411 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1413 if ((ul & 0x8000000000000000) != 0)
1414 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1416 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1422 // given `c' as the next char in the input decide whether
1423 // we need to convert to a special type, and then choose
1424 // the best representation for the integer
1426 ILiteralConstant adjust_int (int c, Location loc)
1429 if (number_pos > 9){
1430 ulong ul = (uint) (number_builder [0] - '0');
1432 for (int i = 1; i < number_pos; i++){
1433 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1436 return integer_type_suffix (ul, c, loc);
1438 uint ui = (uint) (number_builder [0] - '0');
1440 for (int i = 1; i < number_pos; i++){
1441 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1444 return integer_type_suffix (ui, c, loc);
1446 } catch (OverflowException) {
1447 Error_NumericConstantTooLong ();
1448 return new IntLiteral (context.BuiltinTypes, 0, loc);
1450 catch (FormatException) {
1451 Report.Error (1013, Location, "Invalid number");
1452 return new IntLiteral (context.BuiltinTypes, 0, loc);
1456 ILiteralConstant adjust_real (TypeCode t, Location loc)
1458 string s = new string (number_builder, 0, number_pos);
1459 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1462 case TypeCode.Decimal:
1464 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1465 } catch (OverflowException) {
1466 Report.Error (594, Location, error_details, "decimal");
1467 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1469 case TypeCode.Single:
1471 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1472 } catch (OverflowException) {
1473 Report.Error (594, Location, error_details, "float");
1474 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1478 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1479 } catch (OverflowException) {
1480 Report.Error (594, loc, error_details, "double");
1481 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1486 ILiteralConstant handle_hex (Location loc)
1492 while ((d = peek_char ()) != -1){
1494 number_builder [number_pos++] = (char) d;
1500 string s = new String (number_builder, 0, number_pos);
1503 if (number_pos <= 8)
1504 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1506 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1508 return integer_type_suffix (ul, peek_char (), loc);
1509 } catch (OverflowException){
1510 Error_NumericConstantTooLong ();
1511 return new IntLiteral (context.BuiltinTypes, 0, loc);
1513 catch (FormatException) {
1514 Report.Error (1013, Location, "Invalid number");
1515 return new IntLiteral (context.BuiltinTypes, 0, loc);
1520 // Invoked if we know we have .digits or digits
1522 int is_number (int c)
1524 ILiteralConstant res;
1527 int read_start = reader.Position - 1;
1530 // Caller did peek_char
1538 if (c >= '0' && c <= '9'){
1540 int peek = peek_char ();
1542 if (peek == 'x' || peek == 'X') {
1543 val = res = handle_hex (loc);
1545 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1548 return Token.LITERAL;
1556 // We need to handle the case of
1557 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1559 bool is_real = false;
1561 if (decimal_digits ('.')){
1567 val = res = adjust_int (-1, loc);
1570 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1572 return Token.LITERAL;
1576 if (c == 'e' || c == 'E'){
1578 if (number_pos == max_number_size)
1579 Error_NumericConstantTooLong ();
1580 number_builder [number_pos++] = (char) c;
1584 if (number_pos == max_number_size)
1585 Error_NumericConstantTooLong ();
1586 number_builder [number_pos++] = '+';
1588 } else if (c == '-') {
1589 if (number_pos == max_number_size)
1590 Error_NumericConstantTooLong ();
1591 number_builder [number_pos++] = '-';
1594 if (number_pos == max_number_size)
1595 Error_NumericConstantTooLong ();
1596 number_builder [number_pos++] = '+';
1603 var type = real_type_suffix (c);
1604 if (type == TypeCode.Empty && !is_real) {
1606 res = adjust_int (c, loc);
1610 if (type == TypeCode.Empty) {
1614 res = adjust_real (type, loc);
1620 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1621 if (chars[chars.Length - 1] == '\r')
1622 Array.Resize (ref chars, chars.Length - 1);
1623 res.ParsedValue = chars;
1626 return Token.LITERAL;
1630 // Accepts exactly count (4 or 8) hex, no more no less
1632 int getHex (int count, out int surrogate, out bool error)
1637 int top = count != -1 ? count : 4;
1642 for (i = 0; i < top; i++){
1645 if (c >= '0' && c <= '9')
1646 c = (int) c - (int) '0';
1647 else if (c >= 'A' && c <= 'F')
1648 c = (int) c - (int) 'A' + 10;
1649 else if (c >= 'a' && c <= 'f')
1650 c = (int) c - (int) 'a' + 10;
1656 total = (total * 16) + c;
1658 int p = peek_char ();
1661 if (!is_hex ((char)p))
1667 if (total > 0x0010FFFF) {
1672 if (total >= 0x00010000) {
1673 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1674 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1681 int escape (int c, out int surrogate)
1717 v = getHex (-1, out surrogate, out error);
1723 return EscapeUnicode (d, out surrogate);
1726 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1735 int EscapeUnicode (int ch, out int surrogate)
1739 ch = getHex (8, out surrogate, out error);
1741 ch = getHex (4, out surrogate, out error);
1745 Report.Error (1009, Location, "Unrecognized escape sequence");
1753 if (putback_char != -1) {
1761 if (peek_char () == '\n') {
1767 } else if (x == '\n') {
1775 void advance_line ()
1785 if (putback_char == -1)
1786 putback_char = reader.Read ();
1787 return putback_char;
1792 if (putback_char != -1)
1793 return putback_char;
1794 return reader.Peek ();
1797 public void putback (int c)
1799 if (putback_char != -1){
1800 Console.WriteLine ("Col: " + col);
1801 Console.WriteLine ("Row: " + line);
1802 Console.WriteLine ("Name: " + current_source.Name);
1803 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1804 throw new Exception ("This should not happen putback on putback");
1806 if (c == '\n' || col == 0) {
1807 // It won't happen though.
1817 public bool advance ()
1819 return peek_char () != -1 || CompleteOnEOF;
1822 public Object Value {
1828 public Object value ()
1835 current_token = xtoken ();
1836 return current_token;
1839 int TokenizePreprocessorIdentifier (out int c)
1841 // skip over white space
1844 } while (c == ' ' || c == '\t');
1848 while (c != -1 && c >= 'a' && c <= 'z') {
1849 id_builder[pos++] = (char) c;
1852 int peek = peek_char ();
1853 if (peek == 'U' || peek == 'u') {
1855 c = EscapeUnicode (c, out surrogate);
1856 if (surrogate != 0) {
1857 if (is_identifier_part_character ((char) c)) {
1858 id_builder[pos++] = (char) c;
1869 PreprocessorDirective get_cmd_arg (out string arg)
1873 tokens_seen = false;
1876 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1878 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1881 // skip over white space
1882 while (c == ' ' || c == '\t')
1885 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1888 while (c != -1 && c != '\n') {
1889 if (c == '\\' && has_identifier_argument >= 0) {
1890 if (has_identifier_argument != 0) {
1891 has_identifier_argument = 1;
1893 int peek = peek_char ();
1894 if (peek == 'U' || peek == 'u') {
1896 c = EscapeUnicode (c, out surrogate);
1897 if (surrogate != 0) {
1898 if (is_identifier_part_character ((char) c)) {
1899 if (pos == value_builder.Length)
1900 Array.Resize (ref value_builder, pos * 2);
1902 value_builder[pos++] = (char) c;
1908 has_identifier_argument = -1;
1910 } else if (c == '/' && peek_char () == '/') {
1912 // Eat single-line comments
1917 } while (c != -1 && c != '\n');
1922 if (pos == value_builder.Length)
1923 Array.Resize (ref value_builder, pos * 2);
1925 value_builder[pos++] = (char) c;
1930 if (pos > max_id_size)
1931 arg = new string (value_builder, 0, pos);
1933 arg = InternIdentifier (value_builder, pos);
1935 // Eat any trailing whitespaces
1936 arg = arg.Trim (simple_whitespaces);
1943 // Handles the #line directive
1945 bool PreProcessLine ()
1947 Location loc = Location;
1951 int length = TokenizePreprocessorIdentifier (out c);
1952 if (length == line_default.Length) {
1953 if (!IsTokenIdentifierEqual (line_default))
1956 current_source = source_file.SourceFile;
1957 if (!hidden_block_start.IsNull) {
1958 current_source.RegisterHiddenScope (hidden_block_start, loc);
1959 hidden_block_start = Location.Null;
1963 Location.Push (current_source);
1967 if (length == line_hidden.Length) {
1968 if (!IsTokenIdentifierEqual (line_hidden))
1971 if (hidden_block_start.IsNull)
1972 hidden_block_start = loc;
1977 if (length != 0 || c < '0' || c > '9') {
1979 // Eat any remaining characters to continue parsing on next line
1981 while (c != -1 && c != '\n') {
1988 int new_line = TokenizeNumber (c);
1991 // Eat any remaining characters to continue parsing on next line
1993 while (c != -1 && c != '\n') {
1997 return new_line != 0;
2002 // skip over white space
2005 } while (c == ' ' || c == '\t');
2006 } else if (c == '"') {
2010 if (c != '\n' && c != '/' && c != '"') {
2012 // Eat any remaining characters to continue parsing on next line
2014 while (c != -1 && c != '\n') {
2018 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2022 string new_file_name = null;
2024 new_file_name = TokenizeFileName (ref c);
2026 // skip over white space
2027 while (c == ' ' || c == '\t') {
2033 } else if (c == '/') {
2034 ReadSingleLineComment ();
2037 // Eat any remaining characters to continue parsing on next line
2039 while (c != -1 && c != '\n') {
2043 Error_EndLineExpected ();
2047 if (new_file_name != null) {
2048 current_source = context.LookupFile (source_file, new_file_name);
2049 source_file.AddIncludeFile (current_source);
2050 Location.Push (current_source);
2053 if (!hidden_block_start.IsNull) {
2054 current_source.RegisterHiddenScope (hidden_block_start, loc);
2055 hidden_block_start = Location.Null;
2058 ref_line = new_line;
2063 // Handles #define and #undef
2065 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2067 if (ident.Length == 0 || ident == "true" || ident == "false"){
2068 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2072 if (ident.IndexOfAny (simple_whitespaces) != -1){
2073 Error_EndLineExpected ();
2077 if (!is_identifier_start_character (ident [0]))
2078 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2080 foreach (char c in ident.Substring (1)){
2081 if (!is_identifier_part_character (c)){
2082 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2087 if (!caller_is_taking)
2094 if (context.Settings.IsConditionalSymbolDefined (ident))
2097 source_file.AddDefine (ident);
2102 source_file.AddUndefine (ident);
2106 byte read_hex (out bool error)
2109 int c = get_char ();
2111 if ((c >= '0') && (c <= '9'))
2112 total = (int) c - (int) '0';
2113 else if ((c >= 'A') && (c <= 'F'))
2114 total = (int) c - (int) 'A' + 10;
2115 else if ((c >= 'a') && (c <= 'f'))
2116 total = (int) c - (int) 'a' + 10;
2125 if ((c >= '0') && (c <= '9'))
2126 total += (int) c - (int) '0';
2127 else if ((c >= 'A') && (c <= 'F'))
2128 total += (int) c - (int) 'A' + 10;
2129 else if ((c >= 'a') && (c <= 'f'))
2130 total += (int) c - (int) 'a' + 10;
2137 return (byte) total;
2141 // Parses #pragma checksum
2143 bool ParsePragmaChecksum ()
2146 // The syntax is ` "foo.txt" "{guid}" "hash"'
2148 int c = get_char ();
2153 string file_name = TokenizeFileName (ref c);
2155 // TODO: Any white-spaces count
2159 SourceFile file = context.LookupFile (source_file, file_name);
2161 if (get_char () != '"' || get_char () != '{')
2165 byte[] guid_bytes = new byte [16];
2168 for (; i < 4; i++) {
2169 guid_bytes [i] = read_hex (out error);
2174 if (get_char () != '-')
2177 for (; i < 10; i++) {
2178 guid_bytes [i] = read_hex (out error);
2182 guid_bytes [i++] = read_hex (out error);
2186 if (get_char () != '-')
2190 for (; i < 16; i++) {
2191 guid_bytes [i] = read_hex (out error);
2196 if (get_char () != '}' || get_char () != '"')
2199 // TODO: Any white-spaces count
2204 if (get_char () != '"')
2207 // Any length of checksum
2208 List<byte> checksum_bytes = new List<byte> (16);
2211 while (c != '"' && c != -1) {
2212 checksum_bytes.Add (read_hex (out error));
2220 ReadSingleLineComment ();
2221 } else if (get_char () != '"') {
2225 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2226 current_source.AutoGenerated = true;
2233 bool IsTokenIdentifierEqual (char[] identifier)
2235 for (int i = 0; i < identifier.Length; ++i) {
2236 if (identifier[i] != id_builder[i])
2243 int TokenizeNumber (int value)
2247 decimal_digits (value);
2248 uint ui = (uint) (number_builder[0] - '0');
2251 for (int i = 1; i < number_pos; i++) {
2252 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2256 } catch (OverflowException) {
2257 Error_NumericConstantTooLong ();
2262 string TokenizeFileName (ref int c)
2264 var string_builder = new StringBuilder ();
2265 while (c != -1 && c != '\n') {
2272 string_builder.Append ((char) c);
2275 if (string_builder.Length == 0) {
2276 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2280 return string_builder.ToString ();
2283 int TokenizePragmaNumber (ref int c)
2289 if (c >= '0' && c <= '9') {
2290 number = TokenizeNumber (c);
2294 // skip over white space
2295 while (c == ' ' || c == '\t')
2302 // skip over white space
2303 while (c == ' ' || c == '\t')
2308 ReadSingleLineComment ();
2310 Report.Warning (1692, 1, Location, "Invalid number");
2312 // Read everything till the end of the line or file
2315 } while (c != -1 && c != '\n');
2322 void ReadSingleLineComment ()
2324 if (peek_char () != '/')
2325 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2327 // Read everything till the end of the line or file
2331 } while (c != -1 && c != '\n');
2335 /// Handles #pragma directive
2337 void ParsePragmaDirective (string arg)
2340 int length = TokenizePreprocessorIdentifier (out c);
2341 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2342 length = TokenizePreprocessorIdentifier (out c);
2345 // #pragma warning disable
2346 // #pragma warning restore
2348 if (length == pragma_warning_disable.Length) {
2349 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2350 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2351 // skip over white space
2352 while (c == ' ' || c == '\t')
2357 if (c == '\n' || c == '/') {
2359 ReadSingleLineComment ();
2362 // Disable/Restore all warnings
2365 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2367 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2371 // Disable/Restore a warning or group of warnings
2375 code = TokenizePragmaNumber (ref c);
2378 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2380 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2383 } while (code >= 0 && c != '\n' && c != -1);
2390 Report.Warning (1634, 1, Location, "Expected disable or restore");
2397 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2398 if (c != ' ' || !ParsePragmaChecksum ()) {
2399 Report.Warning (1695, 1, Location,
2400 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2406 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2409 bool eval_val (string s)
2416 return source_file.IsConditionalDefined (s);
2419 bool pp_primary (ref string s)
2428 s = s.Substring (1);
2429 bool val = pp_expr (ref s, false);
2430 if (s.Length > 0 && s [0] == ')'){
2431 s = s.Substring (1);
2434 Error_InvalidDirective ();
2438 if (is_identifier_start_character (c)){
2444 if (is_identifier_part_character (c)){
2448 bool v = eval_val (s.Substring (0, j));
2449 s = s.Substring (j);
2452 bool vv = eval_val (s);
2457 Error_InvalidDirective ();
2461 bool pp_unary (ref string s)
2468 if (len > 1 && s [1] == '='){
2469 Error_InvalidDirective ();
2472 s = s.Substring (1);
2473 return ! pp_primary (ref s);
2475 return pp_primary (ref s);
2477 Error_InvalidDirective ();
2482 bool pp_eq (ref string s)
2484 bool va = pp_unary (ref s);
2490 if (len > 2 && s [1] == '='){
2491 s = s.Substring (2);
2492 return va == pp_unary (ref s);
2494 Error_InvalidDirective ();
2497 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2498 s = s.Substring (2);
2500 return va != pp_unary (ref s);
2509 bool pp_and (ref string s)
2511 bool va = pp_eq (ref s);
2517 if (len > 2 && s [1] == '&'){
2518 s = s.Substring (2);
2519 return (va & pp_and (ref s));
2521 Error_InvalidDirective ();
2530 // Evaluates an expression for `#if' or `#elif'
2532 bool pp_expr (ref string s, bool isTerm)
2534 bool va = pp_and (ref s);
2541 if (len > 2 && s [1] == '|'){
2542 s = s.Substring (2);
2543 return va | pp_expr (ref s, isTerm);
2545 Error_InvalidDirective ();
2550 Error_EndLineExpected ();
2558 bool eval (string s)
2560 bool v = pp_expr (ref s, true);
2569 void Error_NumericConstantTooLong ()
2571 Report.Error (1021, Location, "Integral constant is too large");
2574 void Error_InvalidDirective ()
2576 Report.Error (1517, Location, "Invalid preprocessor directive");
2579 void Error_UnexpectedDirective (string extra)
2583 "Unexpected processor directive ({0})", extra);
2586 void Error_TokensSeen ()
2588 Report.Error (1032, Location,
2589 "Cannot define or undefine preprocessor symbols after first token in file");
2592 void Eror_WrongPreprocessorLocation ()
2594 Report.Error (1040, Location,
2595 "Preprocessor directives must appear as the first non-whitespace character on a line");
2598 void Error_EndLineExpected ()
2600 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2604 // Raises a warning when tokenizer found documentation comment
2605 // on unexpected place
2607 void WarningMisplacedComment (Location loc)
2609 if (doc_state != XmlCommentState.Error) {
2610 doc_state = XmlCommentState.Error;
2611 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2616 // if true, then the code continues processing the code
2617 // if false, the code stays in a loop until another directive is
2619 // When caller_is_taking is false we ignore all directives except the ones
2620 // which can help us to identify where the #if block ends
2621 bool ParsePreprocessingDirective (bool caller_is_taking)
2624 bool region_directive = false;
2626 var directive = get_cmd_arg (out arg);
2629 // The first group of pre-processing instructions is always processed
2631 switch (directive) {
2632 case PreprocessorDirective.Region:
2633 region_directive = true;
2635 goto case PreprocessorDirective.If;
2637 case PreprocessorDirective.Endregion:
2638 if (ifstack == null || ifstack.Count == 0){
2639 Error_UnexpectedDirective ("no #region for this #endregion");
2642 int pop = ifstack.Pop ();
2644 if ((pop & REGION) == 0)
2645 Report.Error (1027, Location, "Expected `#endif' directive");
2647 return caller_is_taking;
2649 case PreprocessorDirective.If:
2650 if (ifstack == null)
2651 ifstack = new Stack<int> (2);
2653 int flags = region_directive ? REGION : 0;
2654 if (ifstack.Count == 0){
2655 flags |= PARENT_TAKING;
2657 int state = ifstack.Peek ();
2658 if ((state & TAKING) != 0) {
2659 flags |= PARENT_TAKING;
2663 if (eval (arg) && caller_is_taking) {
2664 ifstack.Push (flags | TAKING);
2667 ifstack.Push (flags);
2670 case PreprocessorDirective.Endif:
2671 if (ifstack == null || ifstack.Count == 0){
2672 Error_UnexpectedDirective ("no #if for this #endif");
2675 pop = ifstack.Pop ();
2677 if ((pop & REGION) != 0)
2678 Report.Error (1038, Location, "#endregion directive expected");
2680 if (arg.Length != 0) {
2681 Error_EndLineExpected ();
2684 if (ifstack.Count == 0)
2687 int state = ifstack.Peek ();
2688 return (state & TAKING) != 0;
2691 case PreprocessorDirective.Elif:
2692 if (ifstack == null || ifstack.Count == 0){
2693 Error_UnexpectedDirective ("no #if for this #elif");
2696 int state = ifstack.Pop ();
2698 if ((state & REGION) != 0) {
2699 Report.Error (1038, Location, "#endregion directive expected");
2703 if ((state & ELSE_SEEN) != 0){
2704 Error_UnexpectedDirective ("#elif not valid after #else");
2708 if ((state & TAKING) != 0) {
2713 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2714 ifstack.Push (state | TAKING);
2718 ifstack.Push (state);
2722 case PreprocessorDirective.Else:
2723 if (ifstack == null || ifstack.Count == 0){
2724 Error_UnexpectedDirective ("no #if for this #else");
2727 int state = ifstack.Peek ();
2729 if ((state & REGION) != 0) {
2730 Report.Error (1038, Location, "#endregion directive expected");
2734 if ((state & ELSE_SEEN) != 0){
2735 Error_UnexpectedDirective ("#else within #else");
2741 if (arg.Length != 0) {
2742 Error_EndLineExpected ();
2747 if ((state & PARENT_TAKING) != 0) {
2748 ret = (state & TAKING) == 0;
2756 ifstack.Push (state | ELSE_SEEN);
2760 case PreprocessorDirective.Define:
2761 if (any_token_seen){
2762 Error_TokensSeen ();
2763 return caller_is_taking;
2765 PreProcessDefinition (true, arg, caller_is_taking);
2766 return caller_is_taking;
2768 case PreprocessorDirective.Undef:
2769 if (any_token_seen){
2770 Error_TokensSeen ();
2771 return caller_is_taking;
2773 PreProcessDefinition (false, arg, caller_is_taking);
2774 return caller_is_taking;
2776 case PreprocessorDirective.Invalid:
2777 Report.Error (1024, Location, "Wrong preprocessor directive");
2782 // These are only processed if we are in a `taking' block
2784 if (!caller_is_taking)
2788 case PreprocessorDirective.Error:
2789 Report.Error (1029, Location, "#error: '{0}'", arg);
2792 case PreprocessorDirective.Warning:
2793 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2796 case PreprocessorDirective.Pragma:
2797 if (context.Settings.Version == LanguageVersion.ISO_1) {
2798 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2801 ParsePragmaDirective (arg);
2804 case PreprocessorDirective.Line:
2805 Location loc = Location;
2806 if (!PreProcessLine ())
2807 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
2809 return caller_is_taking;
2812 throw new NotImplementedException (directive.ToString ());
2815 private int consume_string (bool quoted)
2819 Location start_location = Location;
2821 start_location = start_location - 1;
2824 int reader_pos = reader.Position;
2830 if (quoted && peek_char () == '"') {
2831 if (pos == value_builder.Length)
2832 Array.Resize (ref value_builder, pos * 2);
2834 value_builder[pos++] = (char) c;
2843 s = InternIdentifier (value_builder, pos);
2845 s = new string (value_builder, 0, pos);
2847 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2850 res.ParsedValue = quoted ?
2851 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2852 reader.ReadChars (reader_pos - 1, reader.Position);
2855 return Token.LITERAL;
2860 Report.Error (1010, Location, "Newline in constant");
2861 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2862 return Token.LITERAL;
2864 } else if (c == '\\' && !quoted) {
2866 c = escape (c, out surrogate);
2869 if (surrogate != 0) {
2870 if (pos == value_builder.Length)
2871 Array.Resize (ref value_builder, pos * 2);
2873 value_builder[pos++] = (char) c;
2876 } else if (c == -1) {
2877 Report.Error (1039, Location, "Unterminated string literal");
2881 if (pos == value_builder.Length)
2882 Array.Resize (ref value_builder, pos * 2);
2884 value_builder[pos++] = (char) c;
2888 private int consume_identifier (int s)
2890 int res = consume_identifier (s, false);
2892 if (doc_state == XmlCommentState.Allowed)
2893 doc_state = XmlCommentState.NotAllowed;
2898 int consume_identifier (int c, bool quoted)
2901 // This method is very performance sensitive. It accounts
2902 // for approximately 25% of all parser time
2912 c = escape (c, out surrogate);
2913 if (surrogate != 0) {
2914 id_builder [pos++] = (char) c;
2919 id_builder [pos++] = (char) c;
2925 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2926 id_builder [pos++] = (char) c;
2933 c = escape (c, out surrogate);
2934 if (is_identifier_part_character ((char) c))
2935 id_builder[pos++] = (char) c;
2937 if (surrogate != 0) {
2943 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2944 id_builder [pos++] = (char) c;
2951 } catch (IndexOutOfRangeException) {
2952 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2960 // Optimization: avoids doing the keyword lookup
2961 // on uppercase letters
2963 if (id_builder [0] >= '_' && !quoted) {
2964 int keyword = GetKeyword (id_builder, pos);
2965 if (keyword != -1) {
2966 val = LocatedToken.Create (keyword == Token.AWAIT ? "await" : null, ref_line, column);
2971 string s = InternIdentifier (id_builder, pos);
2972 val = LocatedToken.Create (s, ref_line, column);
2973 if (quoted && parsing_attribute_section)
2974 AddEscapedIdentifier (((LocatedToken) val).Location);
2976 return Token.IDENTIFIER;
2982 string InternIdentifier (char[] charBuffer, int length)
2985 // Keep identifiers in an array of hashtables to avoid needless
2988 var identifiers_group = identifiers[length];
2990 if (identifiers_group != null) {
2991 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2995 // TODO: this should be number of files dependant
2996 // corlib compilation peaks at 1000 and System.Core at 150
2997 int capacity = length > 20 ? 10 : 100;
2998 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2999 identifiers[length] = identifiers_group;
3002 char[] chars = new char[length];
3003 Array.Copy (charBuffer, chars, length);
3005 s = new string (charBuffer, 0, length);
3006 identifiers_group.Add (chars, s);
3010 public int xtoken ()
3014 // Whether we have seen comments on the current line
3015 bool comments_seen = false;
3016 while ((c = get_char ()) != -1) {
3019 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3027 case 0xFEFF: // Ignore BOM anywhere in the file
3030 /* This is required for compatibility with .NET
3032 if (peek_char () == 0xBB) {
3035 if (get_char () == 0xBF)
3043 return consume_identifier (c);
3046 val = LocatedToken.Create (ref_line, col);
3047 return Token.OPEN_BRACE;
3049 val = LocatedToken.Create (ref_line, col);
3050 return Token.CLOSE_BRACE;
3052 // To block doccomment inside attribute declaration.
3053 if (doc_state == XmlCommentState.Allowed)
3054 doc_state = XmlCommentState.NotAllowed;
3056 val = LocatedToken.Create (ref_line, col);
3058 if (parsing_block == 0 || lambda_arguments_parsing)
3059 return Token.OPEN_BRACKET;
3061 int next = peek_char ();
3065 return Token.OPEN_BRACKET;
3073 next = peek_token ();
3074 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3075 return Token.OPEN_BRACKET;
3077 return Token.OPEN_BRACKET_EXPR;
3079 return Token.OPEN_BRACKET_EXPR;
3082 LocatedToken.CreateOptional (ref_line, col, ref val);
3083 return Token.CLOSE_BRACKET;
3085 val = LocatedToken.Create (ref_line, col);
3087 // An expression versions of parens can appear in block context only
3089 if (parsing_block != 0 && !lambda_arguments_parsing) {
3092 // Optmize most common case where we know that parens
3095 switch (current_token) {
3096 case Token.IDENTIFIER:
3104 case Token.DELEGATE:
3105 case Token.OP_GENERICS_GT:
3106 return Token.OPEN_PARENS;
3109 // Optimize using peek
3110 int xx = peek_char ();
3117 return Token.OPEN_PARENS;
3120 lambda_arguments_parsing = true;
3122 d = TokenizeOpenParens ();
3124 lambda_arguments_parsing = false;
3128 return Token.OPEN_PARENS;
3130 LocatedToken.CreateOptional (ref_line, col, ref val);
3131 return Token.CLOSE_PARENS;
3133 LocatedToken.CreateOptional (ref_line, col, ref val);
3136 LocatedToken.CreateOptional (ref_line, col, ref val);
3137 return Token.SEMICOLON;
3139 val = LocatedToken.Create (ref_line, col);
3142 val = LocatedToken.Create (ref_line, col);
3143 return TokenizePossibleNullableType ();
3145 val = LocatedToken.Create (ref_line, col);
3146 if (parsing_generic_less_than++ > 0)
3147 return Token.OP_GENERICS_LT;
3149 return TokenizeLessThan ();
3152 val = LocatedToken.Create (ref_line, col);
3160 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3161 parsing_generic_less_than--;
3162 return Token.OP_GENERICS_GT;
3171 return Token.OP_SHIFT_RIGHT_ASSIGN;
3173 return Token.OP_SHIFT_RIGHT;
3179 val = LocatedToken.Create (ref_line, col);
3183 } else if (d == '=') {
3184 d = Token.OP_ADD_ASSIGN;
3192 val = LocatedToken.Create (ref_line, col);
3196 } else if (d == '=')
3197 d = Token.OP_SUB_ASSIGN;
3207 val = LocatedToken.Create (ref_line, col);
3208 if (peek_char () == '='){
3215 val = LocatedToken.Create (ref_line, col);
3226 return Token.ASSIGN;
3229 val = LocatedToken.Create (ref_line, col);
3233 return Token.OP_AND;
3237 return Token.OP_AND_ASSIGN;
3239 return Token.BITWISE_AND;
3242 val = LocatedToken.Create (ref_line, col);
3250 return Token.OP_OR_ASSIGN;
3252 return Token.BITWISE_OR;
3255 val = LocatedToken.Create (ref_line, col);
3256 if (peek_char () == '='){
3258 return Token.OP_MULT_ASSIGN;
3265 val = LocatedToken.Create (ref_line, col);
3267 return Token.OP_DIV_ASSIGN;
3270 // Handle double-slash comments.
3273 if (doc_processing) {
3274 if (peek_char () == '/') {
3276 // Don't allow ////.
3277 if ((d = peek_char ()) != '/') {
3278 if (doc_state == XmlCommentState.Allowed)
3279 handle_one_line_xml_comment ();
3280 else if (doc_state == XmlCommentState.NotAllowed)
3281 WarningMisplacedComment (Location - 3);
3284 if (xml_comment_buffer.Length > 0)
3285 doc_state = XmlCommentState.NotAllowed;
3289 while ((d = get_char ()) != -1 && d != '\n');
3291 any_token_seen |= tokens_seen;
3292 tokens_seen = false;
3293 comments_seen = false;
3295 } else if (d == '*'){
3297 bool docAppend = false;
3298 if (doc_processing && peek_char () == '*') {
3300 // But when it is /**/, just do nothing.
3301 if (peek_char () == '/') {
3305 if (doc_state == XmlCommentState.Allowed)
3307 else if (doc_state == XmlCommentState.NotAllowed) {
3308 WarningMisplacedComment (Location - 2);
3312 int current_comment_start = 0;
3314 current_comment_start = xml_comment_buffer.Length;
3315 xml_comment_buffer.Append (Environment.NewLine);
3318 while ((d = get_char ()) != -1){
3319 if (d == '*' && peek_char () == '/'){
3321 comments_seen = true;
3325 xml_comment_buffer.Append ((char) d);
3328 any_token_seen |= tokens_seen;
3329 tokens_seen = false;
3331 // Reset 'comments_seen' just to be consistent.
3332 // It doesn't matter either way, here.
3334 comments_seen = false;
3338 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3341 update_formatted_doc_comment (current_comment_start);
3344 val = LocatedToken.Create (ref_line, col);
3348 val = LocatedToken.Create (ref_line, col);
3349 if (peek_char () == '='){
3351 return Token.OP_MOD_ASSIGN;
3353 return Token.PERCENT;
3356 val = LocatedToken.Create (ref_line, col);
3357 if (peek_char () == '='){
3359 return Token.OP_XOR_ASSIGN;
3361 return Token.CARRET;
3364 val = LocatedToken.Create (ref_line, col);
3365 if (peek_char () == ':') {
3367 return Token.DOUBLE_COLON;
3371 case '0': case '1': case '2': case '3': case '4':
3372 case '5': case '6': case '7': case '8': case '9':
3374 return is_number (c);
3376 case '\n': // white space
3377 any_token_seen |= tokens_seen;
3378 tokens_seen = false;
3379 comments_seen = false;
3385 if (d >= '0' && d <= '9')
3386 return is_number (c);
3388 LocatedToken.CreateOptional (ref_line, col, ref val);
3392 if (tokens_seen || comments_seen) {
3393 Eror_WrongPreprocessorLocation ();
3397 if (ParsePreprocessingDirective (true))
3400 bool directive_expected = false;
3401 while ((c = get_char ()) != -1) {
3403 directive_expected = true;
3404 } else if (!directive_expected) {
3405 // TODO: Implement comment support for disabled code and uncomment this code
3407 // Eror_WrongPreprocessorLocation ();
3408 // return Token.ERROR;
3413 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3417 if (ParsePreprocessingDirective (false))
3420 directive_expected = false;
3424 tokens_seen = false;
3431 return consume_string (false);
3434 return TokenizeBackslash ();
3440 return consume_string (true);
3443 if (is_identifier_start_character (c)){
3444 return consume_identifier (c, true);
3447 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3450 case EvalStatementParserCharacter:
3451 return Token.EVAL_STATEMENT_PARSER;
3452 case EvalCompilationUnitParserCharacter:
3453 return Token.EVAL_COMPILATION_UNIT_PARSER;
3454 case EvalUsingDeclarationsParserCharacter:
3455 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3456 case DocumentationXref:
3457 return Token.DOC_SEE;
3460 if (is_identifier_start_character (c)) {
3462 return consume_identifier (c);
3465 if (char.IsWhiteSpace ((char) c))
3468 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3473 return Token.COMPLETE_COMPLETION;
3476 return Token.GENERATE_COMPLETION;
3483 int TokenizeBackslash ()
3486 int read_start = reader.Position;
3488 Location start_location = Location;
3489 int c = get_char ();
3492 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3493 Report.Error (1011, start_location, "Empty character literal");
3494 return Token.LITERAL;
3498 Report.Error (1010, start_location, "Newline in constant");
3503 c = escape (c, out d);
3507 throw new NotImplementedException ();
3509 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3514 Report.Error (1012, start_location, "Too many characters in character literal");
3516 // Try to recover, read until newline or next "'"
3517 while ((c = get_char ()) != -1) {
3518 if (c == '\n' || c == '\'')
3524 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3527 return Token.LITERAL;
3530 int TokenizeLessThan ()
3533 if (handle_typeof) {
3535 if (parse_generic_dimension (out d)) {
3538 return Token.GENERIC_DIMENSION;
3543 // Save current position and parse next token.
3545 if (parse_less_than ()) {
3546 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3547 d = Token.OP_GENERICS_LT_DECL;
3549 d = Token.OP_GENERICS_LT;
3556 parsing_generic_less_than = 0;
3565 return Token.OP_SHIFT_LEFT_ASSIGN;
3567 return Token.OP_SHIFT_LEFT;
3578 // Handles one line xml comment
3580 private void handle_one_line_xml_comment ()
3583 while ((c = peek_char ()) == ' ')
3584 get_char (); // skip heading whitespaces.
3585 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3586 xml_comment_buffer.Append ((char) get_char ());
3588 if (c == '\r' || c == '\n')
3589 xml_comment_buffer.Append (Environment.NewLine);
3593 // Remove heading "*" in Javadoc-like xml documentation.
3595 private void update_formatted_doc_comment (int current_comment_start)
3597 int length = xml_comment_buffer.Length - current_comment_start;
3598 string [] lines = xml_comment_buffer.ToString (
3599 current_comment_start,
3600 length).Replace ("\r", "").Split ('\n');
3602 // The first line starts with /**, thus it is not target
3603 // for the format check.
3604 for (int i = 1; i < lines.Length; i++) {
3605 string s = lines [i];
3606 int idx = s.IndexOf ('*');
3609 if (i < lines.Length - 1)
3613 head = s.Substring (0, idx);
3614 foreach (char c in head)
3617 lines [i] = s.Substring (idx + 1);
3619 xml_comment_buffer.Remove (current_comment_start, length);
3620 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3624 // Checks if there was incorrect doc comments and raise
3627 public void check_incorrect_doc_comment ()
3629 if (xml_comment_buffer.Length > 0)
3630 WarningMisplacedComment (Location);
3634 // Consumes the saved xml comment lines (if any)
3635 // as for current target member or type.
3637 public string consume_doc_comment ()
3639 if (xml_comment_buffer.Length > 0) {
3640 string ret = xml_comment_buffer.ToString ();
3641 reset_doc_comment ();
3648 get { return context.Report; }
3651 void reset_doc_comment ()
3653 xml_comment_buffer.Length = 0;
3656 public void cleanup ()
3658 if (ifstack != null && ifstack.Count >= 1) {
3659 int state = ifstack.Pop ();
3660 if ((state & REGION) != 0)
3661 Report.Error (1038, Location, "#endregion directive expected");
3663 Report.Error (1027, Location, "Expected `#endif' directive");
3669 // Indicates whether it accepts XML documentation or not.
3671 public enum XmlCommentState {
3672 // comment is allowed in this state.
3674 // comment is not allowed in this state.
3676 // once comments appeared when it is NotAllowed, then the
3677 // state is changed to it, until the state is changed to