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:
978 // These can be part of a member access
992 return Token.OPEN_PARENS_CAST;
995 return Token.OPEN_PARENS;
998 case Token.DOUBLE_COLON:
999 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1004 case Token.IDENTIFIER:
1007 if (bracket_level == 0) {
1013 case Token.OP_GENERICS_LT:
1015 case Token.DOUBLE_COLON:
1017 if (bracket_level == 0)
1021 can_be_type = is_type = false;
1041 if (bracket_level == 0)
1046 if (bracket_level == 0) {
1047 bracket_level = 100;
1048 can_be_type = is_type = false;
1052 case Token.OP_GENERICS_LT:
1053 case Token.OPEN_BRACKET:
1054 if (bracket_level++ == 0)
1058 case Token.OP_GENERICS_GT:
1059 case Token.CLOSE_BRACKET:
1063 case Token.INTERR_NULLABLE:
1065 if (bracket_level == 0)
1071 can_be_type = is_type = false;
1075 return Token.OPEN_PARENS;
1080 public static bool IsValidIdentifier (string s)
1082 if (s == null || s.Length == 0)
1085 if (!is_identifier_start_character (s [0]))
1088 for (int i = 1; i < s.Length; i ++)
1089 if (! is_identifier_part_character (s [i]))
1095 bool parse_less_than ()
1098 int the_token = token ();
1099 if (the_token == Token.OPEN_BRACKET) {
1101 the_token = token ();
1102 } while (the_token != Token.CLOSE_BRACKET);
1103 the_token = token ();
1104 } else if (the_token == Token.IN || the_token == Token.OUT) {
1105 the_token = token ();
1107 switch (the_token) {
1108 case Token.IDENTIFIER:
1126 case Token.OP_GENERICS_GT:
1135 the_token = token ();
1137 if (the_token == Token.OP_GENERICS_GT)
1139 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1141 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1143 else if (the_token == Token.OP_GENERICS_LT) {
1144 if (!parse_less_than ())
1147 } else if (the_token == Token.OPEN_BRACKET) {
1149 the_token = token ();
1150 if (the_token == Token.CLOSE_BRACKET)
1152 else if (the_token == Token.COMMA)
1153 goto rank_specifiers;
1160 bool parse_generic_dimension (out int dimension)
1165 int the_token = token ();
1166 if (the_token == Token.OP_GENERICS_GT)
1168 else if (the_token == Token.COMMA) {
1176 public int peek_token ()
1181 the_token = token ();
1188 // Tonizes `?' using custom disambiguous rules to return one
1189 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1191 // Tricky expression look like:
1193 // Foo ? a = x ? b : c;
1195 int TokenizePossibleNullableType ()
1197 if (parsing_block == 0 || parsing_type > 0)
1198 return Token.INTERR_NULLABLE;
1200 int d = peek_char ();
1203 return Token.OP_COALESCING;
1206 switch (current_token) {
1207 case Token.CLOSE_PARENS:
1212 return Token.INTERR;
1216 if (d == ',' || d == ';' || d == '>')
1217 return Token.INTERR_NULLABLE;
1218 if (d == '*' || (d >= '0' && d <= '9'))
1219 return Token.INTERR;
1223 current_token = Token.NONE;
1225 switch (xtoken ()) {
1232 next_token = Token.INTERR;
1235 case Token.SEMICOLON:
1237 case Token.CLOSE_PARENS:
1238 case Token.OPEN_BRACKET:
1239 case Token.OP_GENERICS_GT:
1241 next_token = Token.INTERR_NULLABLE;
1249 if (next_token == -1) {
1250 switch (xtoken ()) {
1252 case Token.SEMICOLON:
1253 case Token.OPEN_BRACE:
1254 case Token.CLOSE_PARENS:
1256 next_token = Token.INTERR_NULLABLE;
1260 next_token = Token.INTERR;
1268 // All shorcuts failed, do it hard way
1270 while ((ntoken = xtoken ()) != Token.EOF) {
1271 if (ntoken == Token.SEMICOLON)
1274 if (ntoken == Token.COLON) {
1275 if (++colons == interrs)
1280 if (ntoken == Token.INTERR) {
1286 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1295 bool decimal_digits (int c)
1298 bool seen_digits = false;
1301 if (number_pos == max_number_size)
1302 Error_NumericConstantTooLong ();
1303 number_builder [number_pos++] = (char) c;
1307 // We use peek_char2, because decimal_digits needs to do a
1308 // 2-character look-ahead (5.ToString for example).
1310 while ((d = peek_char2 ()) != -1){
1311 if (d >= '0' && d <= '9'){
1312 if (number_pos == max_number_size)
1313 Error_NumericConstantTooLong ();
1314 number_builder [number_pos++] = (char) d;
1324 static bool is_hex (int e)
1326 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1329 static TypeCode real_type_suffix (int c)
1333 return TypeCode.Single;
1335 return TypeCode.Double;
1337 return TypeCode.Decimal;
1339 return TypeCode.Empty;
1343 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1345 bool is_unsigned = false;
1346 bool is_long = false;
1349 bool scanning = true;
1362 // if we have not seen anything in between
1363 // report this error
1365 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1385 if (is_long && is_unsigned){
1386 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1390 // uint if possible, or ulong else.
1392 if ((ul & 0xffffffff00000000) == 0)
1393 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1395 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1396 } else if (is_long){
1397 // long if possible, ulong otherwise
1398 if ((ul & 0x8000000000000000) != 0)
1399 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1401 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1403 // int, uint, long or ulong in that order
1404 if ((ul & 0xffffffff00000000) == 0){
1405 uint ui = (uint) ul;
1407 if ((ui & 0x80000000) != 0)
1408 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1410 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1412 if ((ul & 0x8000000000000000) != 0)
1413 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1415 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1421 // given `c' as the next char in the input decide whether
1422 // we need to convert to a special type, and then choose
1423 // the best representation for the integer
1425 ILiteralConstant adjust_int (int c, Location loc)
1428 if (number_pos > 9){
1429 ulong ul = (uint) (number_builder [0] - '0');
1431 for (int i = 1; i < number_pos; i++){
1432 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1435 return integer_type_suffix (ul, c, loc);
1437 uint ui = (uint) (number_builder [0] - '0');
1439 for (int i = 1; i < number_pos; i++){
1440 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1443 return integer_type_suffix (ui, c, loc);
1445 } catch (OverflowException) {
1446 Error_NumericConstantTooLong ();
1447 return new IntLiteral (context.BuiltinTypes, 0, loc);
1449 catch (FormatException) {
1450 Report.Error (1013, Location, "Invalid number");
1451 return new IntLiteral (context.BuiltinTypes, 0, loc);
1455 ILiteralConstant adjust_real (TypeCode t, Location loc)
1457 string s = new string (number_builder, 0, number_pos);
1458 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1461 case TypeCode.Decimal:
1463 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1464 } catch (OverflowException) {
1465 Report.Error (594, Location, error_details, "decimal");
1466 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1468 case TypeCode.Single:
1470 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1471 } catch (OverflowException) {
1472 Report.Error (594, Location, error_details, "float");
1473 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1477 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1478 } catch (OverflowException) {
1479 Report.Error (594, loc, error_details, "double");
1480 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1485 ILiteralConstant handle_hex (Location loc)
1491 while ((d = peek_char ()) != -1){
1493 number_builder [number_pos++] = (char) d;
1499 string s = new String (number_builder, 0, number_pos);
1502 if (number_pos <= 8)
1503 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1505 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1507 return integer_type_suffix (ul, peek_char (), loc);
1508 } catch (OverflowException){
1509 Error_NumericConstantTooLong ();
1510 return new IntLiteral (context.BuiltinTypes, 0, loc);
1512 catch (FormatException) {
1513 Report.Error (1013, Location, "Invalid number");
1514 return new IntLiteral (context.BuiltinTypes, 0, loc);
1519 // Invoked if we know we have .digits or digits
1521 int is_number (int c)
1523 ILiteralConstant res;
1526 int read_start = reader.Position - 1;
1529 // Caller did peek_char
1537 if (c >= '0' && c <= '9'){
1539 int peek = peek_char ();
1541 if (peek == 'x' || peek == 'X') {
1542 val = res = handle_hex (loc);
1544 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1547 return Token.LITERAL;
1555 // We need to handle the case of
1556 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1558 bool is_real = false;
1560 if (decimal_digits ('.')){
1566 val = res = adjust_int (-1, loc);
1569 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1571 return Token.LITERAL;
1575 if (c == 'e' || c == 'E'){
1577 if (number_pos == max_number_size)
1578 Error_NumericConstantTooLong ();
1579 number_builder [number_pos++] = (char) c;
1583 if (number_pos == max_number_size)
1584 Error_NumericConstantTooLong ();
1585 number_builder [number_pos++] = '+';
1587 } else if (c == '-') {
1588 if (number_pos == max_number_size)
1589 Error_NumericConstantTooLong ();
1590 number_builder [number_pos++] = '-';
1593 if (number_pos == max_number_size)
1594 Error_NumericConstantTooLong ();
1595 number_builder [number_pos++] = '+';
1602 var type = real_type_suffix (c);
1603 if (type == TypeCode.Empty && !is_real) {
1605 res = adjust_int (c, loc);
1609 if (type == TypeCode.Empty) {
1613 res = adjust_real (type, loc);
1619 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1620 if (chars[chars.Length - 1] == '\r')
1621 Array.Resize (ref chars, chars.Length - 1);
1622 res.ParsedValue = chars;
1625 return Token.LITERAL;
1629 // Accepts exactly count (4 or 8) hex, no more no less
1631 int getHex (int count, out int surrogate, out bool error)
1636 int top = count != -1 ? count : 4;
1641 for (i = 0; i < top; i++){
1644 if (c >= '0' && c <= '9')
1645 c = (int) c - (int) '0';
1646 else if (c >= 'A' && c <= 'F')
1647 c = (int) c - (int) 'A' + 10;
1648 else if (c >= 'a' && c <= 'f')
1649 c = (int) c - (int) 'a' + 10;
1655 total = (total * 16) + c;
1657 int p = peek_char ();
1660 if (!is_hex ((char)p))
1666 if (total > 0x0010FFFF) {
1671 if (total >= 0x00010000) {
1672 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1673 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1680 int escape (int c, out int surrogate)
1716 v = getHex (-1, out surrogate, out error);
1722 return EscapeUnicode (d, out surrogate);
1725 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1734 int EscapeUnicode (int ch, out int surrogate)
1738 ch = getHex (8, out surrogate, out error);
1740 ch = getHex (4, out surrogate, out error);
1744 Report.Error (1009, Location, "Unrecognized escape sequence");
1752 if (putback_char != -1) {
1760 if (peek_char () == '\n') {
1766 } else if (x == '\n') {
1774 void advance_line ()
1784 if (putback_char == -1)
1785 putback_char = reader.Read ();
1786 return putback_char;
1791 if (putback_char != -1)
1792 return putback_char;
1793 return reader.Peek ();
1796 public void putback (int c)
1798 if (putback_char != -1){
1799 Console.WriteLine ("Col: " + col);
1800 Console.WriteLine ("Row: " + line);
1801 Console.WriteLine ("Name: " + current_source.Name);
1802 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1803 throw new Exception ("This should not happen putback on putback");
1805 if (c == '\n' || col == 0) {
1806 // It won't happen though.
1816 public bool advance ()
1818 return peek_char () != -1 || CompleteOnEOF;
1821 public Object Value {
1827 public Object value ()
1834 current_token = xtoken ();
1835 return current_token;
1838 int TokenizePreprocessorIdentifier (out int c)
1840 // skip over white space
1843 } while (c == ' ' || c == '\t');
1847 while (c != -1 && c >= 'a' && c <= 'z') {
1848 id_builder[pos++] = (char) c;
1851 int peek = peek_char ();
1852 if (peek == 'U' || peek == 'u') {
1854 c = EscapeUnicode (c, out surrogate);
1855 if (surrogate != 0) {
1856 if (is_identifier_part_character ((char) c)) {
1857 id_builder[pos++] = (char) c;
1868 PreprocessorDirective get_cmd_arg (out string arg)
1872 tokens_seen = false;
1875 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1877 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1880 // skip over white space
1881 while (c == ' ' || c == '\t')
1884 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1887 while (c != -1 && c != '\n') {
1888 if (c == '\\' && has_identifier_argument >= 0) {
1889 if (has_identifier_argument != 0) {
1890 has_identifier_argument = 1;
1892 int peek = peek_char ();
1893 if (peek == 'U' || peek == 'u') {
1895 c = EscapeUnicode (c, out surrogate);
1896 if (surrogate != 0) {
1897 if (is_identifier_part_character ((char) c)) {
1898 if (pos == value_builder.Length)
1899 Array.Resize (ref value_builder, pos * 2);
1901 value_builder[pos++] = (char) c;
1907 has_identifier_argument = -1;
1909 } else if (c == '/' && peek_char () == '/') {
1911 // Eat single-line comments
1916 } while (c != -1 && c != '\n');
1921 if (pos == value_builder.Length)
1922 Array.Resize (ref value_builder, pos * 2);
1924 value_builder[pos++] = (char) c;
1929 if (pos > max_id_size)
1930 arg = new string (value_builder, 0, pos);
1932 arg = InternIdentifier (value_builder, pos);
1934 // Eat any trailing whitespaces
1935 arg = arg.Trim (simple_whitespaces);
1942 // Handles the #line directive
1944 bool PreProcessLine ()
1946 Location loc = Location;
1950 int length = TokenizePreprocessorIdentifier (out c);
1951 if (length == line_default.Length) {
1952 if (!IsTokenIdentifierEqual (line_default))
1955 current_source = source_file.SourceFile;
1956 if (!hidden_block_start.IsNull) {
1957 current_source.RegisterHiddenScope (hidden_block_start, loc);
1958 hidden_block_start = Location.Null;
1962 Location.Push (current_source);
1966 if (length == line_hidden.Length) {
1967 if (!IsTokenIdentifierEqual (line_hidden))
1970 if (hidden_block_start.IsNull)
1971 hidden_block_start = loc;
1976 if (length != 0 || c < '0' || c > '9') {
1978 // Eat any remaining characters to continue parsing on next line
1980 while (c != -1 && c != '\n') {
1987 int new_line = TokenizeNumber (c);
1990 // Eat any remaining characters to continue parsing on next line
1992 while (c != -1 && c != '\n') {
1996 return new_line != 0;
2001 // skip over white space
2004 } while (c == ' ' || c == '\t');
2005 } else if (c == '"') {
2009 if (c != '\n' && c != '/' && c != '"') {
2011 // Eat any remaining characters to continue parsing on next line
2013 while (c != -1 && c != '\n') {
2017 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2021 string new_file_name = null;
2023 new_file_name = TokenizeFileName (ref c);
2025 // skip over white space
2026 while (c == ' ' || c == '\t') {
2032 } else if (c == '/') {
2033 ReadSingleLineComment ();
2036 // Eat any remaining characters to continue parsing on next line
2038 while (c != -1 && c != '\n') {
2042 Error_EndLineExpected ();
2046 if (new_file_name != null) {
2047 current_source = context.LookupFile (source_file, new_file_name);
2048 source_file.AddIncludeFile (current_source);
2049 Location.Push (current_source);
2052 if (!hidden_block_start.IsNull) {
2053 current_source.RegisterHiddenScope (hidden_block_start, loc);
2054 hidden_block_start = Location.Null;
2057 ref_line = new_line;
2062 // Handles #define and #undef
2064 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2066 if (ident.Length == 0 || ident == "true" || ident == "false"){
2067 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2071 if (ident.IndexOfAny (simple_whitespaces) != -1){
2072 Error_EndLineExpected ();
2076 if (!is_identifier_start_character (ident [0]))
2077 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2079 foreach (char c in ident.Substring (1)){
2080 if (!is_identifier_part_character (c)){
2081 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2086 if (!caller_is_taking)
2093 if (context.Settings.IsConditionalSymbolDefined (ident))
2096 source_file.AddDefine (ident);
2101 source_file.AddUndefine (ident);
2105 byte read_hex (out bool error)
2108 int c = get_char ();
2110 if ((c >= '0') && (c <= '9'))
2111 total = (int) c - (int) '0';
2112 else if ((c >= 'A') && (c <= 'F'))
2113 total = (int) c - (int) 'A' + 10;
2114 else if ((c >= 'a') && (c <= 'f'))
2115 total = (int) c - (int) 'a' + 10;
2124 if ((c >= '0') && (c <= '9'))
2125 total += (int) c - (int) '0';
2126 else if ((c >= 'A') && (c <= 'F'))
2127 total += (int) c - (int) 'A' + 10;
2128 else if ((c >= 'a') && (c <= 'f'))
2129 total += (int) c - (int) 'a' + 10;
2136 return (byte) total;
2140 // Parses #pragma checksum
2142 bool ParsePragmaChecksum ()
2145 // The syntax is ` "foo.txt" "{guid}" "hash"'
2147 int c = get_char ();
2152 string file_name = TokenizeFileName (ref c);
2154 // TODO: Any white-spaces count
2158 SourceFile file = context.LookupFile (source_file, file_name);
2160 if (get_char () != '"' || get_char () != '{')
2164 byte[] guid_bytes = new byte [16];
2167 for (; i < 4; i++) {
2168 guid_bytes [i] = read_hex (out error);
2173 if (get_char () != '-')
2176 for (; i < 10; i++) {
2177 guid_bytes [i] = read_hex (out error);
2181 guid_bytes [i++] = read_hex (out error);
2185 if (get_char () != '-')
2189 for (; i < 16; i++) {
2190 guid_bytes [i] = read_hex (out error);
2195 if (get_char () != '}' || get_char () != '"')
2198 // TODO: Any white-spaces count
2203 if (get_char () != '"')
2206 // Any length of checksum
2207 List<byte> checksum_bytes = new List<byte> (16);
2210 while (c != '"' && c != -1) {
2211 checksum_bytes.Add (read_hex (out error));
2219 ReadSingleLineComment ();
2220 } else if (get_char () != '"') {
2224 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2225 current_source.AutoGenerated = true;
2229 bool IsTokenIdentifierEqual (char[] identifier)
2231 for (int i = 0; i < identifier.Length; ++i) {
2232 if (identifier[i] != id_builder[i])
2239 int TokenizeNumber (int value)
2243 decimal_digits (value);
2244 uint ui = (uint) (number_builder[0] - '0');
2247 for (int i = 1; i < number_pos; i++) {
2248 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2252 } catch (OverflowException) {
2253 Error_NumericConstantTooLong ();
2258 string TokenizeFileName (ref int c)
2260 var string_builder = new StringBuilder ();
2261 while (c != -1 && c != '\n') {
2268 string_builder.Append ((char) c);
2271 if (string_builder.Length == 0) {
2272 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2275 return string_builder.ToString ();
2278 int TokenizePragmaNumber (ref int c)
2284 if (c >= '0' && c <= '9') {
2285 number = TokenizeNumber (c);
2289 // skip over white space
2290 while (c == ' ' || c == '\t')
2297 // skip over white space
2298 while (c == ' ' || c == '\t')
2303 ReadSingleLineComment ();
2305 Report.Warning (1692, 1, Location, "Invalid number");
2307 // Read everything till the end of the line or file
2310 } while (c != -1 && c != '\n');
2317 void ReadSingleLineComment ()
2319 if (peek_char () != '/')
2320 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2322 // Read everything till the end of the line or file
2326 } while (c != -1 && c != '\n');
2330 /// Handles #pragma directive
2332 void ParsePragmaDirective (string arg)
2335 int length = TokenizePreprocessorIdentifier (out c);
2336 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2337 length = TokenizePreprocessorIdentifier (out c);
2340 // #pragma warning disable
2341 // #pragma warning restore
2343 if (length == pragma_warning_disable.Length) {
2344 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2345 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2346 // skip over white space
2347 while (c == ' ' || c == '\t')
2352 if (c == '\n' || c == '/') {
2354 ReadSingleLineComment ();
2357 // Disable/Restore all warnings
2360 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2362 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2366 // Disable/Restore a warning or group of warnings
2370 code = TokenizePragmaNumber (ref c);
2373 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2375 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2378 } while (code >= 0 && c != '\n' && c != -1);
2385 Report.Warning (1634, 1, Location, "Expected disable or restore");
2392 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2393 if (c != ' ' || !ParsePragmaChecksum ()) {
2394 Report.Warning (1695, 1, Location,
2395 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2401 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2404 bool eval_val (string s)
2411 return source_file.IsConditionalDefined (s);
2414 bool pp_primary (ref string s)
2423 s = s.Substring (1);
2424 bool val = pp_expr (ref s, false);
2425 if (s.Length > 0 && s [0] == ')'){
2426 s = s.Substring (1);
2429 Error_InvalidDirective ();
2433 if (is_identifier_start_character (c)){
2439 if (is_identifier_part_character (c)){
2443 bool v = eval_val (s.Substring (0, j));
2444 s = s.Substring (j);
2447 bool vv = eval_val (s);
2452 Error_InvalidDirective ();
2456 bool pp_unary (ref string s)
2463 if (len > 1 && s [1] == '='){
2464 Error_InvalidDirective ();
2467 s = s.Substring (1);
2468 return ! pp_primary (ref s);
2470 return pp_primary (ref s);
2472 Error_InvalidDirective ();
2477 bool pp_eq (ref string s)
2479 bool va = pp_unary (ref s);
2485 if (len > 2 && s [1] == '='){
2486 s = s.Substring (2);
2487 return va == pp_unary (ref s);
2489 Error_InvalidDirective ();
2492 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2493 s = s.Substring (2);
2495 return va != pp_unary (ref s);
2504 bool pp_and (ref string s)
2506 bool va = pp_eq (ref s);
2512 if (len > 2 && s [1] == '&'){
2513 s = s.Substring (2);
2514 return (va & pp_and (ref s));
2516 Error_InvalidDirective ();
2525 // Evaluates an expression for `#if' or `#elif'
2527 bool pp_expr (ref string s, bool isTerm)
2529 bool va = pp_and (ref s);
2536 if (len > 2 && s [1] == '|'){
2537 s = s.Substring (2);
2538 return va | pp_expr (ref s, isTerm);
2540 Error_InvalidDirective ();
2545 Error_EndLineExpected ();
2553 bool eval (string s)
2555 bool v = pp_expr (ref s, true);
2564 void Error_NumericConstantTooLong ()
2566 Report.Error (1021, Location, "Integral constant is too large");
2569 void Error_InvalidDirective ()
2571 Report.Error (1517, Location, "Invalid preprocessor directive");
2574 void Error_UnexpectedDirective (string extra)
2578 "Unexpected processor directive ({0})", extra);
2581 void Error_TokensSeen ()
2583 Report.Error (1032, Location,
2584 "Cannot define or undefine preprocessor symbols after first token in file");
2587 void Eror_WrongPreprocessorLocation ()
2589 Report.Error (1040, Location,
2590 "Preprocessor directives must appear as the first non-whitespace character on a line");
2593 void Error_EndLineExpected ()
2595 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2599 // Raises a warning when tokenizer found documentation comment
2600 // on unexpected place
2602 void WarningMisplacedComment (Location loc)
2604 if (doc_state != XmlCommentState.Error) {
2605 doc_state = XmlCommentState.Error;
2606 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2611 // if true, then the code continues processing the code
2612 // if false, the code stays in a loop until another directive is
2614 // When caller_is_taking is false we ignore all directives except the ones
2615 // which can help us to identify where the #if block ends
2616 bool ParsePreprocessingDirective (bool caller_is_taking)
2619 bool region_directive = false;
2621 var directive = get_cmd_arg (out arg);
2624 // The first group of pre-processing instructions is always processed
2626 switch (directive) {
2627 case PreprocessorDirective.Region:
2628 region_directive = true;
2630 goto case PreprocessorDirective.If;
2632 case PreprocessorDirective.Endregion:
2633 if (ifstack == null || ifstack.Count == 0){
2634 Error_UnexpectedDirective ("no #region for this #endregion");
2637 int pop = ifstack.Pop ();
2639 if ((pop & REGION) == 0)
2640 Report.Error (1027, Location, "Expected `#endif' directive");
2642 return caller_is_taking;
2644 case PreprocessorDirective.If:
2645 if (ifstack == null)
2646 ifstack = new Stack<int> (2);
2648 int flags = region_directive ? REGION : 0;
2649 if (ifstack.Count == 0){
2650 flags |= PARENT_TAKING;
2652 int state = ifstack.Peek ();
2653 if ((state & TAKING) != 0) {
2654 flags |= PARENT_TAKING;
2658 if (eval (arg) && caller_is_taking) {
2659 ifstack.Push (flags | TAKING);
2662 ifstack.Push (flags);
2665 case PreprocessorDirective.Endif:
2666 if (ifstack == null || ifstack.Count == 0){
2667 Error_UnexpectedDirective ("no #if for this #endif");
2670 pop = ifstack.Pop ();
2672 if ((pop & REGION) != 0)
2673 Report.Error (1038, Location, "#endregion directive expected");
2675 if (arg.Length != 0) {
2676 Error_EndLineExpected ();
2679 if (ifstack.Count == 0)
2682 int state = ifstack.Peek ();
2683 return (state & TAKING) != 0;
2686 case PreprocessorDirective.Elif:
2687 if (ifstack == null || ifstack.Count == 0){
2688 Error_UnexpectedDirective ("no #if for this #elif");
2691 int state = ifstack.Pop ();
2693 if ((state & REGION) != 0) {
2694 Report.Error (1038, Location, "#endregion directive expected");
2698 if ((state & ELSE_SEEN) != 0){
2699 Error_UnexpectedDirective ("#elif not valid after #else");
2703 if ((state & TAKING) != 0) {
2708 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2709 ifstack.Push (state | TAKING);
2713 ifstack.Push (state);
2717 case PreprocessorDirective.Else:
2718 if (ifstack == null || ifstack.Count == 0){
2719 Error_UnexpectedDirective ("no #if for this #else");
2722 int state = ifstack.Peek ();
2724 if ((state & REGION) != 0) {
2725 Report.Error (1038, Location, "#endregion directive expected");
2729 if ((state & ELSE_SEEN) != 0){
2730 Error_UnexpectedDirective ("#else within #else");
2736 if (arg.Length != 0) {
2737 Error_EndLineExpected ();
2742 if ((state & PARENT_TAKING) != 0) {
2743 ret = (state & TAKING) == 0;
2751 ifstack.Push (state | ELSE_SEEN);
2755 case PreprocessorDirective.Define:
2756 if (any_token_seen){
2757 Error_TokensSeen ();
2758 return caller_is_taking;
2760 PreProcessDefinition (true, arg, caller_is_taking);
2761 return caller_is_taking;
2763 case PreprocessorDirective.Undef:
2764 if (any_token_seen){
2765 Error_TokensSeen ();
2766 return caller_is_taking;
2768 PreProcessDefinition (false, arg, caller_is_taking);
2769 return caller_is_taking;
2771 case PreprocessorDirective.Invalid:
2772 Report.Error (1024, Location, "Wrong preprocessor directive");
2777 // These are only processed if we are in a `taking' block
2779 if (!caller_is_taking)
2783 case PreprocessorDirective.Error:
2784 Report.Error (1029, Location, "#error: '{0}'", arg);
2787 case PreprocessorDirective.Warning:
2788 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2791 case PreprocessorDirective.Pragma:
2792 if (context.Settings.Version == LanguageVersion.ISO_1) {
2793 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2796 ParsePragmaDirective (arg);
2799 case PreprocessorDirective.Line:
2800 Location loc = Location;
2801 if (!PreProcessLine ())
2802 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
2804 return caller_is_taking;
2807 throw new NotImplementedException (directive.ToString ());
2810 private int consume_string (bool quoted)
2814 Location start_location = Location;
2816 start_location = start_location - 1;
2819 int reader_pos = reader.Position;
2825 if (quoted && peek_char () == '"') {
2826 if (pos == value_builder.Length)
2827 Array.Resize (ref value_builder, pos * 2);
2829 value_builder[pos++] = (char) c;
2838 s = InternIdentifier (value_builder, pos);
2840 s = new string (value_builder, 0, pos);
2842 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2845 res.ParsedValue = quoted ?
2846 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2847 reader.ReadChars (reader_pos - 1, reader.Position);
2850 return Token.LITERAL;
2855 Report.Error (1010, Location, "Newline in constant");
2856 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2857 return Token.LITERAL;
2859 } else if (c == '\\' && !quoted) {
2861 c = escape (c, out surrogate);
2864 if (surrogate != 0) {
2865 if (pos == value_builder.Length)
2866 Array.Resize (ref value_builder, pos * 2);
2868 value_builder[pos++] = (char) c;
2871 } else if (c == -1) {
2872 Report.Error (1039, Location, "Unterminated string literal");
2876 if (pos == value_builder.Length)
2877 Array.Resize (ref value_builder, pos * 2);
2879 value_builder[pos++] = (char) c;
2883 private int consume_identifier (int s)
2885 int res = consume_identifier (s, false);
2887 if (doc_state == XmlCommentState.Allowed)
2888 doc_state = XmlCommentState.NotAllowed;
2893 int consume_identifier (int c, bool quoted)
2896 // This method is very performance sensitive. It accounts
2897 // for approximately 25% of all parser time
2907 c = escape (c, out surrogate);
2908 if (surrogate != 0) {
2909 id_builder [pos++] = (char) c;
2914 id_builder [pos++] = (char) c;
2920 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2921 id_builder [pos++] = (char) c;
2928 c = escape (c, out surrogate);
2929 if (is_identifier_part_character ((char) c))
2930 id_builder[pos++] = (char) c;
2932 if (surrogate != 0) {
2938 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2939 id_builder [pos++] = (char) c;
2946 } catch (IndexOutOfRangeException) {
2947 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2955 // Optimization: avoids doing the keyword lookup
2956 // on uppercase letters
2958 if (id_builder [0] >= '_' && !quoted) {
2959 int keyword = GetKeyword (id_builder, pos);
2960 if (keyword != -1) {
2961 val = LocatedToken.Create (keyword == Token.AWAIT ? "await" : null, ref_line, column);
2966 string s = InternIdentifier (id_builder, pos);
2967 val = LocatedToken.Create (s, ref_line, column);
2968 if (quoted && parsing_attribute_section)
2969 AddEscapedIdentifier (((LocatedToken) val).Location);
2971 return Token.IDENTIFIER;
2974 string InternIdentifier (char[] charBuffer, int length)
2977 // Keep identifiers in an array of hashtables to avoid needless
2980 var identifiers_group = identifiers[length];
2982 if (identifiers_group != null) {
2983 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2987 // TODO: this should be number of files dependant
2988 // corlib compilation peaks at 1000 and System.Core at 150
2989 int capacity = length > 20 ? 10 : 100;
2990 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2991 identifiers[length] = identifiers_group;
2994 char[] chars = new char[length];
2995 Array.Copy (charBuffer, chars, length);
2997 s = new string (charBuffer, 0, length);
2998 identifiers_group.Add (chars, s);
3002 public int xtoken ()
3006 // Whether we have seen comments on the current line
3007 bool comments_seen = false;
3008 while ((c = get_char ()) != -1) {
3011 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3019 case 0xFEFF: // Ignore BOM anywhere in the file
3022 /* This is required for compatibility with .NET
3024 if (peek_char () == 0xBB) {
3027 if (get_char () == 0xBF)
3035 return consume_identifier (c);
3038 val = LocatedToken.Create (ref_line, col);
3039 return Token.OPEN_BRACE;
3041 val = LocatedToken.Create (ref_line, col);
3042 return Token.CLOSE_BRACE;
3044 // To block doccomment inside attribute declaration.
3045 if (doc_state == XmlCommentState.Allowed)
3046 doc_state = XmlCommentState.NotAllowed;
3048 val = LocatedToken.Create (ref_line, col);
3050 if (parsing_block == 0 || lambda_arguments_parsing)
3051 return Token.OPEN_BRACKET;
3053 int next = peek_char ();
3057 return Token.OPEN_BRACKET;
3065 next = peek_token ();
3066 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3067 return Token.OPEN_BRACKET;
3069 return Token.OPEN_BRACKET_EXPR;
3071 return Token.OPEN_BRACKET_EXPR;
3074 LocatedToken.CreateOptional (ref_line, col, ref val);
3075 return Token.CLOSE_BRACKET;
3077 val = LocatedToken.Create (ref_line, col);
3079 // An expression versions of parens can appear in block context only
3081 if (parsing_block != 0 && !lambda_arguments_parsing) {
3084 // Optmize most common case where we know that parens
3087 switch (current_token) {
3088 case Token.IDENTIFIER:
3096 case Token.DELEGATE:
3097 case Token.OP_GENERICS_GT:
3098 return Token.OPEN_PARENS;
3101 // Optimize using peek
3102 int xx = peek_char ();
3109 return Token.OPEN_PARENS;
3112 lambda_arguments_parsing = true;
3114 d = TokenizeOpenParens ();
3116 lambda_arguments_parsing = false;
3120 return Token.OPEN_PARENS;
3122 LocatedToken.CreateOptional (ref_line, col, ref val);
3123 return Token.CLOSE_PARENS;
3125 LocatedToken.CreateOptional (ref_line, col, ref val);
3128 LocatedToken.CreateOptional (ref_line, col, ref val);
3129 return Token.SEMICOLON;
3131 val = LocatedToken.Create (ref_line, col);
3134 val = LocatedToken.Create (ref_line, col);
3135 return TokenizePossibleNullableType ();
3137 val = LocatedToken.Create (ref_line, col);
3138 if (parsing_generic_less_than++ > 0)
3139 return Token.OP_GENERICS_LT;
3141 return TokenizeLessThan ();
3144 val = LocatedToken.Create (ref_line, col);
3152 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3153 parsing_generic_less_than--;
3154 return Token.OP_GENERICS_GT;
3163 return Token.OP_SHIFT_RIGHT_ASSIGN;
3165 return Token.OP_SHIFT_RIGHT;
3171 val = LocatedToken.Create (ref_line, col);
3175 } else if (d == '=') {
3176 d = Token.OP_ADD_ASSIGN;
3184 val = LocatedToken.Create (ref_line, col);
3188 } else if (d == '=')
3189 d = Token.OP_SUB_ASSIGN;
3199 val = LocatedToken.Create (ref_line, col);
3200 if (peek_char () == '='){
3207 val = LocatedToken.Create (ref_line, col);
3218 return Token.ASSIGN;
3221 val = LocatedToken.Create (ref_line, col);
3225 return Token.OP_AND;
3229 return Token.OP_AND_ASSIGN;
3231 return Token.BITWISE_AND;
3234 val = LocatedToken.Create (ref_line, col);
3242 return Token.OP_OR_ASSIGN;
3244 return Token.BITWISE_OR;
3247 val = LocatedToken.Create (ref_line, col);
3248 if (peek_char () == '='){
3250 return Token.OP_MULT_ASSIGN;
3257 val = LocatedToken.Create (ref_line, col);
3259 return Token.OP_DIV_ASSIGN;
3262 // Handle double-slash comments.
3265 if (doc_processing) {
3266 if (peek_char () == '/') {
3268 // Don't allow ////.
3269 if ((d = peek_char ()) != '/') {
3270 if (doc_state == XmlCommentState.Allowed)
3271 handle_one_line_xml_comment ();
3272 else if (doc_state == XmlCommentState.NotAllowed)
3273 WarningMisplacedComment (Location - 3);
3276 if (xml_comment_buffer.Length > 0)
3277 doc_state = XmlCommentState.NotAllowed;
3281 while ((d = get_char ()) != -1 && d != '\n');
3283 any_token_seen |= tokens_seen;
3284 tokens_seen = false;
3285 comments_seen = false;
3287 } else if (d == '*'){
3289 bool docAppend = false;
3290 if (doc_processing && peek_char () == '*') {
3292 // But when it is /**/, just do nothing.
3293 if (peek_char () == '/') {
3297 if (doc_state == XmlCommentState.Allowed)
3299 else if (doc_state == XmlCommentState.NotAllowed) {
3300 WarningMisplacedComment (Location - 2);
3304 int current_comment_start = 0;
3306 current_comment_start = xml_comment_buffer.Length;
3307 xml_comment_buffer.Append (Environment.NewLine);
3310 while ((d = get_char ()) != -1){
3311 if (d == '*' && peek_char () == '/'){
3313 comments_seen = true;
3317 xml_comment_buffer.Append ((char) d);
3320 any_token_seen |= tokens_seen;
3321 tokens_seen = false;
3323 // Reset 'comments_seen' just to be consistent.
3324 // It doesn't matter either way, here.
3326 comments_seen = false;
3330 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3333 update_formatted_doc_comment (current_comment_start);
3336 val = LocatedToken.Create (ref_line, col);
3340 val = LocatedToken.Create (ref_line, col);
3341 if (peek_char () == '='){
3343 return Token.OP_MOD_ASSIGN;
3345 return Token.PERCENT;
3348 val = LocatedToken.Create (ref_line, col);
3349 if (peek_char () == '='){
3351 return Token.OP_XOR_ASSIGN;
3353 return Token.CARRET;
3356 val = LocatedToken.Create (ref_line, col);
3357 if (peek_char () == ':') {
3359 return Token.DOUBLE_COLON;
3363 case '0': case '1': case '2': case '3': case '4':
3364 case '5': case '6': case '7': case '8': case '9':
3366 return is_number (c);
3368 case '\n': // white space
3369 any_token_seen |= tokens_seen;
3370 tokens_seen = false;
3371 comments_seen = false;
3377 if (d >= '0' && d <= '9')
3378 return is_number (c);
3380 LocatedToken.CreateOptional (ref_line, col, ref val);
3384 if (tokens_seen || comments_seen) {
3385 Eror_WrongPreprocessorLocation ();
3389 if (ParsePreprocessingDirective (true))
3392 bool directive_expected = false;
3393 while ((c = get_char ()) != -1) {
3395 directive_expected = true;
3396 } else if (!directive_expected) {
3397 // TODO: Implement comment support for disabled code and uncomment this code
3399 // Eror_WrongPreprocessorLocation ();
3400 // return Token.ERROR;
3405 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3409 if (ParsePreprocessingDirective (false))
3412 directive_expected = false;
3416 tokens_seen = false;
3423 return consume_string (false);
3426 return TokenizeBackslash ();
3432 return consume_string (true);
3435 if (is_identifier_start_character (c)){
3436 return consume_identifier (c, true);
3439 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3442 case EvalStatementParserCharacter:
3443 return Token.EVAL_STATEMENT_PARSER;
3444 case EvalCompilationUnitParserCharacter:
3445 return Token.EVAL_COMPILATION_UNIT_PARSER;
3446 case EvalUsingDeclarationsParserCharacter:
3447 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3448 case DocumentationXref:
3449 return Token.DOC_SEE;
3452 if (is_identifier_start_character (c)) {
3454 return consume_identifier (c);
3457 if (char.IsWhiteSpace ((char) c))
3460 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3465 return Token.COMPLETE_COMPLETION;
3468 return Token.GENERATE_COMPLETION;
3475 int TokenizeBackslash ()
3478 int read_start = reader.Position;
3480 Location start_location = Location;
3481 int c = get_char ();
3484 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3485 Report.Error (1011, start_location, "Empty character literal");
3486 return Token.LITERAL;
3490 Report.Error (1010, start_location, "Newline in constant");
3495 c = escape (c, out d);
3499 throw new NotImplementedException ();
3501 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3506 Report.Error (1012, start_location, "Too many characters in character literal");
3508 // Try to recover, read until newline or next "'"
3509 while ((c = get_char ()) != -1) {
3510 if (c == '\n' || c == '\'')
3516 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3519 return Token.LITERAL;
3522 int TokenizeLessThan ()
3525 if (handle_typeof) {
3527 if (parse_generic_dimension (out d)) {
3530 return Token.GENERIC_DIMENSION;
3535 // Save current position and parse next token.
3537 if (parse_less_than ()) {
3538 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3539 d = Token.OP_GENERICS_LT_DECL;
3541 d = Token.OP_GENERICS_LT;
3548 parsing_generic_less_than = 0;
3557 return Token.OP_SHIFT_LEFT_ASSIGN;
3559 return Token.OP_SHIFT_LEFT;
3570 // Handles one line xml comment
3572 private void handle_one_line_xml_comment ()
3575 while ((c = peek_char ()) == ' ')
3576 get_char (); // skip heading whitespaces.
3577 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3578 xml_comment_buffer.Append ((char) get_char ());
3580 if (c == '\r' || c == '\n')
3581 xml_comment_buffer.Append (Environment.NewLine);
3585 // Remove heading "*" in Javadoc-like xml documentation.
3587 private void update_formatted_doc_comment (int current_comment_start)
3589 int length = xml_comment_buffer.Length - current_comment_start;
3590 string [] lines = xml_comment_buffer.ToString (
3591 current_comment_start,
3592 length).Replace ("\r", "").Split ('\n');
3594 // The first line starts with /**, thus it is not target
3595 // for the format check.
3596 for (int i = 1; i < lines.Length; i++) {
3597 string s = lines [i];
3598 int idx = s.IndexOf ('*');
3601 if (i < lines.Length - 1)
3605 head = s.Substring (0, idx);
3606 foreach (char c in head)
3609 lines [i] = s.Substring (idx + 1);
3611 xml_comment_buffer.Remove (current_comment_start, length);
3612 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3616 // Checks if there was incorrect doc comments and raise
3619 public void check_incorrect_doc_comment ()
3621 if (xml_comment_buffer.Length > 0)
3622 WarningMisplacedComment (Location);
3626 // Consumes the saved xml comment lines (if any)
3627 // as for current target member or type.
3629 public string consume_doc_comment ()
3631 if (xml_comment_buffer.Length > 0) {
3632 string ret = xml_comment_buffer.ToString ();
3633 reset_doc_comment ();
3640 get { return context.Report; }
3643 void reset_doc_comment ()
3645 xml_comment_buffer.Length = 0;
3648 public void cleanup ()
3650 if (ifstack != null && ifstack.Count >= 1) {
3651 int state = ifstack.Pop ();
3652 if ((state & REGION) != 0)
3653 Report.Error (1038, Location, "#endregion directive expected");
3655 Report.Error (1027, Location, "Expected `#endif' directive");
3661 // Indicates whether it accepts XML documentation or not.
3663 public enum XmlCommentState {
3664 // comment is allowed in this state.
3666 // comment is not allowed in this state.
3668 // once comments appeared when it is NotAllowed, then the
3669 // state is changed to it, until the state is changed to