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;
20 using System.Collections;
25 /// Tokenizer for C# source code.
28 public class Tokenizer : yyParser.yyInput
32 public readonly T Token;
33 public KeywordEntry<T> Next;
34 public readonly char[] Value;
36 public KeywordEntry (string value, T token)
38 this.Value = value.ToCharArray ();
43 sealed class IdentifiersComparer : IEqualityComparer<char[]>
47 public IdentifiersComparer (int length)
52 public bool Equals (char[] x, char[] y)
54 for (int i = 0; i < length; ++i)
61 public int GetHashCode (char[] obj)
64 for (int i = 0; i < length; ++i)
65 h = (h << 5) - h + obj [i];
72 // This class has to be used by parser only, it reuses token
73 // details after each file parse completion
75 public class LocatedToken
77 public int row, column;
79 public SourceFile file;
81 public LocatedToken ()
85 public LocatedToken (string value, Location loc)
88 file = loc.SourceFile;
93 public override string ToString ()
95 return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
98 public Location Location {
99 get { return new Location (file, row, column); }
102 public string Value {
103 get { return value; }
107 public class LocatedTokenBuffer
109 readonly LocatedToken[] buffer;
112 public LocatedTokenBuffer ()
114 buffer = new LocatedToken[0];
117 public LocatedTokenBuffer (LocatedToken[] buffer)
119 this.buffer = buffer ?? new LocatedToken[0];
122 public LocatedToken Create (SourceFile file, int row, int column)
124 return Create (null, file, row, column);
127 public LocatedToken Create (string value, SourceFile file, int row, int column)
130 // TODO: I am not very happy about the logic but it's the best
131 // what I could come up with for now.
132 // Ideally we should be using just tiny buffer (256 elements) which
133 // is enough to hold all details for currect stack and recycle elements
134 // poped from the stack but there is a trick needed to recycle
138 if (pos >= buffer.Length) {
139 entry = new LocatedToken ();
143 entry = new LocatedToken ();
152 entry.column = column;
157 // Used for token not required by expression evaluator
159 [Conditional ("FULL_AST")]
160 public void CreateOptional (SourceFile file, int row, int col, ref object token)
162 token = Create (file, row, col);
166 public enum PreprocessorDirective
172 If = 3 | RequiresArgument,
174 Elif = 5 | RequiresArgument,
176 Define = 7 | RequiresArgument,
177 Undef = 8 | RequiresArgument,
180 Pragma = 11 | CustomArgumentsParsing,
181 Line = 12 | CustomArgumentsParsing,
183 CustomArgumentsParsing = 1 << 10,
184 RequiresArgument = 1 << 11
187 readonly SeekableStreamReader reader;
188 readonly CompilationSourceFile source_file;
189 readonly CompilerContext context;
191 SourceFile current_source;
192 Location hidden_block_start;
198 readonly int tab_size;
199 bool handle_get_set = false;
200 bool handle_remove_add = false;
201 bool handle_where = false;
202 bool handle_typeof = false;
203 bool lambda_arguments_parsing;
204 List<Location> escaped_identifiers;
205 int parsing_generic_less_than;
206 readonly bool doc_processing;
207 readonly LocatedTokenBuffer ltb;
210 // Used mainly for parser optimizations. Some expressions for instance
211 // can appear only in block (including initializer, base initializer)
214 public int parsing_block;
215 internal bool query_parsing;
218 // When parsing type only, useful for ambiguous nullable types
220 public int parsing_type;
223 // Set when parsing generic declaration (type or method header)
225 public bool parsing_generic_declaration;
226 public bool parsing_generic_declaration_doc;
229 // The value indicates that we have not reach any declaration or
232 public int parsing_declaration;
234 public bool parsing_attribute_section;
236 public bool parsing_modifiers;
239 // The special characters to inject on streams to run the unit parser
240 // in the special expression mode. Using private characters from
241 // Plane Sixteen (U+100000 to U+10FFFD)
243 // This character is only tested just before the tokenizer is about to report
244 // an error; So on the regular operation mode, this addition will have no
245 // impact on the tokenizer's performance.
248 public const int EvalStatementParserCharacter = 0x100000;
249 public const int EvalCompilationUnitParserCharacter = 0x100001;
250 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
251 public const int DocumentationXref = 0x100003;
254 // XML documentation buffer. The save point is used to divide
255 // comments on types and comments on members.
257 StringBuilder xml_comment_buffer;
260 // See comment on XmlCommentState enumeration.
262 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
265 // Whether tokens have been seen on this line
267 bool tokens_seen = false;
270 // Set to true once the GENERATE_COMPLETION token has bee
271 // returned. This helps produce one GENERATE_COMPLETION,
272 // as many COMPLETE_COMPLETION as necessary to complete the
273 // AST tree and one final EOF.
278 // Whether a token has been seen on the file
279 // This is needed because `define' is not allowed to be used
280 // after a token has been seen.
287 static readonly KeywordEntry<int>[][] keywords;
288 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
289 static readonly HashSet<string> keyword_strings;
290 static readonly NumberStyles styles;
291 static readonly NumberFormatInfo csharp_format_info;
294 static readonly char[] pragma_warning = "warning".ToCharArray ();
295 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
296 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
297 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
298 static readonly char[] line_hidden = "hidden".ToCharArray ();
299 static readonly char[] line_default = "default".ToCharArray ();
301 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
303 public bool PropertyParsing {
304 get { return handle_get_set; }
305 set { handle_get_set = value; }
308 public bool EventParsing {
309 get { return handle_remove_add; }
310 set { handle_remove_add = value; }
313 public bool ConstraintsParsing {
314 get { return handle_where; }
315 set { handle_where = value; }
318 public bool TypeOfParsing {
319 get { return handle_typeof; }
320 set { handle_typeof = value; }
323 public XmlCommentState doc_state {
324 get { return xml_doc_state; }
326 if (value == XmlCommentState.Allowed) {
327 check_incorrect_doc_comment ();
328 reset_doc_comment ();
330 xml_doc_state = value;
335 // This is used to trigger completion generation on the parser
336 public bool CompleteOnEOF;
338 void AddEscapedIdentifier (Location loc)
340 if (escaped_identifiers == null)
341 escaped_identifiers = new List<Location> ();
343 escaped_identifiers.Add (loc);
346 public bool IsEscapedIdentifier (ATypeNameExpression name)
348 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
352 // Values for the associated token returned
354 internal int putback_char; // Used by repl only
360 const int TAKING = 1;
361 const int ELSE_SEEN = 4;
362 const int PARENT_TAKING = 8;
363 const int REGION = 16;
366 // pre-processor if stack state:
370 public const int MaxIdentifierLength = 512;
371 public const int MaxNumberLength = 512;
373 readonly char[] id_builder;
374 readonly Dictionary<char[], string>[] identifiers;
375 readonly char[] number_builder;
378 char[] value_builder = new char[64];
387 // This is used when the tokenizer needs to save
388 // the current position as it needs to do some parsing
389 // on its own to deamiguate a token in behalf of the
392 Stack<Position> position_stack = new Stack<Position> (2);
399 public Location hidden;
400 public int putback_char;
401 public int previous_col;
402 public Stack<int> ifstack;
403 public int parsing_generic_less_than;
404 public int current_token;
407 public Position (Tokenizer t)
409 position = t.reader.Position;
411 ref_line = t.ref_line;
413 hidden = t.hidden_block_start;
414 putback_char = t.putback_char;
415 previous_col = t.previous_col;
416 if (t.ifstack != null && t.ifstack.Count != 0) {
417 // There is no simple way to clone Stack<T> all
418 // methods reverse the order
419 var clone = t.ifstack.ToArray ();
420 Array.Reverse (clone);
421 ifstack = new Stack<int> (clone);
423 parsing_generic_less_than = t.parsing_generic_less_than;
424 current_token = t.current_token;
429 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session)
431 this.source_file = file;
432 this.context = file.Compiler;
433 this.current_source = file.SourceFile;
434 this.identifiers = session.Identifiers;
435 this.id_builder = session.IDBuilder;
436 this.number_builder = session.NumberBuilder;
437 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
443 xml_comment_buffer = new StringBuilder ();
444 doc_processing = context.Settings.DocumentationFile != null;
446 tab_size = context.Settings.TabSize;
449 public void PushPosition ()
451 position_stack.Push (new Position (this));
454 public void PopPosition ()
456 Position p = position_stack.Pop ();
458 reader.Position = p.position;
459 ref_line = p.ref_line;
462 hidden_block_start = p.hidden;
463 putback_char = p.putback_char;
464 previous_col = p.previous_col;
466 parsing_generic_less_than = p.parsing_generic_less_than;
467 current_token = p.current_token;
471 // Do not reset the position, ignore it.
472 public void DiscardPosition ()
474 position_stack.Pop ();
477 static void AddKeyword (string kw, int token)
479 keyword_strings.Add (kw);
481 AddKeyword (keywords, kw, token);
484 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
486 AddKeyword (keywords_preprocessor, kw, directive);
489 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
491 int length = kw.Length;
492 if (keywords[length] == null) {
493 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
496 int char_index = kw[0] - '_';
497 var kwe = keywords[length][char_index];
499 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
503 while (kwe.Next != null) {
507 kwe.Next = new KeywordEntry<T> (kw, token);
515 keyword_strings = new HashSet<string> ();
517 // 11 is the length of the longest keyword for now
518 keywords = new KeywordEntry<int>[11][];
520 AddKeyword ("__arglist", Token.ARGLIST);
521 AddKeyword ("__makeref", Token.MAKEREF);
522 AddKeyword ("__reftype", Token.REFTYPE);
523 AddKeyword ("__refvalue", Token.REFVALUE);
524 AddKeyword ("abstract", Token.ABSTRACT);
525 AddKeyword ("as", Token.AS);
526 AddKeyword ("add", Token.ADD);
527 AddKeyword ("base", Token.BASE);
528 AddKeyword ("bool", Token.BOOL);
529 AddKeyword ("break", Token.BREAK);
530 AddKeyword ("byte", Token.BYTE);
531 AddKeyword ("case", Token.CASE);
532 AddKeyword ("catch", Token.CATCH);
533 AddKeyword ("char", Token.CHAR);
534 AddKeyword ("checked", Token.CHECKED);
535 AddKeyword ("class", Token.CLASS);
536 AddKeyword ("const", Token.CONST);
537 AddKeyword ("continue", Token.CONTINUE);
538 AddKeyword ("decimal", Token.DECIMAL);
539 AddKeyword ("default", Token.DEFAULT);
540 AddKeyword ("delegate", Token.DELEGATE);
541 AddKeyword ("do", Token.DO);
542 AddKeyword ("double", Token.DOUBLE);
543 AddKeyword ("else", Token.ELSE);
544 AddKeyword ("enum", Token.ENUM);
545 AddKeyword ("event", Token.EVENT);
546 AddKeyword ("explicit", Token.EXPLICIT);
547 AddKeyword ("extern", Token.EXTERN);
548 AddKeyword ("false", Token.FALSE);
549 AddKeyword ("finally", Token.FINALLY);
550 AddKeyword ("fixed", Token.FIXED);
551 AddKeyword ("float", Token.FLOAT);
552 AddKeyword ("for", Token.FOR);
553 AddKeyword ("foreach", Token.FOREACH);
554 AddKeyword ("goto", Token.GOTO);
555 AddKeyword ("get", Token.GET);
556 AddKeyword ("if", Token.IF);
557 AddKeyword ("implicit", Token.IMPLICIT);
558 AddKeyword ("in", Token.IN);
559 AddKeyword ("int", Token.INT);
560 AddKeyword ("interface", Token.INTERFACE);
561 AddKeyword ("internal", Token.INTERNAL);
562 AddKeyword ("is", Token.IS);
563 AddKeyword ("lock", Token.LOCK);
564 AddKeyword ("long", Token.LONG);
565 AddKeyword ("namespace", Token.NAMESPACE);
566 AddKeyword ("new", Token.NEW);
567 AddKeyword ("null", Token.NULL);
568 AddKeyword ("object", Token.OBJECT);
569 AddKeyword ("operator", Token.OPERATOR);
570 AddKeyword ("out", Token.OUT);
571 AddKeyword ("override", Token.OVERRIDE);
572 AddKeyword ("params", Token.PARAMS);
573 AddKeyword ("private", Token.PRIVATE);
574 AddKeyword ("protected", Token.PROTECTED);
575 AddKeyword ("public", Token.PUBLIC);
576 AddKeyword ("readonly", Token.READONLY);
577 AddKeyword ("ref", Token.REF);
578 AddKeyword ("remove", Token.REMOVE);
579 AddKeyword ("return", Token.RETURN);
580 AddKeyword ("sbyte", Token.SBYTE);
581 AddKeyword ("sealed", Token.SEALED);
582 AddKeyword ("set", Token.SET);
583 AddKeyword ("short", Token.SHORT);
584 AddKeyword ("sizeof", Token.SIZEOF);
585 AddKeyword ("stackalloc", Token.STACKALLOC);
586 AddKeyword ("static", Token.STATIC);
587 AddKeyword ("string", Token.STRING);
588 AddKeyword ("struct", Token.STRUCT);
589 AddKeyword ("switch", Token.SWITCH);
590 AddKeyword ("this", Token.THIS);
591 AddKeyword ("throw", Token.THROW);
592 AddKeyword ("true", Token.TRUE);
593 AddKeyword ("try", Token.TRY);
594 AddKeyword ("typeof", Token.TYPEOF);
595 AddKeyword ("uint", Token.UINT);
596 AddKeyword ("ulong", Token.ULONG);
597 AddKeyword ("unchecked", Token.UNCHECKED);
598 AddKeyword ("unsafe", Token.UNSAFE);
599 AddKeyword ("ushort", Token.USHORT);
600 AddKeyword ("using", Token.USING);
601 AddKeyword ("virtual", Token.VIRTUAL);
602 AddKeyword ("void", Token.VOID);
603 AddKeyword ("volatile", Token.VOLATILE);
604 AddKeyword ("while", Token.WHILE);
605 AddKeyword ("partial", Token.PARTIAL);
606 AddKeyword ("where", Token.WHERE);
609 AddKeyword ("from", Token.FROM);
610 AddKeyword ("join", Token.JOIN);
611 AddKeyword ("on", Token.ON);
612 AddKeyword ("equals", Token.EQUALS);
613 AddKeyword ("select", Token.SELECT);
614 AddKeyword ("group", Token.GROUP);
615 AddKeyword ("by", Token.BY);
616 AddKeyword ("let", Token.LET);
617 AddKeyword ("orderby", Token.ORDERBY);
618 AddKeyword ("ascending", Token.ASCENDING);
619 AddKeyword ("descending", Token.DESCENDING);
620 AddKeyword ("into", Token.INTO);
622 // Contextual async keywords
623 AddKeyword ("async", Token.ASYNC);
624 AddKeyword ("await", Token.AWAIT);
626 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
628 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
629 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
630 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
631 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
632 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
633 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
634 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
635 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
636 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
637 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
638 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
639 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
641 csharp_format_info = NumberFormatInfo.InvariantInfo;
642 styles = NumberStyles.Float;
645 int GetKeyword (char[] id, int id_len)
648 // Keywords are stored in an array of arrays grouped by their
649 // length and then by the first character
651 if (id_len >= keywords.Length || keywords [id_len] == null)
654 int first_index = id [0] - '_';
655 if (first_index > 'z' - '_')
658 var kwe = keywords [id_len] [first_index];
665 for (int i = 1; i < id_len; ++i) {
666 if (id [i] != kwe.Value [i]) {
672 } while (res == 0 && kwe != null);
686 if (!handle_remove_add)
690 if (parsing_declaration == 0)
691 res = Token.EXTERN_ALIAS;
694 if (peek_token () == Token.COLON) {
696 res = Token.DEFAULT_COLON;
700 if (!handle_where && !query_parsing)
705 // A query expression is any expression that starts with `from identifier'
706 // followed by any token except ; , =
708 if (!query_parsing) {
709 if (lambda_arguments_parsing) {
715 // HACK: to disable generics micro-parser, because PushPosition does not
716 // store identifiers array
717 parsing_generic_less_than = 1;
719 case Token.IDENTIFIER:
731 next_token = xtoken ();
732 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
735 res = Token.FROM_FIRST;
736 query_parsing = true;
737 if (context.Settings.Version <= LanguageVersion.ISO_2)
738 Report.FeatureIsNotAvailable (context, Location, "query expressions");
741 Expression.Error_VoidInvalidInTheContext (Location, Report);
745 // HACK: A token is not a keyword so we need to restore identifiers buffer
746 // which has been overwritten before we grabbed the identifier
747 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
761 case Token.ASCENDING:
762 case Token.DESCENDING:
769 case Token.NAMESPACE:
770 // TODO: some explanation needed
771 check_incorrect_doc_comment ();
775 if (parsing_block > 0) {
780 // Save current position and parse next token.
783 next_token = token ();
784 bool ok = (next_token == Token.CLASS) ||
785 (next_token == Token.STRUCT) ||
786 (next_token == Token.INTERFACE) ||
787 (next_token == Token.VOID);
792 if (next_token == Token.VOID) {
793 if (context.Settings.Version <= LanguageVersion.ISO_2)
794 Report.FeatureIsNotAvailable (context, Location, "partial methods");
795 } else if (context.Settings.Version == LanguageVersion.ISO_1)
796 Report.FeatureIsNotAvailable (context, Location, "partial types");
801 if (next_token < Token.LAST_KEYWORD) {
802 Report.Error (267, Location,
803 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
811 if (parsing_modifiers) {
813 // Skip attributes section or constructor called async
815 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
820 } else if (parsing_block > 0) {
821 switch (peek_token ()) {
823 case Token.OPEN_PARENS_LAMBDA:
826 case Token.IDENTIFIER:
829 if (xtoken () != Token.ARROW)
835 // peek_token could overwrite id_buffer
836 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
844 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
845 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
851 if (parsing_block == 0)
861 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
864 // Keywords are stored in an array of arrays grouped by their
865 // length and then by the first character
867 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
868 return PreprocessorDirective.Invalid;
870 int first_index = id[0] - '_';
871 if (first_index > 'z' - '_')
872 return PreprocessorDirective.Invalid;
874 var kwe = keywords_preprocessor[id_len][first_index];
876 return PreprocessorDirective.Invalid;
878 PreprocessorDirective res = PreprocessorDirective.Invalid;
881 for (int i = 1; i < id_len; ++i) {
882 if (id[i] != kwe.Value[i]) {
888 } while (res == PreprocessorDirective.Invalid && kwe != null);
893 public Location Location {
895 return new Location (current_source, ref_line, col);
899 static bool is_identifier_start_character (int c)
901 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
904 static bool is_identifier_part_character (char c)
906 if (c >= 'a' && c <= 'z')
909 if (c >= 'A' && c <= 'Z')
912 if (c == '_' || (c >= '0' && c <= '9'))
918 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
921 public static bool IsKeyword (string s)
923 return keyword_strings.Contains (s);
927 // Open parens micro parser. Detects both lambda and cast ambiguity.
929 int TokenizeOpenParens ()
934 int bracket_level = 0;
935 bool is_type = false;
936 bool can_be_type = false;
939 ptoken = current_token;
942 switch (current_token) {
943 case Token.CLOSE_PARENS:
947 // Expression inside parens is lambda, (int i) =>
949 if (current_token == Token.ARROW)
950 return Token.OPEN_PARENS_LAMBDA;
953 // Expression inside parens is single type, (int[])
956 return Token.OPEN_PARENS_CAST;
959 // Expression is possible cast, look at next token, (T)null
962 switch (current_token) {
963 case Token.OPEN_PARENS:
966 case Token.IDENTIFIER:
980 case Token.UNCHECKED:
986 // These can be part of a member access
1000 return Token.OPEN_PARENS_CAST;
1003 return Token.OPEN_PARENS;
1006 case Token.DOUBLE_COLON:
1007 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1012 case Token.IDENTIFIER:
1015 if (bracket_level == 0) {
1021 case Token.OP_GENERICS_LT:
1023 case Token.DOUBLE_COLON:
1025 if (bracket_level == 0)
1029 can_be_type = is_type = false;
1049 if (bracket_level == 0)
1054 if (bracket_level == 0) {
1055 bracket_level = 100;
1056 can_be_type = is_type = false;
1060 case Token.OP_GENERICS_LT:
1061 case Token.OPEN_BRACKET:
1062 if (bracket_level++ == 0)
1066 case Token.OP_GENERICS_GT:
1067 case Token.CLOSE_BRACKET:
1071 case Token.INTERR_NULLABLE:
1073 if (bracket_level == 0)
1079 can_be_type = is_type = false;
1083 return Token.OPEN_PARENS;
1088 public static bool IsValidIdentifier (string s)
1090 if (s == null || s.Length == 0)
1093 if (!is_identifier_start_character (s [0]))
1096 for (int i = 1; i < s.Length; i ++)
1097 if (! is_identifier_part_character (s [i]))
1103 bool parse_less_than ()
1106 int the_token = token ();
1107 if (the_token == Token.OPEN_BRACKET) {
1109 the_token = token ();
1110 if (the_token == Token.EOF)
1113 if (the_token == Token.CLOSE_BRACKET)
1116 the_token = token ();
1117 } else if (the_token == Token.IN || the_token == Token.OUT) {
1118 the_token = token ();
1120 switch (the_token) {
1121 case Token.IDENTIFIER:
1139 case Token.OP_GENERICS_GT:
1148 the_token = token ();
1150 if (the_token == Token.OP_GENERICS_GT)
1152 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1154 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1156 else if (the_token == Token.OP_GENERICS_LT) {
1157 if (!parse_less_than ())
1160 } else if (the_token == Token.OPEN_BRACKET) {
1162 the_token = token ();
1163 if (the_token == Token.CLOSE_BRACKET)
1165 else if (the_token == Token.COMMA)
1166 goto rank_specifiers;
1173 bool parse_generic_dimension (out int dimension)
1178 int the_token = token ();
1179 if (the_token == Token.OP_GENERICS_GT)
1181 else if (the_token == Token.COMMA) {
1189 public int peek_token ()
1194 the_token = token ();
1201 // Tonizes `?' using custom disambiguous rules to return one
1202 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1204 // Tricky expression look like:
1206 // Foo ? a = x ? b : c;
1208 int TokenizePossibleNullableType ()
1210 if (parsing_block == 0 || parsing_type > 0)
1211 return Token.INTERR_NULLABLE;
1213 int d = peek_char ();
1216 return Token.OP_COALESCING;
1219 switch (current_token) {
1220 case Token.CLOSE_PARENS:
1225 return Token.INTERR;
1229 if (d == ',' || d == ';' || d == '>')
1230 return Token.INTERR_NULLABLE;
1231 if (d == '*' || (d >= '0' && d <= '9'))
1232 return Token.INTERR;
1236 current_token = Token.NONE;
1238 switch (xtoken ()) {
1245 next_token = Token.INTERR;
1248 case Token.SEMICOLON:
1250 case Token.CLOSE_PARENS:
1251 case Token.OPEN_BRACKET:
1252 case Token.OP_GENERICS_GT:
1254 next_token = Token.INTERR_NULLABLE;
1262 if (next_token == -1) {
1263 switch (xtoken ()) {
1265 case Token.SEMICOLON:
1266 case Token.OPEN_BRACE:
1267 case Token.CLOSE_PARENS:
1269 next_token = Token.INTERR_NULLABLE;
1273 next_token = Token.INTERR;
1282 // All shorcuts failed, do it hard way
1284 while ((ntoken = xtoken ()) != Token.EOF) {
1285 if (ntoken == Token.OPEN_BRACE) {
1290 if (ntoken == Token.CLOSE_BRACE) {
1298 if (ntoken == Token.SEMICOLON)
1301 if (ntoken == Token.COLON) {
1302 if (++colons == interrs)
1307 if (ntoken == Token.INTERR) {
1313 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1322 bool decimal_digits (int c)
1325 bool seen_digits = false;
1328 if (number_pos == MaxNumberLength)
1329 Error_NumericConstantTooLong ();
1330 number_builder [number_pos++] = (char) c;
1334 // We use peek_char2, because decimal_digits needs to do a
1335 // 2-character look-ahead (5.ToString for example).
1337 while ((d = peek_char2 ()) != -1){
1338 if (d >= '0' && d <= '9'){
1339 if (number_pos == MaxNumberLength)
1340 Error_NumericConstantTooLong ();
1341 number_builder [number_pos++] = (char) d;
1351 static bool is_hex (int e)
1353 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1356 static TypeCode real_type_suffix (int c)
1360 return TypeCode.Single;
1362 return TypeCode.Double;
1364 return TypeCode.Decimal;
1366 return TypeCode.Empty;
1370 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1372 bool is_unsigned = false;
1373 bool is_long = false;
1376 bool scanning = true;
1389 // if we have not seen anything in between
1390 // report this error
1392 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1412 if (is_long && is_unsigned){
1413 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1417 // uint if possible, or ulong else.
1419 if ((ul & 0xffffffff00000000) == 0)
1420 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1422 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1423 } else if (is_long){
1424 // long if possible, ulong otherwise
1425 if ((ul & 0x8000000000000000) != 0)
1426 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1428 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1430 // int, uint, long or ulong in that order
1431 if ((ul & 0xffffffff00000000) == 0){
1432 uint ui = (uint) ul;
1434 if ((ui & 0x80000000) != 0)
1435 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1437 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1439 if ((ul & 0x8000000000000000) != 0)
1440 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1442 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1448 // given `c' as the next char in the input decide whether
1449 // we need to convert to a special type, and then choose
1450 // the best representation for the integer
1452 ILiteralConstant adjust_int (int c, Location loc)
1455 if (number_pos > 9){
1456 ulong ul = (uint) (number_builder [0] - '0');
1458 for (int i = 1; i < number_pos; i++){
1459 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1462 return integer_type_suffix (ul, c, loc);
1464 uint ui = (uint) (number_builder [0] - '0');
1466 for (int i = 1; i < number_pos; i++){
1467 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1470 return integer_type_suffix (ui, c, loc);
1472 } catch (OverflowException) {
1473 Error_NumericConstantTooLong ();
1474 return new IntLiteral (context.BuiltinTypes, 0, loc);
1476 catch (FormatException) {
1477 Report.Error (1013, Location, "Invalid number");
1478 return new IntLiteral (context.BuiltinTypes, 0, loc);
1482 ILiteralConstant adjust_real (TypeCode t, Location loc)
1484 string s = new string (number_builder, 0, number_pos);
1485 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1488 case TypeCode.Decimal:
1490 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1491 } catch (OverflowException) {
1492 Report.Error (594, Location, error_details, "decimal");
1493 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1495 case TypeCode.Single:
1497 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1498 } catch (OverflowException) {
1499 Report.Error (594, Location, error_details, "float");
1500 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1504 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1505 } catch (OverflowException) {
1506 Report.Error (594, loc, error_details, "double");
1507 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1512 ILiteralConstant handle_hex (Location loc)
1518 while ((d = peek_char ()) != -1){
1520 number_builder [number_pos++] = (char) d;
1526 string s = new String (number_builder, 0, number_pos);
1529 if (number_pos <= 8)
1530 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1532 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1534 return integer_type_suffix (ul, peek_char (), loc);
1535 } catch (OverflowException){
1536 Error_NumericConstantTooLong ();
1537 return new IntLiteral (context.BuiltinTypes, 0, loc);
1539 catch (FormatException) {
1540 Report.Error (1013, Location, "Invalid number");
1541 return new IntLiteral (context.BuiltinTypes, 0, loc);
1546 // Invoked if we know we have .digits or digits
1548 int is_number (int c)
1550 ILiteralConstant res;
1553 int read_start = reader.Position - 1;
1556 // Caller did peek_char
1564 if (c >= '0' && c <= '9'){
1566 int peek = peek_char ();
1568 if (peek == 'x' || peek == 'X') {
1569 val = res = handle_hex (loc);
1571 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1574 return Token.LITERAL;
1582 // We need to handle the case of
1583 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1585 bool is_real = false;
1587 if (decimal_digits ('.')){
1593 val = res = adjust_int (-1, loc);
1596 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1598 return Token.LITERAL;
1602 if (c == 'e' || c == 'E'){
1604 if (number_pos == MaxNumberLength)
1605 Error_NumericConstantTooLong ();
1606 number_builder [number_pos++] = (char) c;
1610 if (number_pos == MaxNumberLength)
1611 Error_NumericConstantTooLong ();
1612 number_builder [number_pos++] = '+';
1614 } else if (c == '-') {
1615 if (number_pos == MaxNumberLength)
1616 Error_NumericConstantTooLong ();
1617 number_builder [number_pos++] = '-';
1620 if (number_pos == MaxNumberLength)
1621 Error_NumericConstantTooLong ();
1622 number_builder [number_pos++] = '+';
1629 var type = real_type_suffix (c);
1630 if (type == TypeCode.Empty && !is_real) {
1632 res = adjust_int (c, loc);
1636 if (type == TypeCode.Empty) {
1640 res = adjust_real (type, loc);
1646 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1647 if (chars[chars.Length - 1] == '\r')
1648 Array.Resize (ref chars, chars.Length - 1);
1649 res.ParsedValue = chars;
1652 return Token.LITERAL;
1656 // Accepts exactly count (4 or 8) hex, no more no less
1658 int getHex (int count, out int surrogate, out bool error)
1663 int top = count != -1 ? count : 4;
1668 for (i = 0; i < top; i++){
1671 if (c >= '0' && c <= '9')
1672 c = (int) c - (int) '0';
1673 else if (c >= 'A' && c <= 'F')
1674 c = (int) c - (int) 'A' + 10;
1675 else if (c >= 'a' && c <= 'f')
1676 c = (int) c - (int) 'a' + 10;
1682 total = (total * 16) + c;
1684 int p = peek_char ();
1687 if (!is_hex ((char)p))
1693 if (total > 0x0010FFFF) {
1698 if (total >= 0x00010000) {
1699 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1700 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1707 int escape (int c, out int surrogate)
1743 v = getHex (-1, out surrogate, out error);
1749 return EscapeUnicode (d, out surrogate);
1752 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1761 int EscapeUnicode (int ch, out int surrogate)
1765 ch = getHex (8, out surrogate, out error);
1767 ch = getHex (4, out surrogate, out error);
1771 Report.Error (1009, Location, "Unrecognized escape sequence");
1779 if (putback_char != -1) {
1787 if (peek_char () == '\n') {
1793 } else if (x == '\n') {
1801 void advance_line ()
1811 if (putback_char == -1)
1812 putback_char = reader.Read ();
1813 return putback_char;
1818 if (putback_char != -1)
1819 return putback_char;
1820 return reader.Peek ();
1823 public void putback (int c)
1825 if (putback_char != -1) {
1826 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
1829 if (c == '\n' || col == 0) {
1830 // It won't happen though.
1840 public bool advance ()
1842 return peek_char () != -1 || CompleteOnEOF;
1845 public Object Value {
1851 public Object value ()
1858 current_token = xtoken ();
1859 return current_token;
1862 int TokenizePreprocessorIdentifier (out int c)
1864 // skip over white space
1867 } while (c == ' ' || c == '\t');
1871 while (c != -1 && c >= 'a' && c <= 'z') {
1872 id_builder[pos++] = (char) c;
1875 int peek = peek_char ();
1876 if (peek == 'U' || peek == 'u') {
1878 c = EscapeUnicode (c, out surrogate);
1879 if (surrogate != 0) {
1880 if (is_identifier_part_character ((char) c)) {
1881 id_builder[pos++] = (char) c;
1892 PreprocessorDirective get_cmd_arg (out string arg)
1896 tokens_seen = false;
1899 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1901 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1904 // skip over white space
1905 while (c == ' ' || c == '\t')
1908 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1911 while (c != -1 && c != '\n') {
1912 if (c == '\\' && has_identifier_argument >= 0) {
1913 if (has_identifier_argument != 0) {
1914 has_identifier_argument = 1;
1916 int peek = peek_char ();
1917 if (peek == 'U' || peek == 'u') {
1919 c = EscapeUnicode (c, out surrogate);
1920 if (surrogate != 0) {
1921 if (is_identifier_part_character ((char) c)) {
1922 if (pos == value_builder.Length)
1923 Array.Resize (ref value_builder, pos * 2);
1925 value_builder[pos++] = (char) c;
1931 has_identifier_argument = -1;
1933 } else if (c == '/' && peek_char () == '/') {
1935 // Eat single-line comments
1940 } while (c != -1 && c != '\n');
1945 if (pos == value_builder.Length)
1946 Array.Resize (ref value_builder, pos * 2);
1948 value_builder[pos++] = (char) c;
1953 if (pos > MaxIdentifierLength)
1954 arg = new string (value_builder, 0, pos);
1956 arg = InternIdentifier (value_builder, pos);
1958 // Eat any trailing whitespaces
1959 arg = arg.Trim (simple_whitespaces);
1966 // Handles the #line directive
1968 bool PreProcessLine ()
1970 Location loc = Location;
1974 int length = TokenizePreprocessorIdentifier (out c);
1975 if (length == line_default.Length) {
1976 if (!IsTokenIdentifierEqual (line_default))
1979 current_source = source_file.SourceFile;
1980 if (!hidden_block_start.IsNull) {
1981 current_source.RegisterHiddenScope (hidden_block_start, loc);
1982 hidden_block_start = Location.Null;
1989 if (length == line_hidden.Length) {
1990 if (!IsTokenIdentifierEqual (line_hidden))
1993 if (hidden_block_start.IsNull)
1994 hidden_block_start = loc;
1999 if (length != 0 || c < '0' || c > '9') {
2001 // Eat any remaining characters to continue parsing on next line
2003 while (c != -1 && c != '\n') {
2010 int new_line = TokenizeNumber (c);
2013 // Eat any remaining characters to continue parsing on next line
2015 while (c != -1 && c != '\n') {
2019 return new_line != 0;
2024 // skip over white space
2027 } while (c == ' ' || c == '\t');
2028 } else if (c == '"') {
2032 if (c != '\n' && c != '/' && c != '"') {
2034 // Eat any remaining characters to continue parsing on next line
2036 while (c != -1 && c != '\n') {
2040 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2044 string new_file_name = null;
2046 new_file_name = TokenizeFileName (ref c);
2048 // skip over white space
2049 while (c == ' ' || c == '\t') {
2055 } else if (c == '/') {
2056 ReadSingleLineComment ();
2059 // Eat any remaining characters to continue parsing on next line
2061 while (c != -1 && c != '\n') {
2065 Error_EndLineExpected ();
2069 if (new_file_name != null) {
2070 current_source = context.LookupFile (source_file, new_file_name);
2071 source_file.AddIncludeFile (current_source);
2074 if (!hidden_block_start.IsNull) {
2075 current_source.RegisterHiddenScope (hidden_block_start, loc);
2076 hidden_block_start = Location.Null;
2079 ref_line = new_line;
2084 // Handles #define and #undef
2086 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2088 if (ident.Length == 0 || ident == "true" || ident == "false"){
2089 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2093 if (ident.IndexOfAny (simple_whitespaces) != -1){
2094 Error_EndLineExpected ();
2098 if (!is_identifier_start_character (ident [0]))
2099 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2101 foreach (char c in ident.Substring (1)){
2102 if (!is_identifier_part_character (c)){
2103 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2108 if (!caller_is_taking)
2115 if (context.Settings.IsConditionalSymbolDefined (ident))
2118 source_file.AddDefine (ident);
2123 source_file.AddUndefine (ident);
2127 byte read_hex (out bool error)
2130 int c = get_char ();
2132 if ((c >= '0') && (c <= '9'))
2133 total = (int) c - (int) '0';
2134 else if ((c >= 'A') && (c <= 'F'))
2135 total = (int) c - (int) 'A' + 10;
2136 else if ((c >= 'a') && (c <= 'f'))
2137 total = (int) c - (int) 'a' + 10;
2146 if ((c >= '0') && (c <= '9'))
2147 total += (int) c - (int) '0';
2148 else if ((c >= 'A') && (c <= 'F'))
2149 total += (int) c - (int) 'A' + 10;
2150 else if ((c >= 'a') && (c <= 'f'))
2151 total += (int) c - (int) 'a' + 10;
2158 return (byte) total;
2162 // Parses #pragma checksum
2164 bool ParsePragmaChecksum ()
2167 // The syntax is ` "foo.txt" "{guid}" "hash"'
2169 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2171 int c = get_char ();
2176 string file_name = TokenizeFileName (ref c);
2178 // TODO: Any white-spaces count
2182 SourceFile file = context.LookupFile (source_file, file_name);
2184 if (get_char () != '"' || get_char () != '{')
2188 byte[] guid_bytes = new byte [16];
2191 for (; i < 4; i++) {
2192 guid_bytes [i] = read_hex (out error);
2197 if (get_char () != '-')
2200 for (; i < 10; i++) {
2201 guid_bytes [i] = read_hex (out error);
2205 guid_bytes [i++] = read_hex (out error);
2209 if (get_char () != '-')
2213 for (; i < 16; i++) {
2214 guid_bytes [i] = read_hex (out error);
2219 if (get_char () != '}' || get_char () != '"')
2222 // TODO: Any white-spaces count
2227 if (get_char () != '"')
2230 // Any length of checksum
2231 List<byte> checksum_bytes = new List<byte> (16);
2233 var checksum_location = Location;
2235 while (c != '"' && c != -1) {
2236 checksum_bytes.Add (read_hex (out error));
2244 ReadSingleLineComment ();
2245 } else if (get_char () != '"') {
2249 if (context.Settings.GenerateDebugInfo) {
2250 var chsum = checksum_bytes.ToArray ();
2252 if (file.HasChecksum) {
2253 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2254 // TODO: Report.SymbolRelatedToPreviousError
2255 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2259 file.SetChecksum (guid_bytes, chsum);
2260 current_source.AutoGenerated = true;
2266 bool IsTokenIdentifierEqual (char[] identifier)
2268 for (int i = 0; i < identifier.Length; ++i) {
2269 if (identifier[i] != id_builder[i])
2276 int TokenizeNumber (int value)
2280 decimal_digits (value);
2281 uint ui = (uint) (number_builder[0] - '0');
2284 for (int i = 1; i < number_pos; i++) {
2285 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2289 } catch (OverflowException) {
2290 Error_NumericConstantTooLong ();
2295 string TokenizeFileName (ref int c)
2297 var string_builder = new StringBuilder ();
2298 while (c != -1 && c != '\n') {
2305 string_builder.Append ((char) c);
2308 if (string_builder.Length == 0) {
2309 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2313 return string_builder.ToString ();
2316 int TokenizePragmaNumber (ref int c)
2322 if (c >= '0' && c <= '9') {
2323 number = TokenizeNumber (c);
2327 // skip over white space
2328 while (c == ' ' || c == '\t')
2335 // skip over white space
2336 while (c == ' ' || c == '\t')
2341 ReadSingleLineComment ();
2343 Report.Warning (1692, 1, Location, "Invalid number");
2345 // Read everything till the end of the line or file
2348 } while (c != -1 && c != '\n');
2355 void ReadSingleLineComment ()
2357 if (peek_char () != '/')
2358 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2360 // Read everything till the end of the line or file
2364 } while (c != -1 && c != '\n');
2368 /// Handles #pragma directive
2370 void ParsePragmaDirective (string arg)
2373 int length = TokenizePreprocessorIdentifier (out c);
2374 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2375 length = TokenizePreprocessorIdentifier (out c);
2378 // #pragma warning disable
2379 // #pragma warning restore
2381 if (length == pragma_warning_disable.Length) {
2382 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2383 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2384 // skip over white space
2385 while (c == ' ' || c == '\t')
2390 if (c == '\n' || c == '/') {
2392 ReadSingleLineComment ();
2395 // Disable/Restore all warnings
2398 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2400 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2404 // Disable/Restore a warning or group of warnings
2408 code = TokenizePragmaNumber (ref c);
2411 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2413 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2416 } while (code >= 0 && c != '\n' && c != -1);
2423 Report.Warning (1634, 1, Location, "Expected disable or restore");
2425 // Eat any remaining characters on the line
2426 while (c != '\n' && c != -1)
2435 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2436 if (c != ' ' || !ParsePragmaChecksum ()) {
2437 Report.Warning (1695, 1, Location,
2438 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2444 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2447 bool eval_val (string s)
2454 return source_file.IsConditionalDefined (s);
2457 bool pp_primary (ref string s)
2466 s = s.Substring (1);
2467 bool val = pp_expr (ref s, false);
2468 if (s.Length > 0 && s [0] == ')'){
2469 s = s.Substring (1);
2472 Error_InvalidDirective ();
2476 if (is_identifier_start_character (c)){
2482 if (is_identifier_part_character (c)){
2486 bool v = eval_val (s.Substring (0, j));
2487 s = s.Substring (j);
2490 bool vv = eval_val (s);
2495 Error_InvalidDirective ();
2499 bool pp_unary (ref string s)
2506 if (len > 1 && s [1] == '='){
2507 Error_InvalidDirective ();
2510 s = s.Substring (1);
2511 return ! pp_primary (ref s);
2513 return pp_primary (ref s);
2515 Error_InvalidDirective ();
2520 bool pp_eq (ref string s)
2522 bool va = pp_unary (ref s);
2528 if (len > 2 && s [1] == '='){
2529 s = s.Substring (2);
2530 return va == pp_unary (ref s);
2532 Error_InvalidDirective ();
2535 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2536 s = s.Substring (2);
2538 return va != pp_unary (ref s);
2547 bool pp_and (ref string s)
2549 bool va = pp_eq (ref s);
2555 if (len > 2 && s [1] == '&'){
2556 s = s.Substring (2);
2557 return (va & pp_and (ref s));
2559 Error_InvalidDirective ();
2568 // Evaluates an expression for `#if' or `#elif'
2570 bool pp_expr (ref string s, bool isTerm)
2572 bool va = pp_and (ref s);
2579 if (len > 2 && s [1] == '|'){
2580 s = s.Substring (2);
2581 return va | pp_expr (ref s, isTerm);
2583 Error_InvalidDirective ();
2588 Error_EndLineExpected ();
2596 bool eval (string s)
2598 bool v = pp_expr (ref s, true);
2607 void Error_NumericConstantTooLong ()
2609 Report.Error (1021, Location, "Integral constant is too large");
2612 void Error_InvalidDirective ()
2614 Report.Error (1517, Location, "Invalid preprocessor directive");
2617 void Error_UnexpectedDirective (string extra)
2621 "Unexpected processor directive ({0})", extra);
2624 void Error_TokensSeen ()
2626 Report.Error (1032, Location,
2627 "Cannot define or undefine preprocessor symbols after first token in file");
2630 void Eror_WrongPreprocessorLocation ()
2632 Report.Error (1040, Location,
2633 "Preprocessor directives must appear as the first non-whitespace character on a line");
2636 void Error_EndLineExpected ()
2638 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2642 // Raises a warning when tokenizer found documentation comment
2643 // on unexpected place
2645 void WarningMisplacedComment (Location loc)
2647 if (doc_state != XmlCommentState.Error) {
2648 doc_state = XmlCommentState.Error;
2649 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2654 // if true, then the code continues processing the code
2655 // if false, the code stays in a loop until another directive is
2657 // When caller_is_taking is false we ignore all directives except the ones
2658 // which can help us to identify where the #if block ends
2659 bool ParsePreprocessingDirective (bool caller_is_taking)
2662 bool region_directive = false;
2664 var directive = get_cmd_arg (out arg);
2667 // The first group of pre-processing instructions is always processed
2669 switch (directive) {
2670 case PreprocessorDirective.Region:
2671 region_directive = true;
2673 goto case PreprocessorDirective.If;
2675 case PreprocessorDirective.Endregion:
2676 if (ifstack == null || ifstack.Count == 0){
2677 Error_UnexpectedDirective ("no #region for this #endregion");
2680 int pop = ifstack.Pop ();
2682 if ((pop & REGION) == 0)
2683 Report.Error (1027, Location, "Expected `#endif' directive");
2685 return caller_is_taking;
2687 case PreprocessorDirective.If:
2688 if (ifstack == null)
2689 ifstack = new Stack<int> (2);
2691 int flags = region_directive ? REGION : 0;
2692 if (ifstack.Count == 0){
2693 flags |= PARENT_TAKING;
2695 int state = ifstack.Peek ();
2696 if ((state & TAKING) != 0) {
2697 flags |= PARENT_TAKING;
2701 if (eval (arg) && caller_is_taking) {
2702 ifstack.Push (flags | TAKING);
2705 ifstack.Push (flags);
2708 case PreprocessorDirective.Endif:
2709 if (ifstack == null || ifstack.Count == 0){
2710 Error_UnexpectedDirective ("no #if for this #endif");
2713 pop = ifstack.Pop ();
2715 if ((pop & REGION) != 0)
2716 Report.Error (1038, Location, "#endregion directive expected");
2718 if (arg.Length != 0) {
2719 Error_EndLineExpected ();
2722 if (ifstack.Count == 0)
2725 int state = ifstack.Peek ();
2726 return (state & TAKING) != 0;
2729 case PreprocessorDirective.Elif:
2730 if (ifstack == null || ifstack.Count == 0){
2731 Error_UnexpectedDirective ("no #if for this #elif");
2734 int state = ifstack.Pop ();
2736 if ((state & REGION) != 0) {
2737 Report.Error (1038, Location, "#endregion directive expected");
2741 if ((state & ELSE_SEEN) != 0){
2742 Error_UnexpectedDirective ("#elif not valid after #else");
2746 if ((state & TAKING) != 0) {
2751 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2752 ifstack.Push (state | TAKING);
2756 ifstack.Push (state);
2760 case PreprocessorDirective.Else:
2761 if (ifstack == null || ifstack.Count == 0){
2762 Error_UnexpectedDirective ("no #if for this #else");
2765 int state = ifstack.Peek ();
2767 if ((state & REGION) != 0) {
2768 Report.Error (1038, Location, "#endregion directive expected");
2772 if ((state & ELSE_SEEN) != 0){
2773 Error_UnexpectedDirective ("#else within #else");
2779 if (arg.Length != 0) {
2780 Error_EndLineExpected ();
2785 if ((state & PARENT_TAKING) != 0) {
2786 ret = (state & TAKING) == 0;
2794 ifstack.Push (state | ELSE_SEEN);
2798 case PreprocessorDirective.Define:
2799 if (any_token_seen){
2800 Error_TokensSeen ();
2801 return caller_is_taking;
2803 PreProcessDefinition (true, arg, caller_is_taking);
2804 return caller_is_taking;
2806 case PreprocessorDirective.Undef:
2807 if (any_token_seen){
2808 Error_TokensSeen ();
2809 return caller_is_taking;
2811 PreProcessDefinition (false, arg, caller_is_taking);
2812 return caller_is_taking;
2814 case PreprocessorDirective.Invalid:
2815 Report.Error (1024, Location, "Wrong preprocessor directive");
2820 // These are only processed if we are in a `taking' block
2822 if (!caller_is_taking)
2826 case PreprocessorDirective.Error:
2827 Report.Error (1029, Location, "#error: '{0}'", arg);
2830 case PreprocessorDirective.Warning:
2831 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2834 case PreprocessorDirective.Pragma:
2835 if (context.Settings.Version == LanguageVersion.ISO_1) {
2836 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2839 ParsePragmaDirective (arg);
2842 case PreprocessorDirective.Line:
2843 Location loc = Location;
2844 if (!PreProcessLine ())
2845 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
2847 return caller_is_taking;
2850 throw new NotImplementedException (directive.ToString ());
2853 private int consume_string (bool quoted)
2857 Location start_location = Location;
2859 start_location = start_location - 1;
2862 int reader_pos = reader.Position;
2868 if (quoted && peek_char () == '"') {
2869 if (pos == value_builder.Length)
2870 Array.Resize (ref value_builder, pos * 2);
2872 value_builder[pos++] = (char) c;
2881 s = InternIdentifier (value_builder, pos);
2883 s = new string (value_builder, 0, pos);
2885 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2888 res.ParsedValue = quoted ?
2889 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2890 reader.ReadChars (reader_pos - 1, reader.Position);
2893 return Token.LITERAL;
2898 Report.Error (1010, Location, "Newline in constant");
2899 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2900 return Token.LITERAL;
2902 } else if (c == '\\' && !quoted) {
2904 c = escape (c, out surrogate);
2907 if (surrogate != 0) {
2908 if (pos == value_builder.Length)
2909 Array.Resize (ref value_builder, pos * 2);
2911 value_builder[pos++] = (char) c;
2914 } else if (c == -1) {
2915 Report.Error (1039, Location, "Unterminated string literal");
2919 if (pos == value_builder.Length)
2920 Array.Resize (ref value_builder, pos * 2);
2922 value_builder[pos++] = (char) c;
2926 private int consume_identifier (int s)
2928 int res = consume_identifier (s, false);
2930 if (doc_state == XmlCommentState.Allowed)
2931 doc_state = XmlCommentState.NotAllowed;
2936 int consume_identifier (int c, bool quoted)
2939 // This method is very performance sensitive. It accounts
2940 // for approximately 25% of all parser time
2950 c = escape (c, out surrogate);
2951 if (surrogate != 0) {
2952 id_builder [pos++] = (char) c;
2957 id_builder [pos++] = (char) c;
2963 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2964 id_builder [pos++] = (char) c;
2971 c = escape (c, out surrogate);
2972 if (is_identifier_part_character ((char) c))
2973 id_builder[pos++] = (char) c;
2975 if (surrogate != 0) {
2981 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2982 id_builder [pos++] = (char) c;
2989 } catch (IndexOutOfRangeException) {
2990 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2998 // Optimization: avoids doing the keyword lookup
2999 // on uppercase letters
3001 if (id_builder [0] >= '_' && !quoted) {
3002 int keyword = GetKeyword (id_builder, pos);
3003 if (keyword != -1) {
3004 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3009 string s = InternIdentifier (id_builder, pos);
3010 val = ltb.Create (s, current_source, ref_line, column);
3011 if (quoted && parsing_attribute_section)
3012 AddEscapedIdentifier (((LocatedToken) val).Location);
3014 return Token.IDENTIFIER;
3017 string InternIdentifier (char[] charBuffer, int length)
3020 // Keep identifiers in an array of hashtables to avoid needless
3023 var identifiers_group = identifiers[length];
3025 if (identifiers_group != null) {
3026 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3030 // TODO: this should be number of files dependant
3031 // corlib compilation peaks at 1000 and System.Core at 150
3032 int capacity = length > 20 ? 10 : 100;
3033 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3034 identifiers[length] = identifiers_group;
3037 char[] chars = new char[length];
3038 Array.Copy (charBuffer, chars, length);
3040 s = new string (charBuffer, 0, length);
3041 identifiers_group.Add (chars, s);
3045 public int xtoken ()
3049 // Whether we have seen comments on the current line
3050 bool comments_seen = false;
3051 while ((c = get_char ()) != -1) {
3054 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3062 case 0xFEFF: // Ignore BOM anywhere in the file
3065 /* This is required for compatibility with .NET
3067 if (peek_char () == 0xBB) {
3070 if (get_char () == 0xBF)
3078 return consume_identifier (c);
3081 val = ltb.Create (current_source, ref_line, col);
3082 return Token.OPEN_BRACE;
3084 val = ltb.Create (current_source, ref_line, col);
3085 return Token.CLOSE_BRACE;
3087 // To block doccomment inside attribute declaration.
3088 if (doc_state == XmlCommentState.Allowed)
3089 doc_state = XmlCommentState.NotAllowed;
3091 val = ltb.Create (current_source, ref_line, col);
3093 if (parsing_block == 0 || lambda_arguments_parsing)
3094 return Token.OPEN_BRACKET;
3096 int next = peek_char ();
3100 return Token.OPEN_BRACKET;
3108 next = peek_token ();
3109 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3110 return Token.OPEN_BRACKET;
3112 return Token.OPEN_BRACKET_EXPR;
3114 return Token.OPEN_BRACKET_EXPR;
3117 ltb.CreateOptional (current_source, ref_line, col, ref val);
3118 return Token.CLOSE_BRACKET;
3120 val = ltb.Create (current_source, ref_line, col);
3122 // An expression versions of parens can appear in block context only
3124 if (parsing_block != 0 && !lambda_arguments_parsing) {
3127 // Optmize most common case where we know that parens
3130 switch (current_token) {
3131 case Token.IDENTIFIER:
3139 case Token.DELEGATE:
3140 case Token.OP_GENERICS_GT:
3141 return Token.OPEN_PARENS;
3144 // Optimize using peek
3145 int xx = peek_char ();
3152 return Token.OPEN_PARENS;
3155 lambda_arguments_parsing = true;
3157 d = TokenizeOpenParens ();
3159 lambda_arguments_parsing = false;
3163 return Token.OPEN_PARENS;
3165 ltb.CreateOptional (current_source, ref_line, col, ref val);
3166 return Token.CLOSE_PARENS;
3168 ltb.CreateOptional (current_source, ref_line, col, ref val);
3171 ltb.CreateOptional (current_source, ref_line, col, ref val);
3172 return Token.SEMICOLON;
3174 val = ltb.Create (current_source, ref_line, col);
3177 val = ltb.Create (current_source, ref_line, col);
3178 return TokenizePossibleNullableType ();
3180 val = ltb.Create (current_source, ref_line, col);
3181 if (parsing_generic_less_than++ > 0)
3182 return Token.OP_GENERICS_LT;
3184 return TokenizeLessThan ();
3187 val = ltb.Create (current_source, ref_line, col);
3195 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3196 parsing_generic_less_than--;
3197 return Token.OP_GENERICS_GT;
3206 return Token.OP_SHIFT_RIGHT_ASSIGN;
3208 return Token.OP_SHIFT_RIGHT;
3214 val = ltb.Create (current_source, ref_line, col);
3218 } else if (d == '=') {
3219 d = Token.OP_ADD_ASSIGN;
3227 val = ltb.Create (current_source, ref_line, col);
3231 } else if (d == '=')
3232 d = Token.OP_SUB_ASSIGN;
3242 val = ltb.Create (current_source, ref_line, col);
3243 if (peek_char () == '='){
3250 val = ltb.Create (current_source, ref_line, col);
3261 return Token.ASSIGN;
3264 val = ltb.Create (current_source, ref_line, col);
3268 return Token.OP_AND;
3272 return Token.OP_AND_ASSIGN;
3274 return Token.BITWISE_AND;
3277 val = ltb.Create (current_source, ref_line, col);
3285 return Token.OP_OR_ASSIGN;
3287 return Token.BITWISE_OR;
3290 val = ltb.Create (current_source, ref_line, col);
3291 if (peek_char () == '='){
3293 return Token.OP_MULT_ASSIGN;
3300 val = ltb.Create (current_source, ref_line, col);
3302 return Token.OP_DIV_ASSIGN;
3305 // Handle double-slash comments.
3308 if (doc_processing) {
3309 if (peek_char () == '/') {
3311 // Don't allow ////.
3312 if ((d = peek_char ()) != '/') {
3313 if (doc_state == XmlCommentState.Allowed)
3314 handle_one_line_xml_comment ();
3315 else if (doc_state == XmlCommentState.NotAllowed)
3316 WarningMisplacedComment (Location - 3);
3319 if (xml_comment_buffer.Length > 0)
3320 doc_state = XmlCommentState.NotAllowed;
3324 while ((d = get_char ()) != -1 && d != '\n');
3326 any_token_seen |= tokens_seen;
3327 tokens_seen = false;
3328 comments_seen = false;
3330 } else if (d == '*'){
3332 bool docAppend = false;
3333 if (doc_processing && peek_char () == '*') {
3335 // But when it is /**/, just do nothing.
3336 if (peek_char () == '/') {
3340 if (doc_state == XmlCommentState.Allowed)
3342 else if (doc_state == XmlCommentState.NotAllowed) {
3343 WarningMisplacedComment (Location - 2);
3347 int current_comment_start = 0;
3349 current_comment_start = xml_comment_buffer.Length;
3350 xml_comment_buffer.Append (Environment.NewLine);
3353 while ((d = get_char ()) != -1){
3354 if (d == '*' && peek_char () == '/'){
3356 comments_seen = true;
3360 xml_comment_buffer.Append ((char) d);
3363 any_token_seen |= tokens_seen;
3364 tokens_seen = false;
3366 // Reset 'comments_seen' just to be consistent.
3367 // It doesn't matter either way, here.
3369 comments_seen = false;
3373 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3376 update_formatted_doc_comment (current_comment_start);
3379 val = ltb.Create (current_source, ref_line, col);
3383 val = ltb.Create (current_source, ref_line, col);
3384 if (peek_char () == '='){
3386 return Token.OP_MOD_ASSIGN;
3388 return Token.PERCENT;
3391 val = ltb.Create (current_source, ref_line, col);
3392 if (peek_char () == '='){
3394 return Token.OP_XOR_ASSIGN;
3396 return Token.CARRET;
3399 val = ltb.Create (current_source, ref_line, col);
3400 if (peek_char () == ':') {
3402 return Token.DOUBLE_COLON;
3406 case '0': case '1': case '2': case '3': case '4':
3407 case '5': case '6': case '7': case '8': case '9':
3409 return is_number (c);
3411 case '\n': // white space
3412 any_token_seen |= tokens_seen;
3413 tokens_seen = false;
3414 comments_seen = false;
3420 if (d >= '0' && d <= '9')
3421 return is_number (c);
3423 ltb.CreateOptional (current_source, ref_line, col, ref val);
3427 if (tokens_seen || comments_seen) {
3428 Eror_WrongPreprocessorLocation ();
3432 if (ParsePreprocessingDirective (true))
3435 bool directive_expected = false;
3436 while ((c = get_char ()) != -1) {
3438 directive_expected = true;
3439 } else if (!directive_expected) {
3440 // TODO: Implement comment support for disabled code and uncomment this code
3442 // Eror_WrongPreprocessorLocation ();
3443 // return Token.ERROR;
3448 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3452 if (ParsePreprocessingDirective (false))
3455 directive_expected = false;
3459 tokens_seen = false;
3466 return consume_string (false);
3469 return TokenizeBackslash ();
3475 return consume_string (true);
3478 if (is_identifier_start_character (c)){
3479 return consume_identifier (c, true);
3482 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3485 case EvalStatementParserCharacter:
3486 return Token.EVAL_STATEMENT_PARSER;
3487 case EvalCompilationUnitParserCharacter:
3488 return Token.EVAL_COMPILATION_UNIT_PARSER;
3489 case EvalUsingDeclarationsParserCharacter:
3490 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3491 case DocumentationXref:
3492 return Token.DOC_SEE;
3495 if (is_identifier_start_character (c)) {
3497 return consume_identifier (c);
3500 if (char.IsWhiteSpace ((char) c))
3503 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3508 return Token.COMPLETE_COMPLETION;
3511 return Token.GENERATE_COMPLETION;
3518 int TokenizeBackslash ()
3521 int read_start = reader.Position;
3523 Location start_location = Location;
3524 int c = get_char ();
3527 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3528 Report.Error (1011, start_location, "Empty character literal");
3529 return Token.LITERAL;
3533 Report.Error (1010, start_location, "Newline in constant");
3538 c = escape (c, out d);
3542 throw new NotImplementedException ();
3544 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3549 Report.Error (1012, start_location, "Too many characters in character literal");
3551 // Try to recover, read until newline or next "'"
3552 while ((c = get_char ()) != -1) {
3553 if (c == '\n' || c == '\'')
3559 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3562 return Token.LITERAL;
3565 int TokenizeLessThan ()
3568 if (handle_typeof) {
3570 if (parse_generic_dimension (out d)) {
3573 return Token.GENERIC_DIMENSION;
3578 // Save current position and parse next token.
3580 if (parse_less_than ()) {
3581 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3582 d = Token.OP_GENERICS_LT_DECL;
3584 d = Token.OP_GENERICS_LT;
3591 parsing_generic_less_than = 0;
3600 return Token.OP_SHIFT_LEFT_ASSIGN;
3602 return Token.OP_SHIFT_LEFT;
3613 // Handles one line xml comment
3615 private void handle_one_line_xml_comment ()
3618 while ((c = peek_char ()) == ' ')
3619 get_char (); // skip heading whitespaces.
3620 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3621 xml_comment_buffer.Append ((char) get_char ());
3623 if (c == '\r' || c == '\n')
3624 xml_comment_buffer.Append (Environment.NewLine);
3628 // Remove heading "*" in Javadoc-like xml documentation.
3630 private void update_formatted_doc_comment (int current_comment_start)
3632 int length = xml_comment_buffer.Length - current_comment_start;
3633 string [] lines = xml_comment_buffer.ToString (
3634 current_comment_start,
3635 length).Replace ("\r", "").Split ('\n');
3637 // The first line starts with /**, thus it is not target
3638 // for the format check.
3639 for (int i = 1; i < lines.Length; i++) {
3640 string s = lines [i];
3641 int idx = s.IndexOf ('*');
3644 if (i < lines.Length - 1)
3648 head = s.Substring (0, idx);
3649 foreach (char c in head)
3652 lines [i] = s.Substring (idx + 1);
3654 xml_comment_buffer.Remove (current_comment_start, length);
3655 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3659 // Checks if there was incorrect doc comments and raise
3662 public void check_incorrect_doc_comment ()
3664 if (xml_comment_buffer.Length > 0)
3665 WarningMisplacedComment (Location);
3669 // Consumes the saved xml comment lines (if any)
3670 // as for current target member or type.
3672 public string consume_doc_comment ()
3674 if (xml_comment_buffer.Length > 0) {
3675 string ret = xml_comment_buffer.ToString ();
3676 reset_doc_comment ();
3683 get { return context.Report; }
3686 void reset_doc_comment ()
3688 xml_comment_buffer.Length = 0;
3691 public void cleanup ()
3693 if (ifstack != null && ifstack.Count >= 1) {
3694 int state = ifstack.Pop ();
3695 if ((state & REGION) != 0)
3696 Report.Error (1038, Location, "#endregion directive expected");
3698 Report.Error (1027, Location, "Expected `#endif' directive");
3704 // Indicates whether it accepts XML documentation or not.
3706 public enum XmlCommentState {
3707 // comment is allowed in this state.
3709 // comment is not allowed in this state.
3711 // once comments appeared when it is NotAllowed, then the
3712 // state is changed to it, until the state is changed to