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) {
1271 if (!parse_less_than (ref unused))
1274 } else if (the_token == Token.OPEN_BRACKET) {
1276 the_token = token ();
1277 if (the_token == Token.CLOSE_BRACKET)
1279 else if (the_token == Token.COMMA)
1280 goto rank_specifiers;
1287 public int peek_token ()
1292 the_token = token ();
1299 // Tonizes `?' using custom disambiguous rules to return one
1300 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1302 // Tricky expression looks like:
1304 // Foo ? a = x ? b : c;
1306 int TokenizePossibleNullableType ()
1308 if (parsing_block == 0 || parsing_type > 0)
1309 return Token.INTERR_NULLABLE;
1311 int d = peek_char ();
1314 return Token.OP_COALESCING;
1318 return Token.INTERR_OPERATOR;
1322 if (d == ',' || d == ';' || d == '>')
1323 return Token.INTERR_NULLABLE;
1324 if (d == '*' || (d >= '0' && d <= '9'))
1325 return Token.INTERR;
1329 current_token = Token.NONE;
1338 case Token.OPEN_BRACKET_EXPR:
1339 next_token = Token.INTERR_OPERATOR;
1347 case Token.INTERPOLATED_STRING:
1348 next_token = Token.INTERR;
1351 case Token.SEMICOLON:
1353 case Token.CLOSE_PARENS:
1354 case Token.OPEN_BRACKET:
1355 case Token.OP_GENERICS_GT:
1357 case Token.OP_COALESCING:
1359 next_token = Token.INTERR_NULLABLE;
1362 case Token.OPEN_PARENS:
1363 case Token.OPEN_PARENS_CAST:
1364 case Token.OPEN_PARENS_LAMBDA:
1369 case Token.OP_GENERICS_LT:
1370 case Token.OP_GENERICS_LT_DECL:
1371 case Token.GENERIC_DIMENSION:
1381 if (next_token == -1) {
1382 switch (xtoken ()) {
1384 case Token.SEMICOLON:
1385 case Token.OPEN_BRACE:
1387 next_token = Token.INTERR_NULLABLE;
1391 next_token = Token.INTERR;
1394 case Token.OPEN_PARENS:
1395 case Token.OPEN_PARENS_CAST:
1396 case Token.OPEN_PARENS_LAMBDA:
1400 case Token.OPEN_BRACKET:
1401 case Token.OPEN_BRACKET_EXPR:
1405 case Token.CLOSE_PARENS:
1409 case Token.OP_GENERICS_LT:
1410 case Token.OP_GENERICS_LT_DECL:
1411 case Token.GENERIC_DIMENSION:
1421 // All shorcuts failed, do it hard way
1423 while ((ntoken = xtoken ()) != Token.EOF) {
1425 case Token.OPEN_BRACE:
1428 case Token.OPEN_PARENS:
1429 case Token.OPEN_PARENS_CAST:
1430 case Token.OPEN_PARENS_LAMBDA:
1433 case Token.CLOSE_BRACE:
1436 case Token.OP_GENERICS_LT:
1437 case Token.OP_GENERICS_LT_DECL:
1438 case Token.GENERIC_DIMENSION:
1441 case Token.OPEN_BRACKET:
1442 case Token.OPEN_BRACKET_EXPR:
1445 case Token.CLOSE_BRACKET:
1448 case Token.CLOSE_PARENS:
1455 return Token.INTERR_NULLABLE;
1457 case Token.OP_GENERICS_GT:
1464 return Token.INTERR_NULLABLE;
1470 if (ntoken == Token.SEMICOLON)
1476 if (ntoken == Token.COMMA) {
1477 if (generics != 0 || brackets != 0)
1481 return Token.INTERR_NULLABLE;
1484 if (ntoken == Token.COLON) {
1485 if (++colons == interrs)
1490 if (ntoken == Token.INTERR) {
1496 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1505 bool decimal_digits (int c)
1508 bool seen_digits = false;
1511 if (number_pos == MaxNumberLength)
1512 Error_NumericConstantTooLong ();
1513 number_builder [number_pos++] = (char) c;
1517 // We use peek_char2, because decimal_digits needs to do a
1518 // 2-character look-ahead (5.ToString for example).
1520 while ((d = peek_char2 ()) != -1){
1521 if (d >= '0' && d <= '9'){
1522 if (number_pos == MaxNumberLength)
1523 Error_NumericConstantTooLong ();
1524 number_builder [number_pos++] = (char) d;
1534 static bool is_hex (int e)
1536 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1539 static TypeCode real_type_suffix (int c)
1543 return TypeCode.Single;
1545 return TypeCode.Double;
1547 return TypeCode.Decimal;
1549 return TypeCode.Empty;
1553 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1555 bool is_unsigned = false;
1556 bool is_long = false;
1559 bool scanning = true;
1572 // if we have not seen anything in between
1573 // report this error
1575 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1595 if (is_long && is_unsigned){
1596 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1600 // uint if possible, or ulong else.
1602 if ((ul & 0xffffffff00000000) == 0)
1603 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1605 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1606 } else if (is_long){
1607 // long if possible, ulong otherwise
1608 if ((ul & 0x8000000000000000) != 0)
1609 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1611 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1613 // int, uint, long or ulong in that order
1614 if ((ul & 0xffffffff00000000) == 0){
1615 uint ui = (uint) ul;
1617 if ((ui & 0x80000000) != 0)
1618 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1620 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1622 if ((ul & 0x8000000000000000) != 0)
1623 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1625 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1631 // given `c' as the next char in the input decide whether
1632 // we need to convert to a special type, and then choose
1633 // the best representation for the integer
1635 ILiteralConstant adjust_int (int c, Location loc)
1638 if (number_pos > 9){
1639 ulong ul = (uint) (number_builder [0] - '0');
1641 for (int i = 1; i < number_pos; i++){
1642 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1645 return integer_type_suffix (ul, c, loc);
1647 uint ui = (uint) (number_builder [0] - '0');
1649 for (int i = 1; i < number_pos; i++){
1650 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1653 return integer_type_suffix (ui, c, loc);
1655 } catch (OverflowException) {
1656 Error_NumericConstantTooLong ();
1657 return new IntLiteral (context.BuiltinTypes, 0, loc);
1659 catch (FormatException) {
1660 Report.Error (1013, Location, "Invalid number");
1661 return new IntLiteral (context.BuiltinTypes, 0, loc);
1665 ILiteralConstant adjust_real (TypeCode t, Location loc)
1667 string s = new string (number_builder, 0, number_pos);
1668 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1671 case TypeCode.Decimal:
1673 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1674 } catch (OverflowException) {
1675 Report.Error (594, Location, error_details, "decimal");
1676 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1678 case TypeCode.Single:
1680 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1681 } catch (OverflowException) {
1682 Report.Error (594, Location, error_details, "float");
1683 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1687 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1688 } catch (OverflowException) {
1689 Report.Error (594, loc, error_details, "double");
1690 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1695 ILiteralConstant handle_hex (Location loc)
1701 while ((d = peek_char ()) != -1){
1703 number_builder [number_pos++] = (char) d;
1709 string s = new String (number_builder, 0, number_pos);
1712 if (number_pos <= 8)
1713 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1715 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1717 return integer_type_suffix (ul, peek_char (), loc);
1718 } catch (OverflowException){
1719 Error_NumericConstantTooLong ();
1720 return new IntLiteral (context.BuiltinTypes, 0, loc);
1722 catch (FormatException) {
1723 Report.Error (1013, Location, "Invalid number");
1724 return new IntLiteral (context.BuiltinTypes, 0, loc);
1729 // Invoked if we know we have .digits or digits
1731 int is_number (int c, bool dotLead)
1733 ILiteralConstant res;
1736 int read_start = reader.Position - 1;
1739 // Caller did peek_char
1749 int peek = peek_char ();
1751 if (peek == 'x' || peek == 'X') {
1752 val = res = handle_hex (loc);
1754 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1757 return Token.LITERAL;
1765 // We need to handle the case of
1766 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1768 bool is_real = false;
1773 if (decimal_digits ('.')){
1779 val = res = adjust_int (-1, loc);
1782 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1784 return Token.LITERAL;
1788 if (c == 'e' || c == 'E'){
1791 if (number_pos == MaxNumberLength)
1792 Error_NumericConstantTooLong ();
1793 number_builder [number_pos++] = (char) c;
1797 if (number_pos == MaxNumberLength)
1798 Error_NumericConstantTooLong ();
1799 number_builder [number_pos++] = '+';
1801 } else if (c == '-') {
1802 if (number_pos == MaxNumberLength)
1803 Error_NumericConstantTooLong ();
1804 number_builder [number_pos++] = '-';
1807 if (number_pos == MaxNumberLength)
1808 Error_NumericConstantTooLong ();
1809 number_builder [number_pos++] = '+';
1816 var type = real_type_suffix (c);
1817 if (type == TypeCode.Empty && !is_real) {
1818 res = adjust_int (c, loc);
1822 if (type != TypeCode.Empty) {
1826 res = adjust_real (type, loc);
1832 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1833 if (chars[chars.Length - 1] == '\r')
1834 Array.Resize (ref chars, chars.Length - 1);
1835 res.ParsedValue = chars;
1838 return Token.LITERAL;
1842 // Accepts exactly count (4 or 8) hex, no more no less
1844 int getHex (int count, out int surrogate, out bool error)
1849 int top = count != -1 ? count : 4;
1854 for (i = 0; i < top; i++){
1857 if (c >= '0' && c <= '9')
1858 c = (int) c - (int) '0';
1859 else if (c >= 'A' && c <= 'F')
1860 c = (int) c - (int) 'A' + 10;
1861 else if (c >= 'a' && c <= 'f')
1862 c = (int) c - (int) 'a' + 10;
1868 total = (total * 16) + c;
1870 int p = peek_char ();
1873 if (!is_hex ((char)p))
1879 if (total > 0x0010FFFF) {
1884 if (total >= 0x00010000) {
1885 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1886 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1893 int escape (int c, out int surrogate)
1929 v = getHex (-1, out surrogate, out error);
1935 return EscapeUnicode (d, out surrogate);
1938 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1947 int EscapeUnicode (int ch, out int surrogate)
1951 ch = getHex (8, out surrogate, out error);
1953 ch = getHex (4, out surrogate, out error);
1957 Report.Error (1009, Location, "Unrecognized escape sequence");
1965 if (putback_char != -1) {
1974 if (peek_char () == '\n') {
1980 } else if (x == '\n') {
1985 } else if (x >= UnicodeLS && x <= UnicodePS) {
1994 void advance_line ()
2004 if (putback_char == -1)
2005 putback_char = reader.Read ();
2006 return putback_char;
2011 if (putback_char != -1)
2012 return putback_char;
2013 return reader.Peek ();
2016 public void putback (int c)
2018 if (putback_char != -1) {
2019 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
2022 if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
2023 // It won't happen though.
2033 public bool advance ()
2035 return peek_char () != -1 || CompleteOnEOF;
2038 public Object Value {
2044 public Object value ()
2051 current_token = xtoken ();
2052 return current_token;
2055 int TokenizePreprocessorKeyword (out int c)
2057 // skip over white space
2060 } while (c == ' ' || c == '\t');
2064 while (c != -1 && c >= 'a' && c <= 'z') {
2065 id_builder[pos++] = (char) c;
2068 int peek = peek_char ();
2069 if (peek == 'U' || peek == 'u') {
2071 c = EscapeUnicode (c, out surrogate);
2072 if (surrogate != 0) {
2073 if (is_identifier_part_character ((char) c)) {
2074 id_builder[pos++] = (char) c;
2085 PreprocessorDirective get_cmd_arg (out string arg)
2089 tokens_seen = false;
2092 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2094 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2097 // skip over white space
2098 while (c == ' ' || c == '\t')
2101 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2104 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2105 if (c == '\\' && has_identifier_argument >= 0) {
2106 if (has_identifier_argument != 0) {
2107 has_identifier_argument = 1;
2109 int peek = peek_char ();
2110 if (peek == 'U' || peek == 'u') {
2112 c = EscapeUnicode (c, out surrogate);
2113 if (surrogate != 0) {
2114 if (is_identifier_part_character ((char) c)) {
2115 if (pos == value_builder.Length)
2116 Array.Resize (ref value_builder, pos * 2);
2118 value_builder[pos++] = (char) c;
2124 has_identifier_argument = -1;
2126 } else if (c == '/' && peek_char () == '/') {
2128 // Eat single-line comments
2135 if (pos == value_builder.Length)
2136 Array.Resize (ref value_builder, pos * 2);
2138 value_builder[pos++] = (char) c;
2143 if (pos > MaxIdentifierLength)
2144 arg = new string (value_builder, 0, pos);
2146 arg = InternIdentifier (value_builder, pos);
2148 // Eat any trailing whitespaces
2149 arg = arg.Trim (simple_whitespaces);
2156 // Handles the #line directive
2158 bool PreProcessLine ()
2160 Location loc = Location;
2164 int length = TokenizePreprocessorKeyword (out c);
2165 if (length == line_default.Length) {
2166 if (!IsTokenIdentifierEqual (line_default))
2169 current_source = source_file.SourceFile;
2170 if (!hidden_block_start.IsNull) {
2171 current_source.RegisterHiddenScope (hidden_block_start, loc);
2172 hidden_block_start = Location.Null;
2179 if (length == line_hidden.Length) {
2180 if (!IsTokenIdentifierEqual (line_hidden))
2183 if (hidden_block_start.IsNull)
2184 hidden_block_start = loc;
2189 if (length != 0 || c < '0' || c > '9') {
2191 // Eat any remaining characters to continue parsing on next line
2197 int new_line = TokenizeNumber (c);
2200 // Eat any remaining characters to continue parsing on next line
2203 return new_line != 0;
2208 // skip over white space
2211 } while (c == ' ' || c == '\t');
2212 } else if (c == '"') {
2216 if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2218 // Eat any remaining characters to continue parsing on next line
2222 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2226 string new_file_name = null;
2228 new_file_name = TokenizeFileName (ref c);
2230 // skip over white space
2231 while (c == ' ' || c == '\t') {
2236 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2238 } else if (c == '/') {
2239 ReadSingleLineComment ();
2242 // Eat any remaining characters to continue parsing on next line
2246 Error_EndLineExpected ();
2250 if (new_file_name != null) {
2251 current_source = context.LookupFile (source_file, new_file_name);
2252 source_file.AddIncludeFile (current_source);
2255 if (!hidden_block_start.IsNull) {
2256 current_source.RegisterHiddenScope (hidden_block_start, loc);
2257 hidden_block_start = Location.Null;
2260 ref_line = new_line;
2265 // Handles #define and #undef
2267 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2269 if (ident.Length == 0 || ident == "true" || ident == "false"){
2270 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2274 if (ident.IndexOfAny (simple_whitespaces) != -1){
2275 Error_EndLineExpected ();
2279 if (!is_identifier_start_character (ident [0]))
2280 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2282 foreach (char c in ident.Substring (1)){
2283 if (!is_identifier_part_character (c)){
2284 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2289 if (!caller_is_taking)
2296 if (context.Settings.IsConditionalSymbolDefined (ident))
2299 source_file.AddDefine (ident);
2304 source_file.AddUndefine (ident);
2308 byte read_hex (out bool error)
2311 int c = get_char ();
2313 if ((c >= '0') && (c <= '9'))
2314 total = (int) c - (int) '0';
2315 else if ((c >= 'A') && (c <= 'F'))
2316 total = (int) c - (int) 'A' + 10;
2317 else if ((c >= 'a') && (c <= 'f'))
2318 total = (int) c - (int) 'a' + 10;
2327 if ((c >= '0') && (c <= '9'))
2328 total += (int) c - (int) '0';
2329 else if ((c >= 'A') && (c <= 'F'))
2330 total += (int) c - (int) 'A' + 10;
2331 else if ((c >= 'a') && (c <= 'f'))
2332 total += (int) c - (int) 'a' + 10;
2339 return (byte) total;
2343 // Parses #pragma checksum
2345 bool ParsePragmaChecksum ()
2348 // The syntax is ` "foo.txt" "{guid}" "hash"'
2350 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2352 int c = get_char ();
2357 string file_name = TokenizeFileName (ref c);
2359 // TODO: Any white-spaces count
2363 SourceFile file = context.LookupFile (source_file, file_name);
2365 if (get_char () != '"' || get_char () != '{')
2369 byte[] guid_bytes = new byte [16];
2372 for (; i < 4; i++) {
2373 guid_bytes [i] = read_hex (out error);
2378 if (get_char () != '-')
2381 for (; i < 10; i++) {
2382 guid_bytes [i] = read_hex (out error);
2386 guid_bytes [i++] = read_hex (out error);
2390 if (get_char () != '-')
2394 for (; i < 16; i++) {
2395 guid_bytes [i] = read_hex (out error);
2400 if (get_char () != '}' || get_char () != '"')
2403 // TODO: Any white-spaces count
2408 if (get_char () != '"')
2411 // Any length of checksum
2412 List<byte> checksum_bytes = new List<byte> (16);
2414 var checksum_location = Location;
2416 while (c != '"' && c != -1) {
2417 checksum_bytes.Add (read_hex (out error));
2425 ReadSingleLineComment ();
2426 } else if (get_char () != '"') {
2430 if (context.Settings.GenerateDebugInfo) {
2431 var chsum = checksum_bytes.ToArray ();
2433 if (file.HasChecksum) {
2434 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2435 // TODO: Report.SymbolRelatedToPreviousError
2436 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2440 file.SetChecksum (guid_bytes, chsum);
2441 current_source.AutoGenerated = true;
2447 bool IsTokenIdentifierEqual (char[] identifier)
2449 for (int i = 0; i < identifier.Length; ++i) {
2450 if (identifier[i] != id_builder[i])
2457 bool ScanClosingInterpolationBrace ()
2464 var c = reader.Read ();
2470 // Skip escaped " character
2479 if (str_quote % 2 == 1) {
2485 } while (res == null);
2491 int TokenizeNumber (int value)
2495 decimal_digits (value);
2496 uint ui = (uint) (number_builder[0] - '0');
2499 for (int i = 1; i < number_pos; i++) {
2500 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2504 } catch (OverflowException) {
2505 Error_NumericConstantTooLong ();
2510 string TokenizeFileName (ref int c)
2512 var string_builder = new StringBuilder ();
2513 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2520 string_builder.Append ((char) c);
2523 if (string_builder.Length == 0) {
2524 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2528 return string_builder.ToString ();
2531 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2533 if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2536 if (c >= '0' && c <= '9') {
2538 number = TokenizeNumber (c);
2542 if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2543 return ReadPragmaWarningComment (c);
2547 // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2551 id_builder [pos++] = (char)c;
2552 while (c < MaxIdentifierLength) {
2554 id_builder [pos] = (char)c;
2556 if (c >= '0' && c <= '9') {
2557 if (pos == 5 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2558 // Recognize CSXXXX as C# XXXX warning
2561 for (int i = 0; i < 4; ++i) {
2562 var ch = id_builder [i + 2];
2563 if (ch < '0' || ch > '9') {
2568 number += (ch - '0') * pow;
2572 } else if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2575 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2588 // skip over white space
2589 while (c == ' ' || c == '\t')
2596 // skip over white space
2597 while (c == ' ' || c == '\t')
2603 return ReadPragmaWarningComment (c);
2606 int ReadPragmaWarningComment (int c)
2609 ReadSingleLineComment ();
2611 Report.Warning (1692, 1, Location, "Invalid number");
2613 // Read everything till the end of the line or file
2620 void ReadToEndOfLine ()
2625 } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2628 void ReadSingleLineComment ()
2630 if (peek_char () != '/')
2631 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2633 // Read everything till the end of the line or file
2638 /// Handles #pragma directive
2640 void ParsePragmaDirective ()
2643 int length = TokenizePreprocessorKeyword (out c);
2644 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2645 length = TokenizePreprocessorKeyword (out c);
2648 // #pragma warning disable
2649 // #pragma warning restore
2651 if (length == pragma_warning_disable.Length) {
2652 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2653 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2654 // skip over white space
2655 while (c == ' ' || c == '\t')
2660 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2662 ReadSingleLineComment ();
2665 // Disable/Restore all warnings
2668 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2670 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2674 // Disable/Restore a warning or group of warnings
2678 bool identifier = false;
2679 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2682 // no-op, custom warnings cannot occur in mcs
2683 } else if (disable) {
2684 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2686 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2689 } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2696 Report.Warning (1634, 1, Location, "Expected disable or restore");
2698 // Eat any remaining characters on the line
2707 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2708 if (c != ' ' || !ParsePragmaChecksum ()) {
2709 Report.Warning (1695, 1, Location,
2710 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2716 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2718 // Eat any remaining characters on the line
2722 bool eval_val (string s)
2729 return source_file.IsConditionalDefined (s);
2732 bool pp_primary (ref string s)
2741 s = s.Substring (1);
2742 bool val = pp_expr (ref s, false);
2743 if (s.Length > 0 && s [0] == ')'){
2744 s = s.Substring (1);
2747 Error_InvalidDirective ();
2751 if (is_identifier_start_character (c)){
2757 if (is_identifier_part_character (c)){
2761 bool v = eval_val (s.Substring (0, j));
2762 s = s.Substring (j);
2765 bool vv = eval_val (s);
2770 Error_InvalidDirective ();
2774 bool pp_unary (ref string s)
2781 if (len > 1 && s [1] == '='){
2782 Error_InvalidDirective ();
2785 s = s.Substring (1);
2786 return ! pp_primary (ref s);
2788 return pp_primary (ref s);
2790 Error_InvalidDirective ();
2795 bool pp_eq (ref string s)
2797 bool va = pp_unary (ref s);
2803 if (len > 2 && s [1] == '='){
2804 s = s.Substring (2);
2805 return va == pp_unary (ref s);
2807 Error_InvalidDirective ();
2810 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2811 s = s.Substring (2);
2813 return va != pp_unary (ref s);
2822 bool pp_and (ref string s)
2824 bool va = pp_eq (ref s);
2830 if (len > 2 && s [1] == '&'){
2831 s = s.Substring (2);
2832 return (va & pp_and (ref s));
2834 Error_InvalidDirective ();
2843 // Evaluates an expression for `#if' or `#elif'
2845 bool pp_expr (ref string s, bool isTerm)
2847 bool va = pp_and (ref s);
2854 if (len > 2 && s [1] == '|'){
2855 s = s.Substring (2);
2856 return va | pp_expr (ref s, isTerm);
2858 Error_InvalidDirective ();
2863 Error_EndLineExpected ();
2871 bool eval (string s)
2873 bool v = pp_expr (ref s, true);
2882 void Error_NumericConstantTooLong ()
2884 Report.Error (1021, Location, "Integral constant is too large");
2887 void Error_InvalidDirective ()
2889 Report.Error (1517, Location, "Invalid preprocessor directive");
2892 void Error_UnexpectedDirective (string extra)
2896 "Unexpected processor directive ({0})", extra);
2899 void Error_TokensSeen ()
2901 Report.Error (1032, Location,
2902 "Cannot define or undefine preprocessor symbols after first token in file");
2905 void Eror_WrongPreprocessorLocation ()
2907 Report.Error (1040, Location,
2908 "Preprocessor directives must appear as the first non-whitespace character on a line");
2911 void Error_EndLineExpected ()
2913 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2917 // Raises a warning when tokenizer found documentation comment
2918 // on unexpected place
2920 void WarningMisplacedComment (Location loc)
2922 if (doc_state != XmlCommentState.Error) {
2923 doc_state = XmlCommentState.Error;
2924 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2929 // if true, then the code continues processing the code
2930 // if false, the code stays in a loop until another directive is
2932 // When caller_is_taking is false we ignore all directives except the ones
2933 // which can help us to identify where the #if block ends
2934 bool ParsePreprocessingDirective (bool caller_is_taking)
2937 bool region_directive = false;
2939 var directive = get_cmd_arg (out arg);
2942 // The first group of pre-processing instructions is always processed
2944 switch (directive) {
2945 case PreprocessorDirective.Region:
2946 region_directive = true;
2948 goto case PreprocessorDirective.If;
2950 case PreprocessorDirective.Endregion:
2951 if (ifstack == null || ifstack.Count == 0){
2952 Error_UnexpectedDirective ("no #region for this #endregion");
2955 int pop = ifstack.Pop ();
2957 if ((pop & REGION) == 0)
2958 Report.Error (1027, Location, "Expected `#endif' directive");
2960 return caller_is_taking;
2962 case PreprocessorDirective.If:
2963 if (ifstack == null)
2964 ifstack = new Stack<int> (2);
2966 int flags = region_directive ? REGION : 0;
2967 if (ifstack.Count == 0){
2968 flags |= PARENT_TAKING;
2970 int state = ifstack.Peek ();
2971 if ((state & TAKING) != 0) {
2972 flags |= PARENT_TAKING;
2976 if (eval (arg) && caller_is_taking) {
2977 ifstack.Push (flags | TAKING);
2980 ifstack.Push (flags);
2983 case PreprocessorDirective.Endif:
2984 if (ifstack == null || ifstack.Count == 0){
2985 Error_UnexpectedDirective ("no #if for this #endif");
2988 pop = ifstack.Pop ();
2990 if ((pop & REGION) != 0)
2991 Report.Error (1038, Location, "#endregion directive expected");
2993 if (arg.Length != 0) {
2994 Error_EndLineExpected ();
2997 if (ifstack.Count == 0)
3000 int state = ifstack.Peek ();
3001 return (state & TAKING) != 0;
3004 case PreprocessorDirective.Elif:
3005 if (ifstack == null || ifstack.Count == 0){
3006 Error_UnexpectedDirective ("no #if for this #elif");
3009 int state = ifstack.Pop ();
3011 if ((state & REGION) != 0) {
3012 Report.Error (1038, Location, "#endregion directive expected");
3016 if ((state & ELSE_SEEN) != 0){
3017 Error_UnexpectedDirective ("#elif not valid after #else");
3021 if ((state & TAKING) != 0) {
3026 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
3027 ifstack.Push (state | TAKING);
3031 ifstack.Push (state);
3035 case PreprocessorDirective.Else:
3036 if (ifstack == null || ifstack.Count == 0){
3037 Error_UnexpectedDirective ("no #if for this #else");
3040 int state = ifstack.Peek ();
3042 if ((state & REGION) != 0) {
3043 Report.Error (1038, Location, "#endregion directive expected");
3047 if ((state & ELSE_SEEN) != 0){
3048 Error_UnexpectedDirective ("#else within #else");
3054 if (arg.Length != 0) {
3055 Error_EndLineExpected ();
3060 if ((state & PARENT_TAKING) != 0) {
3061 ret = (state & TAKING) == 0;
3069 ifstack.Push (state | ELSE_SEEN);
3073 case PreprocessorDirective.Define:
3074 if (any_token_seen){
3075 if (caller_is_taking)
3076 Error_TokensSeen ();
3077 return caller_is_taking;
3079 PreProcessDefinition (true, arg, caller_is_taking);
3080 return caller_is_taking;
3082 case PreprocessorDirective.Undef:
3083 if (any_token_seen){
3084 if (caller_is_taking)
3085 Error_TokensSeen ();
3086 return caller_is_taking;
3088 PreProcessDefinition (false, arg, caller_is_taking);
3089 return caller_is_taking;
3091 case PreprocessorDirective.Invalid:
3092 Report.Error (1024, Location, "Wrong preprocessor directive");
3097 // These are only processed if we are in a `taking' block
3099 if (!caller_is_taking)
3103 case PreprocessorDirective.Error:
3104 Report.Error (1029, Location, "#error: '{0}'", arg);
3107 case PreprocessorDirective.Warning:
3108 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3111 case PreprocessorDirective.Pragma:
3112 if (context.Settings.Version == LanguageVersion.ISO_1) {
3113 Report.FeatureIsNotAvailable (context, Location, "#pragma");
3116 ParsePragmaDirective ();
3119 case PreprocessorDirective.Line:
3120 Location loc = Location;
3121 if (!PreProcessLine ())
3122 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3124 return caller_is_taking;
3127 throw new NotImplementedException (directive.ToString ());
3130 int consume_string (bool quoted)
3134 Location start_location = Location;
3136 start_location = start_location - 1;
3139 int reader_pos = reader.Position;
3143 // Cannot use get_char because of \r in quoted strings
3144 if (putback_char != -1) {
3154 if (quoted && peek_char () == '"') {
3155 if (pos == value_builder.Length)
3156 Array.Resize (ref value_builder, pos * 2);
3158 value_builder[pos++] = (char) c;
3163 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3166 res.ParsedValue = quoted ?
3167 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3168 reader.ReadChars (reader_pos - 1, reader.Position);
3171 return Token.LITERAL;
3174 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3176 Report.Error (1010, Location, "Newline in constant");
3180 // Don't add \r to string literal
3181 if (pos > 1 && value_builder [pos - 1] == '\r')
3184 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3185 return Token.LITERAL;
3189 } else if (c == '\\' && !quoted) {
3192 c = escape (c, out surrogate);
3195 if (surrogate != 0) {
3196 if (pos == value_builder.Length)
3197 Array.Resize (ref value_builder, pos * 2);
3199 value_builder[pos++] = (char) c;
3202 } else if (c == -1) {
3203 Report.Error (1039, Location, "Unterminated string literal");
3209 if (pos == value_builder.Length)
3210 Array.Resize (ref value_builder, pos * 2);
3212 value_builder[pos++] = (char) c;
3216 private int consume_identifier (int s)
3218 int res = consume_identifier (s, false);
3220 if (doc_state == XmlCommentState.Allowed)
3221 doc_state = XmlCommentState.NotAllowed;
3226 int consume_identifier (int c, bool quoted)
3229 // This method is very performance sensitive. It accounts
3230 // for approximately 25% of all parser time
3240 c = escape (c, out surrogate);
3241 if (quoted || is_identifier_start_character (c)) {
3242 // it's added bellow
3243 } else if (surrogate != 0) {
3244 id_builder [pos++] = (char)c;
3247 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3252 id_builder [pos++] = (char) c;
3258 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3259 id_builder [pos++] = (char) c;
3266 c = escape (c, out surrogate);
3267 if (is_identifier_part_character ((char) c))
3268 id_builder[pos++] = (char) c;
3269 else if (surrogate != 0) {
3273 // TODO: Probably need more whitespace characters
3278 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3285 } else if (is_identifier_part_character_slow_part ((char) c)) {
3286 id_builder [pos++] = (char) c;
3293 } catch (IndexOutOfRangeException) {
3294 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3302 // Optimization: avoids doing the keyword lookup
3303 // on uppercase letters
3305 if (id_builder [0] >= '_' && !quoted) {
3306 int keyword = GetKeyword (id_builder, pos);
3307 if (keyword != -1) {
3308 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3313 string s = InternIdentifier (id_builder, pos);
3314 val = ltb.Create (s, current_source, ref_line, column);
3315 if (quoted && parsing_attribute_section)
3316 AddEscapedIdentifier (((LocatedToken) val).Location);
3318 return Token.IDENTIFIER;
3321 string InternIdentifier (char[] charBuffer, int length)
3324 // Keep identifiers in an array of hashtables to avoid needless
3327 var identifiers_group = identifiers[length];
3329 if (identifiers_group != null) {
3330 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3334 // TODO: this should be number of files dependant
3335 // corlib compilation peaks at 1000 and System.Core at 150
3336 int capacity = length > 20 ? 10 : 100;
3337 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3338 identifiers[length] = identifiers_group;
3341 char[] chars = new char[length];
3342 Array.Copy (charBuffer, chars, length);
3344 s = new string (charBuffer, 0, length);
3345 identifiers_group.Add (chars, s);
3349 public int xtoken ()
3351 if (parsing_interpolation_format) {
3352 return TokenizeInterpolationFormat ();
3357 // Whether we have seen comments on the current line
3358 bool comments_seen = false;
3359 while ((c = get_char ()) != -1) {
3362 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3370 case 0xFEFF: // Ignore BOM anywhere in the file
3373 /* This is required for compatibility with .NET
3375 if (peek_char () == 0xBB) {
3378 if (get_char () == 0xBF)
3386 return consume_identifier (c);
3389 val = ltb.Create (current_source, ref_line, col);
3391 if (parsing_string_interpolation > 0)
3392 ++string_interpolation_section;
3394 return Token.OPEN_BRACE;
3396 if (parsing_string_interpolation > 0) {
3397 if (string_interpolation_section == 0) {
3398 --parsing_string_interpolation;
3400 if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Count > 0) {
3401 quoted = parsing_string_interpolation_quoted.Pop ();
3406 return TokenizeInterpolatedString (quoted);
3409 --string_interpolation_section;
3412 val = ltb.Create (current_source, ref_line, col);
3413 return Token.CLOSE_BRACE;
3415 // To block doccomment inside attribute declaration.
3416 if (doc_state == XmlCommentState.Allowed)
3417 doc_state = XmlCommentState.NotAllowed;
3419 val = ltb.Create (current_source, ref_line, col);
3421 if (parsing_block == 0 || lambda_arguments_parsing)
3422 return Token.OPEN_BRACKET;
3424 int next = peek_char ();
3428 return Token.OPEN_BRACKET;
3438 next = peek_token ();
3439 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3440 return Token.OPEN_BRACKET;
3442 return Token.OPEN_BRACKET_EXPR;
3444 return Token.OPEN_BRACKET_EXPR;
3447 ltb.CreateOptional (current_source, ref_line, col, ref val);
3448 return Token.CLOSE_BRACKET;
3450 val = ltb.Create (current_source, ref_line, col);
3452 // An expression versions of parens can appear in block context only
3454 if (parsing_block != 0 && !lambda_arguments_parsing) {
3457 // Optmize most common case where we know that parens
3460 switch (current_token) {
3461 case Token.IDENTIFIER:
3470 case Token.DELEGATE:
3471 case Token.OP_GENERICS_GT:
3472 return Token.OPEN_PARENS;
3475 // Optimize using peek
3476 int xx = peek_char ();
3483 return Token.OPEN_PARENS;
3486 lambda_arguments_parsing = true;
3488 d = TokenizeOpenParens ();
3490 lambda_arguments_parsing = false;
3494 return Token.OPEN_PARENS;
3496 ltb.CreateOptional (current_source, ref_line, col, ref val);
3497 return Token.CLOSE_PARENS;
3499 ltb.CreateOptional (current_source, ref_line, col, ref val);
3502 ltb.CreateOptional (current_source, ref_line, col, ref val);
3503 return Token.SEMICOLON;
3505 val = ltb.Create (current_source, ref_line, col);
3508 val = ltb.Create (current_source, ref_line, col);
3509 return TokenizePossibleNullableType ();
3511 val = ltb.Create (current_source, ref_line, col);
3512 if (parsing_generic_less_than++ > 0)
3513 return Token.OP_GENERICS_LT;
3515 return TokenizeLessThan ();
3518 val = ltb.Create (current_source, ref_line, col);
3526 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3527 parsing_generic_less_than--;
3528 return Token.OP_GENERICS_GT;
3537 return Token.OP_SHIFT_RIGHT_ASSIGN;
3539 return Token.OP_SHIFT_RIGHT;
3545 val = ltb.Create (current_source, ref_line, col);
3549 } else if (d == '=') {
3550 d = Token.OP_ADD_ASSIGN;
3558 val = ltb.Create (current_source, ref_line, col);
3562 } else if (d == '=')
3563 d = Token.OP_SUB_ASSIGN;
3573 val = ltb.Create (current_source, ref_line, col);
3574 if (peek_char () == '='){
3581 val = ltb.Create (current_source, ref_line, col);
3592 return Token.ASSIGN;
3595 val = ltb.Create (current_source, ref_line, col);
3599 return Token.OP_AND;
3603 return Token.OP_AND_ASSIGN;
3605 return Token.BITWISE_AND;
3608 val = ltb.Create (current_source, ref_line, col);
3616 return Token.OP_OR_ASSIGN;
3618 return Token.BITWISE_OR;
3621 val = ltb.Create (current_source, ref_line, col);
3622 if (peek_char () == '='){
3624 return Token.OP_MULT_ASSIGN;
3631 val = ltb.Create (current_source, ref_line, col);
3633 return Token.OP_DIV_ASSIGN;
3636 // Handle double-slash comments.
3638 if (parsing_string_interpolation > 0) {
3639 Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3644 if (doc_processing) {
3645 if (peek_char () == '/') {
3647 // Don't allow ////.
3648 if ((d = peek_char ()) != '/') {
3649 if (doc_state == XmlCommentState.Allowed)
3650 handle_one_line_xml_comment ();
3651 else if (doc_state == XmlCommentState.NotAllowed)
3652 WarningMisplacedComment (Location - 3);
3655 if (xml_comment_buffer.Length > 0)
3656 doc_state = XmlCommentState.NotAllowed;
3662 any_token_seen |= tokens_seen;
3663 tokens_seen = false;
3664 comments_seen = false;
3666 } else if (d == '*'){
3668 bool docAppend = false;
3669 if (doc_processing && peek_char () == '*') {
3671 // But when it is /**/, just do nothing.
3672 if (peek_char () == '/') {
3676 if (doc_state == XmlCommentState.Allowed)
3678 else if (doc_state == XmlCommentState.NotAllowed) {
3679 WarningMisplacedComment (Location - 2);
3683 int current_comment_start = 0;
3685 current_comment_start = xml_comment_buffer.Length;
3686 xml_comment_buffer.Append (Environment.NewLine);
3689 while ((d = get_char ()) != -1){
3690 if (d == '*' && peek_char () == '/'){
3692 comments_seen = true;
3696 xml_comment_buffer.Append ((char) d);
3698 if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3699 any_token_seen |= tokens_seen;
3700 tokens_seen = false;
3702 // Reset 'comments_seen' just to be consistent.
3703 // It doesn't matter either way, here.
3705 comments_seen = false;
3709 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3712 update_formatted_doc_comment (current_comment_start);
3715 val = ltb.Create (current_source, ref_line, col);
3719 val = ltb.Create (current_source, ref_line, col);
3720 if (peek_char () == '='){
3722 return Token.OP_MOD_ASSIGN;
3724 return Token.PERCENT;
3727 val = ltb.Create (current_source, ref_line, col);
3728 if (peek_char () == '='){
3730 return Token.OP_XOR_ASSIGN;
3732 return Token.CARRET;
3735 val = ltb.Create (current_source, ref_line, col);
3736 if (peek_char () == ':') {
3738 return Token.DOUBLE_COLON;
3742 case '0': case '1': case '2': case '3': case '4':
3743 case '5': case '6': case '7': case '8': case '9':
3745 return is_number (c, false);
3747 case '\n': // white space
3750 any_token_seen |= tokens_seen;
3751 tokens_seen = false;
3752 comments_seen = false;
3758 if (d >= '0' && d <= '9')
3759 return is_number (c, true);
3761 ltb.CreateOptional (current_source, ref_line, col, ref val);
3765 if (tokens_seen || comments_seen) {
3766 Eror_WrongPreprocessorLocation ();
3770 if (ParsePreprocessingDirective (true))
3773 bool directive_expected = false;
3774 while ((c = get_char ()) != -1) {
3776 directive_expected = true;
3777 } else if (!directive_expected) {
3778 // TODO: Implement comment support for disabled code and uncomment this code
3780 // Eror_WrongPreprocessorLocation ();
3781 // return Token.ERROR;
3786 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3790 if (ParsePreprocessingDirective (false))
3793 directive_expected = false;
3797 tokens_seen = false;
3804 if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3805 parsing_string_interpolation = 0;
3806 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3807 val = new StringLiteral (context.BuiltinTypes, "", Location);
3808 return Token.INTERPOLATED_STRING_END;
3811 return consume_string (false);
3814 return TokenizeBackslash ();
3820 return consume_string (true);
3823 if (is_identifier_start_character (c)){
3824 return consume_identifier (c, true);
3827 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3831 switch (peek_char ()) {
3834 return TokenizeInterpolatedString (false);
3837 if (peek_char () == '"') {
3839 return TokenizeInterpolatedString (true);
3846 case EvalStatementParserCharacter:
3847 return Token.EVAL_STATEMENT_PARSER;
3848 case EvalCompilationUnitParserCharacter:
3849 return Token.EVAL_COMPILATION_UNIT_PARSER;
3850 case EvalUsingDeclarationsParserCharacter:
3851 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3852 case DocumentationXref:
3853 return Token.DOC_SEE;
3856 if (is_identifier_start_character (c)) {
3858 return consume_identifier (c);
3861 if (char.IsWhiteSpace ((char) c))
3864 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3869 return Token.COMPLETE_COMPLETION;
3872 return Token.GENERATE_COMPLETION;
3879 int TokenizeBackslash ()
3882 int read_start = reader.Position;
3884 Location start_location = Location;
3885 int c = get_char ();
3888 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3889 Report.Error (1011, start_location, "Empty character literal");
3890 return Token.LITERAL;
3893 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3894 Report.Error (1010, start_location, "Newline in constant");
3899 c = escape (c, out d);
3903 throw new NotImplementedException ();
3905 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3910 Report.Error (1012, start_location, "Too many characters in character literal");
3912 // Try to recover, read until newline or next "'"
3913 while ((c = get_char ()) != -1) {
3914 if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3920 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3923 return Token.LITERAL;
3926 int TokenizeLessThan ()
3930 // Save current position and parse next token.
3932 int generic_dimension = 0;
3933 if (parse_less_than (ref generic_dimension)) {
3934 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3935 d = Token.OP_GENERICS_LT_DECL;
3937 if (generic_dimension > 0) {
3938 val = generic_dimension;
3940 return Token.GENERIC_DIMENSION;
3943 d = Token.OP_GENERICS_LT;
3950 parsing_generic_less_than = 0;
3959 return Token.OP_SHIFT_LEFT_ASSIGN;
3961 return Token.OP_SHIFT_LEFT;
3971 int TokenizeInterpolatedString (bool quoted)
3974 var start_location = Location;
3977 var ch = get_char ();
3980 if (quoted && peek_char () == '"') {
3985 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3986 return Token.INTERPOLATED_STRING_END;
3988 if (peek_char () == '{') {
3989 value_builder [pos++] = (char)ch;
3994 ++parsing_string_interpolation;
3996 if (parsing_string_interpolation_quoted == null)
3997 parsing_string_interpolation_quoted = new Stack<bool> ();
4000 if (parsing_string_interpolation_quoted != null) {
4001 parsing_string_interpolation_quoted.Push (quoted);
4004 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
4005 return Token.INTERPOLATED_STRING;
4012 ch = escape (ch, out surrogate);
4016 if (ch == '{' || ch == '}') {
4017 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4020 if (surrogate != 0) {
4021 if (pos == value_builder.Length)
4022 Array.Resize (ref value_builder, pos * 2);
4024 if (pos == value_builder.Length)
4025 Array.Resize (ref value_builder, pos * 2);
4027 value_builder [pos++] = (char)ch;
4037 if (pos == value_builder.Length)
4038 Array.Resize (ref value_builder, pos * 2);
4040 value_builder[pos++] = (char) ch;
4044 int TokenizeInterpolationFormat ()
4049 var ch = get_char ();
4058 Report.Error (8089, Location, "Empty interpolated expression format specifier");
4059 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
4060 Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
4063 val = CreateStringFromBuilder (pos);
4064 return Token.LITERAL;
4070 if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Peek ())
4075 ch = escape (ch, out surrogate);
4079 if (ch == '{' || ch == '}') {
4080 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4083 if (surrogate != 0) {
4084 if (pos == value_builder.Length)
4085 Array.Resize (ref value_builder, pos * 2);
4087 value_builder [pos++] = (char)ch;
4097 value_builder[pos++] = (char) ch;
4101 string CreateStringFromBuilder (int pos)
4104 return string.Empty;
4106 return InternIdentifier (value_builder, pos);
4108 return new string (value_builder, 0, pos);
4112 // Handles one line xml comment
4114 private void handle_one_line_xml_comment ()
4117 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4118 xml_comment_buffer.Append ((char) get_char ());
4120 if (c == '\r' || c == '\n')
4121 xml_comment_buffer.Append (Environment.NewLine);
4125 // Remove heading "*" in Javadoc-like xml documentation.
4127 private void update_formatted_doc_comment (int current_comment_start)
4129 int length = xml_comment_buffer.Length - current_comment_start;
4130 string [] lines = xml_comment_buffer.ToString (
4131 current_comment_start,
4132 length).Replace ("\r", "").Split ('\n');
4134 // The first line starts with /**, thus it is not target
4135 // for the format check.
4136 for (int i = 1; i < lines.Length; i++) {
4137 string s = lines [i];
4138 int idx = s.IndexOf ('*');
4141 if (i < lines.Length - 1)
4145 head = s.Substring (0, idx);
4146 foreach (char c in head)
4149 lines [i] = s.Substring (idx + 1);
4151 xml_comment_buffer.Remove (current_comment_start, length);
4152 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4156 // Checks if there was incorrect doc comments and raise
4159 public void check_incorrect_doc_comment ()
4161 if (xml_comment_buffer.Length > 0)
4162 WarningMisplacedComment (Location);
4166 // Consumes the saved xml comment lines (if any)
4167 // as for current target member or type.
4169 public string consume_doc_comment ()
4171 if (xml_comment_buffer.Length > 0) {
4172 string ret = xml_comment_buffer.ToString ();
4173 reset_doc_comment ();
4179 void reset_doc_comment ()
4181 xml_comment_buffer.Length = 0;
4184 public void cleanup ()
4186 if (ifstack != null && ifstack.Count >= 1) {
4187 int state = ifstack.Pop ();
4188 if ((state & REGION) != 0)
4189 Report.Error (1038, Location, "#endregion directive expected");
4191 Report.Error (1027, Location, "Expected `#endif' directive");
4197 // Indicates whether it accepts XML documentation or not.
4199 public enum XmlCommentState {
4200 // comment is allowed in this state.
4202 // comment is not allowed in this state.
4204 // once comments appeared when it is NotAllowed, then the
4205 // state is changed to it, until the state is changed to