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;
413 public Position (Tokenizer t)
415 position = t.reader.Position;
417 ref_line = t.ref_line;
419 hidden = t.hidden_block_start;
420 putback_char = t.putback_char;
421 previous_col = t.previous_col;
422 if (t.ifstack != null && t.ifstack.Count != 0) {
423 // There is no simple way to clone Stack<T> all
424 // methods reverse the order
425 var clone = t.ifstack.ToArray ();
426 Array.Reverse (clone);
427 ifstack = new Stack<int> (clone);
429 parsing_generic_less_than = t.parsing_generic_less_than;
430 current_token = t.current_token;
435 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session, Report report)
437 this.source_file = file;
438 this.context = file.Compiler;
439 this.current_source = file.SourceFile;
440 this.identifiers = session.Identifiers;
441 this.id_builder = session.IDBuilder;
442 this.number_builder = session.NumberBuilder;
443 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
444 this.Report = report;
450 xml_comment_buffer = new StringBuilder ();
451 doc_processing = context.Settings.DocumentationFile != null;
453 tab_size = context.Settings.TabSize;
456 public void PushPosition ()
458 position_stack.Push (new Position (this));
461 public void PopPosition ()
463 Position p = position_stack.Pop ();
465 reader.Position = p.position;
466 ref_line = p.ref_line;
469 hidden_block_start = p.hidden;
470 putback_char = p.putback_char;
471 previous_col = p.previous_col;
473 parsing_generic_less_than = p.parsing_generic_less_than;
474 current_token = p.current_token;
478 // Do not reset the position, ignore it.
479 public void DiscardPosition ()
481 position_stack.Pop ();
484 static void AddKeyword (string kw, int token)
486 keyword_strings.Add (kw);
488 AddKeyword (keywords, kw, token);
491 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
493 AddKeyword (keywords_preprocessor, kw, directive);
496 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
498 int length = kw.Length;
499 if (keywords[length] == null) {
500 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
503 int char_index = kw[0] - '_';
504 var kwe = keywords[length][char_index];
506 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
510 while (kwe.Next != null) {
514 kwe.Next = new KeywordEntry<T> (kw, token);
522 keyword_strings = new HashSet<string> ();
524 // 11 is the length of the longest keyword for now
525 keywords = new KeywordEntry<int>[11][];
527 AddKeyword ("__arglist", Token.ARGLIST);
528 AddKeyword ("__makeref", Token.MAKEREF);
529 AddKeyword ("__reftype", Token.REFTYPE);
530 AddKeyword ("__refvalue", Token.REFVALUE);
531 AddKeyword ("abstract", Token.ABSTRACT);
532 AddKeyword ("as", Token.AS);
533 AddKeyword ("add", Token.ADD);
534 AddKeyword ("base", Token.BASE);
535 AddKeyword ("bool", Token.BOOL);
536 AddKeyword ("break", Token.BREAK);
537 AddKeyword ("byte", Token.BYTE);
538 AddKeyword ("case", Token.CASE);
539 AddKeyword ("catch", Token.CATCH);
540 AddKeyword ("char", Token.CHAR);
541 AddKeyword ("checked", Token.CHECKED);
542 AddKeyword ("class", Token.CLASS);
543 AddKeyword ("const", Token.CONST);
544 AddKeyword ("continue", Token.CONTINUE);
545 AddKeyword ("decimal", Token.DECIMAL);
546 AddKeyword ("default", Token.DEFAULT);
547 AddKeyword ("delegate", Token.DELEGATE);
548 AddKeyword ("do", Token.DO);
549 AddKeyword ("double", Token.DOUBLE);
550 AddKeyword ("else", Token.ELSE);
551 AddKeyword ("enum", Token.ENUM);
552 AddKeyword ("event", Token.EVENT);
553 AddKeyword ("explicit", Token.EXPLICIT);
554 AddKeyword ("extern", Token.EXTERN);
555 AddKeyword ("false", Token.FALSE);
556 AddKeyword ("finally", Token.FINALLY);
557 AddKeyword ("fixed", Token.FIXED);
558 AddKeyword ("float", Token.FLOAT);
559 AddKeyword ("for", Token.FOR);
560 AddKeyword ("foreach", Token.FOREACH);
561 AddKeyword ("goto", Token.GOTO);
562 AddKeyword ("get", Token.GET);
563 AddKeyword ("if", Token.IF);
564 AddKeyword ("implicit", Token.IMPLICIT);
565 AddKeyword ("in", Token.IN);
566 AddKeyword ("int", Token.INT);
567 AddKeyword ("interface", Token.INTERFACE);
568 AddKeyword ("internal", Token.INTERNAL);
569 AddKeyword ("is", Token.IS);
570 AddKeyword ("lock", Token.LOCK);
571 AddKeyword ("long", Token.LONG);
572 AddKeyword ("namespace", Token.NAMESPACE);
573 AddKeyword ("new", Token.NEW);
574 AddKeyword ("null", Token.NULL);
575 AddKeyword ("object", Token.OBJECT);
576 AddKeyword ("operator", Token.OPERATOR);
577 AddKeyword ("out", Token.OUT);
578 AddKeyword ("override", Token.OVERRIDE);
579 AddKeyword ("params", Token.PARAMS);
580 AddKeyword ("private", Token.PRIVATE);
581 AddKeyword ("protected", Token.PROTECTED);
582 AddKeyword ("public", Token.PUBLIC);
583 AddKeyword ("readonly", Token.READONLY);
584 AddKeyword ("ref", Token.REF);
585 AddKeyword ("remove", Token.REMOVE);
586 AddKeyword ("return", Token.RETURN);
587 AddKeyword ("sbyte", Token.SBYTE);
588 AddKeyword ("sealed", Token.SEALED);
589 AddKeyword ("set", Token.SET);
590 AddKeyword ("short", Token.SHORT);
591 AddKeyword ("sizeof", Token.SIZEOF);
592 AddKeyword ("stackalloc", Token.STACKALLOC);
593 AddKeyword ("static", Token.STATIC);
594 AddKeyword ("string", Token.STRING);
595 AddKeyword ("struct", Token.STRUCT);
596 AddKeyword ("switch", Token.SWITCH);
597 AddKeyword ("this", Token.THIS);
598 AddKeyword ("throw", Token.THROW);
599 AddKeyword ("true", Token.TRUE);
600 AddKeyword ("try", Token.TRY);
601 AddKeyword ("typeof", Token.TYPEOF);
602 AddKeyword ("uint", Token.UINT);
603 AddKeyword ("ulong", Token.ULONG);
604 AddKeyword ("unchecked", Token.UNCHECKED);
605 AddKeyword ("unsafe", Token.UNSAFE);
606 AddKeyword ("ushort", Token.USHORT);
607 AddKeyword ("using", Token.USING);
608 AddKeyword ("virtual", Token.VIRTUAL);
609 AddKeyword ("void", Token.VOID);
610 AddKeyword ("volatile", Token.VOLATILE);
611 AddKeyword ("while", Token.WHILE);
612 AddKeyword ("partial", Token.PARTIAL);
613 AddKeyword ("where", Token.WHERE);
616 AddKeyword ("from", Token.FROM);
617 AddKeyword ("join", Token.JOIN);
618 AddKeyword ("on", Token.ON);
619 AddKeyword ("equals", Token.EQUALS);
620 AddKeyword ("select", Token.SELECT);
621 AddKeyword ("group", Token.GROUP);
622 AddKeyword ("by", Token.BY);
623 AddKeyword ("let", Token.LET);
624 AddKeyword ("orderby", Token.ORDERBY);
625 AddKeyword ("ascending", Token.ASCENDING);
626 AddKeyword ("descending", Token.DESCENDING);
627 AddKeyword ("into", Token.INTO);
629 // Contextual async keywords
630 AddKeyword ("async", Token.ASYNC);
631 AddKeyword ("await", Token.AWAIT);
633 // Contextual filter catch keyword
634 AddKeyword ("when", Token.WHEN);
636 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
638 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
639 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
640 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
641 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
642 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
643 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
644 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
645 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
646 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
647 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
648 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
649 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
651 csharp_format_info = NumberFormatInfo.InvariantInfo;
652 styles = NumberStyles.Float;
655 int GetKeyword (char[] id, int id_len)
658 // Keywords are stored in an array of arrays grouped by their
659 // length and then by the first character
661 if (id_len >= keywords.Length || keywords [id_len] == null)
664 int first_index = id [0] - '_';
665 if (first_index > 'z' - '_')
668 var kwe = keywords [id_len] [first_index];
675 for (int i = 1; i < id_len; ++i) {
676 if (id [i] != kwe.Value [i]) {
682 } while (res == 0 && kwe != null);
696 if (!handle_remove_add)
700 if (parsing_declaration == 0)
701 res = Token.EXTERN_ALIAS;
704 if (peek_token () == Token.COLON) {
706 res = Token.DEFAULT_COLON;
710 if (current_token != Token.CATCH && !parsing_catch_when)
714 if (!(handle_where && current_token != Token.COLON) && !query_parsing)
719 // A query expression is any expression that starts with `from identifier'
720 // followed by any token except ; , =
722 if (!query_parsing) {
723 if (lambda_arguments_parsing || parsing_block == 0) {
729 // HACK: to disable generics micro-parser, because PushPosition does not
730 // store identifiers array
731 parsing_generic_less_than = 1;
733 case Token.IDENTIFIER:
746 next_token = xtoken ();
747 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
750 res = Token.FROM_FIRST;
751 query_parsing = true;
752 if (context.Settings.Version <= LanguageVersion.ISO_2)
753 Report.FeatureIsNotAvailable (context, Location, "query expressions");
756 Expression.Error_VoidInvalidInTheContext (Location, Report);
760 // HACK: A token is not a keyword so we need to restore identifiers buffer
761 // which has been overwritten before we grabbed the identifier
762 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
776 case Token.ASCENDING:
777 case Token.DESCENDING:
784 case Token.NAMESPACE:
785 // TODO: some explanation needed
786 check_incorrect_doc_comment ();
787 parsing_modifiers = false;
791 if (parsing_block > 0) {
796 // Save current position and parse next token.
799 next_token = token ();
800 bool ok = (next_token == Token.CLASS) ||
801 (next_token == Token.STRUCT) ||
802 (next_token == Token.INTERFACE) ||
803 (next_token == Token.VOID);
808 if (next_token == Token.VOID) {
809 if (context.Settings.Version <= LanguageVersion.ISO_2)
810 Report.FeatureIsNotAvailable (context, Location, "partial methods");
811 } else if (context.Settings.Version == LanguageVersion.ISO_1)
812 Report.FeatureIsNotAvailable (context, Location, "partial types");
817 if (next_token < Token.LAST_KEYWORD) {
818 Report.Error (267, Location,
819 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
823 // HACK: A token is not a keyword so we need to restore identifiers buffer
824 // which has been overwritten before we grabbed the identifier
836 if (parsing_modifiers) {
838 // Skip attributes section or constructor called async
840 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
845 } else if (parsing_block > 0) {
846 switch (peek_token ()) {
848 case Token.OPEN_PARENS_LAMBDA:
851 case Token.IDENTIFIER:
854 if (xtoken () != Token.ARROW) {
862 // peek_token could overwrite id_buffer
863 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
871 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
872 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
878 if (parsing_block == 0)
888 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
891 // Keywords are stored in an array of arrays grouped by their
892 // length and then by the first character
894 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
895 return PreprocessorDirective.Invalid;
897 int first_index = id[0] - '_';
898 if (first_index > 'z' - '_')
899 return PreprocessorDirective.Invalid;
901 var kwe = keywords_preprocessor[id_len][first_index];
903 return PreprocessorDirective.Invalid;
905 PreprocessorDirective res = PreprocessorDirective.Invalid;
908 for (int i = 1; i < id_len; ++i) {
909 if (id[i] != kwe.Value[i]) {
915 } while (res == PreprocessorDirective.Invalid && kwe != null);
920 public Location Location {
922 return new Location (current_source, ref_line, col);
926 static bool is_identifier_start_character (int c)
928 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
931 static bool is_identifier_part_character (char c)
933 if (c >= 'a' && c <= 'z')
936 if (c >= 'A' && c <= 'Z')
939 if (c == '_' || (c >= '0' && c <= '9'))
945 return is_identifier_part_character_slow_part (c);
948 static bool is_identifier_part_character_slow_part (char c)
950 if (Char.IsLetter (c))
953 switch (Char.GetUnicodeCategory (c)) {
954 case UnicodeCategory.ConnectorPunctuation:
956 // combining-character: A Unicode character of classes Mn or Mc
957 case UnicodeCategory.NonSpacingMark:
958 case UnicodeCategory.SpacingCombiningMark:
960 // decimal-digit-character: A Unicode character of the class Nd
961 case UnicodeCategory.DecimalDigitNumber:
968 public static bool IsKeyword (string s)
970 return keyword_strings.Contains (s);
974 // Open parens micro parser. Detects both lambda and cast ambiguity.
976 int TokenizeOpenParens ()
981 int bracket_level = 0;
982 bool is_type = false;
983 bool can_be_type = false;
986 ptoken = current_token;
989 switch (current_token) {
990 case Token.CLOSE_PARENS:
994 // Expression inside parens is lambda, (int i) =>
996 if (current_token == Token.ARROW)
997 return Token.OPEN_PARENS_LAMBDA;
1000 // Expression inside parens is single type, (int[])
1003 if (current_token == Token.SEMICOLON)
1004 return Token.OPEN_PARENS;
1006 return Token.OPEN_PARENS_CAST;
1010 // Expression is possible cast, look at next token, (T)null
1013 switch (current_token) {
1014 case Token.OPEN_PARENS:
1017 case Token.IDENTIFIER:
1021 case Token.DELEGATE:
1031 case Token.UNCHECKED:
1037 // These can be part of a member access
1052 return Token.OPEN_PARENS_CAST;
1055 return Token.OPEN_PARENS;
1058 case Token.DOUBLE_COLON:
1059 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1064 case Token.IDENTIFIER:
1068 if (bracket_level == 0) {
1074 case Token.OP_GENERICS_LT:
1076 case Token.DOUBLE_COLON:
1078 if (bracket_level == 0)
1082 can_be_type = is_type = false;
1102 if (bracket_level == 0)
1107 if (bracket_level == 0) {
1108 bracket_level = 100;
1109 can_be_type = is_type = false;
1113 case Token.OP_GENERICS_LT:
1114 case Token.OPEN_BRACKET:
1115 if (bracket_level++ == 0)
1119 case Token.OP_GENERICS_GT:
1120 case Token.CLOSE_BRACKET:
1124 case Token.INTERR_NULLABLE:
1126 if (bracket_level == 0)
1132 can_be_type = is_type = false;
1136 return Token.OPEN_PARENS;
1141 public static bool IsValidIdentifier (string s)
1143 if (s == null || s.Length == 0)
1146 if (!is_identifier_start_character (s [0]))
1149 for (int i = 1; i < s.Length; i ++)
1150 if (! is_identifier_part_character (s [i]))
1156 bool parse_less_than (ref int genericDimension)
1159 int the_token = token ();
1160 if (the_token == Token.OPEN_BRACKET) {
1162 the_token = token ();
1163 if (the_token == Token.EOF)
1166 if (the_token == Token.CLOSE_BRACKET)
1169 the_token = token ();
1170 } else if (the_token == Token.IN || the_token == Token.OUT) {
1171 the_token = token ();
1173 switch (the_token) {
1174 case Token.IDENTIFIER:
1192 case Token.OP_GENERICS_GT:
1193 genericDimension = 1;
1201 the_token = token ();
1202 } while (the_token == Token.COMMA);
1204 if (the_token == Token.OP_GENERICS_GT) {
1214 the_token = token ();
1216 if (the_token == Token.OP_GENERICS_GT)
1218 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1220 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1222 else if (the_token == Token.OP_GENERICS_LT) {
1223 if (!parse_less_than (ref genericDimension))
1226 } else if (the_token == Token.OPEN_BRACKET) {
1228 the_token = token ();
1229 if (the_token == Token.CLOSE_BRACKET)
1231 else if (the_token == Token.COMMA)
1232 goto rank_specifiers;
1239 public int peek_token ()
1244 the_token = token ();
1251 // Tonizes `?' using custom disambiguous rules to return one
1252 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1254 // Tricky expression looks like:
1256 // Foo ? a = x ? b : c;
1258 int TokenizePossibleNullableType ()
1260 if (parsing_block == 0 || parsing_type > 0)
1261 return Token.INTERR_NULLABLE;
1263 int d = peek_char ();
1266 return Token.OP_COALESCING;
1270 return Token.INTERR_OPERATOR;
1274 if (d == ',' || d == ';' || d == '>')
1275 return Token.INTERR_NULLABLE;
1276 if (d == '*' || (d >= '0' && d <= '9'))
1277 return Token.INTERR;
1281 current_token = Token.NONE;
1290 case Token.OPEN_BRACKET_EXPR:
1291 next_token = Token.INTERR_OPERATOR;
1299 next_token = Token.INTERR;
1302 case Token.SEMICOLON:
1304 case Token.CLOSE_PARENS:
1305 case Token.OPEN_BRACKET:
1306 case Token.OP_GENERICS_GT:
1308 case Token.OP_COALESCING:
1310 next_token = Token.INTERR_NULLABLE;
1313 case Token.OPEN_PARENS:
1314 case Token.OPEN_PARENS_CAST:
1315 case Token.OPEN_PARENS_LAMBDA:
1320 case Token.OP_GENERICS_LT:
1321 case Token.OP_GENERICS_LT_DECL:
1322 case Token.GENERIC_DIMENSION:
1332 if (next_token == -1) {
1333 switch (xtoken ()) {
1335 case Token.SEMICOLON:
1336 case Token.OPEN_BRACE:
1338 next_token = Token.INTERR_NULLABLE;
1342 next_token = Token.INTERR;
1345 case Token.OPEN_PARENS:
1346 case Token.OPEN_PARENS_CAST:
1347 case Token.OPEN_PARENS_LAMBDA:
1351 case Token.OPEN_BRACKET:
1352 case Token.OPEN_BRACKET_EXPR:
1356 case Token.CLOSE_PARENS:
1360 case Token.OP_GENERICS_LT:
1361 case Token.OP_GENERICS_LT_DECL:
1362 case Token.GENERIC_DIMENSION:
1372 // All shorcuts failed, do it hard way
1374 while ((ntoken = xtoken ()) != Token.EOF) {
1376 case Token.OPEN_BRACE:
1379 case Token.OPEN_PARENS:
1380 case Token.OPEN_PARENS_CAST:
1381 case Token.OPEN_PARENS_LAMBDA:
1384 case Token.CLOSE_BRACE:
1387 case Token.OP_GENERICS_LT:
1388 case Token.OP_GENERICS_LT_DECL:
1389 case Token.GENERIC_DIMENSION:
1392 case Token.OPEN_BRACKET:
1393 case Token.OPEN_BRACKET_EXPR:
1396 case Token.CLOSE_BRACKET:
1399 case Token.CLOSE_PARENS:
1406 return Token.INTERR_NULLABLE;
1408 case Token.OP_GENERICS_GT:
1415 return Token.INTERR_NULLABLE;
1421 if (ntoken == Token.SEMICOLON)
1427 if (ntoken == Token.COMMA) {
1428 if (generics != 0 || brackets != 0)
1432 return Token.INTERR_NULLABLE;
1435 if (ntoken == Token.COLON) {
1436 if (++colons == interrs)
1441 if (ntoken == Token.INTERR) {
1447 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1456 bool decimal_digits (int c)
1459 bool seen_digits = false;
1462 if (number_pos == MaxNumberLength)
1463 Error_NumericConstantTooLong ();
1464 number_builder [number_pos++] = (char) c;
1468 // We use peek_char2, because decimal_digits needs to do a
1469 // 2-character look-ahead (5.ToString for example).
1471 while ((d = peek_char2 ()) != -1){
1472 if (d >= '0' && d <= '9'){
1473 if (number_pos == MaxNumberLength)
1474 Error_NumericConstantTooLong ();
1475 number_builder [number_pos++] = (char) d;
1485 static bool is_hex (int e)
1487 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1490 static TypeCode real_type_suffix (int c)
1494 return TypeCode.Single;
1496 return TypeCode.Double;
1498 return TypeCode.Decimal;
1500 return TypeCode.Empty;
1504 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1506 bool is_unsigned = false;
1507 bool is_long = false;
1510 bool scanning = true;
1523 // if we have not seen anything in between
1524 // report this error
1526 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1546 if (is_long && is_unsigned){
1547 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1551 // uint if possible, or ulong else.
1553 if ((ul & 0xffffffff00000000) == 0)
1554 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1556 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1557 } else if (is_long){
1558 // long if possible, ulong otherwise
1559 if ((ul & 0x8000000000000000) != 0)
1560 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1562 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1564 // int, uint, long or ulong in that order
1565 if ((ul & 0xffffffff00000000) == 0){
1566 uint ui = (uint) ul;
1568 if ((ui & 0x80000000) != 0)
1569 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1571 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1573 if ((ul & 0x8000000000000000) != 0)
1574 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1576 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1582 // given `c' as the next char in the input decide whether
1583 // we need to convert to a special type, and then choose
1584 // the best representation for the integer
1586 ILiteralConstant adjust_int (int c, Location loc)
1589 if (number_pos > 9){
1590 ulong ul = (uint) (number_builder [0] - '0');
1592 for (int i = 1; i < number_pos; i++){
1593 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1596 return integer_type_suffix (ul, c, loc);
1598 uint ui = (uint) (number_builder [0] - '0');
1600 for (int i = 1; i < number_pos; i++){
1601 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1604 return integer_type_suffix (ui, c, loc);
1606 } catch (OverflowException) {
1607 Error_NumericConstantTooLong ();
1608 return new IntLiteral (context.BuiltinTypes, 0, loc);
1610 catch (FormatException) {
1611 Report.Error (1013, Location, "Invalid number");
1612 return new IntLiteral (context.BuiltinTypes, 0, loc);
1616 ILiteralConstant adjust_real (TypeCode t, Location loc)
1618 string s = new string (number_builder, 0, number_pos);
1619 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1622 case TypeCode.Decimal:
1624 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1625 } catch (OverflowException) {
1626 Report.Error (594, Location, error_details, "decimal");
1627 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1629 case TypeCode.Single:
1631 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1632 } catch (OverflowException) {
1633 Report.Error (594, Location, error_details, "float");
1634 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1638 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1639 } catch (OverflowException) {
1640 Report.Error (594, loc, error_details, "double");
1641 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1646 ILiteralConstant handle_hex (Location loc)
1652 while ((d = peek_char ()) != -1){
1654 number_builder [number_pos++] = (char) d;
1660 string s = new String (number_builder, 0, number_pos);
1663 if (number_pos <= 8)
1664 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1666 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1668 return integer_type_suffix (ul, peek_char (), loc);
1669 } catch (OverflowException){
1670 Error_NumericConstantTooLong ();
1671 return new IntLiteral (context.BuiltinTypes, 0, loc);
1673 catch (FormatException) {
1674 Report.Error (1013, Location, "Invalid number");
1675 return new IntLiteral (context.BuiltinTypes, 0, loc);
1680 // Invoked if we know we have .digits or digits
1682 int is_number (int c, bool dotLead)
1684 ILiteralConstant res;
1687 int read_start = reader.Position - 1;
1690 // Caller did peek_char
1700 int peek = peek_char ();
1702 if (peek == 'x' || peek == 'X') {
1703 val = res = handle_hex (loc);
1705 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1708 return Token.LITERAL;
1716 // We need to handle the case of
1717 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1719 bool is_real = false;
1724 if (decimal_digits ('.')){
1730 val = res = adjust_int (-1, loc);
1733 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1735 return Token.LITERAL;
1739 if (c == 'e' || c == 'E'){
1742 if (number_pos == MaxNumberLength)
1743 Error_NumericConstantTooLong ();
1744 number_builder [number_pos++] = (char) c;
1748 if (number_pos == MaxNumberLength)
1749 Error_NumericConstantTooLong ();
1750 number_builder [number_pos++] = '+';
1752 } else if (c == '-') {
1753 if (number_pos == MaxNumberLength)
1754 Error_NumericConstantTooLong ();
1755 number_builder [number_pos++] = '-';
1758 if (number_pos == MaxNumberLength)
1759 Error_NumericConstantTooLong ();
1760 number_builder [number_pos++] = '+';
1767 var type = real_type_suffix (c);
1768 if (type == TypeCode.Empty && !is_real) {
1769 res = adjust_int (c, loc);
1773 if (type != TypeCode.Empty) {
1777 res = adjust_real (type, loc);
1783 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1784 if (chars[chars.Length - 1] == '\r')
1785 Array.Resize (ref chars, chars.Length - 1);
1786 res.ParsedValue = chars;
1789 return Token.LITERAL;
1793 // Accepts exactly count (4 or 8) hex, no more no less
1795 int getHex (int count, out int surrogate, out bool error)
1800 int top = count != -1 ? count : 4;
1805 for (i = 0; i < top; i++){
1808 if (c >= '0' && c <= '9')
1809 c = (int) c - (int) '0';
1810 else if (c >= 'A' && c <= 'F')
1811 c = (int) c - (int) 'A' + 10;
1812 else if (c >= 'a' && c <= 'f')
1813 c = (int) c - (int) 'a' + 10;
1819 total = (total * 16) + c;
1821 int p = peek_char ();
1824 if (!is_hex ((char)p))
1830 if (total > 0x0010FFFF) {
1835 if (total >= 0x00010000) {
1836 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1837 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1844 int escape (int c, out int surrogate)
1880 v = getHex (-1, out surrogate, out error);
1886 return EscapeUnicode (d, out surrogate);
1889 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1898 int EscapeUnicode (int ch, out int surrogate)
1902 ch = getHex (8, out surrogate, out error);
1904 ch = getHex (4, out surrogate, out error);
1908 Report.Error (1009, Location, "Unrecognized escape sequence");
1916 if (putback_char != -1) {
1925 if (peek_char () == '\n') {
1931 } else if (x == '\n') {
1936 } else if (x >= UnicodeLS && x <= UnicodePS) {
1945 void advance_line ()
1955 if (putback_char == -1)
1956 putback_char = reader.Read ();
1957 return putback_char;
1962 if (putback_char != -1)
1963 return putback_char;
1964 return reader.Peek ();
1967 public void putback (int c)
1969 if (putback_char != -1) {
1970 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
1973 if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
1974 // It won't happen though.
1984 public bool advance ()
1986 return peek_char () != -1 || CompleteOnEOF;
1989 public Object Value {
1995 public Object value ()
2002 current_token = xtoken ();
2003 return current_token;
2006 int TokenizePreprocessorKeyword (out int c)
2008 // skip over white space
2011 } while (c == ' ' || c == '\t');
2015 while (c != -1 && c >= 'a' && c <= 'z') {
2016 id_builder[pos++] = (char) c;
2019 int peek = peek_char ();
2020 if (peek == 'U' || peek == 'u') {
2022 c = EscapeUnicode (c, out surrogate);
2023 if (surrogate != 0) {
2024 if (is_identifier_part_character ((char) c)) {
2025 id_builder[pos++] = (char) c;
2036 PreprocessorDirective get_cmd_arg (out string arg)
2040 tokens_seen = false;
2043 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2045 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2048 // skip over white space
2049 while (c == ' ' || c == '\t')
2052 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2055 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2056 if (c == '\\' && has_identifier_argument >= 0) {
2057 if (has_identifier_argument != 0) {
2058 has_identifier_argument = 1;
2060 int peek = peek_char ();
2061 if (peek == 'U' || peek == 'u') {
2063 c = EscapeUnicode (c, out surrogate);
2064 if (surrogate != 0) {
2065 if (is_identifier_part_character ((char) c)) {
2066 if (pos == value_builder.Length)
2067 Array.Resize (ref value_builder, pos * 2);
2069 value_builder[pos++] = (char) c;
2075 has_identifier_argument = -1;
2077 } else if (c == '/' && peek_char () == '/') {
2079 // Eat single-line comments
2086 if (pos == value_builder.Length)
2087 Array.Resize (ref value_builder, pos * 2);
2089 value_builder[pos++] = (char) c;
2094 if (pos > MaxIdentifierLength)
2095 arg = new string (value_builder, 0, pos);
2097 arg = InternIdentifier (value_builder, pos);
2099 // Eat any trailing whitespaces
2100 arg = arg.Trim (simple_whitespaces);
2107 // Handles the #line directive
2109 bool PreProcessLine ()
2111 Location loc = Location;
2115 int length = TokenizePreprocessorKeyword (out c);
2116 if (length == line_default.Length) {
2117 if (!IsTokenIdentifierEqual (line_default))
2120 current_source = source_file.SourceFile;
2121 if (!hidden_block_start.IsNull) {
2122 current_source.RegisterHiddenScope (hidden_block_start, loc);
2123 hidden_block_start = Location.Null;
2130 if (length == line_hidden.Length) {
2131 if (!IsTokenIdentifierEqual (line_hidden))
2134 if (hidden_block_start.IsNull)
2135 hidden_block_start = loc;
2140 if (length != 0 || c < '0' || c > '9') {
2142 // Eat any remaining characters to continue parsing on next line
2148 int new_line = TokenizeNumber (c);
2151 // Eat any remaining characters to continue parsing on next line
2154 return new_line != 0;
2159 // skip over white space
2162 } while (c == ' ' || c == '\t');
2163 } else if (c == '"') {
2167 if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2169 // Eat any remaining characters to continue parsing on next line
2173 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2177 string new_file_name = null;
2179 new_file_name = TokenizeFileName (ref c);
2181 // skip over white space
2182 while (c == ' ' || c == '\t') {
2187 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2189 } else if (c == '/') {
2190 ReadSingleLineComment ();
2193 // Eat any remaining characters to continue parsing on next line
2197 Error_EndLineExpected ();
2201 if (new_file_name != null) {
2202 current_source = context.LookupFile (source_file, new_file_name);
2203 source_file.AddIncludeFile (current_source);
2206 if (!hidden_block_start.IsNull) {
2207 current_source.RegisterHiddenScope (hidden_block_start, loc);
2208 hidden_block_start = Location.Null;
2211 ref_line = new_line;
2216 // Handles #define and #undef
2218 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2220 if (ident.Length == 0 || ident == "true" || ident == "false"){
2221 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2225 if (ident.IndexOfAny (simple_whitespaces) != -1){
2226 Error_EndLineExpected ();
2230 if (!is_identifier_start_character (ident [0]))
2231 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2233 foreach (char c in ident.Substring (1)){
2234 if (!is_identifier_part_character (c)){
2235 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2240 if (!caller_is_taking)
2247 if (context.Settings.IsConditionalSymbolDefined (ident))
2250 source_file.AddDefine (ident);
2255 source_file.AddUndefine (ident);
2259 byte read_hex (out bool error)
2262 int c = get_char ();
2264 if ((c >= '0') && (c <= '9'))
2265 total = (int) c - (int) '0';
2266 else if ((c >= 'A') && (c <= 'F'))
2267 total = (int) c - (int) 'A' + 10;
2268 else if ((c >= 'a') && (c <= 'f'))
2269 total = (int) c - (int) 'a' + 10;
2278 if ((c >= '0') && (c <= '9'))
2279 total += (int) c - (int) '0';
2280 else if ((c >= 'A') && (c <= 'F'))
2281 total += (int) c - (int) 'A' + 10;
2282 else if ((c >= 'a') && (c <= 'f'))
2283 total += (int) c - (int) 'a' + 10;
2290 return (byte) total;
2294 // Parses #pragma checksum
2296 bool ParsePragmaChecksum ()
2299 // The syntax is ` "foo.txt" "{guid}" "hash"'
2301 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2303 int c = get_char ();
2308 string file_name = TokenizeFileName (ref c);
2310 // TODO: Any white-spaces count
2314 SourceFile file = context.LookupFile (source_file, file_name);
2316 if (get_char () != '"' || get_char () != '{')
2320 byte[] guid_bytes = new byte [16];
2323 for (; i < 4; i++) {
2324 guid_bytes [i] = read_hex (out error);
2329 if (get_char () != '-')
2332 for (; i < 10; i++) {
2333 guid_bytes [i] = read_hex (out error);
2337 guid_bytes [i++] = read_hex (out error);
2341 if (get_char () != '-')
2345 for (; i < 16; i++) {
2346 guid_bytes [i] = read_hex (out error);
2351 if (get_char () != '}' || get_char () != '"')
2354 // TODO: Any white-spaces count
2359 if (get_char () != '"')
2362 // Any length of checksum
2363 List<byte> checksum_bytes = new List<byte> (16);
2365 var checksum_location = Location;
2367 while (c != '"' && c != -1) {
2368 checksum_bytes.Add (read_hex (out error));
2376 ReadSingleLineComment ();
2377 } else if (get_char () != '"') {
2381 if (context.Settings.GenerateDebugInfo) {
2382 var chsum = checksum_bytes.ToArray ();
2384 if (file.HasChecksum) {
2385 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2386 // TODO: Report.SymbolRelatedToPreviousError
2387 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2391 file.SetChecksum (guid_bytes, chsum);
2392 current_source.AutoGenerated = true;
2398 bool IsTokenIdentifierEqual (char[] identifier)
2400 for (int i = 0; i < identifier.Length; ++i) {
2401 if (identifier[i] != id_builder[i])
2408 bool ScanClosingInterpolationBrace ()
2415 var c = reader.Read ();
2424 if (str_quote % 2 == 1) {
2430 } while (res == null);
2436 int TokenizeNumber (int value)
2440 decimal_digits (value);
2441 uint ui = (uint) (number_builder[0] - '0');
2444 for (int i = 1; i < number_pos; i++) {
2445 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2449 } catch (OverflowException) {
2450 Error_NumericConstantTooLong ();
2455 string TokenizeFileName (ref int c)
2457 var string_builder = new StringBuilder ();
2458 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2465 string_builder.Append ((char) c);
2468 if (string_builder.Length == 0) {
2469 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2473 return string_builder.ToString ();
2476 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2479 if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2482 if (c >= '0' && c <= '9') {
2484 number = TokenizeNumber (c);
2488 if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2489 return ReadPragmaWarningComment (c);
2493 // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2497 id_builder [pos++] = (char)c;
2498 while (c < MaxIdentifierLength) {
2500 id_builder [pos] = (char)c;
2502 if (c >= '0' && c <= '9') {
2503 if (pos == 6 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2504 // Recognize CSXXXX as C# XXXX warning
2507 for (int i = 0; i < 4; ++i) {
2508 var ch = id_builder [i + 2];
2509 if (ch < '0' || ch > '9') {
2514 number += (ch - '0') * pow;
2518 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2531 // skip over white space
2532 while (c == ' ' || c == '\t')
2539 // skip over white space
2540 while (c == ' ' || c == '\t')
2546 return ReadPragmaWarningComment (c);
2549 int ReadPragmaWarningComment (int c)
2552 ReadSingleLineComment ();
2554 Report.Warning (1692, 1, Location, "Invalid number");
2556 // Read everything till the end of the line or file
2563 void ReadToEndOfLine ()
2568 } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2571 void ReadSingleLineComment ()
2573 if (peek_char () != '/')
2574 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2576 // Read everything till the end of the line or file
2581 /// Handles #pragma directive
2583 void ParsePragmaDirective ()
2586 int length = TokenizePreprocessorKeyword (out c);
2587 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2588 length = TokenizePreprocessorKeyword (out c);
2591 // #pragma warning disable
2592 // #pragma warning restore
2594 if (length == pragma_warning_disable.Length) {
2595 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2596 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2597 // skip over white space
2598 while (c == ' ' || c == '\t')
2603 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2605 ReadSingleLineComment ();
2608 // Disable/Restore all warnings
2611 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2613 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2617 // Disable/Restore a warning or group of warnings
2621 bool identifier = false;
2622 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2625 // no-op, custom warnings cannot occur in mcs
2626 } else if (disable) {
2627 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2629 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2632 } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2639 Report.Warning (1634, 1, Location, "Expected disable or restore");
2641 // Eat any remaining characters on the line
2650 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2651 if (c != ' ' || !ParsePragmaChecksum ()) {
2652 Report.Warning (1695, 1, Location,
2653 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2659 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2661 // Eat any remaining characters on the line
2665 bool eval_val (string s)
2672 return source_file.IsConditionalDefined (s);
2675 bool pp_primary (ref string s)
2684 s = s.Substring (1);
2685 bool val = pp_expr (ref s, false);
2686 if (s.Length > 0 && s [0] == ')'){
2687 s = s.Substring (1);
2690 Error_InvalidDirective ();
2694 if (is_identifier_start_character (c)){
2700 if (is_identifier_part_character (c)){
2704 bool v = eval_val (s.Substring (0, j));
2705 s = s.Substring (j);
2708 bool vv = eval_val (s);
2713 Error_InvalidDirective ();
2717 bool pp_unary (ref string s)
2724 if (len > 1 && s [1] == '='){
2725 Error_InvalidDirective ();
2728 s = s.Substring (1);
2729 return ! pp_primary (ref s);
2731 return pp_primary (ref s);
2733 Error_InvalidDirective ();
2738 bool pp_eq (ref string s)
2740 bool va = pp_unary (ref s);
2746 if (len > 2 && s [1] == '='){
2747 s = s.Substring (2);
2748 return va == pp_unary (ref s);
2750 Error_InvalidDirective ();
2753 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2754 s = s.Substring (2);
2756 return va != pp_unary (ref s);
2765 bool pp_and (ref string s)
2767 bool va = pp_eq (ref s);
2773 if (len > 2 && s [1] == '&'){
2774 s = s.Substring (2);
2775 return (va & pp_and (ref s));
2777 Error_InvalidDirective ();
2786 // Evaluates an expression for `#if' or `#elif'
2788 bool pp_expr (ref string s, bool isTerm)
2790 bool va = pp_and (ref s);
2797 if (len > 2 && s [1] == '|'){
2798 s = s.Substring (2);
2799 return va | pp_expr (ref s, isTerm);
2801 Error_InvalidDirective ();
2806 Error_EndLineExpected ();
2814 bool eval (string s)
2816 bool v = pp_expr (ref s, true);
2825 void Error_NumericConstantTooLong ()
2827 Report.Error (1021, Location, "Integral constant is too large");
2830 void Error_InvalidDirective ()
2832 Report.Error (1517, Location, "Invalid preprocessor directive");
2835 void Error_UnexpectedDirective (string extra)
2839 "Unexpected processor directive ({0})", extra);
2842 void Error_TokensSeen ()
2844 Report.Error (1032, Location,
2845 "Cannot define or undefine preprocessor symbols after first token in file");
2848 void Eror_WrongPreprocessorLocation ()
2850 Report.Error (1040, Location,
2851 "Preprocessor directives must appear as the first non-whitespace character on a line");
2854 void Error_EndLineExpected ()
2856 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2860 // Raises a warning when tokenizer found documentation comment
2861 // on unexpected place
2863 void WarningMisplacedComment (Location loc)
2865 if (doc_state != XmlCommentState.Error) {
2866 doc_state = XmlCommentState.Error;
2867 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2872 // if true, then the code continues processing the code
2873 // if false, the code stays in a loop until another directive is
2875 // When caller_is_taking is false we ignore all directives except the ones
2876 // which can help us to identify where the #if block ends
2877 bool ParsePreprocessingDirective (bool caller_is_taking)
2880 bool region_directive = false;
2882 var directive = get_cmd_arg (out arg);
2885 // The first group of pre-processing instructions is always processed
2887 switch (directive) {
2888 case PreprocessorDirective.Region:
2889 region_directive = true;
2891 goto case PreprocessorDirective.If;
2893 case PreprocessorDirective.Endregion:
2894 if (ifstack == null || ifstack.Count == 0){
2895 Error_UnexpectedDirective ("no #region for this #endregion");
2898 int pop = ifstack.Pop ();
2900 if ((pop & REGION) == 0)
2901 Report.Error (1027, Location, "Expected `#endif' directive");
2903 return caller_is_taking;
2905 case PreprocessorDirective.If:
2906 if (ifstack == null)
2907 ifstack = new Stack<int> (2);
2909 int flags = region_directive ? REGION : 0;
2910 if (ifstack.Count == 0){
2911 flags |= PARENT_TAKING;
2913 int state = ifstack.Peek ();
2914 if ((state & TAKING) != 0) {
2915 flags |= PARENT_TAKING;
2919 if (eval (arg) && caller_is_taking) {
2920 ifstack.Push (flags | TAKING);
2923 ifstack.Push (flags);
2926 case PreprocessorDirective.Endif:
2927 if (ifstack == null || ifstack.Count == 0){
2928 Error_UnexpectedDirective ("no #if for this #endif");
2931 pop = ifstack.Pop ();
2933 if ((pop & REGION) != 0)
2934 Report.Error (1038, Location, "#endregion directive expected");
2936 if (arg.Length != 0) {
2937 Error_EndLineExpected ();
2940 if (ifstack.Count == 0)
2943 int state = ifstack.Peek ();
2944 return (state & TAKING) != 0;
2947 case PreprocessorDirective.Elif:
2948 if (ifstack == null || ifstack.Count == 0){
2949 Error_UnexpectedDirective ("no #if for this #elif");
2952 int state = ifstack.Pop ();
2954 if ((state & REGION) != 0) {
2955 Report.Error (1038, Location, "#endregion directive expected");
2959 if ((state & ELSE_SEEN) != 0){
2960 Error_UnexpectedDirective ("#elif not valid after #else");
2964 if ((state & TAKING) != 0) {
2969 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2970 ifstack.Push (state | TAKING);
2974 ifstack.Push (state);
2978 case PreprocessorDirective.Else:
2979 if (ifstack == null || ifstack.Count == 0){
2980 Error_UnexpectedDirective ("no #if for this #else");
2983 int state = ifstack.Peek ();
2985 if ((state & REGION) != 0) {
2986 Report.Error (1038, Location, "#endregion directive expected");
2990 if ((state & ELSE_SEEN) != 0){
2991 Error_UnexpectedDirective ("#else within #else");
2997 if (arg.Length != 0) {
2998 Error_EndLineExpected ();
3003 if ((state & PARENT_TAKING) != 0) {
3004 ret = (state & TAKING) == 0;
3012 ifstack.Push (state | ELSE_SEEN);
3016 case PreprocessorDirective.Define:
3017 if (any_token_seen){
3018 if (caller_is_taking)
3019 Error_TokensSeen ();
3020 return caller_is_taking;
3022 PreProcessDefinition (true, arg, caller_is_taking);
3023 return caller_is_taking;
3025 case PreprocessorDirective.Undef:
3026 if (any_token_seen){
3027 if (caller_is_taking)
3028 Error_TokensSeen ();
3029 return caller_is_taking;
3031 PreProcessDefinition (false, arg, caller_is_taking);
3032 return caller_is_taking;
3034 case PreprocessorDirective.Invalid:
3035 Report.Error (1024, Location, "Wrong preprocessor directive");
3040 // These are only processed if we are in a `taking' block
3042 if (!caller_is_taking)
3046 case PreprocessorDirective.Error:
3047 Report.Error (1029, Location, "#error: '{0}'", arg);
3050 case PreprocessorDirective.Warning:
3051 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3054 case PreprocessorDirective.Pragma:
3055 if (context.Settings.Version == LanguageVersion.ISO_1) {
3056 Report.FeatureIsNotAvailable (context, Location, "#pragma");
3059 ParsePragmaDirective ();
3062 case PreprocessorDirective.Line:
3063 Location loc = Location;
3064 if (!PreProcessLine ())
3065 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3067 return caller_is_taking;
3070 throw new NotImplementedException (directive.ToString ());
3073 int consume_string (bool quoted)
3077 Location start_location = Location;
3079 start_location = start_location - 1;
3082 int reader_pos = reader.Position;
3086 // Cannot use get_char because of \r in quoted strings
3087 if (putback_char != -1) {
3097 if (quoted && peek_char () == '"') {
3098 if (pos == value_builder.Length)
3099 Array.Resize (ref value_builder, pos * 2);
3101 value_builder[pos++] = (char) c;
3106 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3109 res.ParsedValue = quoted ?
3110 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3111 reader.ReadChars (reader_pos - 1, reader.Position);
3114 return Token.LITERAL;
3117 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3119 Report.Error (1010, Location, "Newline in constant");
3123 // Don't add \r to string literal
3124 if (pos > 1 && value_builder [pos - 1] == '\r')
3127 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3128 return Token.LITERAL;
3132 } else if (c == '\\' && !quoted) {
3135 c = escape (c, out surrogate);
3138 if (surrogate != 0) {
3139 if (pos == value_builder.Length)
3140 Array.Resize (ref value_builder, pos * 2);
3142 value_builder[pos++] = (char) c;
3145 } else if (c == -1) {
3146 Report.Error (1039, Location, "Unterminated string literal");
3152 if (pos == value_builder.Length)
3153 Array.Resize (ref value_builder, pos * 2);
3155 value_builder[pos++] = (char) c;
3159 private int consume_identifier (int s)
3161 int res = consume_identifier (s, false);
3163 if (doc_state == XmlCommentState.Allowed)
3164 doc_state = XmlCommentState.NotAllowed;
3169 int consume_identifier (int c, bool quoted)
3172 // This method is very performance sensitive. It accounts
3173 // for approximately 25% of all parser time
3183 c = escape (c, out surrogate);
3184 if (quoted || is_identifier_start_character (c)) {
3185 // it's added bellow
3186 } else if (surrogate != 0) {
3187 id_builder [pos++] = (char)c;
3190 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3195 id_builder [pos++] = (char) c;
3201 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3202 id_builder [pos++] = (char) c;
3209 c = escape (c, out surrogate);
3210 if (is_identifier_part_character ((char) c))
3211 id_builder[pos++] = (char) c;
3212 else if (surrogate != 0) {
3216 // TODO: Probably need more whitespace characters
3221 Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3228 } else if (is_identifier_part_character_slow_part ((char) c)) {
3229 id_builder [pos++] = (char) c;
3236 } catch (IndexOutOfRangeException) {
3237 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3245 // Optimization: avoids doing the keyword lookup
3246 // on uppercase letters
3248 if (id_builder [0] >= '_' && !quoted) {
3249 int keyword = GetKeyword (id_builder, pos);
3250 if (keyword != -1) {
3251 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3256 string s = InternIdentifier (id_builder, pos);
3257 val = ltb.Create (s, current_source, ref_line, column);
3258 if (quoted && parsing_attribute_section)
3259 AddEscapedIdentifier (((LocatedToken) val).Location);
3261 return Token.IDENTIFIER;
3264 string InternIdentifier (char[] charBuffer, int length)
3267 // Keep identifiers in an array of hashtables to avoid needless
3270 var identifiers_group = identifiers[length];
3272 if (identifiers_group != null) {
3273 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3277 // TODO: this should be number of files dependant
3278 // corlib compilation peaks at 1000 and System.Core at 150
3279 int capacity = length > 20 ? 10 : 100;
3280 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3281 identifiers[length] = identifiers_group;
3284 char[] chars = new char[length];
3285 Array.Copy (charBuffer, chars, length);
3287 s = new string (charBuffer, 0, length);
3288 identifiers_group.Add (chars, s);
3292 public int xtoken ()
3294 if (parsing_interpolation_format) {
3295 return TokenizeInterpolationFormat ();
3300 // Whether we have seen comments on the current line
3301 bool comments_seen = false;
3302 while ((c = get_char ()) != -1) {
3305 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3313 case 0xFEFF: // Ignore BOM anywhere in the file
3316 /* This is required for compatibility with .NET
3318 if (peek_char () == 0xBB) {
3321 if (get_char () == 0xBF)
3329 return consume_identifier (c);
3332 val = ltb.Create (current_source, ref_line, col);
3333 return Token.OPEN_BRACE;
3335 if (parsing_string_interpolation > 0) {
3336 if (peek_char () != '}') {
3337 --parsing_string_interpolation;
3338 return TokenizeInterpolatedString ();
3344 val = ltb.Create (current_source, ref_line, col);
3345 return Token.CLOSE_BRACE;
3347 // To block doccomment inside attribute declaration.
3348 if (doc_state == XmlCommentState.Allowed)
3349 doc_state = XmlCommentState.NotAllowed;
3351 val = ltb.Create (current_source, ref_line, col);
3353 if (parsing_block == 0 || lambda_arguments_parsing)
3354 return Token.OPEN_BRACKET;
3356 int next = peek_char ();
3360 return Token.OPEN_BRACKET;
3370 next = peek_token ();
3371 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3372 return Token.OPEN_BRACKET;
3374 return Token.OPEN_BRACKET_EXPR;
3376 return Token.OPEN_BRACKET_EXPR;
3379 ltb.CreateOptional (current_source, ref_line, col, ref val);
3380 return Token.CLOSE_BRACKET;
3382 val = ltb.Create (current_source, ref_line, col);
3384 // An expression versions of parens can appear in block context only
3386 if (parsing_block != 0 && !lambda_arguments_parsing) {
3389 // Optmize most common case where we know that parens
3392 switch (current_token) {
3393 case Token.IDENTIFIER:
3402 case Token.DELEGATE:
3403 case Token.OP_GENERICS_GT:
3404 return Token.OPEN_PARENS;
3407 // Optimize using peek
3408 int xx = peek_char ();
3415 return Token.OPEN_PARENS;
3418 lambda_arguments_parsing = true;
3420 d = TokenizeOpenParens ();
3422 lambda_arguments_parsing = false;
3426 return Token.OPEN_PARENS;
3428 ltb.CreateOptional (current_source, ref_line, col, ref val);
3429 return Token.CLOSE_PARENS;
3431 ltb.CreateOptional (current_source, ref_line, col, ref val);
3434 ltb.CreateOptional (current_source, ref_line, col, ref val);
3435 return Token.SEMICOLON;
3437 val = ltb.Create (current_source, ref_line, col);
3440 val = ltb.Create (current_source, ref_line, col);
3441 return TokenizePossibleNullableType ();
3443 val = ltb.Create (current_source, ref_line, col);
3444 if (parsing_generic_less_than++ > 0)
3445 return Token.OP_GENERICS_LT;
3447 return TokenizeLessThan ();
3450 val = ltb.Create (current_source, ref_line, col);
3458 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3459 parsing_generic_less_than--;
3460 return Token.OP_GENERICS_GT;
3469 return Token.OP_SHIFT_RIGHT_ASSIGN;
3471 return Token.OP_SHIFT_RIGHT;
3477 val = ltb.Create (current_source, ref_line, col);
3481 } else if (d == '=') {
3482 d = Token.OP_ADD_ASSIGN;
3490 val = ltb.Create (current_source, ref_line, col);
3494 } else if (d == '=')
3495 d = Token.OP_SUB_ASSIGN;
3505 val = ltb.Create (current_source, ref_line, col);
3506 if (peek_char () == '='){
3513 val = ltb.Create (current_source, ref_line, col);
3524 return Token.ASSIGN;
3527 val = ltb.Create (current_source, ref_line, col);
3531 return Token.OP_AND;
3535 return Token.OP_AND_ASSIGN;
3537 return Token.BITWISE_AND;
3540 val = ltb.Create (current_source, ref_line, col);
3548 return Token.OP_OR_ASSIGN;
3550 return Token.BITWISE_OR;
3553 val = ltb.Create (current_source, ref_line, col);
3554 if (peek_char () == '='){
3556 return Token.OP_MULT_ASSIGN;
3563 val = ltb.Create (current_source, ref_line, col);
3565 return Token.OP_DIV_ASSIGN;
3568 // Handle double-slash comments.
3570 if (parsing_string_interpolation > 0) {
3571 Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3576 if (doc_processing) {
3577 if (peek_char () == '/') {
3579 // Don't allow ////.
3580 if ((d = peek_char ()) != '/') {
3581 if (doc_state == XmlCommentState.Allowed)
3582 handle_one_line_xml_comment ();
3583 else if (doc_state == XmlCommentState.NotAllowed)
3584 WarningMisplacedComment (Location - 3);
3587 if (xml_comment_buffer.Length > 0)
3588 doc_state = XmlCommentState.NotAllowed;
3594 any_token_seen |= tokens_seen;
3595 tokens_seen = false;
3596 comments_seen = false;
3598 } else if (d == '*'){
3600 bool docAppend = false;
3601 if (doc_processing && peek_char () == '*') {
3603 // But when it is /**/, just do nothing.
3604 if (peek_char () == '/') {
3608 if (doc_state == XmlCommentState.Allowed)
3610 else if (doc_state == XmlCommentState.NotAllowed) {
3611 WarningMisplacedComment (Location - 2);
3615 int current_comment_start = 0;
3617 current_comment_start = xml_comment_buffer.Length;
3618 xml_comment_buffer.Append (Environment.NewLine);
3621 while ((d = get_char ()) != -1){
3622 if (d == '*' && peek_char () == '/'){
3624 comments_seen = true;
3628 xml_comment_buffer.Append ((char) d);
3630 if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3631 any_token_seen |= tokens_seen;
3632 tokens_seen = false;
3634 // Reset 'comments_seen' just to be consistent.
3635 // It doesn't matter either way, here.
3637 comments_seen = false;
3641 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3644 update_formatted_doc_comment (current_comment_start);
3647 val = ltb.Create (current_source, ref_line, col);
3651 val = ltb.Create (current_source, ref_line, col);
3652 if (peek_char () == '='){
3654 return Token.OP_MOD_ASSIGN;
3656 return Token.PERCENT;
3659 val = ltb.Create (current_source, ref_line, col);
3660 if (peek_char () == '='){
3662 return Token.OP_XOR_ASSIGN;
3664 return Token.CARRET;
3667 val = ltb.Create (current_source, ref_line, col);
3668 if (peek_char () == ':') {
3670 return Token.DOUBLE_COLON;
3674 case '0': case '1': case '2': case '3': case '4':
3675 case '5': case '6': case '7': case '8': case '9':
3677 return is_number (c, false);
3679 case '\n': // white space
3682 any_token_seen |= tokens_seen;
3683 tokens_seen = false;
3684 comments_seen = false;
3690 if (d >= '0' && d <= '9')
3691 return is_number (c, true);
3693 ltb.CreateOptional (current_source, ref_line, col, ref val);
3697 if (tokens_seen || comments_seen) {
3698 Eror_WrongPreprocessorLocation ();
3702 if (ParsePreprocessingDirective (true))
3705 bool directive_expected = false;
3706 while ((c = get_char ()) != -1) {
3708 directive_expected = true;
3709 } else if (!directive_expected) {
3710 // TODO: Implement comment support for disabled code and uncomment this code
3712 // Eror_WrongPreprocessorLocation ();
3713 // return Token.ERROR;
3718 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3722 if (ParsePreprocessingDirective (false))
3725 directive_expected = false;
3729 tokens_seen = false;
3736 if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3737 parsing_string_interpolation = 0;
3738 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3739 val = new StringLiteral (context.BuiltinTypes, "", Location);
3740 return Token.INTERPOLATED_STRING_END;
3743 return consume_string (false);
3746 return TokenizeBackslash ();
3752 return consume_string (true);
3755 if (is_identifier_start_character (c)){
3756 return consume_identifier (c, true);
3759 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3763 if (peek_char () == '"') {
3765 return TokenizeInterpolatedString ();
3769 case EvalStatementParserCharacter:
3770 return Token.EVAL_STATEMENT_PARSER;
3771 case EvalCompilationUnitParserCharacter:
3772 return Token.EVAL_COMPILATION_UNIT_PARSER;
3773 case EvalUsingDeclarationsParserCharacter:
3774 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3775 case DocumentationXref:
3776 return Token.DOC_SEE;
3779 if (is_identifier_start_character (c)) {
3781 return consume_identifier (c);
3784 if (char.IsWhiteSpace ((char) c))
3787 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3792 return Token.COMPLETE_COMPLETION;
3795 return Token.GENERATE_COMPLETION;
3802 int TokenizeBackslash ()
3805 int read_start = reader.Position;
3807 Location start_location = Location;
3808 int c = get_char ();
3811 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3812 Report.Error (1011, start_location, "Empty character literal");
3813 return Token.LITERAL;
3816 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3817 Report.Error (1010, start_location, "Newline in constant");
3822 c = escape (c, out d);
3826 throw new NotImplementedException ();
3828 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3833 Report.Error (1012, start_location, "Too many characters in character literal");
3835 // Try to recover, read until newline or next "'"
3836 while ((c = get_char ()) != -1) {
3837 if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3843 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3846 return Token.LITERAL;
3849 int TokenizeLessThan ()
3853 // Save current position and parse next token.
3855 int generic_dimension = 0;
3856 if (parse_less_than (ref generic_dimension)) {
3857 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3858 d = Token.OP_GENERICS_LT_DECL;
3860 if (generic_dimension > 0) {
3861 val = generic_dimension;
3863 return Token.GENERIC_DIMENSION;
3866 d = Token.OP_GENERICS_LT;
3873 parsing_generic_less_than = 0;
3882 return Token.OP_SHIFT_LEFT_ASSIGN;
3884 return Token.OP_SHIFT_LEFT;
3894 int TokenizeInterpolatedString ()
3897 var start_location = Location;
3900 var ch = get_char ();
3903 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3904 return Token.INTERPOLATED_STRING_END;
3906 if (peek_char () == '{') {
3907 value_builder [pos++] = (char)ch;
3912 ++parsing_string_interpolation;
3913 val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3914 return Token.INTERPOLATED_STRING;
3918 ch = escape (ch, out surrogate);
3922 if (ch == '{' || ch == '}') {
3923 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
3926 if (surrogate != 0) {
3927 if (pos == value_builder.Length)
3928 Array.Resize (ref value_builder, pos * 2);
3930 value_builder [pos++] = (char)ch;
3940 value_builder[pos++] = (char) ch;
3944 int TokenizeInterpolationFormat ()
3949 var ch = get_char ();
3958 Report.Error (8089, Location, "Empty interpolated expression format specifier");
3959 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
3960 Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
3963 val = CreateStringFromBuilder (pos);
3964 return Token.LITERAL;
3972 ch = escape (ch, out surrogate);
3976 if (ch == '{' || ch == '}') {
3977 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
3980 if (surrogate != 0) {
3981 if (pos == value_builder.Length)
3982 Array.Resize (ref value_builder, pos * 2);
3984 value_builder [pos++] = (char)ch;
3994 value_builder[pos++] = (char) ch;
3998 string CreateStringFromBuilder (int pos)
4001 return string.Empty;
4003 return InternIdentifier (value_builder, pos);
4005 return new string (value_builder, 0, pos);
4009 // Handles one line xml comment
4011 private void handle_one_line_xml_comment ()
4014 while ((c = peek_char ()) == ' ')
4015 get_char (); // skip heading whitespaces.
4016 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4017 xml_comment_buffer.Append ((char) get_char ());
4019 if (c == '\r' || c == '\n')
4020 xml_comment_buffer.Append (Environment.NewLine);
4024 // Remove heading "*" in Javadoc-like xml documentation.
4026 private void update_formatted_doc_comment (int current_comment_start)
4028 int length = xml_comment_buffer.Length - current_comment_start;
4029 string [] lines = xml_comment_buffer.ToString (
4030 current_comment_start,
4031 length).Replace ("\r", "").Split ('\n');
4033 // The first line starts with /**, thus it is not target
4034 // for the format check.
4035 for (int i = 1; i < lines.Length; i++) {
4036 string s = lines [i];
4037 int idx = s.IndexOf ('*');
4040 if (i < lines.Length - 1)
4044 head = s.Substring (0, idx);
4045 foreach (char c in head)
4048 lines [i] = s.Substring (idx + 1);
4050 xml_comment_buffer.Remove (current_comment_start, length);
4051 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4055 // Checks if there was incorrect doc comments and raise
4058 public void check_incorrect_doc_comment ()
4060 if (xml_comment_buffer.Length > 0)
4061 WarningMisplacedComment (Location);
4065 // Consumes the saved xml comment lines (if any)
4066 // as for current target member or type.
4068 public string consume_doc_comment ()
4070 if (xml_comment_buffer.Length > 0) {
4071 string ret = xml_comment_buffer.ToString ();
4072 reset_doc_comment ();
4078 void reset_doc_comment ()
4080 xml_comment_buffer.Length = 0;
4083 public void cleanup ()
4085 if (ifstack != null && ifstack.Count >= 1) {
4086 int state = ifstack.Pop ();
4087 if ((state & REGION) != 0)
4088 Report.Error (1038, Location, "#endregion directive expected");
4090 Report.Error (1027, Location, "Expected `#endif' directive");
4096 // Indicates whether it accepts XML documentation or not.
4098 public enum XmlCommentState {
4099 // comment is allowed in this state.
4101 // comment is not allowed in this state.
4103 // once comments appeared when it is NotAllowed, then the
4104 // state is changed to it, until the state is changed to