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 Stack<bool> parsing_string_interpolation_quoted;
245 public bool parsing_interpolation_format;
248 // The special characters to inject on streams to run the unit parser
249 // in the special expression mode. Using private characters from
250 // Plane Sixteen (U+100000 to U+10FFFD)
252 // This character is only tested just before the tokenizer is about to report
253 // an error; So on the regular operation mode, this addition will have no
254 // impact on the tokenizer's performance.
257 public const int EvalStatementParserCharacter = 0x100000;
258 public const int EvalCompilationUnitParserCharacter = 0x100001;
259 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
260 public const int DocumentationXref = 0x100003;
262 const int UnicodeLS = 0x2028;
263 const int UnicodePS = 0x2029;
266 // XML documentation buffer. The save point is used to divide
267 // comments on types and comments on members.
269 StringBuilder xml_comment_buffer;
272 // See comment on XmlCommentState enumeration.
274 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
277 // Whether tokens have been seen on this line
279 bool tokens_seen = false;
282 // Set to true once the GENERATE_COMPLETION token has bee
283 // returned. This helps produce one GENERATE_COMPLETION,
284 // as many COMPLETE_COMPLETION as necessary to complete the
285 // AST tree and one final EOF.
290 // Whether a token has been seen on the file
291 // This is needed because `define' is not allowed to be used
292 // after a token has been seen.
299 static readonly KeywordEntry<int>[][] keywords;
300 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
301 static readonly HashSet<string> keyword_strings;
302 static readonly NumberStyles styles;
303 static readonly NumberFormatInfo csharp_format_info;
306 static readonly char[] pragma_warning = "warning".ToCharArray ();
307 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
308 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
309 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
310 static readonly char[] line_hidden = "hidden".ToCharArray ();
311 static readonly char[] line_default = "default".ToCharArray ();
313 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
315 public bool PropertyParsing {
316 get { return handle_get_set; }
317 set { handle_get_set = value; }
320 public bool EventParsing {
321 get { return handle_remove_add; }
322 set { handle_remove_add = value; }
325 public bool ConstraintsParsing {
326 get { return handle_where; }
327 set { handle_where = value; }
330 public XmlCommentState doc_state {
331 get { return xml_doc_state; }
333 if (value == XmlCommentState.Allowed) {
334 check_incorrect_doc_comment ();
335 reset_doc_comment ();
337 xml_doc_state = value;
342 // This is used to trigger completion generation on the parser
343 public bool CompleteOnEOF;
345 void AddEscapedIdentifier (Location loc)
347 if (escaped_identifiers == null)
348 escaped_identifiers = new List<Location> ();
350 escaped_identifiers.Add (loc);
353 public bool IsEscapedIdentifier (ATypeNameExpression name)
355 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
359 // Values for the associated token returned
361 internal int putback_char; // Used by repl only
367 const int TAKING = 1;
368 const int ELSE_SEEN = 4;
369 const int PARENT_TAKING = 8;
370 const int REGION = 16;
373 // pre-processor if stack state:
377 public const int MaxIdentifierLength = 512;
378 public const int MaxNumberLength = 512;
380 readonly char[] id_builder;
381 readonly Dictionary<char[], string>[] identifiers;
382 readonly char[] number_builder;
385 char[] value_builder = new char[64];
394 // This is used when the tokenizer needs to save
395 // the current position as it needs to do some parsing
396 // on its own to deamiguate a token in behalf of the
399 Stack<Position> position_stack = new Stack<Position> (2);
406 public Location hidden;
407 public int putback_char;
408 public int previous_col;
409 public Stack<int> ifstack;
410 public int parsing_generic_less_than;
411 public int current_token;
413 public int parsing_string_interpolation;
414 public Stack<bool> parsing_string_interpolation_quoted;
416 public Position (Tokenizer t)
418 position = t.reader.Position;
420 ref_line = t.ref_line;
422 hidden = t.hidden_block_start;
423 putback_char = t.putback_char;
424 previous_col = t.previous_col;
425 if (t.ifstack != null && t.ifstack.Count != 0) {
426 // There is no simple way to clone Stack<T> all
427 // methods reverse the order
428 var clone = t.ifstack.ToArray ();
429 Array.Reverse (clone);
430 ifstack = new Stack<int> (clone);
432 parsing_generic_less_than = t.parsing_generic_less_than;
433 current_token = t.current_token;
435 parsing_string_interpolation = t.parsing_string_interpolation;
436 if (t.parsing_string_interpolation_quoted != null && t.parsing_string_interpolation_quoted.Count != 0) {
437 var clone = t.parsing_string_interpolation_quoted.ToArray ();
438 Array.Reverse (clone);
439 parsing_string_interpolation_quoted = new Stack<bool> (clone);
444 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session, Report report)
446 this.source_file = file;
447 this.context = file.Compiler;
448 this.current_source = file.SourceFile;
449 this.identifiers = session.Identifiers;
450 this.id_builder = session.IDBuilder;
451 this.number_builder = session.NumberBuilder;
452 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
453 this.Report = report;
459 xml_comment_buffer = new StringBuilder ();
460 doc_processing = context.Settings.DocumentationFile != null;
462 tab_size = context.Settings.TabSize;
465 public void PushPosition ()
467 position_stack.Push (new Position (this));
470 public void PopPosition ()
472 Position p = position_stack.Pop ();
474 reader.Position = p.position;
475 ref_line = p.ref_line;
478 hidden_block_start = p.hidden;
479 putback_char = p.putback_char;
480 previous_col = p.previous_col;
482 parsing_generic_less_than = p.parsing_generic_less_than;
483 parsing_string_interpolation = p.parsing_string_interpolation;
484 parsing_string_interpolation_quoted = p.parsing_string_interpolation_quoted;
485 current_token = p.current_token;
489 // Do not reset the position, ignore it.
490 public void DiscardPosition ()
492 position_stack.Pop ();
495 static void AddKeyword (string kw, int token)
497 keyword_strings.Add (kw);
499 AddKeyword (keywords, kw, token);
502 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
504 AddKeyword (keywords_preprocessor, kw, directive);
507 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
509 int length = kw.Length;
510 if (keywords[length] == null) {
511 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
514 int char_index = kw[0] - '_';
515 var kwe = keywords[length][char_index];
517 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
521 while (kwe.Next != null) {
525 kwe.Next = new KeywordEntry<T> (kw, token);
533 keyword_strings = new HashSet<string> ();
535 // 11 is the length of the longest keyword for now
536 keywords = new KeywordEntry<int>[11][];
538 AddKeyword ("__arglist", Token.ARGLIST);
539 AddKeyword ("__makeref", Token.MAKEREF);
540 AddKeyword ("__reftype", Token.REFTYPE);
541 AddKeyword ("__refvalue", Token.REFVALUE);
542 AddKeyword ("abstract", Token.ABSTRACT);
543 AddKeyword ("as", Token.AS);
544 AddKeyword ("add", Token.ADD);
545 AddKeyword ("base", Token.BASE);
546 AddKeyword ("bool", Token.BOOL);
547 AddKeyword ("break", Token.BREAK);
548 AddKeyword ("byte", Token.BYTE);
549 AddKeyword ("case", Token.CASE);
550 AddKeyword ("catch", Token.CATCH);
551 AddKeyword ("char", Token.CHAR);
552 AddKeyword ("checked", Token.CHECKED);
553 AddKeyword ("class", Token.CLASS);
554 AddKeyword ("const", Token.CONST);
555 AddKeyword ("continue", Token.CONTINUE);
556 AddKeyword ("decimal", Token.DECIMAL);
557 AddKeyword ("default", Token.DEFAULT);
558 AddKeyword ("delegate", Token.DELEGATE);
559 AddKeyword ("do", Token.DO);
560 AddKeyword ("double", Token.DOUBLE);
561 AddKeyword ("else", Token.ELSE);
562 AddKeyword ("enum", Token.ENUM);
563 AddKeyword ("event", Token.EVENT);
564 AddKeyword ("explicit", Token.EXPLICIT);
565 AddKeyword ("extern", Token.EXTERN);
566 AddKeyword ("false", Token.FALSE);
567 AddKeyword ("finally", Token.FINALLY);
568 AddKeyword ("fixed", Token.FIXED);
569 AddKeyword ("float", Token.FLOAT);
570 AddKeyword ("for", Token.FOR);
571 AddKeyword ("foreach", Token.FOREACH);
572 AddKeyword ("goto", Token.GOTO);
573 AddKeyword ("get", Token.GET);
574 AddKeyword ("if", Token.IF);
575 AddKeyword ("implicit", Token.IMPLICIT);
576 AddKeyword ("in", Token.IN);
577 AddKeyword ("int", Token.INT);
578 AddKeyword ("interface", Token.INTERFACE);
579 AddKeyword ("internal", Token.INTERNAL);
580 AddKeyword ("is", Token.IS);
581 AddKeyword ("lock", Token.LOCK);
582 AddKeyword ("long", Token.LONG);
583 AddKeyword ("namespace", Token.NAMESPACE);
584 AddKeyword ("new", Token.NEW);
585 AddKeyword ("null", Token.NULL);
586 AddKeyword ("object", Token.OBJECT);
587 AddKeyword ("operator", Token.OPERATOR);
588 AddKeyword ("out", Token.OUT);
589 AddKeyword ("override", Token.OVERRIDE);
590 AddKeyword ("params", Token.PARAMS);
591 AddKeyword ("private", Token.PRIVATE);
592 AddKeyword ("protected", Token.PROTECTED);
593 AddKeyword ("public", Token.PUBLIC);
594 AddKeyword ("readonly", Token.READONLY);
595 AddKeyword ("ref", Token.REF);
596 AddKeyword ("remove", Token.REMOVE);
597 AddKeyword ("return", Token.RETURN);
598 AddKeyword ("sbyte", Token.SBYTE);
599 AddKeyword ("sealed", Token.SEALED);
600 AddKeyword ("set", Token.SET);
601 AddKeyword ("short", Token.SHORT);
602 AddKeyword ("sizeof", Token.SIZEOF);
603 AddKeyword ("stackalloc", Token.STACKALLOC);
604 AddKeyword ("static", Token.STATIC);
605 AddKeyword ("string", Token.STRING);
606 AddKeyword ("struct", Token.STRUCT);
607 AddKeyword ("switch", Token.SWITCH);
608 AddKeyword ("this", Token.THIS);
609 AddKeyword ("throw", Token.THROW);
610 AddKeyword ("true", Token.TRUE);
611 AddKeyword ("try", Token.TRY);
612 AddKeyword ("typeof", Token.TYPEOF);
613 AddKeyword ("uint", Token.UINT);
614 AddKeyword ("ulong", Token.ULONG);
615 AddKeyword ("unchecked", Token.UNCHECKED);
616 AddKeyword ("unsafe", Token.UNSAFE);
617 AddKeyword ("ushort", Token.USHORT);
618 AddKeyword ("using", Token.USING);
619 AddKeyword ("virtual", Token.VIRTUAL);
620 AddKeyword ("void", Token.VOID);
621 AddKeyword ("volatile", Token.VOLATILE);
622 AddKeyword ("while", Token.WHILE);
623 AddKeyword ("partial", Token.PARTIAL);
624 AddKeyword ("where", Token.WHERE);
627 AddKeyword ("from", Token.FROM);
628 AddKeyword ("join", Token.JOIN);
629 AddKeyword ("on", Token.ON);
630 AddKeyword ("equals", Token.EQUALS);
631 AddKeyword ("select", Token.SELECT);
632 AddKeyword ("group", Token.GROUP);
633 AddKeyword ("by", Token.BY);
634 AddKeyword ("let", Token.LET);
635 AddKeyword ("orderby", Token.ORDERBY);
636 AddKeyword ("ascending", Token.ASCENDING);
637 AddKeyword ("descending", Token.DESCENDING);
638 AddKeyword ("into", Token.INTO);
640 // Contextual async keywords
641 AddKeyword ("async", Token.ASYNC);
642 AddKeyword ("await", Token.AWAIT);
644 // Contextual filter catch keyword
645 AddKeyword ("when", Token.WHEN);
647 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
649 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
650 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
651 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
652 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
653 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
654 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
655 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
656 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
657 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
658 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
659 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
660 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
662 csharp_format_info = NumberFormatInfo.InvariantInfo;
663 styles = NumberStyles.Float;
666 int GetKeyword (char[] id, int id_len)
669 // Keywords are stored in an array of arrays grouped by their
670 // length and then by the first character
672 if (id_len >= keywords.Length || keywords [id_len] == null)
675 int first_index = id [0] - '_';
676 if (first_index > 'z' - '_')
679 var kwe = keywords [id_len] [first_index];
686 for (int i = 1; i < id_len; ++i) {
687 if (id [i] != kwe.Value [i]) {
693 } while (res == 0 && kwe != null);
707 if (!handle_remove_add)
711 if (parsing_declaration == 0)
712 res = Token.EXTERN_ALIAS;
715 if (peek_token () == Token.COLON) {
717 res = Token.DEFAULT_COLON;
721 if (current_token != Token.CATCH && !parsing_catch_when)
725 if (!(handle_where && current_token != Token.COLON) && !query_parsing)
730 // A query expression is any expression that starts with `from identifier'
731 // followed by any token except ; , =
733 if (!query_parsing) {
734 if (lambda_arguments_parsing || parsing_block == 0) {
740 // HACK: to disable generics micro-parser, because PushPosition does not
741 // store identifiers array
742 parsing_generic_less_than = 1;
744 case Token.IDENTIFIER:
757 next_token = xtoken ();
758 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
761 res = Token.FROM_FIRST;
762 query_parsing = true;
763 if (context.Settings.Version <= LanguageVersion.ISO_2)
764 Report.FeatureIsNotAvailable (context, Location, "query expressions");
767 Expression.Error_VoidInvalidInTheContext (Location, Report);
771 // HACK: A token is not a keyword so we need to restore identifiers buffer
772 // which has been overwritten before we grabbed the identifier
773 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
787 case Token.ASCENDING:
788 case Token.DESCENDING:
795 case Token.NAMESPACE:
796 // TODO: some explanation needed
797 check_incorrect_doc_comment ();
798 parsing_modifiers = false;
802 if (parsing_block > 0) {
807 // Save current position and parse next token.
810 next_token = token ();
811 bool ok = (next_token == Token.CLASS) ||
812 (next_token == Token.STRUCT) ||
813 (next_token == Token.INTERFACE) ||
814 (next_token == Token.VOID);
819 if (next_token == Token.VOID) {
820 if (context.Settings.Version <= LanguageVersion.ISO_2)
821 Report.FeatureIsNotAvailable (context, Location, "partial methods");
822 } else if (context.Settings.Version == LanguageVersion.ISO_1)
823 Report.FeatureIsNotAvailable (context, Location, "partial types");
828 if (next_token < Token.LAST_KEYWORD) {
829 Report.Error (267, Location,
830 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
834 // HACK: A token is not a keyword so we need to restore identifiers buffer
835 // which has been overwritten before we grabbed the identifier
847 if (parsing_modifiers) {
849 // Skip attributes section or constructor called async
851 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
856 } else if (parsing_block > 0) {
857 switch (peek_token ()) {
859 case Token.OPEN_PARENS_LAMBDA:
862 case Token.IDENTIFIER:
865 if (xtoken () != Token.ARROW) {
873 // peek_token could overwrite id_buffer
874 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
882 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
883 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
889 if (parsing_block == 0)
899 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
902 // Keywords are stored in an array of arrays grouped by their
903 // length and then by the first character
905 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
906 return PreprocessorDirective.Invalid;
908 int first_index = id[0] - '_';
909 if (first_index > 'z' - '_')
910 return PreprocessorDirective.Invalid;
912 var kwe = keywords_preprocessor[id_len][first_index];
914 return PreprocessorDirective.Invalid;
916 PreprocessorDirective res = PreprocessorDirective.Invalid;
919 for (int i = 1; i < id_len; ++i) {
920 if (id[i] != kwe.Value[i]) {
926 } while (res == PreprocessorDirective.Invalid && kwe != null);
931 public Location Location {
933 return new Location (current_source, ref_line, col);
937 static bool is_identifier_start_character (int c)
939 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')
945 return is_identifier_start_character_slow_part ((char) c);
948 static bool is_identifier_part_character (char c)
950 if (c >= 'a' && c <= 'z')
953 if (c >= 'A' && c <= 'Z')
956 if (c == '_' || (c >= '0' && c <= '9'))
962 return is_identifier_part_character_slow_part (c);
965 static bool is_identifier_start_character_slow_part (char c)
967 switch (Char.GetUnicodeCategory (c)) {
968 case UnicodeCategory.LetterNumber:
969 case UnicodeCategory.UppercaseLetter:
970 case UnicodeCategory.LowercaseLetter:
971 case UnicodeCategory.TitlecaseLetter:
972 case UnicodeCategory.ModifierLetter:
973 case UnicodeCategory.OtherLetter:
979 static bool is_identifier_part_character_slow_part (char c)
981 switch (Char.GetUnicodeCategory (c)) {
982 // connecting-character: A Unicode character of the class Pc
983 case UnicodeCategory.ConnectorPunctuation:
985 // combining-character: A Unicode character of classes Mn or Mc
986 case UnicodeCategory.NonSpacingMark:
987 case UnicodeCategory.SpacingCombiningMark:
989 // decimal-digit-character: A Unicode character of the class Nd
990 case UnicodeCategory.DecimalDigitNumber:
992 // plus is_identifier_start_character_slow_part
993 case UnicodeCategory.LetterNumber:
994 case UnicodeCategory.UppercaseLetter:
995 case UnicodeCategory.LowercaseLetter:
996 case UnicodeCategory.TitlecaseLetter:
997 case UnicodeCategory.ModifierLetter:
998 case UnicodeCategory.OtherLetter:
1001 // formatting-character: A Unicode character of the class Cf
1002 case UnicodeCategory.Format:
1003 // csc bug compatibility which recognizes it as a whitespace
1010 public static bool IsKeyword (string s)
1012 return keyword_strings.Contains (s);
1016 // Open parens micro parser. Detects both lambda and cast ambiguity.
1018 int TokenizeOpenParens ()
1023 int bracket_level = 0;
1024 bool is_type = false;
1025 bool can_be_type = false;
1028 ptoken = current_token;
1031 switch (current_token) {
1032 case Token.CLOSE_PARENS:
1036 // Expression inside parens is lambda, (int i) =>
1038 if (current_token == Token.ARROW)
1039 return Token.OPEN_PARENS_LAMBDA;
1042 // Expression inside parens is single type, (int[])
1045 if (current_token == Token.SEMICOLON)
1046 return Token.OPEN_PARENS;
1048 return Token.OPEN_PARENS_CAST;
1052 // Expression is possible cast, look at next token, (T)null
1055 switch (current_token) {
1056 case Token.OPEN_PARENS:
1059 case Token.IDENTIFIER:
1063 case Token.DELEGATE:
1073 case Token.UNCHECKED:
1079 // These can be part of a member access
1094 return Token.OPEN_PARENS_CAST;
1097 return Token.OPEN_PARENS;
1100 case Token.DOUBLE_COLON:
1101 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1106 case Token.IDENTIFIER:
1110 if (bracket_level == 0) {
1116 case Token.OP_GENERICS_LT:
1118 case Token.DOUBLE_COLON:
1120 if (bracket_level == 0)
1124 can_be_type = is_type = false;
1144 if (bracket_level == 0)
1149 if (bracket_level == 0) {
1150 bracket_level = 100;
1151 can_be_type = is_type = false;
1155 case Token.OP_GENERICS_LT:
1156 case Token.OPEN_BRACKET:
1157 if (bracket_level++ == 0)
1161 case Token.OP_GENERICS_GT:
1162 case Token.CLOSE_BRACKET:
1166 case Token.INTERR_NULLABLE:
1168 if (bracket_level == 0)
1174 can_be_type = is_type = false;
1178 return Token.OPEN_PARENS;
1183 public static bool IsValidIdentifier (string s)
1185 if (s == null || s.Length == 0)
1188 if (!is_identifier_start_character (s [0]))
1191 for (int i = 1; i < s.Length; i ++)
1192 if (! is_identifier_part_character (s [i]))
1198 bool parse_less_than (ref int genericDimension)
1201 int the_token = token ();
1202 if (the_token == Token.OPEN_BRACKET) {
1204 the_token = token ();
1205 if (the_token == Token.EOF)
1208 if (the_token == Token.CLOSE_BRACKET)
1211 the_token = token ();
1212 } else if (the_token == Token.IN || the_token == Token.OUT) {
1213 the_token = token ();
1215 switch (the_token) {
1216 case Token.IDENTIFIER:
1234 case Token.OP_GENERICS_GT:
1235 genericDimension = 1;
1243 the_token = token ();
1244 } while (the_token == Token.COMMA);
1246 if (the_token == Token.OP_GENERICS_GT) {
1256 the_token = token ();
1258 if (the_token == Token.OP_GENERICS_GT)
1260 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1262 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1264 else if (the_token == Token.OP_GENERICS_LT) {
1265 if (!parse_less_than (ref genericDimension))
1268 } else if (the_token == Token.OPEN_BRACKET) {
1270 the_token = token ();
1271 if (the_token == Token.CLOSE_BRACKET)
1273 else if (the_token == Token.COMMA)
1274 goto rank_specifiers;
1281 public int peek_token ()
1286 the_token = token ();
1293 // Tonizes `?' using custom disambiguous rules to return one
1294 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1296 // Tricky expression looks like:
1298 // Foo ? a = x ? b : c;
1300 int TokenizePossibleNullableType ()
1302 if (parsing_block == 0 || parsing_type > 0)
1303 return Token.INTERR_NULLABLE;
1305 int d = peek_char ();
1308 return Token.OP_COALESCING;
1312 return Token.INTERR_OPERATOR;
1316 if (d == ',' || d == ';' || d == '>')
1317 return Token.INTERR_NULLABLE;
1318 if (d == '*' || (d >= '0' && d <= '9'))
1319 return Token.INTERR;
1323 current_token = Token.NONE;
1332 case Token.OPEN_BRACKET_EXPR:
1333 next_token = Token.INTERR_OPERATOR;
1341 case Token.INTERPOLATED_STRING:
1342 next_token = Token.INTERR;
1345 case Token.SEMICOLON:
1347 case Token.CLOSE_PARENS:
1348 case Token.OPEN_BRACKET:
1349 case Token.OP_GENERICS_GT:
1351 case Token.OP_COALESCING:
1353 next_token = Token.INTERR_NULLABLE;
1356 case Token.OPEN_PARENS:
1357 case Token.OPEN_PARENS_CAST:
1358 case Token.OPEN_PARENS_LAMBDA:
1363 case Token.OP_GENERICS_LT:
1364 case Token.OP_GENERICS_LT_DECL:
1365 case Token.GENERIC_DIMENSION:
1375 if (next_token == -1) {
1376 switch (xtoken ()) {
1378 case Token.SEMICOLON:
1379 case Token.OPEN_BRACE:
1381 next_token = Token.INTERR_NULLABLE;
1385 next_token = Token.INTERR;
1388 case Token.OPEN_PARENS:
1389 case Token.OPEN_PARENS_CAST:
1390 case Token.OPEN_PARENS_LAMBDA:
1394 case Token.OPEN_BRACKET:
1395 case Token.OPEN_BRACKET_EXPR:
1399 case Token.CLOSE_PARENS:
1403 case Token.OP_GENERICS_LT:
1404 case Token.OP_GENERICS_LT_DECL:
1405 case Token.GENERIC_DIMENSION:
1415 // All shorcuts failed, do it hard way
1417 while ((ntoken = xtoken ()) != Token.EOF) {
1419 case Token.OPEN_BRACE:
1422 case Token.OPEN_PARENS:
1423 case Token.OPEN_PARENS_CAST:
1424 case Token.OPEN_PARENS_LAMBDA:
1427 case Token.CLOSE_BRACE:
1430 case Token.OP_GENERICS_LT:
1431 case Token.OP_GENERICS_LT_DECL:
1432 case Token.GENERIC_DIMENSION:
1435 case Token.OPEN_BRACKET:
1436 case Token.OPEN_BRACKET_EXPR:
1439 case Token.CLOSE_BRACKET:
1442 case Token.CLOSE_PARENS:
1449 return Token.INTERR_NULLABLE;
1451 case Token.OP_GENERICS_GT:
1458 return Token.INTERR_NULLABLE;
1464 if (ntoken == Token.SEMICOLON)
1470 if (ntoken == Token.COMMA) {
1471 if (generics != 0 || brackets != 0)
1475 return Token.INTERR_NULLABLE;
1478 if (ntoken == Token.COLON) {
1479 if (++colons == interrs)
1484 if (ntoken == Token.INTERR) {
1490 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1499 bool decimal_digits (int c)
1502 bool seen_digits = false;
1505 if (number_pos == MaxNumberLength)
1506 Error_NumericConstantTooLong ();
1507 number_builder [number_pos++] = (char) c;
1511 // We use peek_char2, because decimal_digits needs to do a
1512 // 2-character look-ahead (5.ToString for example).
1514 while ((d = peek_char2 ()) != -1){
1515 if (d >= '0' && d <= '9'){
1516 if (number_pos == MaxNumberLength)
1517 Error_NumericConstantTooLong ();
1518 number_builder [number_pos++] = (char) d;
1528 static bool is_hex (int e)
1530 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1533 static TypeCode real_type_suffix (int c)
1537 return TypeCode.Single;
1539 return TypeCode.Double;
1541 return TypeCode.Decimal;
1543 return TypeCode.Empty;
1547 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1549 bool is_unsigned = false;
1550 bool is_long = false;
1553 bool scanning = true;
1566 // if we have not seen anything in between
1567 // report this error
1569 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1589 if (is_long && is_unsigned){
1590 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1594 // uint if possible, or ulong else.
1596 if ((ul & 0xffffffff00000000) == 0)
1597 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1599 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1600 } else if (is_long){
1601 // long if possible, ulong otherwise
1602 if ((ul & 0x8000000000000000) != 0)
1603 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1605 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1607 // int, uint, long or ulong in that order
1608 if ((ul & 0xffffffff00000000) == 0){
1609 uint ui = (uint) ul;
1611 if ((ui & 0x80000000) != 0)
1612 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1614 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1616 if ((ul & 0x8000000000000000) != 0)
1617 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1619 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1625 // given `c' as the next char in the input decide whether
1626 // we need to convert to a special type, and then choose
1627 // the best representation for the integer
1629 ILiteralConstant adjust_int (int c, Location loc)
1632 if (number_pos > 9){
1633 ulong ul = (uint) (number_builder [0] - '0');
1635 for (int i = 1; i < number_pos; i++){
1636 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1639 return integer_type_suffix (ul, c, loc);
1641 uint ui = (uint) (number_builder [0] - '0');
1643 for (int i = 1; i < number_pos; i++){
1644 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1647 return integer_type_suffix (ui, c, loc);
1649 } catch (OverflowException) {
1650 Error_NumericConstantTooLong ();
1651 return new IntLiteral (context.BuiltinTypes, 0, loc);
1653 catch (FormatException) {
1654 Report.Error (1013, Location, "Invalid number");
1655 return new IntLiteral (context.BuiltinTypes, 0, loc);
1659 ILiteralConstant adjust_real (TypeCode t, Location loc)
1661 string s = new string (number_builder, 0, number_pos);
1662 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1665 case TypeCode.Decimal:
1667 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1668 } catch (OverflowException) {
1669 Report.Error (594, Location, error_details, "decimal");
1670 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1672 case TypeCode.Single:
1674 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1675 } catch (OverflowException) {
1676 Report.Error (594, Location, error_details, "float");
1677 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1681 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1682 } catch (OverflowException) {
1683 Report.Error (594, loc, error_details, "double");
1684 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1689 ILiteralConstant handle_hex (Location loc)
1695 while ((d = peek_char ()) != -1){
1697 number_builder [number_pos++] = (char) d;
1703 string s = new String (number_builder, 0, number_pos);
1706 if (number_pos <= 8)
1707 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1709 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1711 return integer_type_suffix (ul, peek_char (), loc);
1712 } catch (OverflowException){
1713 Error_NumericConstantTooLong ();
1714 return new IntLiteral (context.BuiltinTypes, 0, loc);
1716 catch (FormatException) {
1717 Report.Error (1013, Location, "Invalid number");
1718 return new IntLiteral (context.BuiltinTypes, 0, loc);
1723 // Invoked if we know we have .digits or digits
1725 int is_number (int c, bool dotLead)
1727 ILiteralConstant res;
1730 int read_start = reader.Position - 1;
1733 // Caller did peek_char
1743 int peek = peek_char ();
1745 if (peek == 'x' || peek == 'X') {
1746 val = res = handle_hex (loc);
1748 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1751 return Token.LITERAL;
1759 // We need to handle the case of
1760 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1762 bool is_real = false;
1767 if (decimal_digits ('.')){
1773 val = res = adjust_int (-1, loc);
1776 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1778 return Token.LITERAL;
1782 if (c == 'e' || c == 'E'){
1785 if (number_pos == MaxNumberLength)
1786 Error_NumericConstantTooLong ();
1787 number_builder [number_pos++] = (char) c;
1791 if (number_pos == MaxNumberLength)
1792 Error_NumericConstantTooLong ();
1793 number_builder [number_pos++] = '+';
1795 } else if (c == '-') {
1796 if (number_pos == MaxNumberLength)
1797 Error_NumericConstantTooLong ();
1798 number_builder [number_pos++] = '-';
1801 if (number_pos == MaxNumberLength)
1802 Error_NumericConstantTooLong ();
1803 number_builder [number_pos++] = '+';
1810 var type = real_type_suffix (c);
1811 if (type == TypeCode.Empty && !is_real) {
1812 res = adjust_int (c, loc);
1816 if (type != TypeCode.Empty) {
1820 res = adjust_real (type, loc);
1826 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1827 if (chars[chars.Length - 1] == '\r')
1828 Array.Resize (ref chars, chars.Length - 1);
1829 res.ParsedValue = chars;
1832 return Token.LITERAL;
1836 // Accepts exactly count (4 or 8) hex, no more no less
1838 int getHex (int count, out int surrogate, out bool error)
1843 int top = count != -1 ? count : 4;
1848 for (i = 0; i < top; i++){
1851 if (c >= '0' && c <= '9')
1852 c = (int) c - (int) '0';
1853 else if (c >= 'A' && c <= 'F')
1854 c = (int) c - (int) 'A' + 10;
1855 else if (c >= 'a' && c <= 'f')
1856 c = (int) c - (int) 'a' + 10;
1862 total = (total * 16) + c;
1864 int p = peek_char ();
1867 if (!is_hex ((char)p))
1873 if (total > 0x0010FFFF) {
1878 if (total >= 0x00010000) {
1879 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1880 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1887 int escape (int c, out int surrogate)
1923 v = getHex (-1, out surrogate, out error);
1929 return EscapeUnicode (d, out surrogate);
1932 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1941 int EscapeUnicode (int ch, out int surrogate)
1945 ch = getHex (8, out surrogate, out error);
1947 ch = getHex (4, out surrogate, out error);
1951 Report.Error (1009, Location, "Unrecognized escape sequence");
1959 if (putback_char != -1) {
1968 if (peek_char () == '\n') {
1974 } else if (x == '\n') {
1979 } else if (x >= UnicodeLS && x <= UnicodePS) {
1988 void advance_line ()
1998 if (putback_char == -1)
1999 putback_char = reader.Read ();
2000 return putback_char;
2005 if (putback_char != -1)
2006 return putback_char;
2007 return reader.Peek ();
2010 public void putback (int c)
2012 if (putback_char != -1) {
2013 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
2016 if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
2017 // It won't happen though.
2027 public bool advance ()
2029 return peek_char () != -1 || CompleteOnEOF;
2032 public Object Value {
2038 public Object value ()
2045 current_token = xtoken ();
2046 return current_token;
2049 int TokenizePreprocessorKeyword (out int c)
2051 // skip over white space
2054 } while (c == ' ' || c == '\t');
2058 while (c != -1 && c >= 'a' && c <= 'z') {
2059 id_builder[pos++] = (char) c;
2062 int peek = peek_char ();
2063 if (peek == 'U' || peek == 'u') {
2065 c = EscapeUnicode (c, out surrogate);
2066 if (surrogate != 0) {
2067 if (is_identifier_part_character ((char) c)) {
2068 id_builder[pos++] = (char) c;
2079 PreprocessorDirective get_cmd_arg (out string arg)
2083 tokens_seen = false;
2086 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2088 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2091 // skip over white space
2092 while (c == ' ' || c == '\t')
2095 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2098 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2099 if (c == '\\' && has_identifier_argument >= 0) {
2100 if (has_identifier_argument != 0) {
2101 has_identifier_argument = 1;
2103 int peek = peek_char ();
2104 if (peek == 'U' || peek == 'u') {
2106 c = EscapeUnicode (c, out surrogate);
2107 if (surrogate != 0) {
2108 if (is_identifier_part_character ((char) c)) {
2109 if (pos == value_builder.Length)
2110 Array.Resize (ref value_builder, pos * 2);
2112 value_builder[pos++] = (char) c;
2118 has_identifier_argument = -1;
2120 } else if (c == '/' && peek_char () == '/') {
2122 // Eat single-line comments
2129 if (pos == value_builder.Length)
2130 Array.Resize (ref value_builder, pos * 2);
2132 value_builder[pos++] = (char) c;
2137 if (pos > MaxIdentifierLength)
2138 arg = new string (value_builder, 0, pos);
2140 arg = InternIdentifier (value_builder, pos);
2142 // Eat any trailing whitespaces
2143 arg = arg.Trim (simple_whitespaces);
2150 // Handles the #line directive
2152 bool PreProcessLine ()
2154 Location loc = Location;
2158 int length = TokenizePreprocessorKeyword (out c);
2159 if (length == line_default.Length) {
2160 if (!IsTokenIdentifierEqual (line_default))
2163 current_source = source_file.SourceFile;
2164 if (!hidden_block_start.IsNull) {
2165 current_source.RegisterHiddenScope (hidden_block_start, loc);
2166 hidden_block_start = Location.Null;
2173 if (length == line_hidden.Length) {
2174 if (!IsTokenIdentifierEqual (line_hidden))
2177 if (hidden_block_start.IsNull)
2178 hidden_block_start = loc;
2183 if (length != 0 || c < '0' || c > '9') {
2185 // Eat any remaining characters to continue parsing on next line
2191 int new_line = TokenizeNumber (c);
2194 // Eat any remaining characters to continue parsing on next line
2197 return new_line != 0;
2202 // skip over white space
2205 } while (c == ' ' || c == '\t');
2206 } else if (c == '"') {
2210 if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2212 // Eat any remaining characters to continue parsing on next line
2216 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2220 string new_file_name = null;
2222 new_file_name = TokenizeFileName (ref c);
2224 // skip over white space
2225 while (c == ' ' || c == '\t') {
2230 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2232 } else if (c == '/') {
2233 ReadSingleLineComment ();
2236 // Eat any remaining characters to continue parsing on next line
2240 Error_EndLineExpected ();
2244 if (new_file_name != null) {
2245 current_source = context.LookupFile (source_file, new_file_name);
2246 source_file.AddIncludeFile (current_source);
2249 if (!hidden_block_start.IsNull) {
2250 current_source.RegisterHiddenScope (hidden_block_start, loc);
2251 hidden_block_start = Location.Null;
2254 ref_line = new_line;
2259 // Handles #define and #undef
2261 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2263 if (ident.Length == 0 || ident == "true" || ident == "false"){
2264 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2268 if (ident.IndexOfAny (simple_whitespaces) != -1){
2269 Error_EndLineExpected ();
2273 if (!is_identifier_start_character (ident [0]))
2274 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2276 foreach (char c in ident.Substring (1)){
2277 if (!is_identifier_part_character (c)){
2278 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2283 if (!caller_is_taking)
2290 if (context.Settings.IsConditionalSymbolDefined (ident))
2293 source_file.AddDefine (ident);
2298 source_file.AddUndefine (ident);
2302 byte read_hex (out bool error)
2305 int c = get_char ();
2307 if ((c >= '0') && (c <= '9'))
2308 total = (int) c - (int) '0';
2309 else if ((c >= 'A') && (c <= 'F'))
2310 total = (int) c - (int) 'A' + 10;
2311 else if ((c >= 'a') && (c <= 'f'))
2312 total = (int) c - (int) 'a' + 10;
2321 if ((c >= '0') && (c <= '9'))
2322 total += (int) c - (int) '0';
2323 else if ((c >= 'A') && (c <= 'F'))
2324 total += (int) c - (int) 'A' + 10;
2325 else if ((c >= 'a') && (c <= 'f'))
2326 total += (int) c - (int) 'a' + 10;
2333 return (byte) total;
2337 // Parses #pragma checksum
2339 bool ParsePragmaChecksum ()
2342 // The syntax is ` "foo.txt" "{guid}" "hash"'
2344 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2346 int c = get_char ();
2351 string file_name = TokenizeFileName (ref c);
2353 // TODO: Any white-spaces count
2357 SourceFile file = context.LookupFile (source_file, file_name);
2359 if (get_char () != '"' || get_char () != '{')
2363 byte[] guid_bytes = new byte [16];
2366 for (; i < 4; i++) {
2367 guid_bytes [i] = read_hex (out error);
2372 if (get_char () != '-')
2375 for (; i < 10; i++) {
2376 guid_bytes [i] = read_hex (out error);
2380 guid_bytes [i++] = read_hex (out error);
2384 if (get_char () != '-')
2388 for (; i < 16; i++) {
2389 guid_bytes [i] = read_hex (out error);
2394 if (get_char () != '}' || get_char () != '"')
2397 // TODO: Any white-spaces count
2402 if (get_char () != '"')
2405 // Any length of checksum
2406 List<byte> checksum_bytes = new List<byte> (16);
2408 var checksum_location = Location;
2410 while (c != '"' && c != -1) {
2411 checksum_bytes.Add (read_hex (out error));
2419 ReadSingleLineComment ();
2420 } else if (get_char () != '"') {
2424 if (context.Settings.GenerateDebugInfo) {
2425 var chsum = checksum_bytes.ToArray ();
2427 if (file.HasChecksum) {
2428 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2429 // TODO: Report.SymbolRelatedToPreviousError
2430 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2434 file.SetChecksum (guid_bytes, chsum);
2435 current_source.AutoGenerated = true;
2441 bool IsTokenIdentifierEqual (char[] identifier)
2443 for (int i = 0; i < identifier.Length; ++i) {
2444 if (identifier[i] != id_builder[i])
2451 bool ScanClosingInterpolationBrace ()
2458 var c = reader.Read ();
2467 if (str_quote % 2 == 1) {
2473 } while (res == null);
2479 int TokenizeNumber (int value)
2483 decimal_digits (value);
2484 uint ui = (uint) (number_builder[0] - '0');
2487 for (int i = 1; i < number_pos; i++) {
2488 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2492 } catch (OverflowException) {
2493 Error_NumericConstantTooLong ();
2498 string TokenizeFileName (ref int c)
2500 var string_builder = new StringBuilder ();
2501 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2508 string_builder.Append ((char) c);
2511 if (string_builder.Length == 0) {
2512 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2516 return string_builder.ToString ();
2519 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2522 if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2525 if (c >= '0' && c <= '9') {
2527 number = TokenizeNumber (c);
2531 if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2532 return ReadPragmaWarningComment (c);
2536 // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2540 id_builder [pos++] = (char)c;
2541 while (c < MaxIdentifierLength) {
2543 id_builder [pos] = (char)c;
2545 if (c >= '0' && c <= '9') {
2546 if (pos == 6 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2547 // Recognize CSXXXX as C# XXXX warning
2550 for (int i = 0; i < 4; ++i) {
2551 var ch = id_builder [i + 2];
2552 if (ch < '0' || ch > '9') {
2557 number += (ch - '0') * pow;
2561 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2574 // skip over white space
2575 while (c == ' ' || c == '\t')
2582 // skip over white space
2583 while (c == ' ' || c == '\t')
2589 return ReadPragmaWarningComment (c);
2592 int ReadPragmaWarningComment (int c)
2595 ReadSingleLineComment ();
2597 Report.Warning (1692, 1, Location, "Invalid number");
2599 // Read everything till the end of the line or file
2606 void ReadToEndOfLine ()
2611 } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2614 void ReadSingleLineComment ()
2616 if (peek_char () != '/')
2617 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2619 // Read everything till the end of the line or file
2624 /// Handles #pragma directive
2626 void ParsePragmaDirective ()
2629 int length = TokenizePreprocessorKeyword (out c);
2630 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2631 length = TokenizePreprocessorKeyword (out c);
2634 // #pragma warning disable
2635 // #pragma warning restore
2637 if (length == pragma_warning_disable.Length) {
2638 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2639 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2640 // skip over white space
2641 while (c == ' ' || c == '\t')
2646 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2648 ReadSingleLineComment ();
2651 // Disable/Restore all warnings
2654 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2656 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2660 // Disable/Restore a warning or group of warnings
2664 bool identifier = false;
2665 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2668 // no-op, custom warnings cannot occur in mcs
2669 } else if (disable) {
2670 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2672 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2675 } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2682 Report.Warning (1634, 1, Location, "Expected disable or restore");
2684 // Eat any remaining characters on the line
2693 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2694 if (c != ' ' || !ParsePragmaChecksum ()) {
2695 Report.Warning (1695, 1, Location,
2696 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2702 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2704 // Eat any remaining characters on the line
2708 bool eval_val (string s)
2715 return source_file.IsConditionalDefined (s);
2718 bool pp_primary (ref string s)
2727 s = s.Substring (1);
2728 bool val = pp_expr (ref s, false);
2729 if (s.Length > 0 && s [0] == ')'){
2730 s = s.Substring (1);
2733 Error_InvalidDirective ();
2737 if (is_identifier_start_character (c)){
2743 if (is_identifier_part_character (c)){
2747 bool v = eval_val (s.Substring (0, j));
2748 s = s.Substring (j);
2751 bool vv = eval_val (s);
2756 Error_InvalidDirective ();
2760 bool pp_unary (ref string s)
2767 if (len > 1 && s [1] == '='){
2768 Error_InvalidDirective ();
2771 s = s.Substring (1);
2772 return ! pp_primary (ref s);
2774 return pp_primary (ref s);
2776 Error_InvalidDirective ();
2781 bool pp_eq (ref string s)
2783 bool va = pp_unary (ref s);
2789 if (len > 2 && s [1] == '='){
2790 s = s.Substring (2);
2791 return va == pp_unary (ref s);
2793 Error_InvalidDirective ();
2796 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2797 s = s.Substring (2);
2799 return va != pp_unary (ref s);
2808 bool pp_and (ref string s)
2810 bool va = pp_eq (ref s);
2816 if (len > 2 && s [1] == '&'){
2817 s = s.Substring (2);
2818 return (va & pp_and (ref s));
2820 Error_InvalidDirective ();
2829 // Evaluates an expression for `#if' or `#elif'
2831 bool pp_expr (ref string s, bool isTerm)
2833 bool va = pp_and (ref s);
2840 if (len > 2 && s [1] == '|'){
2841 s = s.Substring (2);
2842 return va | pp_expr (ref s, isTerm);
2844 Error_InvalidDirective ();
2849 Error_EndLineExpected ();
2857 bool eval (string s)
2859 bool v = pp_expr (ref s, true);
2868 void Error_NumericConstantTooLong ()
2870 Report.Error (1021, Location, "Integral constant is too large");
2873 void Error_InvalidDirective ()
2875 Report.Error (1517, Location, "Invalid preprocessor directive");
2878 void Error_UnexpectedDirective (string extra)
2882 "Unexpected processor directive ({0})", extra);
2885 void Error_TokensSeen ()
2887 Report.Error (1032, Location,
2888 "Cannot define or undefine preprocessor symbols after first token in file");
2891 void Eror_WrongPreprocessorLocation ()
2893 Report.Error (1040, Location,
2894 "Preprocessor directives must appear as the first non-whitespace character on a line");
2897 void Error_EndLineExpected ()
2899 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2903 // Raises a warning when tokenizer found documentation comment
2904 // on unexpected place
2906 void WarningMisplacedComment (Location loc)
2908 if (doc_state != XmlCommentState.Error) {
2909 doc_state = XmlCommentState.Error;
2910 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2915 // if true, then the code continues processing the code
2916 // if false, the code stays in a loop until another directive is
2918 // When caller_is_taking is false we ignore all directives except the ones
2919 // which can help us to identify where the #if block ends
2920 bool ParsePreprocessingDirective (bool caller_is_taking)
2923 bool region_directive = false;
2925 var directive = get_cmd_arg (out arg);
2928 // The first group of pre-processing instructions is always processed
2930 switch (directive) {
2931 case PreprocessorDirective.Region:
2932 region_directive = true;
2934 goto case PreprocessorDirective.If;
2936 case PreprocessorDirective.Endregion:
2937 if (ifstack == null || ifstack.Count == 0){
2938 Error_UnexpectedDirective ("no #region for this #endregion");
2941 int pop = ifstack.Pop ();
2943 if ((pop & REGION) == 0)
2944 Report.Error (1027, Location, "Expected `#endif' directive");
2946 return caller_is_taking;
2948 case PreprocessorDirective.If:
2949 if (ifstack == null)
2950 ifstack = new Stack<int> (2);
2952 int flags = region_directive ? REGION : 0;
2953 if (ifstack.Count == 0){
2954 flags |= PARENT_TAKING;
2956 int state = ifstack.Peek ();
2957 if ((state & TAKING) != 0) {
2958 flags |= PARENT_TAKING;
2962 if (eval (arg) && caller_is_taking) {
2963 ifstack.Push (flags | TAKING);
2966 ifstack.Push (flags);
2969 case PreprocessorDirective.Endif:
2970 if (ifstack == null || ifstack.Count == 0){
2971 Error_UnexpectedDirective ("no #if for this #endif");
2974 pop = ifstack.Pop ();
2976 if ((pop & REGION) != 0)
2977 Report.Error (1038, Location, "#endregion directive expected");
2979 if (arg.Length != 0) {
2980 Error_EndLineExpected ();
2983 if (ifstack.Count == 0)
2986 int state = ifstack.Peek ();
2987 return (state & TAKING) != 0;
2990 case PreprocessorDirective.Elif:
2991 if (ifstack == null || ifstack.Count == 0){
2992 Error_UnexpectedDirective ("no #if for this #elif");
2995 int state = ifstack.Pop ();
2997 if ((state & REGION) != 0) {
2998 Report.Error (1038, Location, "#endregion directive expected");
3002 if ((state & ELSE_SEEN) != 0){
3003 Error_UnexpectedDirective ("#elif not valid after #else");
3007 if ((state & TAKING) != 0) {
3012 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
3013 ifstack.Push (state | TAKING);
3017 ifstack.Push (state);
3021 case PreprocessorDirective.Else:
3022 if (ifstack == null || ifstack.Count == 0){
3023 Error_UnexpectedDirective ("no #if for this #else");
3026 int state = ifstack.Peek ();
3028 if ((state & REGION) != 0) {
3029 Report.Error (1038, Location, "#endregion directive expected");
3033 if ((state & ELSE_SEEN) != 0){
3034 Error_UnexpectedDirective ("#else within #else");
3040 if (arg.Length != 0) {
3041 Error_EndLineExpected ();
3046 if ((state & PARENT_TAKING) != 0) {
3047 ret = (state & TAKING) == 0;
3055 ifstack.Push (state | ELSE_SEEN);
3059 case PreprocessorDirective.Define:
3060 if (any_token_seen){
3061 if (caller_is_taking)
3062 Error_TokensSeen ();
3063 return caller_is_taking;
3065 PreProcessDefinition (true, arg, caller_is_taking);
3066 return caller_is_taking;
3068 case PreprocessorDirective.Undef:
3069 if (any_token_seen){
3070 if (caller_is_taking)
3071 Error_TokensSeen ();
3072 return caller_is_taking;
3074 PreProcessDefinition (false, arg, caller_is_taking);
3075 return caller_is_taking;
3077 case PreprocessorDirective.Invalid:
3078 Report.Error (1024, Location, "Wrong preprocessor directive");
3083 // These are only processed if we are in a `taking' block
3085 if (!caller_is_taking)
3089 case PreprocessorDirective.Error:
3090 Report.Error (1029, Location, "#error: '{0}'", arg);
3093 case PreprocessorDirective.Warning:
3094 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3097 case PreprocessorDirective.Pragma:
3098 if (context.Settings.Version == LanguageVersion.ISO_1) {
3099 Report.FeatureIsNotAvailable (context, Location, "#pragma");
3102 ParsePragmaDirective ();
3105 case PreprocessorDirective.Line:
3106 Location loc = Location;
3107 if (!PreProcessLine ())
3108 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3110 return caller_is_taking;
3113 throw new NotImplementedException (directive.ToString ());
3116 int consume_string (bool quoted)
3120 Location start_location = Location;
3122 start_location = start_location - 1;
3125 int reader_pos = reader.Position;
3129 // Cannot use get_char because of \r in quoted strings
3130 if (putback_char != -1) {
3140 if (quoted && peek_char () == '"') {
3141 if (pos == value_builder.Length)
3142 Array.Resize (ref value_builder, pos * 2);
3144 value_builder[pos++] = (char) c;
3149 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3152 res.ParsedValue = quoted ?
3153 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3154 reader.ReadChars (reader_pos - 1, reader.Position);
3157 return Token.LITERAL;
3160 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3162 Report.Error (1010, Location, "Newline in constant");
3166 // Don't add \r to string literal
3167 if (pos > 1 && value_builder [pos - 1] == '\r')
3170 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3171 return Token.LITERAL;
3175 } else if (c == '\\' && !quoted) {
3178 c = escape (c, out surrogate);
3181 if (surrogate != 0) {
3182 if (pos == value_builder.Length)
3183 Array.Resize (ref value_builder, pos * 2);
3185 value_builder[pos++] = (char) c;
3188 } else if (c == -1) {
3189 Report.Error (1039, Location, "Unterminated string literal");
3195 if (pos == value_builder.Length)
3196 Array.Resize (ref value_builder, pos * 2);
3198 value_builder[pos++] = (char) c;
3202 private int consume_identifier (int s)
3204 int res = consume_identifier (s, false);
3206 if (doc_state == XmlCommentState.Allowed)
3207 doc_state = XmlCommentState.NotAllowed;
3212 int consume_identifier (int c, bool quoted)
3215 // This method is very performance sensitive. It accounts
3216 // for approximately 25% of all parser time
3226 c = escape (c, out surrogate);
3227 if (quoted || is_identifier_start_character (c)) {
3228 // it's added bellow
3229 } else if (surrogate != 0) {
3230 id_builder [pos++] = (char)c;
3233 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3238 id_builder [pos++] = (char) c;
3244 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3245 id_builder [pos++] = (char) c;
3252 c = escape (c, out surrogate);
3253 if (is_identifier_part_character ((char) c))
3254 id_builder[pos++] = (char) c;
3255 else if (surrogate != 0) {
3259 // TODO: Probably need more whitespace characters
3264 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3271 } else if (is_identifier_part_character_slow_part ((char) c)) {
3272 id_builder [pos++] = (char) c;
3279 } catch (IndexOutOfRangeException) {
3280 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3288 // Optimization: avoids doing the keyword lookup
3289 // on uppercase letters
3291 if (id_builder [0] >= '_' && !quoted) {
3292 int keyword = GetKeyword (id_builder, pos);
3293 if (keyword != -1) {
3294 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3299 string s = InternIdentifier (id_builder, pos);
3300 val = ltb.Create (s, current_source, ref_line, column);
3301 if (quoted && parsing_attribute_section)
3302 AddEscapedIdentifier (((LocatedToken) val).Location);
3304 return Token.IDENTIFIER;
3307 string InternIdentifier (char[] charBuffer, int length)
3310 // Keep identifiers in an array of hashtables to avoid needless
3313 var identifiers_group = identifiers[length];
3315 if (identifiers_group != null) {
3316 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3320 // TODO: this should be number of files dependant
3321 // corlib compilation peaks at 1000 and System.Core at 150
3322 int capacity = length > 20 ? 10 : 100;
3323 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3324 identifiers[length] = identifiers_group;
3327 char[] chars = new char[length];
3328 Array.Copy (charBuffer, chars, length);
3330 s = new string (charBuffer, 0, length);
3331 identifiers_group.Add (chars, s);
3335 public int xtoken ()
3337 if (parsing_interpolation_format) {
3338 return TokenizeInterpolationFormat ();
3343 // Whether we have seen comments on the current line
3344 bool comments_seen = false;
3345 while ((c = get_char ()) != -1) {
3348 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3356 case 0xFEFF: // Ignore BOM anywhere in the file
3359 /* This is required for compatibility with .NET
3361 if (peek_char () == 0xBB) {
3364 if (get_char () == 0xBF)
3372 return consume_identifier (c);
3375 val = ltb.Create (current_source, ref_line, col);
3376 return Token.OPEN_BRACE;
3378 if (parsing_string_interpolation > 0) {
3379 --parsing_string_interpolation;
3381 if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Count > 0) {
3382 quoted = parsing_string_interpolation_quoted.Pop ();
3387 return TokenizeInterpolatedString (quoted);
3390 val = ltb.Create (current_source, ref_line, col);
3391 return Token.CLOSE_BRACE;
3393 // To block doccomment inside attribute declaration.
3394 if (doc_state == XmlCommentState.Allowed)
3395 doc_state = XmlCommentState.NotAllowed;
3397 val = ltb.Create (current_source, ref_line, col);
3399 if (parsing_block == 0 || lambda_arguments_parsing)
3400 return Token.OPEN_BRACKET;
3402 int next = peek_char ();
3406 return Token.OPEN_BRACKET;
3416 next = peek_token ();
3417 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3418 return Token.OPEN_BRACKET;
3420 return Token.OPEN_BRACKET_EXPR;
3422 return Token.OPEN_BRACKET_EXPR;
3425 ltb.CreateOptional (current_source, ref_line, col, ref val);
3426 return Token.CLOSE_BRACKET;
3428 val = ltb.Create (current_source, ref_line, col);
3430 // An expression versions of parens can appear in block context only
3432 if (parsing_block != 0 && !lambda_arguments_parsing) {
3435 // Optmize most common case where we know that parens
3438 switch (current_token) {
3439 case Token.IDENTIFIER:
3448 case Token.DELEGATE:
3449 case Token.OP_GENERICS_GT:
3450 return Token.OPEN_PARENS;
3453 // Optimize using peek
3454 int xx = peek_char ();
3461 return Token.OPEN_PARENS;
3464 lambda_arguments_parsing = true;
3466 d = TokenizeOpenParens ();
3468 lambda_arguments_parsing = false;
3472 return Token.OPEN_PARENS;
3474 ltb.CreateOptional (current_source, ref_line, col, ref val);
3475 return Token.CLOSE_PARENS;
3477 ltb.CreateOptional (current_source, ref_line, col, ref val);
3480 ltb.CreateOptional (current_source, ref_line, col, ref val);
3481 return Token.SEMICOLON;
3483 val = ltb.Create (current_source, ref_line, col);
3486 val = ltb.Create (current_source, ref_line, col);
3487 return TokenizePossibleNullableType ();
3489 val = ltb.Create (current_source, ref_line, col);
3490 if (parsing_generic_less_than++ > 0)
3491 return Token.OP_GENERICS_LT;
3493 return TokenizeLessThan ();
3496 val = ltb.Create (current_source, ref_line, col);
3504 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3505 parsing_generic_less_than--;
3506 return Token.OP_GENERICS_GT;
3515 return Token.OP_SHIFT_RIGHT_ASSIGN;
3517 return Token.OP_SHIFT_RIGHT;
3523 val = ltb.Create (current_source, ref_line, col);
3527 } else if (d == '=') {
3528 d = Token.OP_ADD_ASSIGN;
3536 val = ltb.Create (current_source, ref_line, col);
3540 } else if (d == '=')
3541 d = Token.OP_SUB_ASSIGN;
3551 val = ltb.Create (current_source, ref_line, col);
3552 if (peek_char () == '='){
3559 val = ltb.Create (current_source, ref_line, col);
3570 return Token.ASSIGN;
3573 val = ltb.Create (current_source, ref_line, col);
3577 return Token.OP_AND;
3581 return Token.OP_AND_ASSIGN;
3583 return Token.BITWISE_AND;
3586 val = ltb.Create (current_source, ref_line, col);
3594 return Token.OP_OR_ASSIGN;
3596 return Token.BITWISE_OR;
3599 val = ltb.Create (current_source, ref_line, col);
3600 if (peek_char () == '='){
3602 return Token.OP_MULT_ASSIGN;
3609 val = ltb.Create (current_source, ref_line, col);
3611 return Token.OP_DIV_ASSIGN;
3614 // Handle double-slash comments.
3616 if (parsing_string_interpolation > 0) {
3617 Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3622 if (doc_processing) {
3623 if (peek_char () == '/') {
3625 // Don't allow ////.
3626 if ((d = peek_char ()) != '/') {
3627 if (doc_state == XmlCommentState.Allowed)
3628 handle_one_line_xml_comment ();
3629 else if (doc_state == XmlCommentState.NotAllowed)
3630 WarningMisplacedComment (Location - 3);
3633 if (xml_comment_buffer.Length > 0)
3634 doc_state = XmlCommentState.NotAllowed;
3640 any_token_seen |= tokens_seen;
3641 tokens_seen = false;
3642 comments_seen = false;
3644 } else if (d == '*'){
3646 bool docAppend = false;
3647 if (doc_processing && peek_char () == '*') {
3649 // But when it is /**/, just do nothing.
3650 if (peek_char () == '/') {
3654 if (doc_state == XmlCommentState.Allowed)
3656 else if (doc_state == XmlCommentState.NotAllowed) {
3657 WarningMisplacedComment (Location - 2);
3661 int current_comment_start = 0;
3663 current_comment_start = xml_comment_buffer.Length;
3664 xml_comment_buffer.Append (Environment.NewLine);
3667 while ((d = get_char ()) != -1){
3668 if (d == '*' && peek_char () == '/'){
3670 comments_seen = true;
3674 xml_comment_buffer.Append ((char) d);
3676 if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3677 any_token_seen |= tokens_seen;
3678 tokens_seen = false;
3680 // Reset 'comments_seen' just to be consistent.
3681 // It doesn't matter either way, here.
3683 comments_seen = false;
3687 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3690 update_formatted_doc_comment (current_comment_start);
3693 val = ltb.Create (current_source, ref_line, col);
3697 val = ltb.Create (current_source, ref_line, col);
3698 if (peek_char () == '='){
3700 return Token.OP_MOD_ASSIGN;
3702 return Token.PERCENT;
3705 val = ltb.Create (current_source, ref_line, col);
3706 if (peek_char () == '='){
3708 return Token.OP_XOR_ASSIGN;
3710 return Token.CARRET;
3713 val = ltb.Create (current_source, ref_line, col);
3714 if (peek_char () == ':') {
3716 return Token.DOUBLE_COLON;
3720 case '0': case '1': case '2': case '3': case '4':
3721 case '5': case '6': case '7': case '8': case '9':
3723 return is_number (c, false);
3725 case '\n': // white space
3728 any_token_seen |= tokens_seen;
3729 tokens_seen = false;
3730 comments_seen = false;
3736 if (d >= '0' && d <= '9')
3737 return is_number (c, true);
3739 ltb.CreateOptional (current_source, ref_line, col, ref val);
3743 if (tokens_seen || comments_seen) {
3744 Eror_WrongPreprocessorLocation ();
3748 if (ParsePreprocessingDirective (true))
3751 bool directive_expected = false;
3752 while ((c = get_char ()) != -1) {
3754 directive_expected = true;
3755 } else if (!directive_expected) {
3756 // TODO: Implement comment support for disabled code and uncomment this code
3758 // Eror_WrongPreprocessorLocation ();
3759 // return Token.ERROR;
3764 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3768 if (ParsePreprocessingDirective (false))
3771 directive_expected = false;
3775 tokens_seen = false;
3782 if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3783 parsing_string_interpolation = 0;
3784 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3785 val = new StringLiteral (context.BuiltinTypes, "", Location);
3786 return Token.INTERPOLATED_STRING_END;
3789 return consume_string (false);
3792 return TokenizeBackslash ();
3798 return consume_string (true);
3801 if (is_identifier_start_character (c)){
3802 return consume_identifier (c, true);
3805 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3809 switch (peek_char ()) {
3812 return TokenizeInterpolatedString (false);
3815 if (peek_char () == '"') {
3817 return TokenizeInterpolatedString (true);
3824 case EvalStatementParserCharacter:
3825 return Token.EVAL_STATEMENT_PARSER;
3826 case EvalCompilationUnitParserCharacter:
3827 return Token.EVAL_COMPILATION_UNIT_PARSER;
3828 case EvalUsingDeclarationsParserCharacter:
3829 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3830 case DocumentationXref:
3831 return Token.DOC_SEE;
3834 if (is_identifier_start_character (c)) {
3836 return consume_identifier (c);
3839 if (char.IsWhiteSpace ((char) c))
3842 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3847 return Token.COMPLETE_COMPLETION;
3850 return Token.GENERATE_COMPLETION;
3857 int TokenizeBackslash ()
3860 int read_start = reader.Position;
3862 Location start_location = Location;
3863 int c = get_char ();
3866 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3867 Report.Error (1011, start_location, "Empty character literal");
3868 return Token.LITERAL;
3871 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3872 Report.Error (1010, start_location, "Newline in constant");
3877 c = escape (c, out d);
3881 throw new NotImplementedException ();
3883 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3888 Report.Error (1012, start_location, "Too many characters in character literal");
3890 // Try to recover, read until newline or next "'"
3891 while ((c = get_char ()) != -1) {
3892 if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3898 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3901 return Token.LITERAL;
3904 int TokenizeLessThan ()
3908 // Save current position and parse next token.
3910 int generic_dimension = 0;
3911 if (parse_less_than (ref generic_dimension)) {
3912 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3913 d = Token.OP_GENERICS_LT_DECL;
3915 if (generic_dimension > 0) {
3916 val = generic_dimension;
3918 return Token.GENERIC_DIMENSION;
3921 d = Token.OP_GENERICS_LT;
3928 parsing_generic_less_than = 0;
3937 return Token.OP_SHIFT_LEFT_ASSIGN;
3939 return Token.OP_SHIFT_LEFT;
3949 int TokenizeInterpolatedString (bool quoted)
3952 var start_location = Location;
3955 var ch = get_char ();
3958 if (quoted && peek_char () == '"') {
3963 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3964 return Token.INTERPOLATED_STRING_END;
3966 if (peek_char () == '{') {
3967 value_builder [pos++] = (char)ch;
3972 ++parsing_string_interpolation;
3974 if (parsing_string_interpolation_quoted == null)
3975 parsing_string_interpolation_quoted = new Stack<bool> ();
3978 if (parsing_string_interpolation_quoted != null) {
3979 parsing_string_interpolation_quoted.Push (quoted);
3982 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3983 return Token.INTERPOLATED_STRING;
3990 ch = escape (ch, out surrogate);
3994 if (ch == '{' || ch == '}') {
3995 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
3998 if (surrogate != 0) {
3999 if (pos == value_builder.Length)
4000 Array.Resize (ref value_builder, pos * 2);
4002 if (pos == value_builder.Length)
4003 Array.Resize (ref value_builder, pos * 2);
4005 value_builder [pos++] = (char)ch;
4015 if (pos == value_builder.Length)
4016 Array.Resize (ref value_builder, pos * 2);
4018 value_builder[pos++] = (char) ch;
4022 int TokenizeInterpolationFormat ()
4027 var ch = get_char ();
4036 Report.Error (8089, Location, "Empty interpolated expression format specifier");
4037 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
4038 Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
4041 val = CreateStringFromBuilder (pos);
4042 return Token.LITERAL;
4050 ch = escape (ch, out surrogate);
4054 if (ch == '{' || ch == '}') {
4055 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4058 if (surrogate != 0) {
4059 if (pos == value_builder.Length)
4060 Array.Resize (ref value_builder, pos * 2);
4062 value_builder [pos++] = (char)ch;
4072 value_builder[pos++] = (char) ch;
4076 string CreateStringFromBuilder (int pos)
4079 return string.Empty;
4081 return InternIdentifier (value_builder, pos);
4083 return new string (value_builder, 0, pos);
4087 // Handles one line xml comment
4089 private void handle_one_line_xml_comment ()
4092 while ((c = peek_char ()) == ' ')
4093 get_char (); // skip heading whitespaces.
4094 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4095 xml_comment_buffer.Append ((char) get_char ());
4097 if (c == '\r' || c == '\n')
4098 xml_comment_buffer.Append (Environment.NewLine);
4102 // Remove heading "*" in Javadoc-like xml documentation.
4104 private void update_formatted_doc_comment (int current_comment_start)
4106 int length = xml_comment_buffer.Length - current_comment_start;
4107 string [] lines = xml_comment_buffer.ToString (
4108 current_comment_start,
4109 length).Replace ("\r", "").Split ('\n');
4111 // The first line starts with /**, thus it is not target
4112 // for the format check.
4113 for (int i = 1; i < lines.Length; i++) {
4114 string s = lines [i];
4115 int idx = s.IndexOf ('*');
4118 if (i < lines.Length - 1)
4122 head = s.Substring (0, idx);
4123 foreach (char c in head)
4126 lines [i] = s.Substring (idx + 1);
4128 xml_comment_buffer.Remove (current_comment_start, length);
4129 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4133 // Checks if there was incorrect doc comments and raise
4136 public void check_incorrect_doc_comment ()
4138 if (xml_comment_buffer.Length > 0)
4139 WarningMisplacedComment (Location);
4143 // Consumes the saved xml comment lines (if any)
4144 // as for current target member or type.
4146 public string consume_doc_comment ()
4148 if (xml_comment_buffer.Length > 0) {
4149 string ret = xml_comment_buffer.ToString ();
4150 reset_doc_comment ();
4156 void reset_doc_comment ()
4158 xml_comment_buffer.Length = 0;
4161 public void cleanup ()
4163 if (ifstack != null && ifstack.Count >= 1) {
4164 int state = ifstack.Pop ();
4165 if ((state & REGION) != 0)
4166 Report.Error (1038, Location, "#endregion directive expected");
4168 Report.Error (1027, Location, "Expected `#endif' directive");
4174 // Indicates whether it accepts XML documentation or not.
4176 public enum XmlCommentState {
4177 // comment is allowed in this state.
4179 // comment is not allowed in this state.
4181 // once comments appeared when it is NotAllowed, then the
4182 // state is changed to it, until the state is changed to