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)
898 switch (current_token) {
900 case Token.OP_COALESCING:
902 res = Token.THROW_EXPR;
913 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
916 // Keywords are stored in an array of arrays grouped by their
917 // length and then by the first character
919 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
920 return PreprocessorDirective.Invalid;
922 int first_index = id[0] - '_';
923 if (first_index > 'z' - '_')
924 return PreprocessorDirective.Invalid;
926 var kwe = keywords_preprocessor[id_len][first_index];
928 return PreprocessorDirective.Invalid;
930 PreprocessorDirective res = PreprocessorDirective.Invalid;
933 for (int i = 1; i < id_len; ++i) {
934 if (id[i] != kwe.Value[i]) {
940 } while (res == PreprocessorDirective.Invalid && kwe != null);
945 public Location Location {
947 return new Location (current_source, ref_line, col);
951 static bool is_identifier_start_character (int c)
953 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')
959 return is_identifier_start_character_slow_part ((char) c);
962 static bool is_identifier_part_character (char c)
964 if (c >= 'a' && c <= 'z')
967 if (c >= 'A' && c <= 'Z')
970 if (c == '_' || (c >= '0' && c <= '9'))
976 return is_identifier_part_character_slow_part (c);
979 static bool is_identifier_start_character_slow_part (char c)
981 switch (Char.GetUnicodeCategory (c)) {
982 case UnicodeCategory.LetterNumber:
983 case UnicodeCategory.UppercaseLetter:
984 case UnicodeCategory.LowercaseLetter:
985 case UnicodeCategory.TitlecaseLetter:
986 case UnicodeCategory.ModifierLetter:
987 case UnicodeCategory.OtherLetter:
993 static bool is_identifier_part_character_slow_part (char c)
995 switch (Char.GetUnicodeCategory (c)) {
996 // connecting-character: A Unicode character of the class Pc
997 case UnicodeCategory.ConnectorPunctuation:
999 // combining-character: A Unicode character of classes Mn or Mc
1000 case UnicodeCategory.NonSpacingMark:
1001 case UnicodeCategory.SpacingCombiningMark:
1003 // decimal-digit-character: A Unicode character of the class Nd
1004 case UnicodeCategory.DecimalDigitNumber:
1006 // plus is_identifier_start_character_slow_part
1007 case UnicodeCategory.LetterNumber:
1008 case UnicodeCategory.UppercaseLetter:
1009 case UnicodeCategory.LowercaseLetter:
1010 case UnicodeCategory.TitlecaseLetter:
1011 case UnicodeCategory.ModifierLetter:
1012 case UnicodeCategory.OtherLetter:
1015 // formatting-character: A Unicode character of the class Cf
1016 case UnicodeCategory.Format:
1017 // csc bug compatibility which recognizes it as a whitespace
1024 public static bool IsKeyword (string s)
1026 return keyword_strings.Contains (s);
1030 // Open parens micro parser. Detects both lambda and cast ambiguity.
1032 int TokenizeOpenParens ()
1037 int bracket_level = 0;
1038 bool is_type = false;
1039 bool can_be_type = false;
1042 ptoken = current_token;
1045 switch (current_token) {
1046 case Token.CLOSE_PARENS:
1050 // Expression inside parens is lambda, (int i) =>
1052 if (current_token == Token.ARROW)
1053 return Token.OPEN_PARENS_LAMBDA;
1056 // Expression inside parens is single type, (int[])
1059 if (current_token == Token.SEMICOLON)
1060 return Token.OPEN_PARENS;
1062 return Token.OPEN_PARENS_CAST;
1066 // Expression is possible cast, look at next token, (T)null
1069 switch (current_token) {
1070 case Token.OPEN_PARENS:
1073 case Token.IDENTIFIER:
1077 case Token.DELEGATE:
1087 case Token.UNCHECKED:
1093 // These can be part of a member access
1109 return Token.OPEN_PARENS_CAST;
1112 return Token.OPEN_PARENS;
1115 case Token.DOUBLE_COLON:
1116 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1121 case Token.IDENTIFIER:
1125 if (bracket_level == 0) {
1131 case Token.OP_GENERICS_LT:
1133 case Token.DOUBLE_COLON:
1135 if (bracket_level == 0)
1139 can_be_type = is_type = false;
1159 if (bracket_level == 0)
1164 if (bracket_level == 0) {
1165 bracket_level = 100;
1166 can_be_type = is_type = false;
1170 case Token.OP_GENERICS_LT:
1171 case Token.OPEN_BRACKET:
1172 if (bracket_level++ == 0)
1176 case Token.OP_GENERICS_GT:
1177 case Token.CLOSE_BRACKET:
1181 case Token.INTERR_NULLABLE:
1183 if (bracket_level == 0)
1189 can_be_type = is_type = false;
1193 return Token.OPEN_PARENS;
1198 public static bool IsValidIdentifier (string s)
1200 if (s == null || s.Length == 0)
1203 if (!is_identifier_start_character (s [0]))
1206 for (int i = 1; i < s.Length; i ++)
1207 if (! is_identifier_part_character (s [i]))
1213 bool parse_less_than (ref int genericDimension)
1216 int the_token = token ();
1217 if (the_token == Token.OPEN_BRACKET) {
1219 the_token = token ();
1220 if (the_token == Token.EOF)
1223 if (the_token == Token.CLOSE_BRACKET)
1226 the_token = token ();
1227 } else if (the_token == Token.IN || the_token == Token.OUT) {
1228 the_token = token ();
1230 switch (the_token) {
1231 case Token.IDENTIFIER:
1249 case Token.OP_GENERICS_GT:
1250 genericDimension = 1;
1258 the_token = token ();
1259 } while (the_token == Token.COMMA);
1261 if (the_token == Token.OP_GENERICS_GT) {
1271 the_token = token ();
1273 if (the_token == Token.OP_GENERICS_GT)
1275 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1277 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1279 else if (the_token == Token.OP_GENERICS_LT) {
1281 if (!parse_less_than (ref unused))
1284 } else if (the_token == Token.OPEN_BRACKET) {
1286 the_token = token ();
1287 if (the_token == Token.CLOSE_BRACKET)
1289 else if (the_token == Token.COMMA)
1290 goto rank_specifiers;
1297 public int peek_token ()
1302 the_token = token ();
1309 // Tonizes `?' using custom disambiguous rules to return one
1310 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1312 // Tricky expression looks like:
1314 // Foo ? a = x ? b : c;
1316 int TokenizePossibleNullableType ()
1318 if (parsing_block == 0 || parsing_type > 0)
1319 return Token.INTERR_NULLABLE;
1321 int d = peek_char ();
1324 return Token.OP_COALESCING;
1329 return d >= '0' && d <= '9' ? Token.INTERR : Token.INTERR_OPERATOR;
1333 if (d == ',' || d == ';' || d == '>')
1334 return Token.INTERR_NULLABLE;
1335 if (d == '*' || (d >= '0' && d <= '9'))
1336 return Token.INTERR;
1340 current_token = Token.NONE;
1349 case Token.OPEN_BRACKET_EXPR:
1350 next_token = Token.INTERR_OPERATOR;
1358 case Token.INTERPOLATED_STRING:
1360 next_token = Token.INTERR;
1363 case Token.SEMICOLON:
1365 case Token.CLOSE_PARENS:
1366 case Token.OPEN_BRACKET:
1367 case Token.OP_GENERICS_GT:
1369 case Token.OP_COALESCING:
1371 next_token = Token.INTERR_NULLABLE;
1374 case Token.OPEN_PARENS:
1375 case Token.OPEN_PARENS_CAST:
1376 case Token.OPEN_PARENS_LAMBDA:
1381 case Token.OP_GENERICS_LT:
1382 case Token.OP_GENERICS_LT_DECL:
1383 case Token.GENERIC_DIMENSION:
1393 if (next_token == -1) {
1394 switch (xtoken ()) {
1396 case Token.SEMICOLON:
1397 case Token.OPEN_BRACE:
1399 next_token = Token.INTERR_NULLABLE;
1403 next_token = Token.INTERR;
1406 case Token.OPEN_PARENS:
1407 case Token.OPEN_PARENS_CAST:
1408 case Token.OPEN_PARENS_LAMBDA:
1412 case Token.OPEN_BRACKET:
1413 case Token.OPEN_BRACKET_EXPR:
1417 case Token.CLOSE_PARENS:
1421 case Token.OP_GENERICS_LT:
1422 case Token.OP_GENERICS_LT_DECL:
1423 case Token.GENERIC_DIMENSION:
1433 // All shorcuts failed, do it hard way
1435 while ((ntoken = xtoken ()) != Token.EOF) {
1437 case Token.OPEN_BRACE:
1440 case Token.OPEN_PARENS:
1441 case Token.OPEN_PARENS_CAST:
1442 case Token.OPEN_PARENS_LAMBDA:
1445 case Token.CLOSE_BRACE:
1448 case Token.OP_GENERICS_LT:
1449 case Token.OP_GENERICS_LT_DECL:
1450 case Token.GENERIC_DIMENSION:
1453 case Token.OPEN_BRACKET:
1454 case Token.OPEN_BRACKET_EXPR:
1457 case Token.CLOSE_BRACKET:
1460 case Token.CLOSE_PARENS:
1467 return Token.INTERR_NULLABLE;
1469 case Token.OP_GENERICS_GT:
1476 return Token.INTERR_NULLABLE;
1482 if (ntoken == Token.SEMICOLON)
1488 if (ntoken == Token.COMMA) {
1489 if (generics != 0 || brackets != 0)
1493 return Token.INTERR_NULLABLE;
1496 if (ntoken == Token.COLON) {
1497 if (++colons == interrs)
1502 if (ntoken == Token.INTERR) {
1508 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1517 bool decimal_digits (int c)
1520 bool seen_digits = false;
1523 if (number_pos == MaxNumberLength)
1524 Error_NumericConstantTooLong ();
1525 number_builder [number_pos++] = (char) c;
1529 // We use peek_char2, because decimal_digits needs to do a
1530 // 2-character look-ahead (5.ToString for example).
1532 while ((d = peek_char2 ()) != -1){
1533 if (d >= '0' && d <= '9'){
1534 if (number_pos == MaxNumberLength)
1535 Error_NumericConstantTooLong ();
1536 number_builder [number_pos++] = (char) d;
1546 static bool is_hex (int e)
1548 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1551 static TypeCode real_type_suffix (int c)
1555 return TypeCode.Single;
1557 return TypeCode.Double;
1559 return TypeCode.Decimal;
1561 return TypeCode.Empty;
1565 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1567 bool is_unsigned = false;
1568 bool is_long = false;
1571 bool scanning = true;
1584 // if we have not seen anything in between
1585 // report this error
1587 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1607 if (is_long && is_unsigned){
1608 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1612 // uint if possible, or ulong else.
1614 if ((ul & 0xffffffff00000000) == 0)
1615 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1617 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1618 } else if (is_long){
1619 // long if possible, ulong otherwise
1620 if ((ul & 0x8000000000000000) != 0)
1621 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1623 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1625 // int, uint, long or ulong in that order
1626 if ((ul & 0xffffffff00000000) == 0){
1627 uint ui = (uint) ul;
1629 if ((ui & 0x80000000) != 0)
1630 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1632 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1634 if ((ul & 0x8000000000000000) != 0)
1635 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1637 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1643 // given `c' as the next char in the input decide whether
1644 // we need to convert to a special type, and then choose
1645 // the best representation for the integer
1647 ILiteralConstant adjust_int (int c, Location loc)
1650 if (number_pos > 9){
1651 ulong ul = (uint) (number_builder [0] - '0');
1653 for (int i = 1; i < number_pos; i++){
1654 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1657 return integer_type_suffix (ul, c, loc);
1659 uint ui = (uint) (number_builder [0] - '0');
1661 for (int i = 1; i < number_pos; i++){
1662 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1665 return integer_type_suffix (ui, c, loc);
1667 } catch (OverflowException) {
1668 Error_NumericConstantTooLong ();
1669 return new IntLiteral (context.BuiltinTypes, 0, loc);
1671 catch (FormatException) {
1672 Report.Error (1013, Location, "Invalid number");
1673 return new IntLiteral (context.BuiltinTypes, 0, loc);
1677 ILiteralConstant adjust_real (TypeCode t, Location loc)
1679 string s = new string (number_builder, 0, number_pos);
1680 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1683 case TypeCode.Decimal:
1685 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1686 } catch (OverflowException) {
1687 Report.Error (594, Location, error_details, "decimal");
1688 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1690 case TypeCode.Single:
1692 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1693 } catch (OverflowException) {
1694 Report.Error (594, Location, error_details, "float");
1695 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1699 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1700 } catch (OverflowException) {
1701 Report.Error (594, loc, error_details, "double");
1702 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1707 ILiteralConstant handle_hex (Location loc)
1713 while ((d = peek_char ()) != -1){
1715 number_builder [number_pos++] = (char) d;
1721 string s = new String (number_builder, 0, number_pos);
1724 if (number_pos <= 8)
1725 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1727 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1729 return integer_type_suffix (ul, peek_char (), loc);
1730 } catch (OverflowException){
1731 Error_NumericConstantTooLong ();
1732 return new IntLiteral (context.BuiltinTypes, 0, loc);
1734 catch (FormatException) {
1735 Report.Error (1013, Location, "Invalid number");
1736 return new IntLiteral (context.BuiltinTypes, 0, loc);
1741 // Invoked if we know we have .digits or digits
1743 int is_number (int c, bool dotLead)
1745 ILiteralConstant res;
1748 int read_start = reader.Position - 1;
1751 // Caller did peek_char
1761 int peek = peek_char ();
1763 if (peek == 'x' || peek == 'X') {
1764 val = res = handle_hex (loc);
1766 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1769 return Token.LITERAL;
1777 // We need to handle the case of
1778 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1780 bool is_real = false;
1785 if (decimal_digits ('.')){
1791 val = res = adjust_int (-1, loc);
1794 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1796 return Token.LITERAL;
1800 if (c == 'e' || c == 'E'){
1803 if (number_pos == MaxNumberLength)
1804 Error_NumericConstantTooLong ();
1805 number_builder [number_pos++] = (char) c;
1809 if (number_pos == MaxNumberLength)
1810 Error_NumericConstantTooLong ();
1811 number_builder [number_pos++] = '+';
1813 } else if (c == '-') {
1814 if (number_pos == MaxNumberLength)
1815 Error_NumericConstantTooLong ();
1816 number_builder [number_pos++] = '-';
1819 if (number_pos == MaxNumberLength)
1820 Error_NumericConstantTooLong ();
1821 number_builder [number_pos++] = '+';
1828 var type = real_type_suffix (c);
1829 if (type == TypeCode.Empty && !is_real) {
1830 res = adjust_int (c, loc);
1834 if (type != TypeCode.Empty) {
1838 res = adjust_real (type, loc);
1844 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1845 if (chars[chars.Length - 1] == '\r')
1846 Array.Resize (ref chars, chars.Length - 1);
1847 res.ParsedValue = chars;
1850 return Token.LITERAL;
1854 // Accepts exactly count (4 or 8) hex, no more no less
1856 int getHex (int count, out int surrogate, out bool error)
1861 int top = count != -1 ? count : 4;
1866 for (i = 0; i < top; i++){
1869 if (c >= '0' && c <= '9')
1870 c = (int) c - (int) '0';
1871 else if (c >= 'A' && c <= 'F')
1872 c = (int) c - (int) 'A' + 10;
1873 else if (c >= 'a' && c <= 'f')
1874 c = (int) c - (int) 'a' + 10;
1880 total = (total * 16) + c;
1882 int p = peek_char ();
1885 if (!is_hex ((char)p))
1891 if (total > 0x0010FFFF) {
1896 if (total >= 0x00010000) {
1897 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1898 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1905 int escape (int c, out int surrogate)
1941 v = getHex (-1, out surrogate, out error);
1947 return EscapeUnicode (d, out surrogate);
1950 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1959 int EscapeUnicode (int ch, out int surrogate)
1963 ch = getHex (8, out surrogate, out error);
1965 ch = getHex (4, out surrogate, out error);
1969 Report.Error (1009, Location, "Unrecognized escape sequence");
1977 if (putback_char != -1) {
1986 if (peek_char () == '\n') {
1992 } else if (x == '\n') {
1997 } else if (x >= UnicodeLS && x <= UnicodePS) {
2006 void advance_line ()
2016 if (putback_char == -1)
2017 putback_char = reader.Read ();
2018 return putback_char;
2023 if (putback_char != -1)
2024 return putback_char;
2025 return reader.Peek ();
2028 public void putback (int c)
2030 if (putback_char != -1) {
2031 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
2034 if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
2035 // It won't happen though.
2045 public bool advance ()
2047 return peek_char () != -1 || CompleteOnEOF;
2050 public Object Value {
2056 public Object value ()
2063 current_token = xtoken ();
2064 return current_token;
2067 int TokenizePreprocessorKeyword (out int c)
2069 // skip over white space
2072 } while (c == ' ' || c == '\t');
2076 while (c != -1 && c >= 'a' && c <= 'z') {
2077 id_builder[pos++] = (char) c;
2080 int peek = peek_char ();
2081 if (peek == 'U' || peek == 'u') {
2083 c = EscapeUnicode (c, out surrogate);
2084 if (surrogate != 0) {
2085 if (is_identifier_part_character ((char) c)) {
2086 id_builder[pos++] = (char) c;
2097 PreprocessorDirective get_cmd_arg (out string arg)
2101 tokens_seen = false;
2104 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2106 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2109 // skip over white space
2110 while (c == ' ' || c == '\t')
2113 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2116 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2117 if (c == '\\' && has_identifier_argument >= 0) {
2118 if (has_identifier_argument != 0) {
2119 has_identifier_argument = 1;
2121 int peek = peek_char ();
2122 if (peek == 'U' || peek == 'u') {
2124 c = EscapeUnicode (c, out surrogate);
2125 if (surrogate != 0) {
2126 if (is_identifier_part_character ((char) c)) {
2127 if (pos == value_builder.Length)
2128 Array.Resize (ref value_builder, pos * 2);
2130 value_builder[pos++] = (char) c;
2136 has_identifier_argument = -1;
2138 } else if (c == '/' && peek_char () == '/') {
2140 // Eat single-line comments
2147 if (pos == value_builder.Length)
2148 Array.Resize (ref value_builder, pos * 2);
2150 value_builder[pos++] = (char) c;
2155 if (pos > MaxIdentifierLength)
2156 arg = new string (value_builder, 0, pos);
2158 arg = InternIdentifier (value_builder, pos);
2160 // Eat any trailing whitespaces
2161 arg = arg.Trim (simple_whitespaces);
2168 // Handles the #line directive
2170 bool PreProcessLine ()
2172 Location loc = Location;
2176 int length = TokenizePreprocessorKeyword (out c);
2177 if (length == line_default.Length) {
2178 if (!IsTokenIdentifierEqual (line_default))
2181 current_source = source_file.SourceFile;
2182 if (!hidden_block_start.IsNull) {
2183 current_source.RegisterHiddenScope (hidden_block_start, loc);
2184 hidden_block_start = Location.Null;
2191 if (length == line_hidden.Length) {
2192 if (!IsTokenIdentifierEqual (line_hidden))
2195 if (hidden_block_start.IsNull)
2196 hidden_block_start = loc;
2201 if (length != 0 || c < '0' || c > '9') {
2203 // Eat any remaining characters to continue parsing on next line
2209 int new_line = TokenizeNumber (c);
2212 // Eat any remaining characters to continue parsing on next line
2215 return new_line != 0;
2220 // skip over white space
2223 } while (c == ' ' || c == '\t');
2224 } else if (c == '"') {
2228 if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2230 // Eat any remaining characters to continue parsing on next line
2234 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2238 string new_file_name = null;
2240 new_file_name = TokenizeFileName (ref c);
2242 // skip over white space
2243 while (c == ' ' || c == '\t') {
2248 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2250 } else if (c == '/') {
2251 ReadSingleLineComment ();
2254 // Eat any remaining characters to continue parsing on next line
2258 Error_EndLineExpected ();
2262 if (new_file_name != null) {
2263 current_source = context.LookupFile (source_file, new_file_name);
2264 source_file.AddIncludeFile (current_source);
2267 if (!hidden_block_start.IsNull) {
2268 current_source.RegisterHiddenScope (hidden_block_start, loc);
2269 hidden_block_start = Location.Null;
2272 ref_line = new_line;
2277 // Handles #define and #undef
2279 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2281 if (ident.Length == 0 || ident == "true" || ident == "false"){
2282 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2286 if (ident.IndexOfAny (simple_whitespaces) != -1){
2287 Error_EndLineExpected ();
2291 if (!is_identifier_start_character (ident [0]))
2292 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2294 foreach (char c in ident.Substring (1)){
2295 if (!is_identifier_part_character (c)){
2296 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2301 if (!caller_is_taking)
2308 if (context.Settings.IsConditionalSymbolDefined (ident))
2311 source_file.AddDefine (ident);
2316 source_file.AddUndefine (ident);
2320 byte read_hex (out bool error)
2323 int c = get_char ();
2325 if ((c >= '0') && (c <= '9'))
2326 total = (int) c - (int) '0';
2327 else if ((c >= 'A') && (c <= 'F'))
2328 total = (int) c - (int) 'A' + 10;
2329 else if ((c >= 'a') && (c <= 'f'))
2330 total = (int) c - (int) 'a' + 10;
2339 if ((c >= '0') && (c <= '9'))
2340 total += (int) c - (int) '0';
2341 else if ((c >= 'A') && (c <= 'F'))
2342 total += (int) c - (int) 'A' + 10;
2343 else if ((c >= 'a') && (c <= 'f'))
2344 total += (int) c - (int) 'a' + 10;
2351 return (byte) total;
2355 // Parses #pragma checksum
2357 bool ParsePragmaChecksum ()
2360 // The syntax is ` "foo.txt" "{guid}" "hash"'
2362 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2364 int c = get_char ();
2369 string file_name = TokenizeFileName (ref c);
2371 // TODO: Any white-spaces count
2375 SourceFile file = context.LookupFile (source_file, file_name);
2377 if (get_char () != '"' || get_char () != '{')
2381 byte[] guid_bytes = new byte [16];
2384 for (; i < 4; i++) {
2385 guid_bytes [i] = read_hex (out error);
2390 if (get_char () != '-')
2393 for (; i < 10; i++) {
2394 guid_bytes [i] = read_hex (out error);
2398 guid_bytes [i++] = read_hex (out error);
2402 if (get_char () != '-')
2406 for (; i < 16; i++) {
2407 guid_bytes [i] = read_hex (out error);
2412 if (get_char () != '}' || get_char () != '"')
2415 // TODO: Any white-spaces count
2420 if (get_char () != '"')
2423 // Any length of checksum
2424 List<byte> checksum_bytes = new List<byte> (16);
2426 var checksum_location = Location;
2428 while (c != '"' && c != -1) {
2429 checksum_bytes.Add (read_hex (out error));
2437 ReadSingleLineComment ();
2438 } else if (get_char () != '"') {
2442 if (context.Settings.GenerateDebugInfo) {
2443 var chsum = checksum_bytes.ToArray ();
2445 if (file.HasChecksum) {
2446 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2447 // TODO: Report.SymbolRelatedToPreviousError
2448 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2452 file.SetChecksum (guid_bytes, chsum);
2453 current_source.AutoGenerated = true;
2459 bool IsTokenIdentifierEqual (char[] identifier)
2461 for (int i = 0; i < identifier.Length; ++i) {
2462 if (identifier[i] != id_builder[i])
2469 bool ScanClosingInterpolationBrace ()
2476 var c = reader.Read ();
2482 // Skip escaped " character
2491 if (str_quote % 2 == 1) {
2497 } while (res == null);
2503 int TokenizeNumber (int value)
2507 decimal_digits (value);
2508 uint ui = (uint) (number_builder[0] - '0');
2511 for (int i = 1; i < number_pos; i++) {
2512 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2516 } catch (OverflowException) {
2517 Error_NumericConstantTooLong ();
2522 string TokenizeFileName (ref int c)
2524 var string_builder = new StringBuilder ();
2525 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2532 string_builder.Append ((char) c);
2535 if (string_builder.Length == 0) {
2536 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2540 return string_builder.ToString ();
2543 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2545 if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2548 if (c >= '0' && c <= '9') {
2550 number = TokenizeNumber (c);
2554 if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2555 return ReadPragmaWarningComment (c);
2559 // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2563 id_builder [pos++] = (char)c;
2564 while (c < MaxIdentifierLength) {
2566 id_builder [pos] = (char)c;
2568 if (c >= '0' && c <= '9') {
2569 if (pos == 5 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2570 // Recognize CSXXXX as C# XXXX warning
2573 for (int i = 0; i < 4; ++i) {
2574 var ch = id_builder [i + 2];
2575 if (ch < '0' || ch > '9') {
2580 number += (ch - '0') * pow;
2584 } else if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2587 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2600 // skip over white space
2601 while (c == ' ' || c == '\t')
2608 // skip over white space
2609 while (c == ' ' || c == '\t')
2615 return ReadPragmaWarningComment (c);
2618 int ReadPragmaWarningComment (int c)
2621 ReadSingleLineComment ();
2623 Report.Warning (1692, 1, Location, "Invalid number");
2625 // Read everything till the end of the line or file
2632 void ReadToEndOfLine ()
2637 } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2640 void ReadSingleLineComment ()
2642 if (peek_char () != '/')
2643 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2645 // Read everything till the end of the line or file
2650 /// Handles #pragma directive
2652 void ParsePragmaDirective ()
2655 int length = TokenizePreprocessorKeyword (out c);
2656 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2657 length = TokenizePreprocessorKeyword (out c);
2660 // #pragma warning disable
2661 // #pragma warning restore
2663 if (length == pragma_warning_disable.Length) {
2664 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2665 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2666 // skip over white space
2667 while (c == ' ' || c == '\t')
2672 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2674 ReadSingleLineComment ();
2677 // Disable/Restore all warnings
2680 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2682 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2686 // Disable/Restore a warning or group of warnings
2690 bool identifier = false;
2691 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2694 // no-op, custom warnings cannot occur in mcs
2695 } else if (disable) {
2696 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2698 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2701 } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2708 Report.Warning (1634, 1, Location, "Expected disable or restore");
2710 // Eat any remaining characters on the line
2719 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2720 if (c != ' ' || !ParsePragmaChecksum ()) {
2721 Report.Warning (1695, 1, Location,
2722 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2728 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2730 // Eat any remaining characters on the line
2734 bool eval_val (string s)
2741 return source_file.IsConditionalDefined (s);
2744 bool pp_primary (ref string s)
2753 s = s.Substring (1);
2754 bool val = pp_expr (ref s, false);
2755 if (s.Length > 0 && s [0] == ')'){
2756 s = s.Substring (1);
2759 Error_InvalidDirective ();
2763 if (is_identifier_start_character (c)){
2769 if (is_identifier_part_character (c)){
2773 bool v = eval_val (s.Substring (0, j));
2774 s = s.Substring (j);
2777 bool vv = eval_val (s);
2782 Error_InvalidDirective ();
2786 bool pp_unary (ref string s)
2793 if (len > 1 && s [1] == '='){
2794 Error_InvalidDirective ();
2797 s = s.Substring (1);
2798 return ! pp_primary (ref s);
2800 return pp_primary (ref s);
2802 Error_InvalidDirective ();
2807 bool pp_eq (ref string s)
2809 bool va = pp_unary (ref s);
2815 if (len > 2 && s [1] == '='){
2816 s = s.Substring (2);
2817 return va == pp_unary (ref s);
2819 Error_InvalidDirective ();
2822 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2823 s = s.Substring (2);
2825 return va != pp_unary (ref s);
2834 bool pp_and (ref string s)
2836 bool va = pp_eq (ref s);
2842 if (len > 2 && s [1] == '&'){
2843 s = s.Substring (2);
2844 return (va & pp_and (ref s));
2846 Error_InvalidDirective ();
2855 // Evaluates an expression for `#if' or `#elif'
2857 bool pp_expr (ref string s, bool isTerm)
2859 bool va = pp_and (ref s);
2866 if (len > 2 && s [1] == '|'){
2867 s = s.Substring (2);
2868 return va | pp_expr (ref s, isTerm);
2870 Error_InvalidDirective ();
2875 Error_EndLineExpected ();
2883 bool eval (string s)
2885 bool v = pp_expr (ref s, true);
2894 void Error_NumericConstantTooLong ()
2896 Report.Error (1021, Location, "Integral constant is too large");
2899 void Error_InvalidDirective ()
2901 Report.Error (1517, Location, "Invalid preprocessor directive");
2904 void Error_UnexpectedDirective (string extra)
2908 "Unexpected processor directive ({0})", extra);
2911 void Error_TokensSeen ()
2913 Report.Error (1032, Location,
2914 "Cannot define or undefine preprocessor symbols after first token in file");
2917 void Eror_WrongPreprocessorLocation ()
2919 Report.Error (1040, Location,
2920 "Preprocessor directives must appear as the first non-whitespace character on a line");
2923 void Error_EndLineExpected ()
2925 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2929 // Raises a warning when tokenizer found documentation comment
2930 // on unexpected place
2932 void WarningMisplacedComment (Location loc)
2934 if (doc_state != XmlCommentState.Error) {
2935 doc_state = XmlCommentState.Error;
2936 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2941 // if true, then the code continues processing the code
2942 // if false, the code stays in a loop until another directive is
2944 // When caller_is_taking is false we ignore all directives except the ones
2945 // which can help us to identify where the #if block ends
2946 bool ParsePreprocessingDirective (bool caller_is_taking)
2949 bool region_directive = false;
2951 var directive = get_cmd_arg (out arg);
2954 // The first group of pre-processing instructions is always processed
2956 switch (directive) {
2957 case PreprocessorDirective.Region:
2958 region_directive = true;
2960 goto case PreprocessorDirective.If;
2962 case PreprocessorDirective.Endregion:
2963 if (ifstack == null || ifstack.Count == 0){
2964 Error_UnexpectedDirective ("no #region for this #endregion");
2967 int pop = ifstack.Pop ();
2969 if ((pop & REGION) == 0)
2970 Report.Error (1027, Location, "Expected `#endif' directive");
2972 return caller_is_taking;
2974 case PreprocessorDirective.If:
2975 if (ifstack == null)
2976 ifstack = new Stack<int> (2);
2978 int flags = region_directive ? REGION : 0;
2979 if (ifstack.Count == 0){
2980 flags |= PARENT_TAKING;
2982 int state = ifstack.Peek ();
2983 if ((state & TAKING) != 0) {
2984 flags |= PARENT_TAKING;
2988 if (eval (arg) && caller_is_taking) {
2989 ifstack.Push (flags | TAKING);
2992 ifstack.Push (flags);
2995 case PreprocessorDirective.Endif:
2996 if (ifstack == null || ifstack.Count == 0){
2997 Error_UnexpectedDirective ("no #if for this #endif");
3000 pop = ifstack.Pop ();
3002 if ((pop & REGION) != 0)
3003 Report.Error (1038, Location, "#endregion directive expected");
3005 if (arg.Length != 0) {
3006 Error_EndLineExpected ();
3009 if (ifstack.Count == 0)
3012 int state = ifstack.Peek ();
3013 return (state & TAKING) != 0;
3016 case PreprocessorDirective.Elif:
3017 if (ifstack == null || ifstack.Count == 0){
3018 Error_UnexpectedDirective ("no #if for this #elif");
3021 int state = ifstack.Pop ();
3023 if ((state & REGION) != 0) {
3024 Report.Error (1038, Location, "#endregion directive expected");
3028 if ((state & ELSE_SEEN) != 0){
3029 Error_UnexpectedDirective ("#elif not valid after #else");
3033 if ((state & TAKING) != 0) {
3038 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
3039 ifstack.Push (state | TAKING);
3043 ifstack.Push (state);
3047 case PreprocessorDirective.Else:
3048 if (ifstack == null || ifstack.Count == 0){
3049 Error_UnexpectedDirective ("no #if for this #else");
3052 int state = ifstack.Peek ();
3054 if ((state & REGION) != 0) {
3055 Report.Error (1038, Location, "#endregion directive expected");
3059 if ((state & ELSE_SEEN) != 0){
3060 Error_UnexpectedDirective ("#else within #else");
3066 if (arg.Length != 0) {
3067 Error_EndLineExpected ();
3072 if ((state & PARENT_TAKING) != 0) {
3073 ret = (state & TAKING) == 0;
3081 ifstack.Push (state | ELSE_SEEN);
3085 case PreprocessorDirective.Define:
3086 if (any_token_seen){
3087 if (caller_is_taking)
3088 Error_TokensSeen ();
3089 return caller_is_taking;
3091 PreProcessDefinition (true, arg, caller_is_taking);
3092 return caller_is_taking;
3094 case PreprocessorDirective.Undef:
3095 if (any_token_seen){
3096 if (caller_is_taking)
3097 Error_TokensSeen ();
3098 return caller_is_taking;
3100 PreProcessDefinition (false, arg, caller_is_taking);
3101 return caller_is_taking;
3103 case PreprocessorDirective.Invalid:
3104 Report.Error (1024, Location, "Wrong preprocessor directive");
3109 // These are only processed if we are in a `taking' block
3111 if (!caller_is_taking)
3115 case PreprocessorDirective.Error:
3116 Report.Error (1029, Location, "#error: '{0}'", arg);
3119 case PreprocessorDirective.Warning:
3120 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3123 case PreprocessorDirective.Pragma:
3124 if (context.Settings.Version == LanguageVersion.ISO_1) {
3125 Report.FeatureIsNotAvailable (context, Location, "#pragma");
3128 ParsePragmaDirective ();
3131 case PreprocessorDirective.Line:
3132 Location loc = Location;
3133 if (!PreProcessLine ())
3134 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3136 return caller_is_taking;
3139 throw new NotImplementedException (directive.ToString ());
3142 int consume_string (bool quoted)
3146 Location start_location = Location;
3148 start_location = start_location - 1;
3151 int reader_pos = reader.Position;
3155 // Cannot use get_char because of \r in quoted strings
3156 if (putback_char != -1) {
3166 if (quoted && peek_char () == '"') {
3167 if (pos == value_builder.Length)
3168 Array.Resize (ref value_builder, pos * 2);
3170 value_builder[pos++] = (char) c;
3175 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3178 res.ParsedValue = quoted ?
3179 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3180 reader.ReadChars (reader_pos - 1, reader.Position);
3183 return Token.LITERAL;
3186 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3188 Report.Error (1010, Location, "Newline in constant");
3192 // Don't add \r to string literal
3193 if (pos > 1 && value_builder [pos - 1] == '\r')
3196 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3197 return Token.LITERAL;
3201 } else if (c == '\\' && !quoted) {
3204 c = escape (c, out surrogate);
3207 if (surrogate != 0) {
3208 if (pos == value_builder.Length)
3209 Array.Resize (ref value_builder, pos * 2);
3211 value_builder[pos++] = (char) c;
3214 } else if (c == -1) {
3215 Report.Error (1039, Location, "Unterminated string literal");
3221 if (pos == value_builder.Length)
3222 Array.Resize (ref value_builder, pos * 2);
3224 value_builder[pos++] = (char) c;
3228 private int consume_identifier (int s)
3230 int res = consume_identifier (s, false);
3232 if (doc_state == XmlCommentState.Allowed)
3233 doc_state = XmlCommentState.NotAllowed;
3238 int consume_identifier (int c, bool quoted)
3241 // This method is very performance sensitive. It accounts
3242 // for approximately 25% of all parser time
3252 c = escape (c, out surrogate);
3253 if (quoted || is_identifier_start_character (c)) {
3254 // it's added bellow
3255 } else if (surrogate != 0) {
3256 id_builder [pos++] = (char)c;
3259 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3264 id_builder [pos++] = (char) c;
3270 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3271 id_builder [pos++] = (char) c;
3278 c = escape (c, out surrogate);
3279 if (is_identifier_part_character ((char) c))
3280 id_builder[pos++] = (char) c;
3281 else if (surrogate != 0) {
3285 // TODO: Probably need more whitespace characters
3290 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3297 } else if (is_identifier_part_character_slow_part ((char) c)) {
3298 id_builder [pos++] = (char) c;
3305 } catch (IndexOutOfRangeException) {
3306 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3314 // Optimization: avoids doing the keyword lookup
3315 // on uppercase letters
3317 if (id_builder [0] >= '_' && !quoted) {
3318 int keyword = GetKeyword (id_builder, pos);
3319 if (keyword != -1) {
3320 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3325 string s = InternIdentifier (id_builder, pos);
3326 val = ltb.Create (s, current_source, ref_line, column);
3327 if (quoted && parsing_attribute_section)
3328 AddEscapedIdentifier (((LocatedToken) val).Location);
3330 return Token.IDENTIFIER;
3333 string InternIdentifier (char[] charBuffer, int length)
3336 // Keep identifiers in an array of hashtables to avoid needless
3339 var identifiers_group = identifiers[length];
3341 if (identifiers_group != null) {
3342 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3346 // TODO: this should be number of files dependant
3347 // corlib compilation peaks at 1000 and System.Core at 150
3348 int capacity = length > 20 ? 10 : 100;
3349 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3350 identifiers[length] = identifiers_group;
3353 char[] chars = new char[length];
3354 Array.Copy (charBuffer, chars, length);
3356 s = new string (charBuffer, 0, length);
3357 identifiers_group.Add (chars, s);
3361 public int xtoken ()
3363 if (parsing_interpolation_format) {
3364 return TokenizeInterpolationFormat ();
3369 // Whether we have seen comments on the current line
3370 bool comments_seen = false;
3371 while ((c = get_char ()) != -1) {
3374 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3382 case 0xFEFF: // Ignore BOM anywhere in the file
3385 /* This is required for compatibility with .NET
3387 if (peek_char () == 0xBB) {
3390 if (get_char () == 0xBF)
3398 return consume_identifier (c);
3401 val = ltb.Create (current_source, ref_line, col);
3403 if (parsing_string_interpolation > 0)
3404 ++string_interpolation_section;
3406 return Token.OPEN_BRACE;
3408 if (parsing_string_interpolation > 0) {
3409 if (string_interpolation_section == 0) {
3410 --parsing_string_interpolation;
3412 if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Count > 0) {
3413 quoted = parsing_string_interpolation_quoted.Pop ();
3418 return TokenizeInterpolatedString (quoted);
3421 --string_interpolation_section;
3424 val = ltb.Create (current_source, ref_line, col);
3425 return Token.CLOSE_BRACE;
3427 // To block doccomment inside attribute declaration.
3428 if (doc_state == XmlCommentState.Allowed)
3429 doc_state = XmlCommentState.NotAllowed;
3431 val = ltb.Create (current_source, ref_line, col);
3433 if (parsing_block == 0 || lambda_arguments_parsing)
3434 return Token.OPEN_BRACKET;
3436 int next = peek_char ();
3440 return Token.OPEN_BRACKET;
3450 next = peek_token ();
3451 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3452 return Token.OPEN_BRACKET;
3454 return Token.OPEN_BRACKET_EXPR;
3456 return Token.OPEN_BRACKET_EXPR;
3459 ltb.CreateOptional (current_source, ref_line, col, ref val);
3460 return Token.CLOSE_BRACKET;
3462 val = ltb.Create (current_source, ref_line, col);
3464 // An expression versions of parens can appear in block context only
3466 if (parsing_block != 0 && !lambda_arguments_parsing) {
3469 // Optmize most common case where we know that parens
3472 switch (current_token) {
3473 case Token.IDENTIFIER:
3482 case Token.DELEGATE:
3483 case Token.OP_GENERICS_GT:
3484 return Token.OPEN_PARENS;
3487 // Optimize using peek
3488 int xx = peek_char ();
3495 return Token.OPEN_PARENS;
3498 lambda_arguments_parsing = true;
3500 d = TokenizeOpenParens ();
3502 lambda_arguments_parsing = false;
3506 return Token.OPEN_PARENS;
3508 ltb.CreateOptional (current_source, ref_line, col, ref val);
3509 return Token.CLOSE_PARENS;
3511 ltb.CreateOptional (current_source, ref_line, col, ref val);
3514 ltb.CreateOptional (current_source, ref_line, col, ref val);
3515 return Token.SEMICOLON;
3517 val = ltb.Create (current_source, ref_line, col);
3520 val = ltb.Create (current_source, ref_line, col);
3521 return TokenizePossibleNullableType ();
3523 val = ltb.Create (current_source, ref_line, col);
3524 if (parsing_generic_less_than++ > 0)
3525 return Token.OP_GENERICS_LT;
3527 return TokenizeLessThan ();
3530 val = ltb.Create (current_source, ref_line, col);
3538 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3539 parsing_generic_less_than--;
3540 return Token.OP_GENERICS_GT;
3549 return Token.OP_SHIFT_RIGHT_ASSIGN;
3551 return Token.OP_SHIFT_RIGHT;
3557 val = ltb.Create (current_source, ref_line, col);
3561 } else if (d == '=') {
3562 d = Token.OP_ADD_ASSIGN;
3570 val = ltb.Create (current_source, ref_line, col);
3574 } else if (d == '=')
3575 d = Token.OP_SUB_ASSIGN;
3585 val = ltb.Create (current_source, ref_line, col);
3586 if (peek_char () == '='){
3593 val = ltb.Create (current_source, ref_line, col);
3604 return Token.ASSIGN;
3607 val = ltb.Create (current_source, ref_line, col);
3611 return Token.OP_AND;
3615 return Token.OP_AND_ASSIGN;
3617 return Token.BITWISE_AND;
3620 val = ltb.Create (current_source, ref_line, col);
3628 return Token.OP_OR_ASSIGN;
3630 return Token.BITWISE_OR;
3633 val = ltb.Create (current_source, ref_line, col);
3634 if (peek_char () == '='){
3636 return Token.OP_MULT_ASSIGN;
3643 val = ltb.Create (current_source, ref_line, col);
3645 return Token.OP_DIV_ASSIGN;
3648 // Handle double-slash comments.
3650 if (parsing_string_interpolation > 0) {
3651 Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3656 if (doc_processing) {
3657 if (peek_char () == '/') {
3659 // Don't allow ////.
3660 if ((d = peek_char ()) != '/') {
3661 if (doc_state == XmlCommentState.Allowed)
3662 handle_one_line_xml_comment ();
3663 else if (doc_state == XmlCommentState.NotAllowed)
3664 WarningMisplacedComment (Location - 3);
3667 if (xml_comment_buffer.Length > 0)
3668 doc_state = XmlCommentState.NotAllowed;
3674 any_token_seen |= tokens_seen;
3675 tokens_seen = false;
3676 comments_seen = false;
3678 } else if (d == '*'){
3680 bool docAppend = false;
3681 if (doc_processing && peek_char () == '*') {
3683 // But when it is /**/, just do nothing.
3684 if (peek_char () == '/') {
3688 if (doc_state == XmlCommentState.Allowed)
3690 else if (doc_state == XmlCommentState.NotAllowed) {
3691 WarningMisplacedComment (Location - 2);
3695 int current_comment_start = 0;
3697 current_comment_start = xml_comment_buffer.Length;
3698 xml_comment_buffer.Append (Environment.NewLine);
3701 while ((d = get_char ()) != -1){
3702 if (d == '*' && peek_char () == '/'){
3704 comments_seen = true;
3708 xml_comment_buffer.Append ((char) d);
3710 if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3711 any_token_seen |= tokens_seen;
3712 tokens_seen = false;
3714 // Reset 'comments_seen' just to be consistent.
3715 // It doesn't matter either way, here.
3717 comments_seen = false;
3721 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3724 update_formatted_doc_comment (current_comment_start);
3727 val = ltb.Create (current_source, ref_line, col);
3731 val = ltb.Create (current_source, ref_line, col);
3732 if (peek_char () == '='){
3734 return Token.OP_MOD_ASSIGN;
3736 return Token.PERCENT;
3739 val = ltb.Create (current_source, ref_line, col);
3740 if (peek_char () == '='){
3742 return Token.OP_XOR_ASSIGN;
3744 return Token.CARRET;
3747 val = ltb.Create (current_source, ref_line, col);
3748 if (peek_char () == ':') {
3750 return Token.DOUBLE_COLON;
3754 case '0': case '1': case '2': case '3': case '4':
3755 case '5': case '6': case '7': case '8': case '9':
3757 return is_number (c, false);
3759 case '\n': // white space
3762 any_token_seen |= tokens_seen;
3763 tokens_seen = false;
3764 comments_seen = false;
3770 if (d >= '0' && d <= '9')
3771 return is_number (c, true);
3773 ltb.CreateOptional (current_source, ref_line, col, ref val);
3777 if (tokens_seen || comments_seen) {
3778 Eror_WrongPreprocessorLocation ();
3782 if (ParsePreprocessingDirective (true))
3785 bool directive_expected = false;
3786 while ((c = get_char ()) != -1) {
3788 directive_expected = true;
3789 } else if (!directive_expected) {
3790 // TODO: Implement comment support for disabled code and uncomment this code
3792 // Eror_WrongPreprocessorLocation ();
3793 // return Token.ERROR;
3798 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3802 if (ParsePreprocessingDirective (false))
3805 directive_expected = false;
3809 tokens_seen = false;
3816 if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3817 parsing_string_interpolation = 0;
3818 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3819 val = new StringLiteral (context.BuiltinTypes, "", Location);
3820 return Token.INTERPOLATED_STRING_END;
3823 return consume_string (false);
3826 return TokenizeBackslash ();
3832 return consume_string (true);
3835 if (is_identifier_start_character (c)){
3836 return consume_identifier (c, true);
3839 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3843 switch (peek_char ()) {
3846 return TokenizeInterpolatedString (false);
3849 if (peek_char () == '"') {
3851 return TokenizeInterpolatedString (true);
3858 case EvalStatementParserCharacter:
3859 return Token.EVAL_STATEMENT_PARSER;
3860 case EvalCompilationUnitParserCharacter:
3861 return Token.EVAL_COMPILATION_UNIT_PARSER;
3862 case EvalUsingDeclarationsParserCharacter:
3863 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3864 case DocumentationXref:
3865 return Token.DOC_SEE;
3868 if (is_identifier_start_character (c)) {
3870 return consume_identifier (c);
3873 if (char.IsWhiteSpace ((char) c))
3876 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3881 return Token.COMPLETE_COMPLETION;
3884 return Token.GENERATE_COMPLETION;
3891 int TokenizeBackslash ()
3894 int read_start = reader.Position;
3896 Location start_location = Location;
3897 int c = get_char ();
3900 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3901 Report.Error (1011, start_location, "Empty character literal");
3902 return Token.LITERAL;
3905 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3906 Report.Error (1010, start_location, "Newline in constant");
3911 c = escape (c, out d);
3915 throw new NotImplementedException ();
3917 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3922 Report.Error (1012, start_location, "Too many characters in character literal");
3924 // Try to recover, read until newline or next "'"
3925 while ((c = get_char ()) != -1) {
3926 if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3932 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3935 return Token.LITERAL;
3938 int TokenizeLessThan ()
3942 // Save current position and parse next token.
3944 int generic_dimension = 0;
3945 if (parse_less_than (ref generic_dimension)) {
3946 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3947 d = Token.OP_GENERICS_LT_DECL;
3949 if (generic_dimension > 0) {
3950 val = generic_dimension;
3952 return Token.GENERIC_DIMENSION;
3955 d = Token.OP_GENERICS_LT;
3962 parsing_generic_less_than = 0;
3971 return Token.OP_SHIFT_LEFT_ASSIGN;
3973 return Token.OP_SHIFT_LEFT;
3983 int TokenizeInterpolatedString (bool quoted)
3986 var start_location = Location;
3989 var ch = get_char ();
3992 if (quoted && peek_char () == '"') {
3997 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3998 return Token.INTERPOLATED_STRING_END;
4000 if (peek_char () == '{') {
4001 value_builder [pos++] = (char)ch;
4006 ++parsing_string_interpolation;
4008 if (parsing_string_interpolation_quoted == null)
4009 parsing_string_interpolation_quoted = new Stack<bool> ();
4012 if (parsing_string_interpolation_quoted != null) {
4013 parsing_string_interpolation_quoted.Push (quoted);
4016 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
4017 return Token.INTERPOLATED_STRING;
4024 ch = escape (ch, out surrogate);
4028 if (ch == '{' || ch == '}') {
4029 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4032 if (surrogate != 0) {
4033 if (pos == value_builder.Length)
4034 Array.Resize (ref value_builder, pos * 2);
4036 if (pos == value_builder.Length)
4037 Array.Resize (ref value_builder, pos * 2);
4039 value_builder [pos++] = (char)ch;
4049 if (pos == value_builder.Length)
4050 Array.Resize (ref value_builder, pos * 2);
4052 value_builder[pos++] = (char) ch;
4056 int TokenizeInterpolationFormat ()
4061 var ch = get_char ();
4070 Report.Error (8089, Location, "Empty interpolated expression format specifier");
4071 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
4072 Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
4075 val = CreateStringFromBuilder (pos);
4076 return Token.LITERAL;
4082 if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Peek ())
4087 ch = escape (ch, out surrogate);
4091 if (ch == '{' || ch == '}') {
4092 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4095 if (surrogate != 0) {
4096 if (pos == value_builder.Length)
4097 Array.Resize (ref value_builder, pos * 2);
4099 value_builder [pos++] = (char)ch;
4109 value_builder[pos++] = (char) ch;
4113 string CreateStringFromBuilder (int pos)
4116 return string.Empty;
4118 return InternIdentifier (value_builder, pos);
4120 return new string (value_builder, 0, pos);
4124 // Handles one line xml comment
4126 private void handle_one_line_xml_comment ()
4129 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4130 xml_comment_buffer.Append ((char) get_char ());
4132 if (c == '\r' || c == '\n')
4133 xml_comment_buffer.Append (Environment.NewLine);
4137 // Remove heading "*" in Javadoc-like xml documentation.
4139 private void update_formatted_doc_comment (int current_comment_start)
4141 int length = xml_comment_buffer.Length - current_comment_start;
4142 string [] lines = xml_comment_buffer.ToString (
4143 current_comment_start,
4144 length).Replace ("\r", "").Split ('\n');
4146 // The first line starts with /**, thus it is not target
4147 // for the format check.
4148 for (int i = 1; i < lines.Length; i++) {
4149 string s = lines [i];
4150 int idx = s.IndexOf ('*');
4153 if (i < lines.Length - 1)
4157 head = s.Substring (0, idx);
4158 foreach (char c in head)
4161 lines [i] = s.Substring (idx + 1);
4163 xml_comment_buffer.Remove (current_comment_start, length);
4164 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4168 // Checks if there was incorrect doc comments and raise
4171 public void check_incorrect_doc_comment ()
4173 if (xml_comment_buffer.Length > 0)
4174 WarningMisplacedComment (Location);
4178 // Consumes the saved xml comment lines (if any)
4179 // as for current target member or type.
4181 public string consume_doc_comment ()
4183 if (xml_comment_buffer.Length > 0) {
4184 string ret = xml_comment_buffer.ToString ();
4185 reset_doc_comment ();
4191 void reset_doc_comment ()
4193 xml_comment_buffer.Length = 0;
4196 public void cleanup ()
4198 if (ifstack != null && ifstack.Count >= 1) {
4199 int state = ifstack.Pop ();
4200 if ((state & REGION) != 0)
4201 Report.Error (1038, Location, "#endregion directive expected");
4203 Report.Error (1027, Location, "Expected `#endif' directive");
4209 // Indicates whether it accepts XML documentation or not.
4211 public enum XmlCommentState {
4212 // comment is allowed in this state.
4214 // comment is not allowed in this state.
4216 // once comments appeared when it is NotAllowed, then the
4217 // state is changed to it, until the state is changed to