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;
244 public bool parsing_interpolation_format;
247 // The special characters to inject on streams to run the unit parser
248 // in the special expression mode. Using private characters from
249 // Plane Sixteen (U+100000 to U+10FFFD)
251 // This character is only tested just before the tokenizer is about to report
252 // an error; So on the regular operation mode, this addition will have no
253 // impact on the tokenizer's performance.
256 public const int EvalStatementParserCharacter = 0x100000;
257 public const int EvalCompilationUnitParserCharacter = 0x100001;
258 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
259 public const int DocumentationXref = 0x100003;
261 const int UnicodeLS = 0x2028;
262 const int UnicodePS = 0x2029;
265 // XML documentation buffer. The save point is used to divide
266 // comments on types and comments on members.
268 StringBuilder xml_comment_buffer;
271 // See comment on XmlCommentState enumeration.
273 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
276 // Whether tokens have been seen on this line
278 bool tokens_seen = false;
281 // Set to true once the GENERATE_COMPLETION token has bee
282 // returned. This helps produce one GENERATE_COMPLETION,
283 // as many COMPLETE_COMPLETION as necessary to complete the
284 // AST tree and one final EOF.
289 // Whether a token has been seen on the file
290 // This is needed because `define' is not allowed to be used
291 // after a token has been seen.
298 static readonly KeywordEntry<int>[][] keywords;
299 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
300 static readonly HashSet<string> keyword_strings;
301 static readonly NumberStyles styles;
302 static readonly NumberFormatInfo csharp_format_info;
305 static readonly char[] pragma_warning = "warning".ToCharArray ();
306 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
307 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
308 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
309 static readonly char[] line_hidden = "hidden".ToCharArray ();
310 static readonly char[] line_default = "default".ToCharArray ();
312 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
314 public bool PropertyParsing {
315 get { return handle_get_set; }
316 set { handle_get_set = value; }
319 public bool EventParsing {
320 get { return handle_remove_add; }
321 set { handle_remove_add = value; }
324 public bool ConstraintsParsing {
325 get { return handle_where; }
326 set { handle_where = value; }
329 public XmlCommentState doc_state {
330 get { return xml_doc_state; }
332 if (value == XmlCommentState.Allowed) {
333 check_incorrect_doc_comment ();
334 reset_doc_comment ();
336 xml_doc_state = value;
341 // This is used to trigger completion generation on the parser
342 public bool CompleteOnEOF;
344 void AddEscapedIdentifier (Location loc)
346 if (escaped_identifiers == null)
347 escaped_identifiers = new List<Location> ();
349 escaped_identifiers.Add (loc);
352 public bool IsEscapedIdentifier (ATypeNameExpression name)
354 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
358 // Values for the associated token returned
360 internal int putback_char; // Used by repl only
366 const int TAKING = 1;
367 const int ELSE_SEEN = 4;
368 const int PARENT_TAKING = 8;
369 const int REGION = 16;
372 // pre-processor if stack state:
376 public const int MaxIdentifierLength = 512;
377 public const int MaxNumberLength = 512;
379 readonly char[] id_builder;
380 readonly Dictionary<char[], string>[] identifiers;
381 readonly char[] number_builder;
384 char[] value_builder = new char[64];
393 // This is used when the tokenizer needs to save
394 // the current position as it needs to do some parsing
395 // on its own to deamiguate a token in behalf of the
398 Stack<Position> position_stack = new Stack<Position> (2);
405 public Location hidden;
406 public int putback_char;
407 public int previous_col;
408 public Stack<int> ifstack;
409 public int parsing_generic_less_than;
410 public int current_token;
412 public int parsing_string_interpolation;
414 public Position (Tokenizer t)
416 position = t.reader.Position;
418 ref_line = t.ref_line;
420 hidden = t.hidden_block_start;
421 putback_char = t.putback_char;
422 previous_col = t.previous_col;
423 if (t.ifstack != null && t.ifstack.Count != 0) {
424 // There is no simple way to clone Stack<T> all
425 // methods reverse the order
426 var clone = t.ifstack.ToArray ();
427 Array.Reverse (clone);
428 ifstack = new Stack<int> (clone);
430 parsing_generic_less_than = t.parsing_generic_less_than;
431 parsing_string_interpolation = t.parsing_string_interpolation;
432 current_token = t.current_token;
437 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session, Report report)
439 this.source_file = file;
440 this.context = file.Compiler;
441 this.current_source = file.SourceFile;
442 this.identifiers = session.Identifiers;
443 this.id_builder = session.IDBuilder;
444 this.number_builder = session.NumberBuilder;
445 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
446 this.Report = report;
452 xml_comment_buffer = new StringBuilder ();
453 doc_processing = context.Settings.DocumentationFile != null;
455 tab_size = context.Settings.TabSize;
458 public void PushPosition ()
460 position_stack.Push (new Position (this));
463 public void PopPosition ()
465 Position p = position_stack.Pop ();
467 reader.Position = p.position;
468 ref_line = p.ref_line;
471 hidden_block_start = p.hidden;
472 putback_char = p.putback_char;
473 previous_col = p.previous_col;
475 parsing_generic_less_than = p.parsing_generic_less_than;
476 parsing_string_interpolation = p.parsing_string_interpolation;
477 current_token = p.current_token;
481 // Do not reset the position, ignore it.
482 public void DiscardPosition ()
484 position_stack.Pop ();
487 static void AddKeyword (string kw, int token)
489 keyword_strings.Add (kw);
491 AddKeyword (keywords, kw, token);
494 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
496 AddKeyword (keywords_preprocessor, kw, directive);
499 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
501 int length = kw.Length;
502 if (keywords[length] == null) {
503 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
506 int char_index = kw[0] - '_';
507 var kwe = keywords[length][char_index];
509 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
513 while (kwe.Next != null) {
517 kwe.Next = new KeywordEntry<T> (kw, token);
525 keyword_strings = new HashSet<string> ();
527 // 11 is the length of the longest keyword for now
528 keywords = new KeywordEntry<int>[11][];
530 AddKeyword ("__arglist", Token.ARGLIST);
531 AddKeyword ("__makeref", Token.MAKEREF);
532 AddKeyword ("__reftype", Token.REFTYPE);
533 AddKeyword ("__refvalue", Token.REFVALUE);
534 AddKeyword ("abstract", Token.ABSTRACT);
535 AddKeyword ("as", Token.AS);
536 AddKeyword ("add", Token.ADD);
537 AddKeyword ("base", Token.BASE);
538 AddKeyword ("bool", Token.BOOL);
539 AddKeyword ("break", Token.BREAK);
540 AddKeyword ("byte", Token.BYTE);
541 AddKeyword ("case", Token.CASE);
542 AddKeyword ("catch", Token.CATCH);
543 AddKeyword ("char", Token.CHAR);
544 AddKeyword ("checked", Token.CHECKED);
545 AddKeyword ("class", Token.CLASS);
546 AddKeyword ("const", Token.CONST);
547 AddKeyword ("continue", Token.CONTINUE);
548 AddKeyword ("decimal", Token.DECIMAL);
549 AddKeyword ("default", Token.DEFAULT);
550 AddKeyword ("delegate", Token.DELEGATE);
551 AddKeyword ("do", Token.DO);
552 AddKeyword ("double", Token.DOUBLE);
553 AddKeyword ("else", Token.ELSE);
554 AddKeyword ("enum", Token.ENUM);
555 AddKeyword ("event", Token.EVENT);
556 AddKeyword ("explicit", Token.EXPLICIT);
557 AddKeyword ("extern", Token.EXTERN);
558 AddKeyword ("false", Token.FALSE);
559 AddKeyword ("finally", Token.FINALLY);
560 AddKeyword ("fixed", Token.FIXED);
561 AddKeyword ("float", Token.FLOAT);
562 AddKeyword ("for", Token.FOR);
563 AddKeyword ("foreach", Token.FOREACH);
564 AddKeyword ("goto", Token.GOTO);
565 AddKeyword ("get", Token.GET);
566 AddKeyword ("if", Token.IF);
567 AddKeyword ("implicit", Token.IMPLICIT);
568 AddKeyword ("in", Token.IN);
569 AddKeyword ("int", Token.INT);
570 AddKeyword ("interface", Token.INTERFACE);
571 AddKeyword ("internal", Token.INTERNAL);
572 AddKeyword ("is", Token.IS);
573 AddKeyword ("lock", Token.LOCK);
574 AddKeyword ("long", Token.LONG);
575 AddKeyword ("namespace", Token.NAMESPACE);
576 AddKeyword ("new", Token.NEW);
577 AddKeyword ("null", Token.NULL);
578 AddKeyword ("object", Token.OBJECT);
579 AddKeyword ("operator", Token.OPERATOR);
580 AddKeyword ("out", Token.OUT);
581 AddKeyword ("override", Token.OVERRIDE);
582 AddKeyword ("params", Token.PARAMS);
583 AddKeyword ("private", Token.PRIVATE);
584 AddKeyword ("protected", Token.PROTECTED);
585 AddKeyword ("public", Token.PUBLIC);
586 AddKeyword ("readonly", Token.READONLY);
587 AddKeyword ("ref", Token.REF);
588 AddKeyword ("remove", Token.REMOVE);
589 AddKeyword ("return", Token.RETURN);
590 AddKeyword ("sbyte", Token.SBYTE);
591 AddKeyword ("sealed", Token.SEALED);
592 AddKeyword ("set", Token.SET);
593 AddKeyword ("short", Token.SHORT);
594 AddKeyword ("sizeof", Token.SIZEOF);
595 AddKeyword ("stackalloc", Token.STACKALLOC);
596 AddKeyword ("static", Token.STATIC);
597 AddKeyword ("string", Token.STRING);
598 AddKeyword ("struct", Token.STRUCT);
599 AddKeyword ("switch", Token.SWITCH);
600 AddKeyword ("this", Token.THIS);
601 AddKeyword ("throw", Token.THROW);
602 AddKeyword ("true", Token.TRUE);
603 AddKeyword ("try", Token.TRY);
604 AddKeyword ("typeof", Token.TYPEOF);
605 AddKeyword ("uint", Token.UINT);
606 AddKeyword ("ulong", Token.ULONG);
607 AddKeyword ("unchecked", Token.UNCHECKED);
608 AddKeyword ("unsafe", Token.UNSAFE);
609 AddKeyword ("ushort", Token.USHORT);
610 AddKeyword ("using", Token.USING);
611 AddKeyword ("virtual", Token.VIRTUAL);
612 AddKeyword ("void", Token.VOID);
613 AddKeyword ("volatile", Token.VOLATILE);
614 AddKeyword ("while", Token.WHILE);
615 AddKeyword ("partial", Token.PARTIAL);
616 AddKeyword ("where", Token.WHERE);
619 AddKeyword ("from", Token.FROM);
620 AddKeyword ("join", Token.JOIN);
621 AddKeyword ("on", Token.ON);
622 AddKeyword ("equals", Token.EQUALS);
623 AddKeyword ("select", Token.SELECT);
624 AddKeyword ("group", Token.GROUP);
625 AddKeyword ("by", Token.BY);
626 AddKeyword ("let", Token.LET);
627 AddKeyword ("orderby", Token.ORDERBY);
628 AddKeyword ("ascending", Token.ASCENDING);
629 AddKeyword ("descending", Token.DESCENDING);
630 AddKeyword ("into", Token.INTO);
632 // Contextual async keywords
633 AddKeyword ("async", Token.ASYNC);
634 AddKeyword ("await", Token.AWAIT);
636 // Contextual filter catch keyword
637 AddKeyword ("when", Token.WHEN);
639 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
641 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
642 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
643 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
644 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
645 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
646 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
647 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
648 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
649 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
650 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
651 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
652 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
654 csharp_format_info = NumberFormatInfo.InvariantInfo;
655 styles = NumberStyles.Float;
658 int GetKeyword (char[] id, int id_len)
661 // Keywords are stored in an array of arrays grouped by their
662 // length and then by the first character
664 if (id_len >= keywords.Length || keywords [id_len] == null)
667 int first_index = id [0] - '_';
668 if (first_index > 'z' - '_')
671 var kwe = keywords [id_len] [first_index];
678 for (int i = 1; i < id_len; ++i) {
679 if (id [i] != kwe.Value [i]) {
685 } while (res == 0 && kwe != null);
699 if (!handle_remove_add)
703 if (parsing_declaration == 0)
704 res = Token.EXTERN_ALIAS;
707 if (peek_token () == Token.COLON) {
709 res = Token.DEFAULT_COLON;
713 if (current_token != Token.CATCH && !parsing_catch_when)
717 if (!(handle_where && current_token != Token.COLON) && !query_parsing)
722 // A query expression is any expression that starts with `from identifier'
723 // followed by any token except ; , =
725 if (!query_parsing) {
726 if (lambda_arguments_parsing || parsing_block == 0) {
732 // HACK: to disable generics micro-parser, because PushPosition does not
733 // store identifiers array
734 parsing_generic_less_than = 1;
736 case Token.IDENTIFIER:
749 next_token = xtoken ();
750 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
753 res = Token.FROM_FIRST;
754 query_parsing = true;
755 if (context.Settings.Version <= LanguageVersion.ISO_2)
756 Report.FeatureIsNotAvailable (context, Location, "query expressions");
759 Expression.Error_VoidInvalidInTheContext (Location, Report);
763 // HACK: A token is not a keyword so we need to restore identifiers buffer
764 // which has been overwritten before we grabbed the identifier
765 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
779 case Token.ASCENDING:
780 case Token.DESCENDING:
787 case Token.NAMESPACE:
788 // TODO: some explanation needed
789 check_incorrect_doc_comment ();
790 parsing_modifiers = false;
794 if (parsing_block > 0) {
799 // Save current position and parse next token.
802 next_token = token ();
803 bool ok = (next_token == Token.CLASS) ||
804 (next_token == Token.STRUCT) ||
805 (next_token == Token.INTERFACE) ||
806 (next_token == Token.VOID);
811 if (next_token == Token.VOID) {
812 if (context.Settings.Version <= LanguageVersion.ISO_2)
813 Report.FeatureIsNotAvailable (context, Location, "partial methods");
814 } else if (context.Settings.Version == LanguageVersion.ISO_1)
815 Report.FeatureIsNotAvailable (context, Location, "partial types");
820 if (next_token < Token.LAST_KEYWORD) {
821 Report.Error (267, Location,
822 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
826 // HACK: A token is not a keyword so we need to restore identifiers buffer
827 // which has been overwritten before we grabbed the identifier
839 if (parsing_modifiers) {
841 // Skip attributes section or constructor called async
843 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
848 } else if (parsing_block > 0) {
849 switch (peek_token ()) {
851 case Token.OPEN_PARENS_LAMBDA:
854 case Token.IDENTIFIER:
857 if (xtoken () != Token.ARROW) {
865 // peek_token could overwrite id_buffer
866 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
874 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
875 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
881 if (parsing_block == 0)
891 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
894 // Keywords are stored in an array of arrays grouped by their
895 // length and then by the first character
897 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
898 return PreprocessorDirective.Invalid;
900 int first_index = id[0] - '_';
901 if (first_index > 'z' - '_')
902 return PreprocessorDirective.Invalid;
904 var kwe = keywords_preprocessor[id_len][first_index];
906 return PreprocessorDirective.Invalid;
908 PreprocessorDirective res = PreprocessorDirective.Invalid;
911 for (int i = 1; i < id_len; ++i) {
912 if (id[i] != kwe.Value[i]) {
918 } while (res == PreprocessorDirective.Invalid && kwe != null);
923 public Location Location {
925 return new Location (current_source, ref_line, col);
929 static bool is_identifier_start_character (int c)
931 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')
937 return is_identifier_start_character_slow_part ((char) c);
940 static bool is_identifier_part_character (char c)
942 if (c >= 'a' && c <= 'z')
945 if (c >= 'A' && c <= 'Z')
948 if (c == '_' || (c >= '0' && c <= '9'))
954 return is_identifier_part_character_slow_part (c);
957 static bool is_identifier_start_character_slow_part (char c)
959 switch (Char.GetUnicodeCategory (c)) {
960 case UnicodeCategory.LetterNumber:
961 case UnicodeCategory.UppercaseLetter:
962 case UnicodeCategory.LowercaseLetter:
963 case UnicodeCategory.TitlecaseLetter:
964 case UnicodeCategory.ModifierLetter:
965 case UnicodeCategory.OtherLetter:
971 static bool is_identifier_part_character_slow_part (char c)
973 switch (Char.GetUnicodeCategory (c)) {
974 // connecting-character: A Unicode character of the class Pc
975 case UnicodeCategory.ConnectorPunctuation:
977 // combining-character: A Unicode character of classes Mn or Mc
978 case UnicodeCategory.NonSpacingMark:
979 case UnicodeCategory.SpacingCombiningMark:
981 // decimal-digit-character: A Unicode character of the class Nd
982 case UnicodeCategory.DecimalDigitNumber:
984 // plus is_identifier_start_character_slow_part
985 case UnicodeCategory.LetterNumber:
986 case UnicodeCategory.UppercaseLetter:
987 case UnicodeCategory.LowercaseLetter:
988 case UnicodeCategory.TitlecaseLetter:
989 case UnicodeCategory.ModifierLetter:
990 case UnicodeCategory.OtherLetter:
993 // formatting-character: A Unicode character of the class Cf
994 case UnicodeCategory.Format:
995 // csc bug compatibility which recognizes it as a whitespace
1002 public static bool IsKeyword (string s)
1004 return keyword_strings.Contains (s);
1008 // Open parens micro parser. Detects both lambda and cast ambiguity.
1010 int TokenizeOpenParens ()
1015 int bracket_level = 0;
1016 bool is_type = false;
1017 bool can_be_type = false;
1020 ptoken = current_token;
1023 switch (current_token) {
1024 case Token.CLOSE_PARENS:
1028 // Expression inside parens is lambda, (int i) =>
1030 if (current_token == Token.ARROW)
1031 return Token.OPEN_PARENS_LAMBDA;
1034 // Expression inside parens is single type, (int[])
1037 if (current_token == Token.SEMICOLON)
1038 return Token.OPEN_PARENS;
1040 return Token.OPEN_PARENS_CAST;
1044 // Expression is possible cast, look at next token, (T)null
1047 switch (current_token) {
1048 case Token.OPEN_PARENS:
1051 case Token.IDENTIFIER:
1055 case Token.DELEGATE:
1065 case Token.UNCHECKED:
1071 // These can be part of a member access
1086 return Token.OPEN_PARENS_CAST;
1089 return Token.OPEN_PARENS;
1092 case Token.DOUBLE_COLON:
1093 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1098 case Token.IDENTIFIER:
1102 if (bracket_level == 0) {
1108 case Token.OP_GENERICS_LT:
1110 case Token.DOUBLE_COLON:
1112 if (bracket_level == 0)
1116 can_be_type = is_type = false;
1136 if (bracket_level == 0)
1141 if (bracket_level == 0) {
1142 bracket_level = 100;
1143 can_be_type = is_type = false;
1147 case Token.OP_GENERICS_LT:
1148 case Token.OPEN_BRACKET:
1149 if (bracket_level++ == 0)
1153 case Token.OP_GENERICS_GT:
1154 case Token.CLOSE_BRACKET:
1158 case Token.INTERR_NULLABLE:
1160 if (bracket_level == 0)
1166 can_be_type = is_type = false;
1170 return Token.OPEN_PARENS;
1175 public static bool IsValidIdentifier (string s)
1177 if (s == null || s.Length == 0)
1180 if (!is_identifier_start_character (s [0]))
1183 for (int i = 1; i < s.Length; i ++)
1184 if (! is_identifier_part_character (s [i]))
1190 bool parse_less_than (ref int genericDimension)
1193 int the_token = token ();
1194 if (the_token == Token.OPEN_BRACKET) {
1196 the_token = token ();
1197 if (the_token == Token.EOF)
1200 if (the_token == Token.CLOSE_BRACKET)
1203 the_token = token ();
1204 } else if (the_token == Token.IN || the_token == Token.OUT) {
1205 the_token = token ();
1207 switch (the_token) {
1208 case Token.IDENTIFIER:
1226 case Token.OP_GENERICS_GT:
1227 genericDimension = 1;
1235 the_token = token ();
1236 } while (the_token == Token.COMMA);
1238 if (the_token == Token.OP_GENERICS_GT) {
1248 the_token = token ();
1250 if (the_token == Token.OP_GENERICS_GT)
1252 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1254 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1256 else if (the_token == Token.OP_GENERICS_LT) {
1257 if (!parse_less_than (ref genericDimension))
1260 } else if (the_token == Token.OPEN_BRACKET) {
1262 the_token = token ();
1263 if (the_token == Token.CLOSE_BRACKET)
1265 else if (the_token == Token.COMMA)
1266 goto rank_specifiers;
1273 public int peek_token ()
1278 the_token = token ();
1285 // Tonizes `?' using custom disambiguous rules to return one
1286 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1288 // Tricky expression looks like:
1290 // Foo ? a = x ? b : c;
1292 int TokenizePossibleNullableType ()
1294 if (parsing_block == 0 || parsing_type > 0)
1295 return Token.INTERR_NULLABLE;
1297 int d = peek_char ();
1300 return Token.OP_COALESCING;
1304 return Token.INTERR_OPERATOR;
1308 if (d == ',' || d == ';' || d == '>')
1309 return Token.INTERR_NULLABLE;
1310 if (d == '*' || (d >= '0' && d <= '9'))
1311 return Token.INTERR;
1315 current_token = Token.NONE;
1324 case Token.OPEN_BRACKET_EXPR:
1325 next_token = Token.INTERR_OPERATOR;
1333 case Token.INTERPOLATED_STRING:
1334 next_token = Token.INTERR;
1337 case Token.SEMICOLON:
1339 case Token.CLOSE_PARENS:
1340 case Token.OPEN_BRACKET:
1341 case Token.OP_GENERICS_GT:
1343 case Token.OP_COALESCING:
1345 next_token = Token.INTERR_NULLABLE;
1348 case Token.OPEN_PARENS:
1349 case Token.OPEN_PARENS_CAST:
1350 case Token.OPEN_PARENS_LAMBDA:
1355 case Token.OP_GENERICS_LT:
1356 case Token.OP_GENERICS_LT_DECL:
1357 case Token.GENERIC_DIMENSION:
1367 if (next_token == -1) {
1368 switch (xtoken ()) {
1370 case Token.SEMICOLON:
1371 case Token.OPEN_BRACE:
1373 next_token = Token.INTERR_NULLABLE;
1377 next_token = Token.INTERR;
1380 case Token.OPEN_PARENS:
1381 case Token.OPEN_PARENS_CAST:
1382 case Token.OPEN_PARENS_LAMBDA:
1386 case Token.OPEN_BRACKET:
1387 case Token.OPEN_BRACKET_EXPR:
1391 case Token.CLOSE_PARENS:
1395 case Token.OP_GENERICS_LT:
1396 case Token.OP_GENERICS_LT_DECL:
1397 case Token.GENERIC_DIMENSION:
1407 // All shorcuts failed, do it hard way
1409 while ((ntoken = xtoken ()) != Token.EOF) {
1411 case Token.OPEN_BRACE:
1414 case Token.OPEN_PARENS:
1415 case Token.OPEN_PARENS_CAST:
1416 case Token.OPEN_PARENS_LAMBDA:
1419 case Token.CLOSE_BRACE:
1422 case Token.OP_GENERICS_LT:
1423 case Token.OP_GENERICS_LT_DECL:
1424 case Token.GENERIC_DIMENSION:
1427 case Token.OPEN_BRACKET:
1428 case Token.OPEN_BRACKET_EXPR:
1431 case Token.CLOSE_BRACKET:
1434 case Token.CLOSE_PARENS:
1441 return Token.INTERR_NULLABLE;
1443 case Token.OP_GENERICS_GT:
1450 return Token.INTERR_NULLABLE;
1456 if (ntoken == Token.SEMICOLON)
1462 if (ntoken == Token.COMMA) {
1463 if (generics != 0 || brackets != 0)
1467 return Token.INTERR_NULLABLE;
1470 if (ntoken == Token.COLON) {
1471 if (++colons == interrs)
1476 if (ntoken == Token.INTERR) {
1482 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1491 bool decimal_digits (int c)
1494 bool seen_digits = false;
1497 if (number_pos == MaxNumberLength)
1498 Error_NumericConstantTooLong ();
1499 number_builder [number_pos++] = (char) c;
1503 // We use peek_char2, because decimal_digits needs to do a
1504 // 2-character look-ahead (5.ToString for example).
1506 while ((d = peek_char2 ()) != -1){
1507 if (d >= '0' && d <= '9'){
1508 if (number_pos == MaxNumberLength)
1509 Error_NumericConstantTooLong ();
1510 number_builder [number_pos++] = (char) d;
1520 static bool is_hex (int e)
1522 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1525 static TypeCode real_type_suffix (int c)
1529 return TypeCode.Single;
1531 return TypeCode.Double;
1533 return TypeCode.Decimal;
1535 return TypeCode.Empty;
1539 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1541 bool is_unsigned = false;
1542 bool is_long = false;
1545 bool scanning = true;
1558 // if we have not seen anything in between
1559 // report this error
1561 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1581 if (is_long && is_unsigned){
1582 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1586 // uint if possible, or ulong else.
1588 if ((ul & 0xffffffff00000000) == 0)
1589 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1591 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1592 } else if (is_long){
1593 // long if possible, ulong otherwise
1594 if ((ul & 0x8000000000000000) != 0)
1595 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1597 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1599 // int, uint, long or ulong in that order
1600 if ((ul & 0xffffffff00000000) == 0){
1601 uint ui = (uint) ul;
1603 if ((ui & 0x80000000) != 0)
1604 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1606 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1608 if ((ul & 0x8000000000000000) != 0)
1609 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1611 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1617 // given `c' as the next char in the input decide whether
1618 // we need to convert to a special type, and then choose
1619 // the best representation for the integer
1621 ILiteralConstant adjust_int (int c, Location loc)
1624 if (number_pos > 9){
1625 ulong ul = (uint) (number_builder [0] - '0');
1627 for (int i = 1; i < number_pos; i++){
1628 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1631 return integer_type_suffix (ul, c, loc);
1633 uint ui = (uint) (number_builder [0] - '0');
1635 for (int i = 1; i < number_pos; i++){
1636 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1639 return integer_type_suffix (ui, c, loc);
1641 } catch (OverflowException) {
1642 Error_NumericConstantTooLong ();
1643 return new IntLiteral (context.BuiltinTypes, 0, loc);
1645 catch (FormatException) {
1646 Report.Error (1013, Location, "Invalid number");
1647 return new IntLiteral (context.BuiltinTypes, 0, loc);
1651 ILiteralConstant adjust_real (TypeCode t, Location loc)
1653 string s = new string (number_builder, 0, number_pos);
1654 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1657 case TypeCode.Decimal:
1659 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1660 } catch (OverflowException) {
1661 Report.Error (594, Location, error_details, "decimal");
1662 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1664 case TypeCode.Single:
1666 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1667 } catch (OverflowException) {
1668 Report.Error (594, Location, error_details, "float");
1669 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1673 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1674 } catch (OverflowException) {
1675 Report.Error (594, loc, error_details, "double");
1676 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1681 ILiteralConstant handle_hex (Location loc)
1687 while ((d = peek_char ()) != -1){
1689 number_builder [number_pos++] = (char) d;
1695 string s = new String (number_builder, 0, number_pos);
1698 if (number_pos <= 8)
1699 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1701 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1703 return integer_type_suffix (ul, peek_char (), loc);
1704 } catch (OverflowException){
1705 Error_NumericConstantTooLong ();
1706 return new IntLiteral (context.BuiltinTypes, 0, loc);
1708 catch (FormatException) {
1709 Report.Error (1013, Location, "Invalid number");
1710 return new IntLiteral (context.BuiltinTypes, 0, loc);
1715 // Invoked if we know we have .digits or digits
1717 int is_number (int c, bool dotLead)
1719 ILiteralConstant res;
1722 int read_start = reader.Position - 1;
1725 // Caller did peek_char
1735 int peek = peek_char ();
1737 if (peek == 'x' || peek == 'X') {
1738 val = res = handle_hex (loc);
1740 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1743 return Token.LITERAL;
1751 // We need to handle the case of
1752 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1754 bool is_real = false;
1759 if (decimal_digits ('.')){
1765 val = res = adjust_int (-1, loc);
1768 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1770 return Token.LITERAL;
1774 if (c == 'e' || c == 'E'){
1777 if (number_pos == MaxNumberLength)
1778 Error_NumericConstantTooLong ();
1779 number_builder [number_pos++] = (char) c;
1783 if (number_pos == MaxNumberLength)
1784 Error_NumericConstantTooLong ();
1785 number_builder [number_pos++] = '+';
1787 } else if (c == '-') {
1788 if (number_pos == MaxNumberLength)
1789 Error_NumericConstantTooLong ();
1790 number_builder [number_pos++] = '-';
1793 if (number_pos == MaxNumberLength)
1794 Error_NumericConstantTooLong ();
1795 number_builder [number_pos++] = '+';
1802 var type = real_type_suffix (c);
1803 if (type == TypeCode.Empty && !is_real) {
1804 res = adjust_int (c, loc);
1808 if (type != TypeCode.Empty) {
1812 res = adjust_real (type, loc);
1818 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1819 if (chars[chars.Length - 1] == '\r')
1820 Array.Resize (ref chars, chars.Length - 1);
1821 res.ParsedValue = chars;
1824 return Token.LITERAL;
1828 // Accepts exactly count (4 or 8) hex, no more no less
1830 int getHex (int count, out int surrogate, out bool error)
1835 int top = count != -1 ? count : 4;
1840 for (i = 0; i < top; i++){
1843 if (c >= '0' && c <= '9')
1844 c = (int) c - (int) '0';
1845 else if (c >= 'A' && c <= 'F')
1846 c = (int) c - (int) 'A' + 10;
1847 else if (c >= 'a' && c <= 'f')
1848 c = (int) c - (int) 'a' + 10;
1854 total = (total * 16) + c;
1856 int p = peek_char ();
1859 if (!is_hex ((char)p))
1865 if (total > 0x0010FFFF) {
1870 if (total >= 0x00010000) {
1871 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1872 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1879 int escape (int c, out int surrogate)
1915 v = getHex (-1, out surrogate, out error);
1921 return EscapeUnicode (d, out surrogate);
1924 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1933 int EscapeUnicode (int ch, out int surrogate)
1937 ch = getHex (8, out surrogate, out error);
1939 ch = getHex (4, out surrogate, out error);
1943 Report.Error (1009, Location, "Unrecognized escape sequence");
1951 if (putback_char != -1) {
1960 if (peek_char () == '\n') {
1966 } else if (x == '\n') {
1971 } else if (x >= UnicodeLS && x <= UnicodePS) {
1980 void advance_line ()
1990 if (putback_char == -1)
1991 putback_char = reader.Read ();
1992 return putback_char;
1997 if (putback_char != -1)
1998 return putback_char;
1999 return reader.Peek ();
2002 public void putback (int c)
2004 if (putback_char != -1) {
2005 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
2008 if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
2009 // It won't happen though.
2019 public bool advance ()
2021 return peek_char () != -1 || CompleteOnEOF;
2024 public Object Value {
2030 public Object value ()
2037 current_token = xtoken ();
2038 return current_token;
2041 int TokenizePreprocessorKeyword (out int c)
2043 // skip over white space
2046 } while (c == ' ' || c == '\t');
2050 while (c != -1 && c >= 'a' && c <= 'z') {
2051 id_builder[pos++] = (char) c;
2054 int peek = peek_char ();
2055 if (peek == 'U' || peek == 'u') {
2057 c = EscapeUnicode (c, out surrogate);
2058 if (surrogate != 0) {
2059 if (is_identifier_part_character ((char) c)) {
2060 id_builder[pos++] = (char) c;
2071 PreprocessorDirective get_cmd_arg (out string arg)
2075 tokens_seen = false;
2078 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2080 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2083 // skip over white space
2084 while (c == ' ' || c == '\t')
2087 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2090 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2091 if (c == '\\' && has_identifier_argument >= 0) {
2092 if (has_identifier_argument != 0) {
2093 has_identifier_argument = 1;
2095 int peek = peek_char ();
2096 if (peek == 'U' || peek == 'u') {
2098 c = EscapeUnicode (c, out surrogate);
2099 if (surrogate != 0) {
2100 if (is_identifier_part_character ((char) c)) {
2101 if (pos == value_builder.Length)
2102 Array.Resize (ref value_builder, pos * 2);
2104 value_builder[pos++] = (char) c;
2110 has_identifier_argument = -1;
2112 } else if (c == '/' && peek_char () == '/') {
2114 // Eat single-line comments
2121 if (pos == value_builder.Length)
2122 Array.Resize (ref value_builder, pos * 2);
2124 value_builder[pos++] = (char) c;
2129 if (pos > MaxIdentifierLength)
2130 arg = new string (value_builder, 0, pos);
2132 arg = InternIdentifier (value_builder, pos);
2134 // Eat any trailing whitespaces
2135 arg = arg.Trim (simple_whitespaces);
2142 // Handles the #line directive
2144 bool PreProcessLine ()
2146 Location loc = Location;
2150 int length = TokenizePreprocessorKeyword (out c);
2151 if (length == line_default.Length) {
2152 if (!IsTokenIdentifierEqual (line_default))
2155 current_source = source_file.SourceFile;
2156 if (!hidden_block_start.IsNull) {
2157 current_source.RegisterHiddenScope (hidden_block_start, loc);
2158 hidden_block_start = Location.Null;
2165 if (length == line_hidden.Length) {
2166 if (!IsTokenIdentifierEqual (line_hidden))
2169 if (hidden_block_start.IsNull)
2170 hidden_block_start = loc;
2175 if (length != 0 || c < '0' || c > '9') {
2177 // Eat any remaining characters to continue parsing on next line
2183 int new_line = TokenizeNumber (c);
2186 // Eat any remaining characters to continue parsing on next line
2189 return new_line != 0;
2194 // skip over white space
2197 } while (c == ' ' || c == '\t');
2198 } else if (c == '"') {
2202 if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2204 // Eat any remaining characters to continue parsing on next line
2208 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2212 string new_file_name = null;
2214 new_file_name = TokenizeFileName (ref c);
2216 // skip over white space
2217 while (c == ' ' || c == '\t') {
2222 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2224 } else if (c == '/') {
2225 ReadSingleLineComment ();
2228 // Eat any remaining characters to continue parsing on next line
2232 Error_EndLineExpected ();
2236 if (new_file_name != null) {
2237 current_source = context.LookupFile (source_file, new_file_name);
2238 source_file.AddIncludeFile (current_source);
2241 if (!hidden_block_start.IsNull) {
2242 current_source.RegisterHiddenScope (hidden_block_start, loc);
2243 hidden_block_start = Location.Null;
2246 ref_line = new_line;
2251 // Handles #define and #undef
2253 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2255 if (ident.Length == 0 || ident == "true" || ident == "false"){
2256 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2260 if (ident.IndexOfAny (simple_whitespaces) != -1){
2261 Error_EndLineExpected ();
2265 if (!is_identifier_start_character (ident [0]))
2266 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2268 foreach (char c in ident.Substring (1)){
2269 if (!is_identifier_part_character (c)){
2270 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2275 if (!caller_is_taking)
2282 if (context.Settings.IsConditionalSymbolDefined (ident))
2285 source_file.AddDefine (ident);
2290 source_file.AddUndefine (ident);
2294 byte read_hex (out bool error)
2297 int c = get_char ();
2299 if ((c >= '0') && (c <= '9'))
2300 total = (int) c - (int) '0';
2301 else if ((c >= 'A') && (c <= 'F'))
2302 total = (int) c - (int) 'A' + 10;
2303 else if ((c >= 'a') && (c <= 'f'))
2304 total = (int) c - (int) 'a' + 10;
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;
2325 return (byte) total;
2329 // Parses #pragma checksum
2331 bool ParsePragmaChecksum ()
2334 // The syntax is ` "foo.txt" "{guid}" "hash"'
2336 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2338 int c = get_char ();
2343 string file_name = TokenizeFileName (ref c);
2345 // TODO: Any white-spaces count
2349 SourceFile file = context.LookupFile (source_file, file_name);
2351 if (get_char () != '"' || get_char () != '{')
2355 byte[] guid_bytes = new byte [16];
2358 for (; i < 4; i++) {
2359 guid_bytes [i] = read_hex (out error);
2364 if (get_char () != '-')
2367 for (; i < 10; i++) {
2368 guid_bytes [i] = read_hex (out error);
2372 guid_bytes [i++] = read_hex (out error);
2376 if (get_char () != '-')
2380 for (; i < 16; i++) {
2381 guid_bytes [i] = read_hex (out error);
2386 if (get_char () != '}' || get_char () != '"')
2389 // TODO: Any white-spaces count
2394 if (get_char () != '"')
2397 // Any length of checksum
2398 List<byte> checksum_bytes = new List<byte> (16);
2400 var checksum_location = Location;
2402 while (c != '"' && c != -1) {
2403 checksum_bytes.Add (read_hex (out error));
2411 ReadSingleLineComment ();
2412 } else if (get_char () != '"') {
2416 if (context.Settings.GenerateDebugInfo) {
2417 var chsum = checksum_bytes.ToArray ();
2419 if (file.HasChecksum) {
2420 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2421 // TODO: Report.SymbolRelatedToPreviousError
2422 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2426 file.SetChecksum (guid_bytes, chsum);
2427 current_source.AutoGenerated = true;
2433 bool IsTokenIdentifierEqual (char[] identifier)
2435 for (int i = 0; i < identifier.Length; ++i) {
2436 if (identifier[i] != id_builder[i])
2443 bool ScanClosingInterpolationBrace ()
2450 var c = reader.Read ();
2459 if (str_quote % 2 == 1) {
2465 } while (res == null);
2471 int TokenizeNumber (int value)
2475 decimal_digits (value);
2476 uint ui = (uint) (number_builder[0] - '0');
2479 for (int i = 1; i < number_pos; i++) {
2480 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2484 } catch (OverflowException) {
2485 Error_NumericConstantTooLong ();
2490 string TokenizeFileName (ref int c)
2492 var string_builder = new StringBuilder ();
2493 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2500 string_builder.Append ((char) c);
2503 if (string_builder.Length == 0) {
2504 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2508 return string_builder.ToString ();
2511 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2514 if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2517 if (c >= '0' && c <= '9') {
2519 number = TokenizeNumber (c);
2523 if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2524 return ReadPragmaWarningComment (c);
2528 // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2532 id_builder [pos++] = (char)c;
2533 while (c < MaxIdentifierLength) {
2535 id_builder [pos] = (char)c;
2537 if (c >= '0' && c <= '9') {
2538 if (pos == 6 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2539 // Recognize CSXXXX as C# XXXX warning
2542 for (int i = 0; i < 4; ++i) {
2543 var ch = id_builder [i + 2];
2544 if (ch < '0' || ch > '9') {
2549 number += (ch - '0') * pow;
2553 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2566 // skip over white space
2567 while (c == ' ' || c == '\t')
2574 // skip over white space
2575 while (c == ' ' || c == '\t')
2581 return ReadPragmaWarningComment (c);
2584 int ReadPragmaWarningComment (int c)
2587 ReadSingleLineComment ();
2589 Report.Warning (1692, 1, Location, "Invalid number");
2591 // Read everything till the end of the line or file
2598 void ReadToEndOfLine ()
2603 } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2606 void ReadSingleLineComment ()
2608 if (peek_char () != '/')
2609 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2611 // Read everything till the end of the line or file
2616 /// Handles #pragma directive
2618 void ParsePragmaDirective ()
2621 int length = TokenizePreprocessorKeyword (out c);
2622 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2623 length = TokenizePreprocessorKeyword (out c);
2626 // #pragma warning disable
2627 // #pragma warning restore
2629 if (length == pragma_warning_disable.Length) {
2630 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2631 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2632 // skip over white space
2633 while (c == ' ' || c == '\t')
2638 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2640 ReadSingleLineComment ();
2643 // Disable/Restore all warnings
2646 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2648 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2652 // Disable/Restore a warning or group of warnings
2656 bool identifier = false;
2657 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2660 // no-op, custom warnings cannot occur in mcs
2661 } else if (disable) {
2662 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2664 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2667 } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2674 Report.Warning (1634, 1, Location, "Expected disable or restore");
2676 // Eat any remaining characters on the line
2685 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2686 if (c != ' ' || !ParsePragmaChecksum ()) {
2687 Report.Warning (1695, 1, Location,
2688 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2694 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2696 // Eat any remaining characters on the line
2700 bool eval_val (string s)
2707 return source_file.IsConditionalDefined (s);
2710 bool pp_primary (ref string s)
2719 s = s.Substring (1);
2720 bool val = pp_expr (ref s, false);
2721 if (s.Length > 0 && s [0] == ')'){
2722 s = s.Substring (1);
2725 Error_InvalidDirective ();
2729 if (is_identifier_start_character (c)){
2735 if (is_identifier_part_character (c)){
2739 bool v = eval_val (s.Substring (0, j));
2740 s = s.Substring (j);
2743 bool vv = eval_val (s);
2748 Error_InvalidDirective ();
2752 bool pp_unary (ref string s)
2759 if (len > 1 && s [1] == '='){
2760 Error_InvalidDirective ();
2763 s = s.Substring (1);
2764 return ! pp_primary (ref s);
2766 return pp_primary (ref s);
2768 Error_InvalidDirective ();
2773 bool pp_eq (ref string s)
2775 bool va = pp_unary (ref s);
2781 if (len > 2 && s [1] == '='){
2782 s = s.Substring (2);
2783 return va == pp_unary (ref s);
2785 Error_InvalidDirective ();
2788 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2789 s = s.Substring (2);
2791 return va != pp_unary (ref s);
2800 bool pp_and (ref string s)
2802 bool va = pp_eq (ref s);
2808 if (len > 2 && s [1] == '&'){
2809 s = s.Substring (2);
2810 return (va & pp_and (ref s));
2812 Error_InvalidDirective ();
2821 // Evaluates an expression for `#if' or `#elif'
2823 bool pp_expr (ref string s, bool isTerm)
2825 bool va = pp_and (ref s);
2832 if (len > 2 && s [1] == '|'){
2833 s = s.Substring (2);
2834 return va | pp_expr (ref s, isTerm);
2836 Error_InvalidDirective ();
2841 Error_EndLineExpected ();
2849 bool eval (string s)
2851 bool v = pp_expr (ref s, true);
2860 void Error_NumericConstantTooLong ()
2862 Report.Error (1021, Location, "Integral constant is too large");
2865 void Error_InvalidDirective ()
2867 Report.Error (1517, Location, "Invalid preprocessor directive");
2870 void Error_UnexpectedDirective (string extra)
2874 "Unexpected processor directive ({0})", extra);
2877 void Error_TokensSeen ()
2879 Report.Error (1032, Location,
2880 "Cannot define or undefine preprocessor symbols after first token in file");
2883 void Eror_WrongPreprocessorLocation ()
2885 Report.Error (1040, Location,
2886 "Preprocessor directives must appear as the first non-whitespace character on a line");
2889 void Error_EndLineExpected ()
2891 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2895 // Raises a warning when tokenizer found documentation comment
2896 // on unexpected place
2898 void WarningMisplacedComment (Location loc)
2900 if (doc_state != XmlCommentState.Error) {
2901 doc_state = XmlCommentState.Error;
2902 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2907 // if true, then the code continues processing the code
2908 // if false, the code stays in a loop until another directive is
2910 // When caller_is_taking is false we ignore all directives except the ones
2911 // which can help us to identify where the #if block ends
2912 bool ParsePreprocessingDirective (bool caller_is_taking)
2915 bool region_directive = false;
2917 var directive = get_cmd_arg (out arg);
2920 // The first group of pre-processing instructions is always processed
2922 switch (directive) {
2923 case PreprocessorDirective.Region:
2924 region_directive = true;
2926 goto case PreprocessorDirective.If;
2928 case PreprocessorDirective.Endregion:
2929 if (ifstack == null || ifstack.Count == 0){
2930 Error_UnexpectedDirective ("no #region for this #endregion");
2933 int pop = ifstack.Pop ();
2935 if ((pop & REGION) == 0)
2936 Report.Error (1027, Location, "Expected `#endif' directive");
2938 return caller_is_taking;
2940 case PreprocessorDirective.If:
2941 if (ifstack == null)
2942 ifstack = new Stack<int> (2);
2944 int flags = region_directive ? REGION : 0;
2945 if (ifstack.Count == 0){
2946 flags |= PARENT_TAKING;
2948 int state = ifstack.Peek ();
2949 if ((state & TAKING) != 0) {
2950 flags |= PARENT_TAKING;
2954 if (eval (arg) && caller_is_taking) {
2955 ifstack.Push (flags | TAKING);
2958 ifstack.Push (flags);
2961 case PreprocessorDirective.Endif:
2962 if (ifstack == null || ifstack.Count == 0){
2963 Error_UnexpectedDirective ("no #if for this #endif");
2966 pop = ifstack.Pop ();
2968 if ((pop & REGION) != 0)
2969 Report.Error (1038, Location, "#endregion directive expected");
2971 if (arg.Length != 0) {
2972 Error_EndLineExpected ();
2975 if (ifstack.Count == 0)
2978 int state = ifstack.Peek ();
2979 return (state & TAKING) != 0;
2982 case PreprocessorDirective.Elif:
2983 if (ifstack == null || ifstack.Count == 0){
2984 Error_UnexpectedDirective ("no #if for this #elif");
2987 int state = ifstack.Pop ();
2989 if ((state & REGION) != 0) {
2990 Report.Error (1038, Location, "#endregion directive expected");
2994 if ((state & ELSE_SEEN) != 0){
2995 Error_UnexpectedDirective ("#elif not valid after #else");
2999 if ((state & TAKING) != 0) {
3004 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
3005 ifstack.Push (state | TAKING);
3009 ifstack.Push (state);
3013 case PreprocessorDirective.Else:
3014 if (ifstack == null || ifstack.Count == 0){
3015 Error_UnexpectedDirective ("no #if for this #else");
3018 int state = ifstack.Peek ();
3020 if ((state & REGION) != 0) {
3021 Report.Error (1038, Location, "#endregion directive expected");
3025 if ((state & ELSE_SEEN) != 0){
3026 Error_UnexpectedDirective ("#else within #else");
3032 if (arg.Length != 0) {
3033 Error_EndLineExpected ();
3038 if ((state & PARENT_TAKING) != 0) {
3039 ret = (state & TAKING) == 0;
3047 ifstack.Push (state | ELSE_SEEN);
3051 case PreprocessorDirective.Define:
3052 if (any_token_seen){
3053 if (caller_is_taking)
3054 Error_TokensSeen ();
3055 return caller_is_taking;
3057 PreProcessDefinition (true, arg, caller_is_taking);
3058 return caller_is_taking;
3060 case PreprocessorDirective.Undef:
3061 if (any_token_seen){
3062 if (caller_is_taking)
3063 Error_TokensSeen ();
3064 return caller_is_taking;
3066 PreProcessDefinition (false, arg, caller_is_taking);
3067 return caller_is_taking;
3069 case PreprocessorDirective.Invalid:
3070 Report.Error (1024, Location, "Wrong preprocessor directive");
3075 // These are only processed if we are in a `taking' block
3077 if (!caller_is_taking)
3081 case PreprocessorDirective.Error:
3082 Report.Error (1029, Location, "#error: '{0}'", arg);
3085 case PreprocessorDirective.Warning:
3086 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3089 case PreprocessorDirective.Pragma:
3090 if (context.Settings.Version == LanguageVersion.ISO_1) {
3091 Report.FeatureIsNotAvailable (context, Location, "#pragma");
3094 ParsePragmaDirective ();
3097 case PreprocessorDirective.Line:
3098 Location loc = Location;
3099 if (!PreProcessLine ())
3100 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3102 return caller_is_taking;
3105 throw new NotImplementedException (directive.ToString ());
3108 int consume_string (bool quoted)
3112 Location start_location = Location;
3114 start_location = start_location - 1;
3117 int reader_pos = reader.Position;
3121 // Cannot use get_char because of \r in quoted strings
3122 if (putback_char != -1) {
3132 if (quoted && peek_char () == '"') {
3133 if (pos == value_builder.Length)
3134 Array.Resize (ref value_builder, pos * 2);
3136 value_builder[pos++] = (char) c;
3141 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3144 res.ParsedValue = quoted ?
3145 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3146 reader.ReadChars (reader_pos - 1, reader.Position);
3149 return Token.LITERAL;
3152 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3154 Report.Error (1010, Location, "Newline in constant");
3158 // Don't add \r to string literal
3159 if (pos > 1 && value_builder [pos - 1] == '\r')
3162 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3163 return Token.LITERAL;
3167 } else if (c == '\\' && !quoted) {
3170 c = escape (c, out surrogate);
3173 if (surrogate != 0) {
3174 if (pos == value_builder.Length)
3175 Array.Resize (ref value_builder, pos * 2);
3177 value_builder[pos++] = (char) c;
3180 } else if (c == -1) {
3181 Report.Error (1039, Location, "Unterminated string literal");
3187 if (pos == value_builder.Length)
3188 Array.Resize (ref value_builder, pos * 2);
3190 value_builder[pos++] = (char) c;
3194 private int consume_identifier (int s)
3196 int res = consume_identifier (s, false);
3198 if (doc_state == XmlCommentState.Allowed)
3199 doc_state = XmlCommentState.NotAllowed;
3204 int consume_identifier (int c, bool quoted)
3207 // This method is very performance sensitive. It accounts
3208 // for approximately 25% of all parser time
3218 c = escape (c, out surrogate);
3219 if (quoted || is_identifier_start_character (c)) {
3220 // it's added bellow
3221 } else if (surrogate != 0) {
3222 id_builder [pos++] = (char)c;
3225 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3230 id_builder [pos++] = (char) c;
3236 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3237 id_builder [pos++] = (char) c;
3244 c = escape (c, out surrogate);
3245 if (is_identifier_part_character ((char) c))
3246 id_builder[pos++] = (char) c;
3247 else if (surrogate != 0) {
3251 // TODO: Probably need more whitespace characters
3256 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3263 } else if (is_identifier_part_character_slow_part ((char) c)) {
3264 id_builder [pos++] = (char) c;
3271 } catch (IndexOutOfRangeException) {
3272 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3280 // Optimization: avoids doing the keyword lookup
3281 // on uppercase letters
3283 if (id_builder [0] >= '_' && !quoted) {
3284 int keyword = GetKeyword (id_builder, pos);
3285 if (keyword != -1) {
3286 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3291 string s = InternIdentifier (id_builder, pos);
3292 val = ltb.Create (s, current_source, ref_line, column);
3293 if (quoted && parsing_attribute_section)
3294 AddEscapedIdentifier (((LocatedToken) val).Location);
3296 return Token.IDENTIFIER;
3299 string InternIdentifier (char[] charBuffer, int length)
3302 // Keep identifiers in an array of hashtables to avoid needless
3305 var identifiers_group = identifiers[length];
3307 if (identifiers_group != null) {
3308 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3312 // TODO: this should be number of files dependant
3313 // corlib compilation peaks at 1000 and System.Core at 150
3314 int capacity = length > 20 ? 10 : 100;
3315 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3316 identifiers[length] = identifiers_group;
3319 char[] chars = new char[length];
3320 Array.Copy (charBuffer, chars, length);
3322 s = new string (charBuffer, 0, length);
3323 identifiers_group.Add (chars, s);
3327 public int xtoken ()
3329 if (parsing_interpolation_format) {
3330 return TokenizeInterpolationFormat ();
3335 // Whether we have seen comments on the current line
3336 bool comments_seen = false;
3337 while ((c = get_char ()) != -1) {
3340 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3348 case 0xFEFF: // Ignore BOM anywhere in the file
3351 /* This is required for compatibility with .NET
3353 if (peek_char () == 0xBB) {
3356 if (get_char () == 0xBF)
3364 return consume_identifier (c);
3367 val = ltb.Create (current_source, ref_line, col);
3368 return Token.OPEN_BRACE;
3370 if (parsing_string_interpolation > 0) {
3371 --parsing_string_interpolation;
3372 return TokenizeInterpolatedString ();
3375 val = ltb.Create (current_source, ref_line, col);
3376 return Token.CLOSE_BRACE;
3378 // To block doccomment inside attribute declaration.
3379 if (doc_state == XmlCommentState.Allowed)
3380 doc_state = XmlCommentState.NotAllowed;
3382 val = ltb.Create (current_source, ref_line, col);
3384 if (parsing_block == 0 || lambda_arguments_parsing)
3385 return Token.OPEN_BRACKET;
3387 int next = peek_char ();
3391 return Token.OPEN_BRACKET;
3401 next = peek_token ();
3402 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3403 return Token.OPEN_BRACKET;
3405 return Token.OPEN_BRACKET_EXPR;
3407 return Token.OPEN_BRACKET_EXPR;
3410 ltb.CreateOptional (current_source, ref_line, col, ref val);
3411 return Token.CLOSE_BRACKET;
3413 val = ltb.Create (current_source, ref_line, col);
3415 // An expression versions of parens can appear in block context only
3417 if (parsing_block != 0 && !lambda_arguments_parsing) {
3420 // Optmize most common case where we know that parens
3423 switch (current_token) {
3424 case Token.IDENTIFIER:
3433 case Token.DELEGATE:
3434 case Token.OP_GENERICS_GT:
3435 return Token.OPEN_PARENS;
3438 // Optimize using peek
3439 int xx = peek_char ();
3446 return Token.OPEN_PARENS;
3449 lambda_arguments_parsing = true;
3451 d = TokenizeOpenParens ();
3453 lambda_arguments_parsing = false;
3457 return Token.OPEN_PARENS;
3459 ltb.CreateOptional (current_source, ref_line, col, ref val);
3460 return Token.CLOSE_PARENS;
3462 ltb.CreateOptional (current_source, ref_line, col, ref val);
3465 ltb.CreateOptional (current_source, ref_line, col, ref val);
3466 return Token.SEMICOLON;
3468 val = ltb.Create (current_source, ref_line, col);
3471 val = ltb.Create (current_source, ref_line, col);
3472 return TokenizePossibleNullableType ();
3474 val = ltb.Create (current_source, ref_line, col);
3475 if (parsing_generic_less_than++ > 0)
3476 return Token.OP_GENERICS_LT;
3478 return TokenizeLessThan ();
3481 val = ltb.Create (current_source, ref_line, col);
3489 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3490 parsing_generic_less_than--;
3491 return Token.OP_GENERICS_GT;
3500 return Token.OP_SHIFT_RIGHT_ASSIGN;
3502 return Token.OP_SHIFT_RIGHT;
3508 val = ltb.Create (current_source, ref_line, col);
3512 } else if (d == '=') {
3513 d = Token.OP_ADD_ASSIGN;
3521 val = ltb.Create (current_source, ref_line, col);
3525 } else if (d == '=')
3526 d = Token.OP_SUB_ASSIGN;
3536 val = ltb.Create (current_source, ref_line, col);
3537 if (peek_char () == '='){
3544 val = ltb.Create (current_source, ref_line, col);
3555 return Token.ASSIGN;
3558 val = ltb.Create (current_source, ref_line, col);
3562 return Token.OP_AND;
3566 return Token.OP_AND_ASSIGN;
3568 return Token.BITWISE_AND;
3571 val = ltb.Create (current_source, ref_line, col);
3579 return Token.OP_OR_ASSIGN;
3581 return Token.BITWISE_OR;
3584 val = ltb.Create (current_source, ref_line, col);
3585 if (peek_char () == '='){
3587 return Token.OP_MULT_ASSIGN;
3594 val = ltb.Create (current_source, ref_line, col);
3596 return Token.OP_DIV_ASSIGN;
3599 // Handle double-slash comments.
3601 if (parsing_string_interpolation > 0) {
3602 Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3607 if (doc_processing) {
3608 if (peek_char () == '/') {
3610 // Don't allow ////.
3611 if ((d = peek_char ()) != '/') {
3612 if (doc_state == XmlCommentState.Allowed)
3613 handle_one_line_xml_comment ();
3614 else if (doc_state == XmlCommentState.NotAllowed)
3615 WarningMisplacedComment (Location - 3);
3618 if (xml_comment_buffer.Length > 0)
3619 doc_state = XmlCommentState.NotAllowed;
3625 any_token_seen |= tokens_seen;
3626 tokens_seen = false;
3627 comments_seen = false;
3629 } else if (d == '*'){
3631 bool docAppend = false;
3632 if (doc_processing && peek_char () == '*') {
3634 // But when it is /**/, just do nothing.
3635 if (peek_char () == '/') {
3639 if (doc_state == XmlCommentState.Allowed)
3641 else if (doc_state == XmlCommentState.NotAllowed) {
3642 WarningMisplacedComment (Location - 2);
3646 int current_comment_start = 0;
3648 current_comment_start = xml_comment_buffer.Length;
3649 xml_comment_buffer.Append (Environment.NewLine);
3652 while ((d = get_char ()) != -1){
3653 if (d == '*' && peek_char () == '/'){
3655 comments_seen = true;
3659 xml_comment_buffer.Append ((char) d);
3661 if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3662 any_token_seen |= tokens_seen;
3663 tokens_seen = false;
3665 // Reset 'comments_seen' just to be consistent.
3666 // It doesn't matter either way, here.
3668 comments_seen = false;
3672 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3675 update_formatted_doc_comment (current_comment_start);
3678 val = ltb.Create (current_source, ref_line, col);
3682 val = ltb.Create (current_source, ref_line, col);
3683 if (peek_char () == '='){
3685 return Token.OP_MOD_ASSIGN;
3687 return Token.PERCENT;
3690 val = ltb.Create (current_source, ref_line, col);
3691 if (peek_char () == '='){
3693 return Token.OP_XOR_ASSIGN;
3695 return Token.CARRET;
3698 val = ltb.Create (current_source, ref_line, col);
3699 if (peek_char () == ':') {
3701 return Token.DOUBLE_COLON;
3705 case '0': case '1': case '2': case '3': case '4':
3706 case '5': case '6': case '7': case '8': case '9':
3708 return is_number (c, false);
3710 case '\n': // white space
3713 any_token_seen |= tokens_seen;
3714 tokens_seen = false;
3715 comments_seen = false;
3721 if (d >= '0' && d <= '9')
3722 return is_number (c, true);
3724 ltb.CreateOptional (current_source, ref_line, col, ref val);
3728 if (tokens_seen || comments_seen) {
3729 Eror_WrongPreprocessorLocation ();
3733 if (ParsePreprocessingDirective (true))
3736 bool directive_expected = false;
3737 while ((c = get_char ()) != -1) {
3739 directive_expected = true;
3740 } else if (!directive_expected) {
3741 // TODO: Implement comment support for disabled code and uncomment this code
3743 // Eror_WrongPreprocessorLocation ();
3744 // return Token.ERROR;
3749 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3753 if (ParsePreprocessingDirective (false))
3756 directive_expected = false;
3760 tokens_seen = false;
3767 if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3768 parsing_string_interpolation = 0;
3769 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3770 val = new StringLiteral (context.BuiltinTypes, "", Location);
3771 return Token.INTERPOLATED_STRING_END;
3774 return consume_string (false);
3777 return TokenizeBackslash ();
3783 return consume_string (true);
3786 if (is_identifier_start_character (c)){
3787 return consume_identifier (c, true);
3790 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3794 if (peek_char () == '"') {
3796 return TokenizeInterpolatedString ();
3800 case EvalStatementParserCharacter:
3801 return Token.EVAL_STATEMENT_PARSER;
3802 case EvalCompilationUnitParserCharacter:
3803 return Token.EVAL_COMPILATION_UNIT_PARSER;
3804 case EvalUsingDeclarationsParserCharacter:
3805 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3806 case DocumentationXref:
3807 return Token.DOC_SEE;
3810 if (is_identifier_start_character (c)) {
3812 return consume_identifier (c);
3815 if (char.IsWhiteSpace ((char) c))
3818 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3823 return Token.COMPLETE_COMPLETION;
3826 return Token.GENERATE_COMPLETION;
3833 int TokenizeBackslash ()
3836 int read_start = reader.Position;
3838 Location start_location = Location;
3839 int c = get_char ();
3842 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3843 Report.Error (1011, start_location, "Empty character literal");
3844 return Token.LITERAL;
3847 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3848 Report.Error (1010, start_location, "Newline in constant");
3853 c = escape (c, out d);
3857 throw new NotImplementedException ();
3859 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3864 Report.Error (1012, start_location, "Too many characters in character literal");
3866 // Try to recover, read until newline or next "'"
3867 while ((c = get_char ()) != -1) {
3868 if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3874 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3877 return Token.LITERAL;
3880 int TokenizeLessThan ()
3884 // Save current position and parse next token.
3886 int generic_dimension = 0;
3887 if (parse_less_than (ref generic_dimension)) {
3888 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3889 d = Token.OP_GENERICS_LT_DECL;
3891 if (generic_dimension > 0) {
3892 val = generic_dimension;
3894 return Token.GENERIC_DIMENSION;
3897 d = Token.OP_GENERICS_LT;
3904 parsing_generic_less_than = 0;
3913 return Token.OP_SHIFT_LEFT_ASSIGN;
3915 return Token.OP_SHIFT_LEFT;
3925 int TokenizeInterpolatedString ()
3928 var start_location = Location;
3931 var ch = get_char ();
3934 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3935 return Token.INTERPOLATED_STRING_END;
3937 if (peek_char () == '{') {
3938 value_builder [pos++] = (char)ch;
3943 ++parsing_string_interpolation;
3944 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3945 return Token.INTERPOLATED_STRING;
3949 ch = escape (ch, out surrogate);
3953 if (ch == '{' || ch == '}') {
3954 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
3957 if (surrogate != 0) {
3958 if (pos == value_builder.Length)
3959 Array.Resize (ref value_builder, pos * 2);
3961 if (pos == value_builder.Length)
3962 Array.Resize (ref value_builder, pos * 2);
3964 value_builder [pos++] = (char)ch;
3974 if (pos == value_builder.Length)
3975 Array.Resize (ref value_builder, pos * 2);
3977 value_builder[pos++] = (char) ch;
3981 int TokenizeInterpolationFormat ()
3986 var ch = get_char ();
3995 Report.Error (8089, Location, "Empty interpolated expression format specifier");
3996 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
3997 Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
4000 val = CreateStringFromBuilder (pos);
4001 return Token.LITERAL;
4009 ch = escape (ch, out surrogate);
4013 if (ch == '{' || ch == '}') {
4014 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4017 if (surrogate != 0) {
4018 if (pos == value_builder.Length)
4019 Array.Resize (ref value_builder, pos * 2);
4021 value_builder [pos++] = (char)ch;
4031 value_builder[pos++] = (char) ch;
4035 string CreateStringFromBuilder (int pos)
4038 return string.Empty;
4040 return InternIdentifier (value_builder, pos);
4042 return new string (value_builder, 0, pos);
4046 // Handles one line xml comment
4048 private void handle_one_line_xml_comment ()
4051 while ((c = peek_char ()) == ' ')
4052 get_char (); // skip heading whitespaces.
4053 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4054 xml_comment_buffer.Append ((char) get_char ());
4056 if (c == '\r' || c == '\n')
4057 xml_comment_buffer.Append (Environment.NewLine);
4061 // Remove heading "*" in Javadoc-like xml documentation.
4063 private void update_formatted_doc_comment (int current_comment_start)
4065 int length = xml_comment_buffer.Length - current_comment_start;
4066 string [] lines = xml_comment_buffer.ToString (
4067 current_comment_start,
4068 length).Replace ("\r", "").Split ('\n');
4070 // The first line starts with /**, thus it is not target
4071 // for the format check.
4072 for (int i = 1; i < lines.Length; i++) {
4073 string s = lines [i];
4074 int idx = s.IndexOf ('*');
4077 if (i < lines.Length - 1)
4081 head = s.Substring (0, idx);
4082 foreach (char c in head)
4085 lines [i] = s.Substring (idx + 1);
4087 xml_comment_buffer.Remove (current_comment_start, length);
4088 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4092 // Checks if there was incorrect doc comments and raise
4095 public void check_incorrect_doc_comment ()
4097 if (xml_comment_buffer.Length > 0)
4098 WarningMisplacedComment (Location);
4102 // Consumes the saved xml comment lines (if any)
4103 // as for current target member or type.
4105 public string consume_doc_comment ()
4107 if (xml_comment_buffer.Length > 0) {
4108 string ret = xml_comment_buffer.ToString ();
4109 reset_doc_comment ();
4115 void reset_doc_comment ()
4117 xml_comment_buffer.Length = 0;
4120 public void cleanup ()
4122 if (ifstack != null && ifstack.Count >= 1) {
4123 int state = ifstack.Pop ();
4124 if ((state & REGION) != 0)
4125 Report.Error (1038, Location, "#endregion directive expected");
4127 Report.Error (1027, Location, "Expected `#endif' directive");
4133 // Indicates whether it accepts XML documentation or not.
4135 public enum XmlCommentState {
4136 // comment is allowed in this state.
4138 // comment is not allowed in this state.
4140 // once comments appeared when it is NotAllowed, then the
4141 // state is changed to it, until the state is changed to