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 // This class has to be used by parser only, it reuses token
26 // details once a file is parsed
28 public class LocatedToken
30 public int row, column;
32 public SourceFile file;
34 public LocatedToken ()
38 public LocatedToken (string value, Location loc)
41 file = loc.SourceFile;
46 public override string ToString ()
48 return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
51 public Location Location
53 get { return new Location (file, row, column); }
63 /// Tokenizer for C# source code.
65 public class Tokenizer : yyParser.yyInput
69 public readonly T Token;
70 public KeywordEntry<T> Next;
71 public readonly char[] Value;
73 public KeywordEntry (string value, T token)
75 this.Value = value.ToCharArray ();
80 sealed class IdentifiersComparer : IEqualityComparer<char[]>
84 public IdentifiersComparer (int length)
89 public bool Equals (char[] x, char[] y)
91 for (int i = 0; i < length; ++i)
98 public int GetHashCode (char[] obj)
101 for (int i = 0; i < length; ++i)
102 h = (h << 5) - h + obj [i];
108 public class LocatedTokenBuffer
110 readonly LocatedToken[] buffer;
113 public LocatedTokenBuffer ()
115 buffer = new LocatedToken[0];
118 public LocatedTokenBuffer (LocatedToken[] buffer)
120 this.buffer = buffer ?? new LocatedToken[0];
123 public LocatedToken Create (SourceFile file, int row, int column)
125 return Create (null, file, row, column);
128 public LocatedToken Create (string value, SourceFile file, int row, int column)
131 // TODO: I am not very happy about the logic but it's the best
132 // what I could come up with for now.
133 // Ideally we should be using just tiny buffer (256 elements) which
134 // is enough to hold all details for currect stack and recycle elements
135 // poped from the stack but there is a trick needed to recycle
139 if (pos >= buffer.Length) {
140 entry = new LocatedToken ();
144 entry = new LocatedToken ();
153 entry.column = column;
158 // Used for token not required by expression evaluator
160 [Conditional ("FULL_AST")]
161 public void CreateOptional (SourceFile file, int row, int col, ref object token)
163 token = Create (file, row, col);
167 public enum PreprocessorDirective
173 If = 3 | RequiresArgument,
175 Elif = 5 | RequiresArgument,
177 Define = 7 | RequiresArgument,
178 Undef = 8 | RequiresArgument,
181 Pragma = 11 | CustomArgumentsParsing,
182 Line = 12 | CustomArgumentsParsing,
184 CustomArgumentsParsing = 1 << 10,
185 RequiresArgument = 1 << 11
188 readonly SeekableStreamReader reader;
189 readonly CompilationSourceFile source_file;
190 readonly CompilerContext context;
191 readonly Report Report;
194 SourceFile current_source;
195 Location hidden_block_start;
201 readonly int tab_size;
202 bool handle_get_set = false;
203 bool handle_remove_add = false;
205 bool lambda_arguments_parsing;
206 List<Location> escaped_identifiers;
207 int parsing_generic_less_than;
208 readonly bool doc_processing;
209 readonly LocatedTokenBuffer ltb;
212 // Used mainly for parser optimizations. Some expressions for instance
213 // can appear only in block (including initializer, base initializer)
216 public int parsing_block;
217 internal bool query_parsing;
220 // When parsing type only, useful for ambiguous nullable types
222 public int parsing_type;
225 // Set when parsing generic declaration (type or method header)
227 public bool parsing_generic_declaration;
228 public bool parsing_generic_declaration_doc;
231 // The value indicates that we have not reach any declaration or
234 public int parsing_declaration;
236 public bool parsing_attribute_section;
238 public bool parsing_modifiers;
240 public bool parsing_catch_when;
242 int parsing_string_interpolation;
243 int string_interpolation_section;
244 Stack<bool> parsing_string_interpolation_quoted;
246 public bool parsing_interpolation_format;
249 // The special characters to inject on streams to run the unit parser
250 // in the special expression mode. Using private characters from
251 // Plane Sixteen (U+100000 to U+10FFFD)
253 // This character is only tested just before the tokenizer is about to report
254 // an error; So on the regular operation mode, this addition will have no
255 // impact on the tokenizer's performance.
258 public const int EvalStatementParserCharacter = 0x100000;
259 public const int EvalCompilationUnitParserCharacter = 0x100001;
260 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
261 public const int DocumentationXref = 0x100003;
263 const int UnicodeLS = 0x2028;
264 const int UnicodePS = 0x2029;
267 // XML documentation buffer. The save point is used to divide
268 // comments on types and comments on members.
270 StringBuilder xml_comment_buffer;
273 // See comment on XmlCommentState enumeration.
275 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
278 // Whether tokens have been seen on this line
280 bool tokens_seen = false;
283 // Set to true once the GENERATE_COMPLETION token has bee
284 // returned. This helps produce one GENERATE_COMPLETION,
285 // as many COMPLETE_COMPLETION as necessary to complete the
286 // AST tree and one final EOF.
291 // Whether a token has been seen on the file
292 // This is needed because `define' is not allowed to be used
293 // after a token has been seen.
300 static readonly KeywordEntry<int>[][] keywords;
301 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
302 static readonly HashSet<string> keyword_strings;
303 static readonly NumberStyles styles;
304 static readonly NumberFormatInfo csharp_format_info;
307 static readonly char[] pragma_warning = "warning".ToCharArray ();
308 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
309 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
310 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
311 static readonly char[] line_hidden = "hidden".ToCharArray ();
312 static readonly char[] line_default = "default".ToCharArray ();
314 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
316 public bool PropertyParsing {
317 get { return handle_get_set; }
318 set { handle_get_set = value; }
321 public bool EventParsing {
322 get { return handle_remove_add; }
323 set { handle_remove_add = value; }
326 public bool ConstraintsParsing {
327 get { return handle_where; }
328 set { handle_where = value; }
331 public XmlCommentState doc_state {
332 get { return xml_doc_state; }
334 if (value == XmlCommentState.Allowed) {
335 check_incorrect_doc_comment ();
336 reset_doc_comment ();
338 xml_doc_state = value;
343 // This is used to trigger completion generation on the parser
344 public bool CompleteOnEOF;
346 void AddEscapedIdentifier (Location loc)
348 if (escaped_identifiers == null)
349 escaped_identifiers = new List<Location> ();
351 escaped_identifiers.Add (loc);
354 public bool IsEscapedIdentifier (ATypeNameExpression name)
356 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
360 // Values for the associated token returned
362 internal int putback_char; // Used by repl only
368 const int TAKING = 1;
369 const int ELSE_SEEN = 4;
370 const int PARENT_TAKING = 8;
371 const int REGION = 16;
374 // pre-processor if stack state:
378 public const int MaxIdentifierLength = 512;
379 public const int MaxNumberLength = 512;
381 readonly char[] id_builder;
382 readonly Dictionary<char[], string>[] identifiers;
383 readonly char[] number_builder;
386 char[] value_builder = new char[64];
395 // This is used when the tokenizer needs to save
396 // the current position as it needs to do some parsing
397 // on its own to deamiguate a token in behalf of the
400 Stack<Position> position_stack = new Stack<Position> (2);
407 public Location hidden;
408 public int putback_char;
409 public int previous_col;
410 public Stack<int> ifstack;
411 public int parsing_generic_less_than;
412 public int current_token;
414 public int parsing_string_interpolation;
415 public int string_interpolation_section;
416 public Stack<bool> parsing_string_interpolation_quoted;
418 public Position (Tokenizer t)
420 position = t.reader.Position;
422 ref_line = t.ref_line;
424 hidden = t.hidden_block_start;
425 putback_char = t.putback_char;
426 previous_col = t.previous_col;
427 if (t.ifstack != null && t.ifstack.Count != 0) {
428 // There is no simple way to clone Stack<T> all
429 // methods reverse the order
430 var clone = t.ifstack.ToArray ();
431 Array.Reverse (clone);
432 ifstack = new Stack<int> (clone);
434 parsing_generic_less_than = t.parsing_generic_less_than;
435 string_interpolation_section = t.string_interpolation_section;
436 current_token = t.current_token;
438 parsing_string_interpolation = t.parsing_string_interpolation;
439 string_interpolation_section = t.string_interpolation_section;
440 if (t.parsing_string_interpolation_quoted != null && t.parsing_string_interpolation_quoted.Count != 0) {
441 var clone = t.parsing_string_interpolation_quoted.ToArray ();
442 Array.Reverse (clone);
443 parsing_string_interpolation_quoted = new Stack<bool> (clone);
448 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session, Report report)
450 this.source_file = file;
451 this.context = file.Compiler;
452 this.current_source = file.SourceFile;
453 this.identifiers = session.Identifiers;
454 this.id_builder = session.IDBuilder;
455 this.number_builder = session.NumberBuilder;
456 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
457 this.Report = report;
463 xml_comment_buffer = new StringBuilder ();
464 doc_processing = context.Settings.DocumentationFile != null;
466 tab_size = context.Settings.TabSize;
469 public void PushPosition ()
471 position_stack.Push (new Position (this));
474 public void PopPosition ()
476 Position p = position_stack.Pop ();
478 reader.Position = p.position;
479 ref_line = p.ref_line;
482 hidden_block_start = p.hidden;
483 putback_char = p.putback_char;
484 previous_col = p.previous_col;
486 parsing_generic_less_than = p.parsing_generic_less_than;
487 parsing_string_interpolation = p.parsing_string_interpolation;
488 parsing_string_interpolation_quoted = p.parsing_string_interpolation_quoted;
489 current_token = p.current_token;
493 // Do not reset the position, ignore it.
494 public void DiscardPosition ()
496 position_stack.Pop ();
499 static void AddKeyword (string kw, int token)
501 keyword_strings.Add (kw);
503 AddKeyword (keywords, kw, token);
506 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
508 AddKeyword (keywords_preprocessor, kw, directive);
511 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
513 int length = kw.Length;
514 if (keywords[length] == null) {
515 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
518 int char_index = kw[0] - '_';
519 var kwe = keywords[length][char_index];
521 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
525 while (kwe.Next != null) {
529 kwe.Next = new KeywordEntry<T> (kw, token);
537 keyword_strings = new HashSet<string> ();
539 // 11 is the length of the longest keyword for now
540 keywords = new KeywordEntry<int>[11][];
542 AddKeyword ("__arglist", Token.ARGLIST);
543 AddKeyword ("__makeref", Token.MAKEREF);
544 AddKeyword ("__reftype", Token.REFTYPE);
545 AddKeyword ("__refvalue", Token.REFVALUE);
546 AddKeyword ("abstract", Token.ABSTRACT);
547 AddKeyword ("as", Token.AS);
548 AddKeyword ("add", Token.ADD);
549 AddKeyword ("base", Token.BASE);
550 AddKeyword ("bool", Token.BOOL);
551 AddKeyword ("break", Token.BREAK);
552 AddKeyword ("byte", Token.BYTE);
553 AddKeyword ("case", Token.CASE);
554 AddKeyword ("catch", Token.CATCH);
555 AddKeyword ("char", Token.CHAR);
556 AddKeyword ("checked", Token.CHECKED);
557 AddKeyword ("class", Token.CLASS);
558 AddKeyword ("const", Token.CONST);
559 AddKeyword ("continue", Token.CONTINUE);
560 AddKeyword ("decimal", Token.DECIMAL);
561 AddKeyword ("default", Token.DEFAULT);
562 AddKeyword ("delegate", Token.DELEGATE);
563 AddKeyword ("do", Token.DO);
564 AddKeyword ("double", Token.DOUBLE);
565 AddKeyword ("else", Token.ELSE);
566 AddKeyword ("enum", Token.ENUM);
567 AddKeyword ("event", Token.EVENT);
568 AddKeyword ("explicit", Token.EXPLICIT);
569 AddKeyword ("extern", Token.EXTERN);
570 AddKeyword ("false", Token.FALSE);
571 AddKeyword ("finally", Token.FINALLY);
572 AddKeyword ("fixed", Token.FIXED);
573 AddKeyword ("float", Token.FLOAT);
574 AddKeyword ("for", Token.FOR);
575 AddKeyword ("foreach", Token.FOREACH);
576 AddKeyword ("goto", Token.GOTO);
577 AddKeyword ("get", Token.GET);
578 AddKeyword ("if", Token.IF);
579 AddKeyword ("implicit", Token.IMPLICIT);
580 AddKeyword ("in", Token.IN);
581 AddKeyword ("int", Token.INT);
582 AddKeyword ("interface", Token.INTERFACE);
583 AddKeyword ("internal", Token.INTERNAL);
584 AddKeyword ("is", Token.IS);
585 AddKeyword ("lock", Token.LOCK);
586 AddKeyword ("long", Token.LONG);
587 AddKeyword ("namespace", Token.NAMESPACE);
588 AddKeyword ("new", Token.NEW);
589 AddKeyword ("null", Token.NULL);
590 AddKeyword ("object", Token.OBJECT);
591 AddKeyword ("operator", Token.OPERATOR);
592 AddKeyword ("out", Token.OUT);
593 AddKeyword ("override", Token.OVERRIDE);
594 AddKeyword ("params", Token.PARAMS);
595 AddKeyword ("private", Token.PRIVATE);
596 AddKeyword ("protected", Token.PROTECTED);
597 AddKeyword ("public", Token.PUBLIC);
598 AddKeyword ("readonly", Token.READONLY);
599 AddKeyword ("ref", Token.REF);
600 AddKeyword ("remove", Token.REMOVE);
601 AddKeyword ("return", Token.RETURN);
602 AddKeyword ("sbyte", Token.SBYTE);
603 AddKeyword ("sealed", Token.SEALED);
604 AddKeyword ("set", Token.SET);
605 AddKeyword ("short", Token.SHORT);
606 AddKeyword ("sizeof", Token.SIZEOF);
607 AddKeyword ("stackalloc", Token.STACKALLOC);
608 AddKeyword ("static", Token.STATIC);
609 AddKeyword ("string", Token.STRING);
610 AddKeyword ("struct", Token.STRUCT);
611 AddKeyword ("switch", Token.SWITCH);
612 AddKeyword ("this", Token.THIS);
613 AddKeyword ("throw", Token.THROW);
614 AddKeyword ("true", Token.TRUE);
615 AddKeyword ("try", Token.TRY);
616 AddKeyword ("typeof", Token.TYPEOF);
617 AddKeyword ("uint", Token.UINT);
618 AddKeyword ("ulong", Token.ULONG);
619 AddKeyword ("unchecked", Token.UNCHECKED);
620 AddKeyword ("unsafe", Token.UNSAFE);
621 AddKeyword ("ushort", Token.USHORT);
622 AddKeyword ("using", Token.USING);
623 AddKeyword ("virtual", Token.VIRTUAL);
624 AddKeyword ("void", Token.VOID);
625 AddKeyword ("volatile", Token.VOLATILE);
626 AddKeyword ("while", Token.WHILE);
627 AddKeyword ("partial", Token.PARTIAL);
628 AddKeyword ("where", Token.WHERE);
631 AddKeyword ("from", Token.FROM);
632 AddKeyword ("join", Token.JOIN);
633 AddKeyword ("on", Token.ON);
634 AddKeyword ("equals", Token.EQUALS);
635 AddKeyword ("select", Token.SELECT);
636 AddKeyword ("group", Token.GROUP);
637 AddKeyword ("by", Token.BY);
638 AddKeyword ("let", Token.LET);
639 AddKeyword ("orderby", Token.ORDERBY);
640 AddKeyword ("ascending", Token.ASCENDING);
641 AddKeyword ("descending", Token.DESCENDING);
642 AddKeyword ("into", Token.INTO);
644 // Contextual async keywords
645 AddKeyword ("async", Token.ASYNC);
646 AddKeyword ("await", Token.AWAIT);
648 // Contextual filter catch keyword
649 AddKeyword ("when", Token.WHEN);
651 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
653 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
654 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
655 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
656 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
657 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
658 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
659 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
660 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
661 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
662 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
663 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
664 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
666 csharp_format_info = NumberFormatInfo.InvariantInfo;
667 styles = NumberStyles.Float;
670 int GetKeyword (char[] id, int id_len)
673 // Keywords are stored in an array of arrays grouped by their
674 // length and then by the first character
676 if (id_len >= keywords.Length || keywords [id_len] == null)
679 int first_index = id [0] - '_';
680 if (first_index > 'z' - '_')
683 var kwe = keywords [id_len] [first_index];
690 for (int i = 1; i < id_len; ++i) {
691 if (id [i] != kwe.Value [i]) {
697 } while (res == 0 && kwe != null);
711 if (!handle_remove_add)
715 if (parsing_declaration == 0)
716 res = Token.EXTERN_ALIAS;
719 if (peek_token () == Token.COLON) {
721 res = Token.DEFAULT_COLON;
725 if (current_token != Token.CATCH && !parsing_catch_when)
729 if (!(handle_where && current_token != Token.COLON) && !query_parsing)
734 // A query expression is any expression that starts with `from identifier'
735 // followed by any token except ; , =
737 if (!query_parsing) {
738 if (lambda_arguments_parsing || parsing_block == 0) {
744 // HACK: to disable generics micro-parser, because PushPosition does not
745 // store identifiers array
746 parsing_generic_less_than = 1;
748 case Token.IDENTIFIER:
761 next_token = xtoken ();
762 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
765 res = Token.FROM_FIRST;
766 query_parsing = true;
767 if (context.Settings.Version <= LanguageVersion.ISO_2)
768 Report.FeatureIsNotAvailable (context, Location, "query expressions");
771 Expression.Error_VoidInvalidInTheContext (Location, Report);
775 // HACK: A token is not a keyword so we need to restore identifiers buffer
776 // which has been overwritten before we grabbed the identifier
777 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
791 case Token.ASCENDING:
792 case Token.DESCENDING:
799 case Token.NAMESPACE:
800 // TODO: some explanation needed
801 check_incorrect_doc_comment ();
802 parsing_modifiers = false;
806 if (parsing_block > 0) {
811 // Save current position and parse next token.
814 next_token = token ();
815 bool ok = (next_token == Token.CLASS) ||
816 (next_token == Token.STRUCT) ||
817 (next_token == Token.INTERFACE) ||
818 (next_token == Token.VOID);
823 if (next_token == Token.VOID) {
824 if (context.Settings.Version <= LanguageVersion.ISO_2)
825 Report.FeatureIsNotAvailable (context, Location, "partial methods");
826 } else if (context.Settings.Version == LanguageVersion.ISO_1)
827 Report.FeatureIsNotAvailable (context, Location, "partial types");
832 if (next_token < Token.LAST_KEYWORD) {
833 Report.Error (267, Location,
834 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
838 // HACK: A token is not a keyword so we need to restore identifiers buffer
839 // which has been overwritten before we grabbed the identifier
851 if (parsing_modifiers) {
853 // Skip attributes section or constructor called async
855 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
860 } else if (parsing_block > 0) {
861 switch (peek_token ()) {
863 case Token.OPEN_PARENS_LAMBDA:
866 case Token.IDENTIFIER:
869 if (xtoken () != Token.ARROW) {
877 // peek_token could overwrite id_buffer
878 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
886 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
887 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
893 if (parsing_block == 0)
903 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
906 // Keywords are stored in an array of arrays grouped by their
907 // length and then by the first character
909 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
910 return PreprocessorDirective.Invalid;
912 int first_index = id[0] - '_';
913 if (first_index > 'z' - '_')
914 return PreprocessorDirective.Invalid;
916 var kwe = keywords_preprocessor[id_len][first_index];
918 return PreprocessorDirective.Invalid;
920 PreprocessorDirective res = PreprocessorDirective.Invalid;
923 for (int i = 1; i < id_len; ++i) {
924 if (id[i] != kwe.Value[i]) {
930 } while (res == PreprocessorDirective.Invalid && kwe != null);
935 public Location Location {
937 return new Location (current_source, ref_line, col);
941 static bool is_identifier_start_character (int c)
943 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')
949 return is_identifier_start_character_slow_part ((char) c);
952 static bool is_identifier_part_character (char c)
954 if (c >= 'a' && c <= 'z')
957 if (c >= 'A' && c <= 'Z')
960 if (c == '_' || (c >= '0' && c <= '9'))
966 return is_identifier_part_character_slow_part (c);
969 static bool is_identifier_start_character_slow_part (char c)
971 switch (Char.GetUnicodeCategory (c)) {
972 case UnicodeCategory.LetterNumber:
973 case UnicodeCategory.UppercaseLetter:
974 case UnicodeCategory.LowercaseLetter:
975 case UnicodeCategory.TitlecaseLetter:
976 case UnicodeCategory.ModifierLetter:
977 case UnicodeCategory.OtherLetter:
983 static bool is_identifier_part_character_slow_part (char c)
985 switch (Char.GetUnicodeCategory (c)) {
986 // connecting-character: A Unicode character of the class Pc
987 case UnicodeCategory.ConnectorPunctuation:
989 // combining-character: A Unicode character of classes Mn or Mc
990 case UnicodeCategory.NonSpacingMark:
991 case UnicodeCategory.SpacingCombiningMark:
993 // decimal-digit-character: A Unicode character of the class Nd
994 case UnicodeCategory.DecimalDigitNumber:
996 // plus is_identifier_start_character_slow_part
997 case UnicodeCategory.LetterNumber:
998 case UnicodeCategory.UppercaseLetter:
999 case UnicodeCategory.LowercaseLetter:
1000 case UnicodeCategory.TitlecaseLetter:
1001 case UnicodeCategory.ModifierLetter:
1002 case UnicodeCategory.OtherLetter:
1005 // formatting-character: A Unicode character of the class Cf
1006 case UnicodeCategory.Format:
1007 // csc bug compatibility which recognizes it as a whitespace
1014 public static bool IsKeyword (string s)
1016 return keyword_strings.Contains (s);
1020 // Open parens micro parser. Detects both lambda and cast ambiguity.
1022 int TokenizeOpenParens ()
1027 int bracket_level = 0;
1028 bool is_type = false;
1029 bool can_be_type = false;
1032 ptoken = current_token;
1035 switch (current_token) {
1036 case Token.CLOSE_PARENS:
1040 // Expression inside parens is lambda, (int i) =>
1042 if (current_token == Token.ARROW)
1043 return Token.OPEN_PARENS_LAMBDA;
1046 // Expression inside parens is single type, (int[])
1049 if (current_token == Token.SEMICOLON)
1050 return Token.OPEN_PARENS;
1052 return Token.OPEN_PARENS_CAST;
1056 // Expression is possible cast, look at next token, (T)null
1059 switch (current_token) {
1060 case Token.OPEN_PARENS:
1063 case Token.IDENTIFIER:
1067 case Token.DELEGATE:
1077 case Token.UNCHECKED:
1083 // These can be part of a member access
1099 return Token.OPEN_PARENS_CAST;
1102 return Token.OPEN_PARENS;
1105 case Token.DOUBLE_COLON:
1106 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1111 case Token.IDENTIFIER:
1115 if (bracket_level == 0) {
1121 case Token.OP_GENERICS_LT:
1123 case Token.DOUBLE_COLON:
1125 if (bracket_level == 0)
1129 can_be_type = is_type = false;
1149 if (bracket_level == 0)
1154 if (bracket_level == 0) {
1155 bracket_level = 100;
1156 can_be_type = is_type = false;
1160 case Token.OP_GENERICS_LT:
1161 case Token.OPEN_BRACKET:
1162 if (bracket_level++ == 0)
1166 case Token.OP_GENERICS_GT:
1167 case Token.CLOSE_BRACKET:
1171 case Token.INTERR_NULLABLE:
1173 if (bracket_level == 0)
1179 can_be_type = is_type = false;
1183 return Token.OPEN_PARENS;
1188 public static bool IsValidIdentifier (string s)
1190 if (s == null || s.Length == 0)
1193 if (!is_identifier_start_character (s [0]))
1196 for (int i = 1; i < s.Length; i ++)
1197 if (! is_identifier_part_character (s [i]))
1203 bool parse_less_than (ref int genericDimension)
1206 int the_token = token ();
1207 if (the_token == Token.OPEN_BRACKET) {
1209 the_token = token ();
1210 if (the_token == Token.EOF)
1213 if (the_token == Token.CLOSE_BRACKET)
1216 the_token = token ();
1217 } else if (the_token == Token.IN || the_token == Token.OUT) {
1218 the_token = token ();
1220 switch (the_token) {
1221 case Token.IDENTIFIER:
1239 case Token.OP_GENERICS_GT:
1240 genericDimension = 1;
1248 the_token = token ();
1249 } while (the_token == Token.COMMA);
1251 if (the_token == Token.OP_GENERICS_GT) {
1261 the_token = token ();
1263 if (the_token == Token.OP_GENERICS_GT)
1265 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1267 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1269 else if (the_token == Token.OP_GENERICS_LT) {
1270 if (!parse_less_than (ref genericDimension))
1273 } else if (the_token == Token.OPEN_BRACKET) {
1275 the_token = token ();
1276 if (the_token == Token.CLOSE_BRACKET)
1278 else if (the_token == Token.COMMA)
1279 goto rank_specifiers;
1286 public int peek_token ()
1291 the_token = token ();
1298 // Tonizes `?' using custom disambiguous rules to return one
1299 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1301 // Tricky expression looks like:
1303 // Foo ? a = x ? b : c;
1305 int TokenizePossibleNullableType ()
1307 if (parsing_block == 0 || parsing_type > 0)
1308 return Token.INTERR_NULLABLE;
1310 int d = peek_char ();
1313 return Token.OP_COALESCING;
1317 return Token.INTERR_OPERATOR;
1321 if (d == ',' || d == ';' || d == '>')
1322 return Token.INTERR_NULLABLE;
1323 if (d == '*' || (d >= '0' && d <= '9'))
1324 return Token.INTERR;
1328 current_token = Token.NONE;
1337 case Token.OPEN_BRACKET_EXPR:
1338 next_token = Token.INTERR_OPERATOR;
1346 case Token.INTERPOLATED_STRING:
1347 next_token = Token.INTERR;
1350 case Token.SEMICOLON:
1352 case Token.CLOSE_PARENS:
1353 case Token.OPEN_BRACKET:
1354 case Token.OP_GENERICS_GT:
1356 case Token.OP_COALESCING:
1358 next_token = Token.INTERR_NULLABLE;
1361 case Token.OPEN_PARENS:
1362 case Token.OPEN_PARENS_CAST:
1363 case Token.OPEN_PARENS_LAMBDA:
1368 case Token.OP_GENERICS_LT:
1369 case Token.OP_GENERICS_LT_DECL:
1370 case Token.GENERIC_DIMENSION:
1380 if (next_token == -1) {
1381 switch (xtoken ()) {
1383 case Token.SEMICOLON:
1384 case Token.OPEN_BRACE:
1386 next_token = Token.INTERR_NULLABLE;
1390 next_token = Token.INTERR;
1393 case Token.OPEN_PARENS:
1394 case Token.OPEN_PARENS_CAST:
1395 case Token.OPEN_PARENS_LAMBDA:
1399 case Token.OPEN_BRACKET:
1400 case Token.OPEN_BRACKET_EXPR:
1404 case Token.CLOSE_PARENS:
1408 case Token.OP_GENERICS_LT:
1409 case Token.OP_GENERICS_LT_DECL:
1410 case Token.GENERIC_DIMENSION:
1420 // All shorcuts failed, do it hard way
1422 while ((ntoken = xtoken ()) != Token.EOF) {
1424 case Token.OPEN_BRACE:
1427 case Token.OPEN_PARENS:
1428 case Token.OPEN_PARENS_CAST:
1429 case Token.OPEN_PARENS_LAMBDA:
1432 case Token.CLOSE_BRACE:
1435 case Token.OP_GENERICS_LT:
1436 case Token.OP_GENERICS_LT_DECL:
1437 case Token.GENERIC_DIMENSION:
1440 case Token.OPEN_BRACKET:
1441 case Token.OPEN_BRACKET_EXPR:
1444 case Token.CLOSE_BRACKET:
1447 case Token.CLOSE_PARENS:
1454 return Token.INTERR_NULLABLE;
1456 case Token.OP_GENERICS_GT:
1463 return Token.INTERR_NULLABLE;
1469 if (ntoken == Token.SEMICOLON)
1475 if (ntoken == Token.COMMA) {
1476 if (generics != 0 || brackets != 0)
1480 return Token.INTERR_NULLABLE;
1483 if (ntoken == Token.COLON) {
1484 if (++colons == interrs)
1489 if (ntoken == Token.INTERR) {
1495 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1504 bool decimal_digits (int c)
1507 bool seen_digits = false;
1510 if (number_pos == MaxNumberLength)
1511 Error_NumericConstantTooLong ();
1512 number_builder [number_pos++] = (char) c;
1516 // We use peek_char2, because decimal_digits needs to do a
1517 // 2-character look-ahead (5.ToString for example).
1519 while ((d = peek_char2 ()) != -1){
1520 if (d >= '0' && d <= '9'){
1521 if (number_pos == MaxNumberLength)
1522 Error_NumericConstantTooLong ();
1523 number_builder [number_pos++] = (char) d;
1533 static bool is_hex (int e)
1535 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1538 static TypeCode real_type_suffix (int c)
1542 return TypeCode.Single;
1544 return TypeCode.Double;
1546 return TypeCode.Decimal;
1548 return TypeCode.Empty;
1552 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1554 bool is_unsigned = false;
1555 bool is_long = false;
1558 bool scanning = true;
1571 // if we have not seen anything in between
1572 // report this error
1574 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1594 if (is_long && is_unsigned){
1595 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1599 // uint if possible, or ulong else.
1601 if ((ul & 0xffffffff00000000) == 0)
1602 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1604 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1605 } else if (is_long){
1606 // long if possible, ulong otherwise
1607 if ((ul & 0x8000000000000000) != 0)
1608 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1610 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1612 // int, uint, long or ulong in that order
1613 if ((ul & 0xffffffff00000000) == 0){
1614 uint ui = (uint) ul;
1616 if ((ui & 0x80000000) != 0)
1617 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1619 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1621 if ((ul & 0x8000000000000000) != 0)
1622 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1624 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1630 // given `c' as the next char in the input decide whether
1631 // we need to convert to a special type, and then choose
1632 // the best representation for the integer
1634 ILiteralConstant adjust_int (int c, Location loc)
1637 if (number_pos > 9){
1638 ulong ul = (uint) (number_builder [0] - '0');
1640 for (int i = 1; i < number_pos; i++){
1641 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1644 return integer_type_suffix (ul, c, loc);
1646 uint ui = (uint) (number_builder [0] - '0');
1648 for (int i = 1; i < number_pos; i++){
1649 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1652 return integer_type_suffix (ui, c, loc);
1654 } catch (OverflowException) {
1655 Error_NumericConstantTooLong ();
1656 return new IntLiteral (context.BuiltinTypes, 0, loc);
1658 catch (FormatException) {
1659 Report.Error (1013, Location, "Invalid number");
1660 return new IntLiteral (context.BuiltinTypes, 0, loc);
1664 ILiteralConstant adjust_real (TypeCode t, Location loc)
1666 string s = new string (number_builder, 0, number_pos);
1667 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1670 case TypeCode.Decimal:
1672 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1673 } catch (OverflowException) {
1674 Report.Error (594, Location, error_details, "decimal");
1675 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1677 case TypeCode.Single:
1679 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1680 } catch (OverflowException) {
1681 Report.Error (594, Location, error_details, "float");
1682 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1686 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1687 } catch (OverflowException) {
1688 Report.Error (594, loc, error_details, "double");
1689 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1694 ILiteralConstant handle_hex (Location loc)
1700 while ((d = peek_char ()) != -1){
1702 number_builder [number_pos++] = (char) d;
1708 string s = new String (number_builder, 0, number_pos);
1711 if (number_pos <= 8)
1712 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1714 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1716 return integer_type_suffix (ul, peek_char (), loc);
1717 } catch (OverflowException){
1718 Error_NumericConstantTooLong ();
1719 return new IntLiteral (context.BuiltinTypes, 0, loc);
1721 catch (FormatException) {
1722 Report.Error (1013, Location, "Invalid number");
1723 return new IntLiteral (context.BuiltinTypes, 0, loc);
1728 // Invoked if we know we have .digits or digits
1730 int is_number (int c, bool dotLead)
1732 ILiteralConstant res;
1735 int read_start = reader.Position - 1;
1738 // Caller did peek_char
1748 int peek = peek_char ();
1750 if (peek == 'x' || peek == 'X') {
1751 val = res = handle_hex (loc);
1753 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1756 return Token.LITERAL;
1764 // We need to handle the case of
1765 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1767 bool is_real = false;
1772 if (decimal_digits ('.')){
1778 val = res = adjust_int (-1, loc);
1781 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1783 return Token.LITERAL;
1787 if (c == 'e' || c == 'E'){
1790 if (number_pos == MaxNumberLength)
1791 Error_NumericConstantTooLong ();
1792 number_builder [number_pos++] = (char) c;
1796 if (number_pos == MaxNumberLength)
1797 Error_NumericConstantTooLong ();
1798 number_builder [number_pos++] = '+';
1800 } else if (c == '-') {
1801 if (number_pos == MaxNumberLength)
1802 Error_NumericConstantTooLong ();
1803 number_builder [number_pos++] = '-';
1806 if (number_pos == MaxNumberLength)
1807 Error_NumericConstantTooLong ();
1808 number_builder [number_pos++] = '+';
1815 var type = real_type_suffix (c);
1816 if (type == TypeCode.Empty && !is_real) {
1817 res = adjust_int (c, loc);
1821 if (type != TypeCode.Empty) {
1825 res = adjust_real (type, loc);
1831 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1832 if (chars[chars.Length - 1] == '\r')
1833 Array.Resize (ref chars, chars.Length - 1);
1834 res.ParsedValue = chars;
1837 return Token.LITERAL;
1841 // Accepts exactly count (4 or 8) hex, no more no less
1843 int getHex (int count, out int surrogate, out bool error)
1848 int top = count != -1 ? count : 4;
1853 for (i = 0; i < top; i++){
1856 if (c >= '0' && c <= '9')
1857 c = (int) c - (int) '0';
1858 else if (c >= 'A' && c <= 'F')
1859 c = (int) c - (int) 'A' + 10;
1860 else if (c >= 'a' && c <= 'f')
1861 c = (int) c - (int) 'a' + 10;
1867 total = (total * 16) + c;
1869 int p = peek_char ();
1872 if (!is_hex ((char)p))
1878 if (total > 0x0010FFFF) {
1883 if (total >= 0x00010000) {
1884 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1885 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1892 int escape (int c, out int surrogate)
1928 v = getHex (-1, out surrogate, out error);
1934 return EscapeUnicode (d, out surrogate);
1937 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1946 int EscapeUnicode (int ch, out int surrogate)
1950 ch = getHex (8, out surrogate, out error);
1952 ch = getHex (4, out surrogate, out error);
1956 Report.Error (1009, Location, "Unrecognized escape sequence");
1964 if (putback_char != -1) {
1973 if (peek_char () == '\n') {
1979 } else if (x == '\n') {
1984 } else if (x >= UnicodeLS && x <= UnicodePS) {
1993 void advance_line ()
2003 if (putback_char == -1)
2004 putback_char = reader.Read ();
2005 return putback_char;
2010 if (putback_char != -1)
2011 return putback_char;
2012 return reader.Peek ();
2015 public void putback (int c)
2017 if (putback_char != -1) {
2018 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
2021 if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
2022 // It won't happen though.
2032 public bool advance ()
2034 return peek_char () != -1 || CompleteOnEOF;
2037 public Object Value {
2043 public Object value ()
2050 current_token = xtoken ();
2051 return current_token;
2054 int TokenizePreprocessorKeyword (out int c)
2056 // skip over white space
2059 } while (c == ' ' || c == '\t');
2063 while (c != -1 && c >= 'a' && c <= 'z') {
2064 id_builder[pos++] = (char) c;
2067 int peek = peek_char ();
2068 if (peek == 'U' || peek == 'u') {
2070 c = EscapeUnicode (c, out surrogate);
2071 if (surrogate != 0) {
2072 if (is_identifier_part_character ((char) c)) {
2073 id_builder[pos++] = (char) c;
2084 PreprocessorDirective get_cmd_arg (out string arg)
2088 tokens_seen = false;
2091 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2093 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2096 // skip over white space
2097 while (c == ' ' || c == '\t')
2100 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2103 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2104 if (c == '\\' && has_identifier_argument >= 0) {
2105 if (has_identifier_argument != 0) {
2106 has_identifier_argument = 1;
2108 int peek = peek_char ();
2109 if (peek == 'U' || peek == 'u') {
2111 c = EscapeUnicode (c, out surrogate);
2112 if (surrogate != 0) {
2113 if (is_identifier_part_character ((char) c)) {
2114 if (pos == value_builder.Length)
2115 Array.Resize (ref value_builder, pos * 2);
2117 value_builder[pos++] = (char) c;
2123 has_identifier_argument = -1;
2125 } else if (c == '/' && peek_char () == '/') {
2127 // Eat single-line comments
2134 if (pos == value_builder.Length)
2135 Array.Resize (ref value_builder, pos * 2);
2137 value_builder[pos++] = (char) c;
2142 if (pos > MaxIdentifierLength)
2143 arg = new string (value_builder, 0, pos);
2145 arg = InternIdentifier (value_builder, pos);
2147 // Eat any trailing whitespaces
2148 arg = arg.Trim (simple_whitespaces);
2155 // Handles the #line directive
2157 bool PreProcessLine ()
2159 Location loc = Location;
2163 int length = TokenizePreprocessorKeyword (out c);
2164 if (length == line_default.Length) {
2165 if (!IsTokenIdentifierEqual (line_default))
2168 current_source = source_file.SourceFile;
2169 if (!hidden_block_start.IsNull) {
2170 current_source.RegisterHiddenScope (hidden_block_start, loc);
2171 hidden_block_start = Location.Null;
2178 if (length == line_hidden.Length) {
2179 if (!IsTokenIdentifierEqual (line_hidden))
2182 if (hidden_block_start.IsNull)
2183 hidden_block_start = loc;
2188 if (length != 0 || c < '0' || c > '9') {
2190 // Eat any remaining characters to continue parsing on next line
2196 int new_line = TokenizeNumber (c);
2199 // Eat any remaining characters to continue parsing on next line
2202 return new_line != 0;
2207 // skip over white space
2210 } while (c == ' ' || c == '\t');
2211 } else if (c == '"') {
2215 if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2217 // Eat any remaining characters to continue parsing on next line
2221 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2225 string new_file_name = null;
2227 new_file_name = TokenizeFileName (ref c);
2229 // skip over white space
2230 while (c == ' ' || c == '\t') {
2235 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2237 } else if (c == '/') {
2238 ReadSingleLineComment ();
2241 // Eat any remaining characters to continue parsing on next line
2245 Error_EndLineExpected ();
2249 if (new_file_name != null) {
2250 current_source = context.LookupFile (source_file, new_file_name);
2251 source_file.AddIncludeFile (current_source);
2254 if (!hidden_block_start.IsNull) {
2255 current_source.RegisterHiddenScope (hidden_block_start, loc);
2256 hidden_block_start = Location.Null;
2259 ref_line = new_line;
2264 // Handles #define and #undef
2266 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2268 if (ident.Length == 0 || ident == "true" || ident == "false"){
2269 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2273 if (ident.IndexOfAny (simple_whitespaces) != -1){
2274 Error_EndLineExpected ();
2278 if (!is_identifier_start_character (ident [0]))
2279 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2281 foreach (char c in ident.Substring (1)){
2282 if (!is_identifier_part_character (c)){
2283 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2288 if (!caller_is_taking)
2295 if (context.Settings.IsConditionalSymbolDefined (ident))
2298 source_file.AddDefine (ident);
2303 source_file.AddUndefine (ident);
2307 byte read_hex (out bool error)
2310 int c = get_char ();
2312 if ((c >= '0') && (c <= '9'))
2313 total = (int) c - (int) '0';
2314 else if ((c >= 'A') && (c <= 'F'))
2315 total = (int) c - (int) 'A' + 10;
2316 else if ((c >= 'a') && (c <= 'f'))
2317 total = (int) c - (int) 'a' + 10;
2326 if ((c >= '0') && (c <= '9'))
2327 total += (int) c - (int) '0';
2328 else if ((c >= 'A') && (c <= 'F'))
2329 total += (int) c - (int) 'A' + 10;
2330 else if ((c >= 'a') && (c <= 'f'))
2331 total += (int) c - (int) 'a' + 10;
2338 return (byte) total;
2342 // Parses #pragma checksum
2344 bool ParsePragmaChecksum ()
2347 // The syntax is ` "foo.txt" "{guid}" "hash"'
2349 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2351 int c = get_char ();
2356 string file_name = TokenizeFileName (ref c);
2358 // TODO: Any white-spaces count
2362 SourceFile file = context.LookupFile (source_file, file_name);
2364 if (get_char () != '"' || get_char () != '{')
2368 byte[] guid_bytes = new byte [16];
2371 for (; i < 4; i++) {
2372 guid_bytes [i] = read_hex (out error);
2377 if (get_char () != '-')
2380 for (; i < 10; i++) {
2381 guid_bytes [i] = read_hex (out error);
2385 guid_bytes [i++] = read_hex (out error);
2389 if (get_char () != '-')
2393 for (; i < 16; i++) {
2394 guid_bytes [i] = read_hex (out error);
2399 if (get_char () != '}' || get_char () != '"')
2402 // TODO: Any white-spaces count
2407 if (get_char () != '"')
2410 // Any length of checksum
2411 List<byte> checksum_bytes = new List<byte> (16);
2413 var checksum_location = Location;
2415 while (c != '"' && c != -1) {
2416 checksum_bytes.Add (read_hex (out error));
2424 ReadSingleLineComment ();
2425 } else if (get_char () != '"') {
2429 if (context.Settings.GenerateDebugInfo) {
2430 var chsum = checksum_bytes.ToArray ();
2432 if (file.HasChecksum) {
2433 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2434 // TODO: Report.SymbolRelatedToPreviousError
2435 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2439 file.SetChecksum (guid_bytes, chsum);
2440 current_source.AutoGenerated = true;
2446 bool IsTokenIdentifierEqual (char[] identifier)
2448 for (int i = 0; i < identifier.Length; ++i) {
2449 if (identifier[i] != id_builder[i])
2456 bool ScanClosingInterpolationBrace ()
2463 var c = reader.Read ();
2472 if (str_quote % 2 == 1) {
2478 } while (res == null);
2484 int TokenizeNumber (int value)
2488 decimal_digits (value);
2489 uint ui = (uint) (number_builder[0] - '0');
2492 for (int i = 1; i < number_pos; i++) {
2493 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2497 } catch (OverflowException) {
2498 Error_NumericConstantTooLong ();
2503 string TokenizeFileName (ref int c)
2505 var string_builder = new StringBuilder ();
2506 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2513 string_builder.Append ((char) c);
2516 if (string_builder.Length == 0) {
2517 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2521 return string_builder.ToString ();
2524 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2526 if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2529 if (c >= '0' && c <= '9') {
2531 number = TokenizeNumber (c);
2535 if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2536 return ReadPragmaWarningComment (c);
2540 // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2544 id_builder [pos++] = (char)c;
2545 while (c < MaxIdentifierLength) {
2547 id_builder [pos] = (char)c;
2549 if (c >= '0' && c <= '9') {
2550 if (pos == 6 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2551 // Recognize CSXXXX as C# XXXX warning
2554 for (int i = 0; i < 4; ++i) {
2555 var ch = id_builder [i + 2];
2556 if (ch < '0' || ch > '9') {
2561 number += (ch - '0') * pow;
2565 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2578 // skip over white space
2579 while (c == ' ' || c == '\t')
2586 // skip over white space
2587 while (c == ' ' || c == '\t')
2590 if (c == '\n' || c == UnicodeLS || c == UnicodePS)
2596 return ReadPragmaWarningComment (c);
2599 int ReadPragmaWarningComment (int c)
2602 ReadSingleLineComment ();
2604 Report.Warning (1692, 1, Location, "Invalid number");
2606 // Read everything till the end of the line or file
2613 void ReadToEndOfLine ()
2618 } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2621 void ReadSingleLineComment ()
2623 if (peek_char () != '/')
2624 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2626 // Read everything till the end of the line or file
2631 /// Handles #pragma directive
2633 void ParsePragmaDirective ()
2636 int length = TokenizePreprocessorKeyword (out c);
2637 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2638 length = TokenizePreprocessorKeyword (out c);
2641 // #pragma warning disable
2642 // #pragma warning restore
2644 if (length == pragma_warning_disable.Length) {
2645 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2646 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2647 // skip over white space
2648 while (c == ' ' || c == '\t')
2653 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2655 ReadSingleLineComment ();
2658 // Disable/Restore all warnings
2661 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2663 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2667 // Disable/Restore a warning or group of warnings
2671 bool identifier = false;
2672 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2675 // no-op, custom warnings cannot occur in mcs
2676 } else if (disable) {
2677 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2679 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2682 } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2689 Report.Warning (1634, 1, Location, "Expected disable or restore");
2691 // Eat any remaining characters on the line
2700 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2701 if (c != ' ' || !ParsePragmaChecksum ()) {
2702 Report.Warning (1695, 1, Location,
2703 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2709 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2711 // Eat any remaining characters on the line
2715 bool eval_val (string s)
2722 return source_file.IsConditionalDefined (s);
2725 bool pp_primary (ref string s)
2734 s = s.Substring (1);
2735 bool val = pp_expr (ref s, false);
2736 if (s.Length > 0 && s [0] == ')'){
2737 s = s.Substring (1);
2740 Error_InvalidDirective ();
2744 if (is_identifier_start_character (c)){
2750 if (is_identifier_part_character (c)){
2754 bool v = eval_val (s.Substring (0, j));
2755 s = s.Substring (j);
2758 bool vv = eval_val (s);
2763 Error_InvalidDirective ();
2767 bool pp_unary (ref string s)
2774 if (len > 1 && s [1] == '='){
2775 Error_InvalidDirective ();
2778 s = s.Substring (1);
2779 return ! pp_primary (ref s);
2781 return pp_primary (ref s);
2783 Error_InvalidDirective ();
2788 bool pp_eq (ref string s)
2790 bool va = pp_unary (ref s);
2796 if (len > 2 && s [1] == '='){
2797 s = s.Substring (2);
2798 return va == pp_unary (ref s);
2800 Error_InvalidDirective ();
2803 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2804 s = s.Substring (2);
2806 return va != pp_unary (ref s);
2815 bool pp_and (ref string s)
2817 bool va = pp_eq (ref s);
2823 if (len > 2 && s [1] == '&'){
2824 s = s.Substring (2);
2825 return (va & pp_and (ref s));
2827 Error_InvalidDirective ();
2836 // Evaluates an expression for `#if' or `#elif'
2838 bool pp_expr (ref string s, bool isTerm)
2840 bool va = pp_and (ref s);
2847 if (len > 2 && s [1] == '|'){
2848 s = s.Substring (2);
2849 return va | pp_expr (ref s, isTerm);
2851 Error_InvalidDirective ();
2856 Error_EndLineExpected ();
2864 bool eval (string s)
2866 bool v = pp_expr (ref s, true);
2875 void Error_NumericConstantTooLong ()
2877 Report.Error (1021, Location, "Integral constant is too large");
2880 void Error_InvalidDirective ()
2882 Report.Error (1517, Location, "Invalid preprocessor directive");
2885 void Error_UnexpectedDirective (string extra)
2889 "Unexpected processor directive ({0})", extra);
2892 void Error_TokensSeen ()
2894 Report.Error (1032, Location,
2895 "Cannot define or undefine preprocessor symbols after first token in file");
2898 void Eror_WrongPreprocessorLocation ()
2900 Report.Error (1040, Location,
2901 "Preprocessor directives must appear as the first non-whitespace character on a line");
2904 void Error_EndLineExpected ()
2906 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2910 // Raises a warning when tokenizer found documentation comment
2911 // on unexpected place
2913 void WarningMisplacedComment (Location loc)
2915 if (doc_state != XmlCommentState.Error) {
2916 doc_state = XmlCommentState.Error;
2917 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2922 // if true, then the code continues processing the code
2923 // if false, the code stays in a loop until another directive is
2925 // When caller_is_taking is false we ignore all directives except the ones
2926 // which can help us to identify where the #if block ends
2927 bool ParsePreprocessingDirective (bool caller_is_taking)
2930 bool region_directive = false;
2932 var directive = get_cmd_arg (out arg);
2935 // The first group of pre-processing instructions is always processed
2937 switch (directive) {
2938 case PreprocessorDirective.Region:
2939 region_directive = true;
2941 goto case PreprocessorDirective.If;
2943 case PreprocessorDirective.Endregion:
2944 if (ifstack == null || ifstack.Count == 0){
2945 Error_UnexpectedDirective ("no #region for this #endregion");
2948 int pop = ifstack.Pop ();
2950 if ((pop & REGION) == 0)
2951 Report.Error (1027, Location, "Expected `#endif' directive");
2953 return caller_is_taking;
2955 case PreprocessorDirective.If:
2956 if (ifstack == null)
2957 ifstack = new Stack<int> (2);
2959 int flags = region_directive ? REGION : 0;
2960 if (ifstack.Count == 0){
2961 flags |= PARENT_TAKING;
2963 int state = ifstack.Peek ();
2964 if ((state & TAKING) != 0) {
2965 flags |= PARENT_TAKING;
2969 if (eval (arg) && caller_is_taking) {
2970 ifstack.Push (flags | TAKING);
2973 ifstack.Push (flags);
2976 case PreprocessorDirective.Endif:
2977 if (ifstack == null || ifstack.Count == 0){
2978 Error_UnexpectedDirective ("no #if for this #endif");
2981 pop = ifstack.Pop ();
2983 if ((pop & REGION) != 0)
2984 Report.Error (1038, Location, "#endregion directive expected");
2986 if (arg.Length != 0) {
2987 Error_EndLineExpected ();
2990 if (ifstack.Count == 0)
2993 int state = ifstack.Peek ();
2994 return (state & TAKING) != 0;
2997 case PreprocessorDirective.Elif:
2998 if (ifstack == null || ifstack.Count == 0){
2999 Error_UnexpectedDirective ("no #if for this #elif");
3002 int state = ifstack.Pop ();
3004 if ((state & REGION) != 0) {
3005 Report.Error (1038, Location, "#endregion directive expected");
3009 if ((state & ELSE_SEEN) != 0){
3010 Error_UnexpectedDirective ("#elif not valid after #else");
3014 if ((state & TAKING) != 0) {
3019 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
3020 ifstack.Push (state | TAKING);
3024 ifstack.Push (state);
3028 case PreprocessorDirective.Else:
3029 if (ifstack == null || ifstack.Count == 0){
3030 Error_UnexpectedDirective ("no #if for this #else");
3033 int state = ifstack.Peek ();
3035 if ((state & REGION) != 0) {
3036 Report.Error (1038, Location, "#endregion directive expected");
3040 if ((state & ELSE_SEEN) != 0){
3041 Error_UnexpectedDirective ("#else within #else");
3047 if (arg.Length != 0) {
3048 Error_EndLineExpected ();
3053 if ((state & PARENT_TAKING) != 0) {
3054 ret = (state & TAKING) == 0;
3062 ifstack.Push (state | ELSE_SEEN);
3066 case PreprocessorDirective.Define:
3067 if (any_token_seen){
3068 if (caller_is_taking)
3069 Error_TokensSeen ();
3070 return caller_is_taking;
3072 PreProcessDefinition (true, arg, caller_is_taking);
3073 return caller_is_taking;
3075 case PreprocessorDirective.Undef:
3076 if (any_token_seen){
3077 if (caller_is_taking)
3078 Error_TokensSeen ();
3079 return caller_is_taking;
3081 PreProcessDefinition (false, arg, caller_is_taking);
3082 return caller_is_taking;
3084 case PreprocessorDirective.Invalid:
3085 Report.Error (1024, Location, "Wrong preprocessor directive");
3090 // These are only processed if we are in a `taking' block
3092 if (!caller_is_taking)
3096 case PreprocessorDirective.Error:
3097 Report.Error (1029, Location, "#error: '{0}'", arg);
3100 case PreprocessorDirective.Warning:
3101 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3104 case PreprocessorDirective.Pragma:
3105 if (context.Settings.Version == LanguageVersion.ISO_1) {
3106 Report.FeatureIsNotAvailable (context, Location, "#pragma");
3109 ParsePragmaDirective ();
3112 case PreprocessorDirective.Line:
3113 Location loc = Location;
3114 if (!PreProcessLine ())
3115 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3117 return caller_is_taking;
3120 throw new NotImplementedException (directive.ToString ());
3123 int consume_string (bool quoted)
3127 Location start_location = Location;
3129 start_location = start_location - 1;
3132 int reader_pos = reader.Position;
3136 // Cannot use get_char because of \r in quoted strings
3137 if (putback_char != -1) {
3147 if (quoted && peek_char () == '"') {
3148 if (pos == value_builder.Length)
3149 Array.Resize (ref value_builder, pos * 2);
3151 value_builder[pos++] = (char) c;
3156 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3159 res.ParsedValue = quoted ?
3160 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3161 reader.ReadChars (reader_pos - 1, reader.Position);
3164 return Token.LITERAL;
3167 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3169 Report.Error (1010, Location, "Newline in constant");
3173 // Don't add \r to string literal
3174 if (pos > 1 && value_builder [pos - 1] == '\r')
3177 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3178 return Token.LITERAL;
3182 } else if (c == '\\' && !quoted) {
3185 c = escape (c, out surrogate);
3188 if (surrogate != 0) {
3189 if (pos == value_builder.Length)
3190 Array.Resize (ref value_builder, pos * 2);
3192 value_builder[pos++] = (char) c;
3195 } else if (c == -1) {
3196 Report.Error (1039, Location, "Unterminated string literal");
3202 if (pos == value_builder.Length)
3203 Array.Resize (ref value_builder, pos * 2);
3205 value_builder[pos++] = (char) c;
3209 private int consume_identifier (int s)
3211 int res = consume_identifier (s, false);
3213 if (doc_state == XmlCommentState.Allowed)
3214 doc_state = XmlCommentState.NotAllowed;
3219 int consume_identifier (int c, bool quoted)
3222 // This method is very performance sensitive. It accounts
3223 // for approximately 25% of all parser time
3233 c = escape (c, out surrogate);
3234 if (quoted || is_identifier_start_character (c)) {
3235 // it's added bellow
3236 } else if (surrogate != 0) {
3237 id_builder [pos++] = (char)c;
3240 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3245 id_builder [pos++] = (char) c;
3251 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3252 id_builder [pos++] = (char) c;
3259 c = escape (c, out surrogate);
3260 if (is_identifier_part_character ((char) c))
3261 id_builder[pos++] = (char) c;
3262 else if (surrogate != 0) {
3266 // TODO: Probably need more whitespace characters
3271 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3278 } else if (is_identifier_part_character_slow_part ((char) c)) {
3279 id_builder [pos++] = (char) c;
3286 } catch (IndexOutOfRangeException) {
3287 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3295 // Optimization: avoids doing the keyword lookup
3296 // on uppercase letters
3298 if (id_builder [0] >= '_' && !quoted) {
3299 int keyword = GetKeyword (id_builder, pos);
3300 if (keyword != -1) {
3301 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3306 string s = InternIdentifier (id_builder, pos);
3307 val = ltb.Create (s, current_source, ref_line, column);
3308 if (quoted && parsing_attribute_section)
3309 AddEscapedIdentifier (((LocatedToken) val).Location);
3311 return Token.IDENTIFIER;
3314 string InternIdentifier (char[] charBuffer, int length)
3317 // Keep identifiers in an array of hashtables to avoid needless
3320 var identifiers_group = identifiers[length];
3322 if (identifiers_group != null) {
3323 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3327 // TODO: this should be number of files dependant
3328 // corlib compilation peaks at 1000 and System.Core at 150
3329 int capacity = length > 20 ? 10 : 100;
3330 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3331 identifiers[length] = identifiers_group;
3334 char[] chars = new char[length];
3335 Array.Copy (charBuffer, chars, length);
3337 s = new string (charBuffer, 0, length);
3338 identifiers_group.Add (chars, s);
3342 public int xtoken ()
3344 if (parsing_interpolation_format) {
3345 return TokenizeInterpolationFormat ();
3350 // Whether we have seen comments on the current line
3351 bool comments_seen = false;
3352 while ((c = get_char ()) != -1) {
3355 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3363 case 0xFEFF: // Ignore BOM anywhere in the file
3366 /* This is required for compatibility with .NET
3368 if (peek_char () == 0xBB) {
3371 if (get_char () == 0xBF)
3379 return consume_identifier (c);
3382 val = ltb.Create (current_source, ref_line, col);
3384 if (parsing_string_interpolation > 0)
3385 ++string_interpolation_section;
3387 return Token.OPEN_BRACE;
3389 if (parsing_string_interpolation > 0) {
3390 if (string_interpolation_section == 0) {
3391 --parsing_string_interpolation;
3393 if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Count > 0) {
3394 quoted = parsing_string_interpolation_quoted.Pop ();
3399 return TokenizeInterpolatedString (quoted);
3402 --string_interpolation_section;
3405 val = ltb.Create (current_source, ref_line, col);
3406 return Token.CLOSE_BRACE;
3408 // To block doccomment inside attribute declaration.
3409 if (doc_state == XmlCommentState.Allowed)
3410 doc_state = XmlCommentState.NotAllowed;
3412 val = ltb.Create (current_source, ref_line, col);
3414 if (parsing_block == 0 || lambda_arguments_parsing)
3415 return Token.OPEN_BRACKET;
3417 int next = peek_char ();
3421 return Token.OPEN_BRACKET;
3431 next = peek_token ();
3432 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3433 return Token.OPEN_BRACKET;
3435 return Token.OPEN_BRACKET_EXPR;
3437 return Token.OPEN_BRACKET_EXPR;
3440 ltb.CreateOptional (current_source, ref_line, col, ref val);
3441 return Token.CLOSE_BRACKET;
3443 val = ltb.Create (current_source, ref_line, col);
3445 // An expression versions of parens can appear in block context only
3447 if (parsing_block != 0 && !lambda_arguments_parsing) {
3450 // Optmize most common case where we know that parens
3453 switch (current_token) {
3454 case Token.IDENTIFIER:
3463 case Token.DELEGATE:
3464 case Token.OP_GENERICS_GT:
3465 return Token.OPEN_PARENS;
3468 // Optimize using peek
3469 int xx = peek_char ();
3476 return Token.OPEN_PARENS;
3479 lambda_arguments_parsing = true;
3481 d = TokenizeOpenParens ();
3483 lambda_arguments_parsing = false;
3487 return Token.OPEN_PARENS;
3489 ltb.CreateOptional (current_source, ref_line, col, ref val);
3490 return Token.CLOSE_PARENS;
3492 ltb.CreateOptional (current_source, ref_line, col, ref val);
3495 ltb.CreateOptional (current_source, ref_line, col, ref val);
3496 return Token.SEMICOLON;
3498 val = ltb.Create (current_source, ref_line, col);
3501 val = ltb.Create (current_source, ref_line, col);
3502 return TokenizePossibleNullableType ();
3504 val = ltb.Create (current_source, ref_line, col);
3505 if (parsing_generic_less_than++ > 0)
3506 return Token.OP_GENERICS_LT;
3508 return TokenizeLessThan ();
3511 val = ltb.Create (current_source, ref_line, col);
3519 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3520 parsing_generic_less_than--;
3521 return Token.OP_GENERICS_GT;
3530 return Token.OP_SHIFT_RIGHT_ASSIGN;
3532 return Token.OP_SHIFT_RIGHT;
3538 val = ltb.Create (current_source, ref_line, col);
3542 } else if (d == '=') {
3543 d = Token.OP_ADD_ASSIGN;
3551 val = ltb.Create (current_source, ref_line, col);
3555 } else if (d == '=')
3556 d = Token.OP_SUB_ASSIGN;
3566 val = ltb.Create (current_source, ref_line, col);
3567 if (peek_char () == '='){
3574 val = ltb.Create (current_source, ref_line, col);
3585 return Token.ASSIGN;
3588 val = ltb.Create (current_source, ref_line, col);
3592 return Token.OP_AND;
3596 return Token.OP_AND_ASSIGN;
3598 return Token.BITWISE_AND;
3601 val = ltb.Create (current_source, ref_line, col);
3609 return Token.OP_OR_ASSIGN;
3611 return Token.BITWISE_OR;
3614 val = ltb.Create (current_source, ref_line, col);
3615 if (peek_char () == '='){
3617 return Token.OP_MULT_ASSIGN;
3624 val = ltb.Create (current_source, ref_line, col);
3626 return Token.OP_DIV_ASSIGN;
3629 // Handle double-slash comments.
3631 if (parsing_string_interpolation > 0) {
3632 Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3637 if (doc_processing) {
3638 if (peek_char () == '/') {
3640 // Don't allow ////.
3641 if ((d = peek_char ()) != '/') {
3642 if (doc_state == XmlCommentState.Allowed)
3643 handle_one_line_xml_comment ();
3644 else if (doc_state == XmlCommentState.NotAllowed)
3645 WarningMisplacedComment (Location - 3);
3648 if (xml_comment_buffer.Length > 0)
3649 doc_state = XmlCommentState.NotAllowed;
3655 any_token_seen |= tokens_seen;
3656 tokens_seen = false;
3657 comments_seen = false;
3659 } else if (d == '*'){
3661 bool docAppend = false;
3662 if (doc_processing && peek_char () == '*') {
3664 // But when it is /**/, just do nothing.
3665 if (peek_char () == '/') {
3669 if (doc_state == XmlCommentState.Allowed)
3671 else if (doc_state == XmlCommentState.NotAllowed) {
3672 WarningMisplacedComment (Location - 2);
3676 int current_comment_start = 0;
3678 current_comment_start = xml_comment_buffer.Length;
3679 xml_comment_buffer.Append (Environment.NewLine);
3682 while ((d = get_char ()) != -1){
3683 if (d == '*' && peek_char () == '/'){
3685 comments_seen = true;
3689 xml_comment_buffer.Append ((char) d);
3691 if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3692 any_token_seen |= tokens_seen;
3693 tokens_seen = false;
3695 // Reset 'comments_seen' just to be consistent.
3696 // It doesn't matter either way, here.
3698 comments_seen = false;
3702 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3705 update_formatted_doc_comment (current_comment_start);
3708 val = ltb.Create (current_source, ref_line, col);
3712 val = ltb.Create (current_source, ref_line, col);
3713 if (peek_char () == '='){
3715 return Token.OP_MOD_ASSIGN;
3717 return Token.PERCENT;
3720 val = ltb.Create (current_source, ref_line, col);
3721 if (peek_char () == '='){
3723 return Token.OP_XOR_ASSIGN;
3725 return Token.CARRET;
3728 val = ltb.Create (current_source, ref_line, col);
3729 if (peek_char () == ':') {
3731 return Token.DOUBLE_COLON;
3735 case '0': case '1': case '2': case '3': case '4':
3736 case '5': case '6': case '7': case '8': case '9':
3738 return is_number (c, false);
3740 case '\n': // white space
3743 any_token_seen |= tokens_seen;
3744 tokens_seen = false;
3745 comments_seen = false;
3751 if (d >= '0' && d <= '9')
3752 return is_number (c, true);
3754 ltb.CreateOptional (current_source, ref_line, col, ref val);
3758 if (tokens_seen || comments_seen) {
3759 Eror_WrongPreprocessorLocation ();
3763 if (ParsePreprocessingDirective (true))
3766 bool directive_expected = false;
3767 while ((c = get_char ()) != -1) {
3769 directive_expected = true;
3770 } else if (!directive_expected) {
3771 // TODO: Implement comment support for disabled code and uncomment this code
3773 // Eror_WrongPreprocessorLocation ();
3774 // return Token.ERROR;
3779 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3783 if (ParsePreprocessingDirective (false))
3786 directive_expected = false;
3790 tokens_seen = false;
3797 if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3798 parsing_string_interpolation = 0;
3799 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3800 val = new StringLiteral (context.BuiltinTypes, "", Location);
3801 return Token.INTERPOLATED_STRING_END;
3804 return consume_string (false);
3807 return TokenizeBackslash ();
3813 return consume_string (true);
3816 if (is_identifier_start_character (c)){
3817 return consume_identifier (c, true);
3820 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3824 switch (peek_char ()) {
3827 return TokenizeInterpolatedString (false);
3830 if (peek_char () == '"') {
3832 return TokenizeInterpolatedString (true);
3839 case EvalStatementParserCharacter:
3840 return Token.EVAL_STATEMENT_PARSER;
3841 case EvalCompilationUnitParserCharacter:
3842 return Token.EVAL_COMPILATION_UNIT_PARSER;
3843 case EvalUsingDeclarationsParserCharacter:
3844 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3845 case DocumentationXref:
3846 return Token.DOC_SEE;
3849 if (is_identifier_start_character (c)) {
3851 return consume_identifier (c);
3854 if (char.IsWhiteSpace ((char) c))
3857 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3862 return Token.COMPLETE_COMPLETION;
3865 return Token.GENERATE_COMPLETION;
3872 int TokenizeBackslash ()
3875 int read_start = reader.Position;
3877 Location start_location = Location;
3878 int c = get_char ();
3881 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3882 Report.Error (1011, start_location, "Empty character literal");
3883 return Token.LITERAL;
3886 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3887 Report.Error (1010, start_location, "Newline in constant");
3892 c = escape (c, out d);
3896 throw new NotImplementedException ();
3898 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3903 Report.Error (1012, start_location, "Too many characters in character literal");
3905 // Try to recover, read until newline or next "'"
3906 while ((c = get_char ()) != -1) {
3907 if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3913 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3916 return Token.LITERAL;
3919 int TokenizeLessThan ()
3923 // Save current position and parse next token.
3925 int generic_dimension = 0;
3926 if (parse_less_than (ref generic_dimension)) {
3927 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3928 d = Token.OP_GENERICS_LT_DECL;
3930 if (generic_dimension > 0) {
3931 val = generic_dimension;
3933 return Token.GENERIC_DIMENSION;
3936 d = Token.OP_GENERICS_LT;
3943 parsing_generic_less_than = 0;
3952 return Token.OP_SHIFT_LEFT_ASSIGN;
3954 return Token.OP_SHIFT_LEFT;
3964 int TokenizeInterpolatedString (bool quoted)
3967 var start_location = Location;
3970 var ch = get_char ();
3973 if (quoted && peek_char () == '"') {
3978 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3979 return Token.INTERPOLATED_STRING_END;
3981 if (peek_char () == '{') {
3982 value_builder [pos++] = (char)ch;
3987 ++parsing_string_interpolation;
3989 if (parsing_string_interpolation_quoted == null)
3990 parsing_string_interpolation_quoted = new Stack<bool> ();
3993 if (parsing_string_interpolation_quoted != null) {
3994 parsing_string_interpolation_quoted.Push (quoted);
3997 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3998 return Token.INTERPOLATED_STRING;
4005 ch = escape (ch, out surrogate);
4009 if (ch == '{' || ch == '}') {
4010 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4013 if (surrogate != 0) {
4014 if (pos == value_builder.Length)
4015 Array.Resize (ref value_builder, pos * 2);
4017 if (pos == value_builder.Length)
4018 Array.Resize (ref value_builder, pos * 2);
4020 value_builder [pos++] = (char)ch;
4030 if (pos == value_builder.Length)
4031 Array.Resize (ref value_builder, pos * 2);
4033 value_builder[pos++] = (char) ch;
4037 int TokenizeInterpolationFormat ()
4042 var ch = get_char ();
4051 Report.Error (8089, Location, "Empty interpolated expression format specifier");
4052 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
4053 Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
4056 val = CreateStringFromBuilder (pos);
4057 return Token.LITERAL;
4063 if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Peek ())
4068 ch = escape (ch, out surrogate);
4072 if (ch == '{' || ch == '}') {
4073 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4076 if (surrogate != 0) {
4077 if (pos == value_builder.Length)
4078 Array.Resize (ref value_builder, pos * 2);
4080 value_builder [pos++] = (char)ch;
4090 value_builder[pos++] = (char) ch;
4094 string CreateStringFromBuilder (int pos)
4097 return string.Empty;
4099 return InternIdentifier (value_builder, pos);
4101 return new string (value_builder, 0, pos);
4105 // Handles one line xml comment
4107 private void handle_one_line_xml_comment ()
4110 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4111 xml_comment_buffer.Append ((char) get_char ());
4113 if (c == '\r' || c == '\n')
4114 xml_comment_buffer.Append (Environment.NewLine);
4118 // Remove heading "*" in Javadoc-like xml documentation.
4120 private void update_formatted_doc_comment (int current_comment_start)
4122 int length = xml_comment_buffer.Length - current_comment_start;
4123 string [] lines = xml_comment_buffer.ToString (
4124 current_comment_start,
4125 length).Replace ("\r", "").Split ('\n');
4127 // The first line starts with /**, thus it is not target
4128 // for the format check.
4129 for (int i = 1; i < lines.Length; i++) {
4130 string s = lines [i];
4131 int idx = s.IndexOf ('*');
4134 if (i < lines.Length - 1)
4138 head = s.Substring (0, idx);
4139 foreach (char c in head)
4142 lines [i] = s.Substring (idx + 1);
4144 xml_comment_buffer.Remove (current_comment_start, length);
4145 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4149 // Checks if there was incorrect doc comments and raise
4152 public void check_incorrect_doc_comment ()
4154 if (xml_comment_buffer.Length > 0)
4155 WarningMisplacedComment (Location);
4159 // Consumes the saved xml comment lines (if any)
4160 // as for current target member or type.
4162 public string consume_doc_comment ()
4164 if (xml_comment_buffer.Length > 0) {
4165 string ret = xml_comment_buffer.ToString ();
4166 reset_doc_comment ();
4172 void reset_doc_comment ()
4174 xml_comment_buffer.Length = 0;
4177 public void cleanup ()
4179 if (ifstack != null && ifstack.Count >= 1) {
4180 int state = ifstack.Pop ();
4181 if ((state & REGION) != 0)
4182 Report.Error (1038, Location, "#endregion directive expected");
4184 Report.Error (1027, Location, "Expected `#endif' directive");
4190 // Indicates whether it accepts XML documentation or not.
4192 public enum XmlCommentState {
4193 // comment is allowed in this state.
4195 // comment is not allowed in this state.
4197 // once comments appeared when it is NotAllowed, then the
4198 // state is changed to it, until the state is changed to