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 /// Tokenizer for C# source code.
28 public class Tokenizer : yyParser.yyInput
32 public readonly T Token;
33 public KeywordEntry<T> Next;
34 public readonly char[] Value;
36 public KeywordEntry (string value, T token)
38 this.Value = value.ToCharArray ();
43 sealed class IdentifiersComparer : IEqualityComparer<char[]>
47 public IdentifiersComparer (int length)
52 public bool Equals (char[] x, char[] y)
54 for (int i = 0; i < length; ++i)
61 public int GetHashCode (char[] obj)
64 for (int i = 0; i < length; ++i)
65 h = (h << 5) - h + obj [i];
72 // This class has to be used by parser only, it reuses token
73 // details after each file parse completion
75 public class LocatedToken
77 public int row, column;
79 public SourceFile file;
81 public LocatedToken ()
85 public LocatedToken (string value, Location loc)
88 file = loc.SourceFile;
93 public override string ToString ()
95 return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
98 public Location Location {
99 get { return new Location (file, row, column); }
102 public string Value {
103 get { return value; }
107 public class LocatedTokenBuffer
109 readonly LocatedToken[] buffer;
112 public LocatedTokenBuffer ()
114 buffer = new LocatedToken[0];
117 public LocatedTokenBuffer (LocatedToken[] buffer)
119 this.buffer = buffer ?? new LocatedToken[0];
122 public LocatedToken Create (SourceFile file, int row, int column)
124 return Create (null, file, row, column);
127 public LocatedToken Create (string value, SourceFile file, int row, int column)
130 // TODO: I am not very happy about the logic but it's the best
131 // what I could come up with for now.
132 // Ideally we should be using just tiny buffer (256 elements) which
133 // is enough to hold all details for currect stack and recycle elements
134 // poped from the stack but there is a trick needed to recycle
138 if (pos >= buffer.Length) {
139 entry = new LocatedToken ();
143 entry = new LocatedToken ();
152 entry.column = column;
157 // Used for token not required by expression evaluator
159 [Conditional ("FULL_AST")]
160 public void CreateOptional (SourceFile file, int row, int col, ref object token)
162 token = Create (file, row, col);
166 public enum PreprocessorDirective
172 If = 3 | RequiresArgument,
174 Elif = 5 | RequiresArgument,
176 Define = 7 | RequiresArgument,
177 Undef = 8 | RequiresArgument,
180 Pragma = 11 | CustomArgumentsParsing,
181 Line = 12 | CustomArgumentsParsing,
183 CustomArgumentsParsing = 1 << 10,
184 RequiresArgument = 1 << 11
187 readonly SeekableStreamReader reader;
188 readonly CompilationSourceFile source_file;
189 readonly CompilerContext context;
191 SourceFile current_source;
192 Location hidden_block_start;
198 readonly int tab_size;
199 bool handle_get_set = false;
200 bool handle_remove_add = false;
201 bool handle_where = false;
202 bool handle_typeof = false;
203 bool lambda_arguments_parsing;
204 List<Location> escaped_identifiers;
205 int parsing_generic_less_than;
206 readonly bool doc_processing;
207 readonly LocatedTokenBuffer ltb;
210 // Used mainly for parser optimizations. Some expressions for instance
211 // can appear only in block (including initializer, base initializer)
214 public int parsing_block;
215 internal bool query_parsing;
218 // When parsing type only, useful for ambiguous nullable types
220 public int parsing_type;
223 // Set when parsing generic declaration (type or method header)
225 public bool parsing_generic_declaration;
226 public bool parsing_generic_declaration_doc;
229 // The value indicates that we have not reach any declaration or
232 public int parsing_declaration;
234 public bool parsing_attribute_section;
236 public bool parsing_modifiers;
239 // The special characters to inject on streams to run the unit parser
240 // in the special expression mode. Using private characters from
241 // Plane Sixteen (U+100000 to U+10FFFD)
243 // This character is only tested just before the tokenizer is about to report
244 // an error; So on the regular operation mode, this addition will have no
245 // impact on the tokenizer's performance.
248 public const int EvalStatementParserCharacter = 0x100000;
249 public const int EvalCompilationUnitParserCharacter = 0x100001;
250 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
251 public const int DocumentationXref = 0x100003;
254 // XML documentation buffer. The save point is used to divide
255 // comments on types and comments on members.
257 StringBuilder xml_comment_buffer;
260 // See comment on XmlCommentState enumeration.
262 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
265 // Whether tokens have been seen on this line
267 bool tokens_seen = false;
270 // Set to true once the GENERATE_COMPLETION token has bee
271 // returned. This helps produce one GENERATE_COMPLETION,
272 // as many COMPLETE_COMPLETION as necessary to complete the
273 // AST tree and one final EOF.
278 // Whether a token has been seen on the file
279 // This is needed because `define' is not allowed to be used
280 // after a token has been seen.
287 static readonly KeywordEntry<int>[][] keywords;
288 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
289 static readonly HashSet<string> keyword_strings;
290 static readonly NumberStyles styles;
291 static readonly NumberFormatInfo csharp_format_info;
294 static readonly char[] pragma_warning = "warning".ToCharArray ();
295 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
296 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
297 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
298 static readonly char[] line_hidden = "hidden".ToCharArray ();
299 static readonly char[] line_default = "default".ToCharArray ();
301 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
303 public bool PropertyParsing {
304 get { return handle_get_set; }
305 set { handle_get_set = value; }
308 public bool EventParsing {
309 get { return handle_remove_add; }
310 set { handle_remove_add = value; }
313 public bool ConstraintsParsing {
314 get { return handle_where; }
315 set { handle_where = value; }
318 public bool TypeOfParsing {
319 get { return handle_typeof; }
320 set { handle_typeof = value; }
323 public XmlCommentState doc_state {
324 get { return xml_doc_state; }
326 if (value == XmlCommentState.Allowed) {
327 check_incorrect_doc_comment ();
328 reset_doc_comment ();
330 xml_doc_state = value;
335 // This is used to trigger completion generation on the parser
336 public bool CompleteOnEOF;
338 void AddEscapedIdentifier (Location loc)
340 if (escaped_identifiers == null)
341 escaped_identifiers = new List<Location> ();
343 escaped_identifiers.Add (loc);
346 public bool IsEscapedIdentifier (ATypeNameExpression name)
348 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
352 // Values for the associated token returned
354 internal int putback_char; // Used by repl only
360 const int TAKING = 1;
361 const int ELSE_SEEN = 4;
362 const int PARENT_TAKING = 8;
363 const int REGION = 16;
366 // pre-processor if stack state:
370 public const int MaxIdentifierLength = 512;
371 public const int MaxNumberLength = 512;
373 readonly char[] id_builder;
374 readonly Dictionary<char[], string>[] identifiers;
375 readonly char[] number_builder;
378 char[] value_builder = new char[64];
387 // This is used when the tokenizer needs to save
388 // the current position as it needs to do some parsing
389 // on its own to deamiguate a token in behalf of the
392 Stack<Position> position_stack = new Stack<Position> (2);
399 public Location hidden;
400 public int putback_char;
401 public int previous_col;
402 public Stack<int> ifstack;
403 public int parsing_generic_less_than;
404 public int current_token;
407 public Position (Tokenizer t)
409 position = t.reader.Position;
411 ref_line = t.ref_line;
413 hidden = t.hidden_block_start;
414 putback_char = t.putback_char;
415 previous_col = t.previous_col;
416 if (t.ifstack != null && t.ifstack.Count != 0) {
417 // There is no simple way to clone Stack<T> all
418 // methods reverse the order
419 var clone = t.ifstack.ToArray ();
420 Array.Reverse (clone);
421 ifstack = new Stack<int> (clone);
423 parsing_generic_less_than = t.parsing_generic_less_than;
424 current_token = t.current_token;
429 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session)
431 this.source_file = file;
432 this.context = file.Compiler;
433 this.current_source = file.SourceFile;
434 this.identifiers = session.Identifiers;
435 this.id_builder = session.IDBuilder;
436 this.number_builder = session.NumberBuilder;
437 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
443 xml_comment_buffer = new StringBuilder ();
444 doc_processing = context.Settings.DocumentationFile != null;
446 tab_size = context.Settings.TabSize;
449 public void PushPosition ()
451 position_stack.Push (new Position (this));
454 public void PopPosition ()
456 Position p = position_stack.Pop ();
458 reader.Position = p.position;
459 ref_line = p.ref_line;
462 hidden_block_start = p.hidden;
463 putback_char = p.putback_char;
464 previous_col = p.previous_col;
466 parsing_generic_less_than = p.parsing_generic_less_than;
467 current_token = p.current_token;
471 // Do not reset the position, ignore it.
472 public void DiscardPosition ()
474 position_stack.Pop ();
477 static void AddKeyword (string kw, int token)
479 keyword_strings.Add (kw);
481 AddKeyword (keywords, kw, token);
484 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
486 AddKeyword (keywords_preprocessor, kw, directive);
489 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
491 int length = kw.Length;
492 if (keywords[length] == null) {
493 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
496 int char_index = kw[0] - '_';
497 var kwe = keywords[length][char_index];
499 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
503 while (kwe.Next != null) {
507 kwe.Next = new KeywordEntry<T> (kw, token);
515 keyword_strings = new HashSet<string> ();
517 // 11 is the length of the longest keyword for now
518 keywords = new KeywordEntry<int>[11][];
520 AddKeyword ("__arglist", Token.ARGLIST);
521 AddKeyword ("__makeref", Token.MAKEREF);
522 AddKeyword ("__reftype", Token.REFTYPE);
523 AddKeyword ("__refvalue", Token.REFVALUE);
524 AddKeyword ("abstract", Token.ABSTRACT);
525 AddKeyword ("as", Token.AS);
526 AddKeyword ("add", Token.ADD);
527 AddKeyword ("base", Token.BASE);
528 AddKeyword ("bool", Token.BOOL);
529 AddKeyword ("break", Token.BREAK);
530 AddKeyword ("byte", Token.BYTE);
531 AddKeyword ("case", Token.CASE);
532 AddKeyword ("catch", Token.CATCH);
533 AddKeyword ("char", Token.CHAR);
534 AddKeyword ("checked", Token.CHECKED);
535 AddKeyword ("class", Token.CLASS);
536 AddKeyword ("const", Token.CONST);
537 AddKeyword ("continue", Token.CONTINUE);
538 AddKeyword ("decimal", Token.DECIMAL);
539 AddKeyword ("default", Token.DEFAULT);
540 AddKeyword ("delegate", Token.DELEGATE);
541 AddKeyword ("do", Token.DO);
542 AddKeyword ("double", Token.DOUBLE);
543 AddKeyword ("else", Token.ELSE);
544 AddKeyword ("enum", Token.ENUM);
545 AddKeyword ("event", Token.EVENT);
546 AddKeyword ("explicit", Token.EXPLICIT);
547 AddKeyword ("extern", Token.EXTERN);
548 AddKeyword ("false", Token.FALSE);
549 AddKeyword ("finally", Token.FINALLY);
550 AddKeyword ("fixed", Token.FIXED);
551 AddKeyword ("float", Token.FLOAT);
552 AddKeyword ("for", Token.FOR);
553 AddKeyword ("foreach", Token.FOREACH);
554 AddKeyword ("goto", Token.GOTO);
555 AddKeyword ("get", Token.GET);
556 AddKeyword ("if", Token.IF);
557 AddKeyword ("implicit", Token.IMPLICIT);
558 AddKeyword ("in", Token.IN);
559 AddKeyword ("int", Token.INT);
560 AddKeyword ("interface", Token.INTERFACE);
561 AddKeyword ("internal", Token.INTERNAL);
562 AddKeyword ("is", Token.IS);
563 AddKeyword ("lock", Token.LOCK);
564 AddKeyword ("long", Token.LONG);
565 AddKeyword ("namespace", Token.NAMESPACE);
566 AddKeyword ("new", Token.NEW);
567 AddKeyword ("null", Token.NULL);
568 AddKeyword ("object", Token.OBJECT);
569 AddKeyword ("operator", Token.OPERATOR);
570 AddKeyword ("out", Token.OUT);
571 AddKeyword ("override", Token.OVERRIDE);
572 AddKeyword ("params", Token.PARAMS);
573 AddKeyword ("private", Token.PRIVATE);
574 AddKeyword ("protected", Token.PROTECTED);
575 AddKeyword ("public", Token.PUBLIC);
576 AddKeyword ("readonly", Token.READONLY);
577 AddKeyword ("ref", Token.REF);
578 AddKeyword ("remove", Token.REMOVE);
579 AddKeyword ("return", Token.RETURN);
580 AddKeyword ("sbyte", Token.SBYTE);
581 AddKeyword ("sealed", Token.SEALED);
582 AddKeyword ("set", Token.SET);
583 AddKeyword ("short", Token.SHORT);
584 AddKeyword ("sizeof", Token.SIZEOF);
585 AddKeyword ("stackalloc", Token.STACKALLOC);
586 AddKeyword ("static", Token.STATIC);
587 AddKeyword ("string", Token.STRING);
588 AddKeyword ("struct", Token.STRUCT);
589 AddKeyword ("switch", Token.SWITCH);
590 AddKeyword ("this", Token.THIS);
591 AddKeyword ("throw", Token.THROW);
592 AddKeyword ("true", Token.TRUE);
593 AddKeyword ("try", Token.TRY);
594 AddKeyword ("typeof", Token.TYPEOF);
595 AddKeyword ("uint", Token.UINT);
596 AddKeyword ("ulong", Token.ULONG);
597 AddKeyword ("unchecked", Token.UNCHECKED);
598 AddKeyword ("unsafe", Token.UNSAFE);
599 AddKeyword ("ushort", Token.USHORT);
600 AddKeyword ("using", Token.USING);
601 AddKeyword ("virtual", Token.VIRTUAL);
602 AddKeyword ("void", Token.VOID);
603 AddKeyword ("volatile", Token.VOLATILE);
604 AddKeyword ("while", Token.WHILE);
605 AddKeyword ("partial", Token.PARTIAL);
606 AddKeyword ("where", Token.WHERE);
609 AddKeyword ("from", Token.FROM);
610 AddKeyword ("join", Token.JOIN);
611 AddKeyword ("on", Token.ON);
612 AddKeyword ("equals", Token.EQUALS);
613 AddKeyword ("select", Token.SELECT);
614 AddKeyword ("group", Token.GROUP);
615 AddKeyword ("by", Token.BY);
616 AddKeyword ("let", Token.LET);
617 AddKeyword ("orderby", Token.ORDERBY);
618 AddKeyword ("ascending", Token.ASCENDING);
619 AddKeyword ("descending", Token.DESCENDING);
620 AddKeyword ("into", Token.INTO);
622 // Contextual async keywords
623 AddKeyword ("async", Token.ASYNC);
624 AddKeyword ("await", Token.AWAIT);
626 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
628 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
629 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
630 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
631 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
632 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
633 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
634 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
635 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
636 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
637 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
638 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
639 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
641 csharp_format_info = NumberFormatInfo.InvariantInfo;
642 styles = NumberStyles.Float;
645 int GetKeyword (char[] id, int id_len)
648 // Keywords are stored in an array of arrays grouped by their
649 // length and then by the first character
651 if (id_len >= keywords.Length || keywords [id_len] == null)
654 int first_index = id [0] - '_';
655 if (first_index > 'z' - '_')
658 var kwe = keywords [id_len] [first_index];
665 for (int i = 1; i < id_len; ++i) {
666 if (id [i] != kwe.Value [i]) {
672 } while (res == 0 && kwe != null);
686 if (!handle_remove_add)
690 if (parsing_declaration == 0)
691 res = Token.EXTERN_ALIAS;
694 if (peek_token () == Token.COLON) {
696 res = Token.DEFAULT_COLON;
700 if (!handle_where && !query_parsing)
705 // A query expression is any expression that starts with `from identifier'
706 // followed by any token except ; , =
708 if (!query_parsing) {
709 if (lambda_arguments_parsing) {
715 // HACK: to disable generics micro-parser, because PushPosition does not
716 // store identifiers array
717 parsing_generic_less_than = 1;
719 case Token.IDENTIFIER:
731 next_token = xtoken ();
732 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
735 res = Token.FROM_FIRST;
736 query_parsing = true;
737 if (context.Settings.Version <= LanguageVersion.ISO_2)
738 Report.FeatureIsNotAvailable (context, Location, "query expressions");
741 Expression.Error_VoidInvalidInTheContext (Location, Report);
745 // HACK: A token is not a keyword so we need to restore identifiers buffer
746 // which has been overwritten before we grabbed the identifier
747 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
761 case Token.ASCENDING:
762 case Token.DESCENDING:
769 case Token.NAMESPACE:
770 // TODO: some explanation needed
771 check_incorrect_doc_comment ();
775 if (parsing_block > 0) {
780 // Save current position and parse next token.
783 next_token = token ();
784 bool ok = (next_token == Token.CLASS) ||
785 (next_token == Token.STRUCT) ||
786 (next_token == Token.INTERFACE) ||
787 (next_token == Token.VOID);
792 if (next_token == Token.VOID) {
793 if (context.Settings.Version <= LanguageVersion.ISO_2)
794 Report.FeatureIsNotAvailable (context, Location, "partial methods");
795 } else if (context.Settings.Version == LanguageVersion.ISO_1)
796 Report.FeatureIsNotAvailable (context, Location, "partial types");
801 if (next_token < Token.LAST_KEYWORD) {
802 Report.Error (267, Location,
803 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
811 if (parsing_modifiers) {
813 // Skip attributes section or constructor called async
815 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
820 } else if (parsing_block > 0) {
821 switch (peek_token ()) {
823 case Token.OPEN_PARENS_LAMBDA:
826 case Token.IDENTIFIER:
829 if (xtoken () != Token.ARROW)
835 // peek_token could overwrite id_buffer
836 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
844 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
845 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
851 if (parsing_block == 0)
861 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
864 // Keywords are stored in an array of arrays grouped by their
865 // length and then by the first character
867 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
868 return PreprocessorDirective.Invalid;
870 int first_index = id[0] - '_';
871 if (first_index > 'z' - '_')
872 return PreprocessorDirective.Invalid;
874 var kwe = keywords_preprocessor[id_len][first_index];
876 return PreprocessorDirective.Invalid;
878 PreprocessorDirective res = PreprocessorDirective.Invalid;
881 for (int i = 1; i < id_len; ++i) {
882 if (id[i] != kwe.Value[i]) {
888 } while (res == PreprocessorDirective.Invalid && kwe != null);
893 public Location Location {
895 return new Location (current_source, ref_line, col);
899 static bool is_identifier_start_character (int c)
901 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
904 static bool is_identifier_part_character (char c)
906 if (c >= 'a' && c <= 'z')
909 if (c >= 'A' && c <= 'Z')
912 if (c == '_' || (c >= '0' && c <= '9'))
918 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
921 public static bool IsKeyword (string s)
923 return keyword_strings.Contains (s);
927 // Open parens micro parser. Detects both lambda and cast ambiguity.
929 int TokenizeOpenParens ()
934 int bracket_level = 0;
935 bool is_type = false;
936 bool can_be_type = false;
939 ptoken = current_token;
942 switch (current_token) {
943 case Token.CLOSE_PARENS:
947 // Expression inside parens is lambda, (int i) =>
949 if (current_token == Token.ARROW)
950 return Token.OPEN_PARENS_LAMBDA;
953 // Expression inside parens is single type, (int[])
956 return Token.OPEN_PARENS_CAST;
959 // Expression is possible cast, look at next token, (T)null
962 switch (current_token) {
963 case Token.OPEN_PARENS:
966 case Token.IDENTIFIER:
980 case Token.UNCHECKED:
986 // These can be part of a member access
1000 return Token.OPEN_PARENS_CAST;
1003 return Token.OPEN_PARENS;
1006 case Token.DOUBLE_COLON:
1007 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1012 case Token.IDENTIFIER:
1015 if (bracket_level == 0) {
1021 case Token.OP_GENERICS_LT:
1023 case Token.DOUBLE_COLON:
1025 if (bracket_level == 0)
1029 can_be_type = is_type = false;
1049 if (bracket_level == 0)
1054 if (bracket_level == 0) {
1055 bracket_level = 100;
1056 can_be_type = is_type = false;
1060 case Token.OP_GENERICS_LT:
1061 case Token.OPEN_BRACKET:
1062 if (bracket_level++ == 0)
1066 case Token.OP_GENERICS_GT:
1067 case Token.CLOSE_BRACKET:
1071 case Token.INTERR_NULLABLE:
1073 if (bracket_level == 0)
1079 can_be_type = is_type = false;
1083 return Token.OPEN_PARENS;
1088 public static bool IsValidIdentifier (string s)
1090 if (s == null || s.Length == 0)
1093 if (!is_identifier_start_character (s [0]))
1096 for (int i = 1; i < s.Length; i ++)
1097 if (! is_identifier_part_character (s [i]))
1103 bool parse_less_than ()
1106 int the_token = token ();
1107 if (the_token == Token.OPEN_BRACKET) {
1109 the_token = token ();
1110 if (the_token == Token.EOF)
1113 if (the_token == Token.CLOSE_BRACKET)
1116 the_token = token ();
1117 } else if (the_token == Token.IN || the_token == Token.OUT) {
1118 the_token = token ();
1120 switch (the_token) {
1121 case Token.IDENTIFIER:
1139 case Token.OP_GENERICS_GT:
1148 the_token = token ();
1150 if (the_token == Token.OP_GENERICS_GT)
1152 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1154 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1156 else if (the_token == Token.OP_GENERICS_LT) {
1157 if (!parse_less_than ())
1160 } else if (the_token == Token.OPEN_BRACKET) {
1162 the_token = token ();
1163 if (the_token == Token.CLOSE_BRACKET)
1165 else if (the_token == Token.COMMA)
1166 goto rank_specifiers;
1173 bool parse_generic_dimension (out int dimension)
1178 int the_token = token ();
1179 if (the_token == Token.OP_GENERICS_GT)
1181 else if (the_token == Token.COMMA) {
1189 public int peek_token ()
1194 the_token = token ();
1201 // Tonizes `?' using custom disambiguous rules to return one
1202 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1204 // Tricky expression look like:
1206 // Foo ? a = x ? b : c;
1208 int TokenizePossibleNullableType ()
1210 if (parsing_block == 0 || parsing_type > 0)
1211 return Token.INTERR_NULLABLE;
1213 int d = peek_char ();
1216 return Token.OP_COALESCING;
1219 switch (current_token) {
1220 case Token.CLOSE_PARENS:
1225 return Token.INTERR;
1229 if (d == ',' || d == ';' || d == '>')
1230 return Token.INTERR_NULLABLE;
1231 if (d == '*' || (d >= '0' && d <= '9'))
1232 return Token.INTERR;
1236 current_token = Token.NONE;
1238 switch (xtoken ()) {
1245 next_token = Token.INTERR;
1248 case Token.SEMICOLON:
1250 case Token.CLOSE_PARENS:
1251 case Token.OPEN_BRACKET:
1252 case Token.OP_GENERICS_GT:
1254 case Token.OP_COALESCING:
1255 next_token = Token.INTERR_NULLABLE;
1263 if (next_token == -1) {
1264 switch (xtoken ()) {
1266 case Token.SEMICOLON:
1267 case Token.OPEN_BRACE:
1268 case Token.CLOSE_PARENS:
1270 next_token = Token.INTERR_NULLABLE;
1274 next_token = Token.INTERR;
1283 // All shorcuts failed, do it hard way
1285 while ((ntoken = xtoken ()) != Token.EOF) {
1286 if (ntoken == Token.OPEN_BRACE) {
1291 if (ntoken == Token.CLOSE_BRACE) {
1299 if (ntoken == Token.SEMICOLON)
1302 if (ntoken == Token.COLON) {
1303 if (++colons == interrs)
1308 if (ntoken == Token.INTERR) {
1314 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1323 bool decimal_digits (int c)
1326 bool seen_digits = false;
1329 if (number_pos == MaxNumberLength)
1330 Error_NumericConstantTooLong ();
1331 number_builder [number_pos++] = (char) c;
1335 // We use peek_char2, because decimal_digits needs to do a
1336 // 2-character look-ahead (5.ToString for example).
1338 while ((d = peek_char2 ()) != -1){
1339 if (d >= '0' && d <= '9'){
1340 if (number_pos == MaxNumberLength)
1341 Error_NumericConstantTooLong ();
1342 number_builder [number_pos++] = (char) d;
1352 static bool is_hex (int e)
1354 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1357 static TypeCode real_type_suffix (int c)
1361 return TypeCode.Single;
1363 return TypeCode.Double;
1365 return TypeCode.Decimal;
1367 return TypeCode.Empty;
1371 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1373 bool is_unsigned = false;
1374 bool is_long = false;
1377 bool scanning = true;
1390 // if we have not seen anything in between
1391 // report this error
1393 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1413 if (is_long && is_unsigned){
1414 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1418 // uint if possible, or ulong else.
1420 if ((ul & 0xffffffff00000000) == 0)
1421 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1423 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1424 } else if (is_long){
1425 // long if possible, ulong otherwise
1426 if ((ul & 0x8000000000000000) != 0)
1427 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1429 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1431 // int, uint, long or ulong in that order
1432 if ((ul & 0xffffffff00000000) == 0){
1433 uint ui = (uint) ul;
1435 if ((ui & 0x80000000) != 0)
1436 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1438 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1440 if ((ul & 0x8000000000000000) != 0)
1441 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1443 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1449 // given `c' as the next char in the input decide whether
1450 // we need to convert to a special type, and then choose
1451 // the best representation for the integer
1453 ILiteralConstant adjust_int (int c, Location loc)
1456 if (number_pos > 9){
1457 ulong ul = (uint) (number_builder [0] - '0');
1459 for (int i = 1; i < number_pos; i++){
1460 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1463 return integer_type_suffix (ul, c, loc);
1465 uint ui = (uint) (number_builder [0] - '0');
1467 for (int i = 1; i < number_pos; i++){
1468 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1471 return integer_type_suffix (ui, c, loc);
1473 } catch (OverflowException) {
1474 Error_NumericConstantTooLong ();
1475 return new IntLiteral (context.BuiltinTypes, 0, loc);
1477 catch (FormatException) {
1478 Report.Error (1013, Location, "Invalid number");
1479 return new IntLiteral (context.BuiltinTypes, 0, loc);
1483 ILiteralConstant adjust_real (TypeCode t, Location loc)
1485 string s = new string (number_builder, 0, number_pos);
1486 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1489 case TypeCode.Decimal:
1491 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1492 } catch (OverflowException) {
1493 Report.Error (594, Location, error_details, "decimal");
1494 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1496 case TypeCode.Single:
1498 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1499 } catch (OverflowException) {
1500 Report.Error (594, Location, error_details, "float");
1501 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1505 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1506 } catch (OverflowException) {
1507 Report.Error (594, loc, error_details, "double");
1508 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1513 ILiteralConstant handle_hex (Location loc)
1519 while ((d = peek_char ()) != -1){
1521 number_builder [number_pos++] = (char) d;
1527 string s = new String (number_builder, 0, number_pos);
1530 if (number_pos <= 8)
1531 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1533 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1535 return integer_type_suffix (ul, peek_char (), loc);
1536 } catch (OverflowException){
1537 Error_NumericConstantTooLong ();
1538 return new IntLiteral (context.BuiltinTypes, 0, loc);
1540 catch (FormatException) {
1541 Report.Error (1013, Location, "Invalid number");
1542 return new IntLiteral (context.BuiltinTypes, 0, loc);
1547 // Invoked if we know we have .digits or digits
1549 int is_number (int c)
1551 ILiteralConstant res;
1554 int read_start = reader.Position - 1;
1557 // Caller did peek_char
1565 if (c >= '0' && c <= '9'){
1567 int peek = peek_char ();
1569 if (peek == 'x' || peek == 'X') {
1570 val = res = handle_hex (loc);
1572 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1575 return Token.LITERAL;
1583 // We need to handle the case of
1584 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1586 bool is_real = false;
1588 if (decimal_digits ('.')){
1594 val = res = adjust_int (-1, loc);
1597 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1599 return Token.LITERAL;
1603 if (c == 'e' || c == 'E'){
1605 if (number_pos == MaxNumberLength)
1606 Error_NumericConstantTooLong ();
1607 number_builder [number_pos++] = (char) c;
1611 if (number_pos == MaxNumberLength)
1612 Error_NumericConstantTooLong ();
1613 number_builder [number_pos++] = '+';
1615 } else if (c == '-') {
1616 if (number_pos == MaxNumberLength)
1617 Error_NumericConstantTooLong ();
1618 number_builder [number_pos++] = '-';
1621 if (number_pos == MaxNumberLength)
1622 Error_NumericConstantTooLong ();
1623 number_builder [number_pos++] = '+';
1630 var type = real_type_suffix (c);
1631 if (type == TypeCode.Empty && !is_real) {
1633 res = adjust_int (c, loc);
1637 if (type == TypeCode.Empty) {
1641 res = adjust_real (type, loc);
1647 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1648 if (chars[chars.Length - 1] == '\r')
1649 Array.Resize (ref chars, chars.Length - 1);
1650 res.ParsedValue = chars;
1653 return Token.LITERAL;
1657 // Accepts exactly count (4 or 8) hex, no more no less
1659 int getHex (int count, out int surrogate, out bool error)
1664 int top = count != -1 ? count : 4;
1669 for (i = 0; i < top; i++){
1672 if (c >= '0' && c <= '9')
1673 c = (int) c - (int) '0';
1674 else if (c >= 'A' && c <= 'F')
1675 c = (int) c - (int) 'A' + 10;
1676 else if (c >= 'a' && c <= 'f')
1677 c = (int) c - (int) 'a' + 10;
1683 total = (total * 16) + c;
1685 int p = peek_char ();
1688 if (!is_hex ((char)p))
1694 if (total > 0x0010FFFF) {
1699 if (total >= 0x00010000) {
1700 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1701 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1708 int escape (int c, out int surrogate)
1744 v = getHex (-1, out surrogate, out error);
1750 return EscapeUnicode (d, out surrogate);
1753 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1762 int EscapeUnicode (int ch, out int surrogate)
1766 ch = getHex (8, out surrogate, out error);
1768 ch = getHex (4, out surrogate, out error);
1772 Report.Error (1009, Location, "Unrecognized escape sequence");
1780 if (putback_char != -1) {
1788 if (peek_char () == '\n') {
1794 } else if (x == '\n') {
1802 void advance_line ()
1812 if (putback_char == -1)
1813 putback_char = reader.Read ();
1814 return putback_char;
1819 if (putback_char != -1)
1820 return putback_char;
1821 return reader.Peek ();
1824 public void putback (int c)
1826 if (putback_char != -1) {
1827 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
1830 if (c == '\n' || col == 0) {
1831 // It won't happen though.
1841 public bool advance ()
1843 return peek_char () != -1 || CompleteOnEOF;
1846 public Object Value {
1852 public Object value ()
1859 current_token = xtoken ();
1860 return current_token;
1863 int TokenizePreprocessorIdentifier (out int c)
1865 // skip over white space
1868 } while (c == ' ' || c == '\t');
1872 while (c != -1 && c >= 'a' && c <= 'z') {
1873 id_builder[pos++] = (char) c;
1876 int peek = peek_char ();
1877 if (peek == 'U' || peek == 'u') {
1879 c = EscapeUnicode (c, out surrogate);
1880 if (surrogate != 0) {
1881 if (is_identifier_part_character ((char) c)) {
1882 id_builder[pos++] = (char) c;
1893 PreprocessorDirective get_cmd_arg (out string arg)
1897 tokens_seen = false;
1900 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1902 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1905 // skip over white space
1906 while (c == ' ' || c == '\t')
1909 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1912 while (c != -1 && c != '\n') {
1913 if (c == '\\' && has_identifier_argument >= 0) {
1914 if (has_identifier_argument != 0) {
1915 has_identifier_argument = 1;
1917 int peek = peek_char ();
1918 if (peek == 'U' || peek == 'u') {
1920 c = EscapeUnicode (c, out surrogate);
1921 if (surrogate != 0) {
1922 if (is_identifier_part_character ((char) c)) {
1923 if (pos == value_builder.Length)
1924 Array.Resize (ref value_builder, pos * 2);
1926 value_builder[pos++] = (char) c;
1932 has_identifier_argument = -1;
1934 } else if (c == '/' && peek_char () == '/') {
1936 // Eat single-line comments
1941 } while (c != -1 && c != '\n');
1946 if (pos == value_builder.Length)
1947 Array.Resize (ref value_builder, pos * 2);
1949 value_builder[pos++] = (char) c;
1954 if (pos > MaxIdentifierLength)
1955 arg = new string (value_builder, 0, pos);
1957 arg = InternIdentifier (value_builder, pos);
1959 // Eat any trailing whitespaces
1960 arg = arg.Trim (simple_whitespaces);
1967 // Handles the #line directive
1969 bool PreProcessLine ()
1971 Location loc = Location;
1975 int length = TokenizePreprocessorIdentifier (out c);
1976 if (length == line_default.Length) {
1977 if (!IsTokenIdentifierEqual (line_default))
1980 current_source = source_file.SourceFile;
1981 if (!hidden_block_start.IsNull) {
1982 current_source.RegisterHiddenScope (hidden_block_start, loc);
1983 hidden_block_start = Location.Null;
1990 if (length == line_hidden.Length) {
1991 if (!IsTokenIdentifierEqual (line_hidden))
1994 if (hidden_block_start.IsNull)
1995 hidden_block_start = loc;
2000 if (length != 0 || c < '0' || c > '9') {
2002 // Eat any remaining characters to continue parsing on next line
2004 while (c != -1 && c != '\n') {
2011 int new_line = TokenizeNumber (c);
2014 // Eat any remaining characters to continue parsing on next line
2016 while (c != -1 && c != '\n') {
2020 return new_line != 0;
2025 // skip over white space
2028 } while (c == ' ' || c == '\t');
2029 } else if (c == '"') {
2033 if (c != '\n' && c != '/' && c != '"') {
2035 // Eat any remaining characters to continue parsing on next line
2037 while (c != -1 && c != '\n') {
2041 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2045 string new_file_name = null;
2047 new_file_name = TokenizeFileName (ref c);
2049 // skip over white space
2050 while (c == ' ' || c == '\t') {
2056 } else if (c == '/') {
2057 ReadSingleLineComment ();
2060 // Eat any remaining characters to continue parsing on next line
2062 while (c != -1 && c != '\n') {
2066 Error_EndLineExpected ();
2070 if (new_file_name != null) {
2071 current_source = context.LookupFile (source_file, new_file_name);
2072 source_file.AddIncludeFile (current_source);
2075 if (!hidden_block_start.IsNull) {
2076 current_source.RegisterHiddenScope (hidden_block_start, loc);
2077 hidden_block_start = Location.Null;
2080 ref_line = new_line;
2085 // Handles #define and #undef
2087 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2089 if (ident.Length == 0 || ident == "true" || ident == "false"){
2090 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2094 if (ident.IndexOfAny (simple_whitespaces) != -1){
2095 Error_EndLineExpected ();
2099 if (!is_identifier_start_character (ident [0]))
2100 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2102 foreach (char c in ident.Substring (1)){
2103 if (!is_identifier_part_character (c)){
2104 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2109 if (!caller_is_taking)
2116 if (context.Settings.IsConditionalSymbolDefined (ident))
2119 source_file.AddDefine (ident);
2124 source_file.AddUndefine (ident);
2128 byte read_hex (out bool error)
2131 int c = get_char ();
2133 if ((c >= '0') && (c <= '9'))
2134 total = (int) c - (int) '0';
2135 else if ((c >= 'A') && (c <= 'F'))
2136 total = (int) c - (int) 'A' + 10;
2137 else if ((c >= 'a') && (c <= 'f'))
2138 total = (int) c - (int) 'a' + 10;
2147 if ((c >= '0') && (c <= '9'))
2148 total += (int) c - (int) '0';
2149 else if ((c >= 'A') && (c <= 'F'))
2150 total += (int) c - (int) 'A' + 10;
2151 else if ((c >= 'a') && (c <= 'f'))
2152 total += (int) c - (int) 'a' + 10;
2159 return (byte) total;
2163 // Parses #pragma checksum
2165 bool ParsePragmaChecksum ()
2168 // The syntax is ` "foo.txt" "{guid}" "hash"'
2170 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2172 int c = get_char ();
2177 string file_name = TokenizeFileName (ref c);
2179 // TODO: Any white-spaces count
2183 SourceFile file = context.LookupFile (source_file, file_name);
2185 if (get_char () != '"' || get_char () != '{')
2189 byte[] guid_bytes = new byte [16];
2192 for (; i < 4; i++) {
2193 guid_bytes [i] = read_hex (out error);
2198 if (get_char () != '-')
2201 for (; i < 10; i++) {
2202 guid_bytes [i] = read_hex (out error);
2206 guid_bytes [i++] = read_hex (out error);
2210 if (get_char () != '-')
2214 for (; i < 16; i++) {
2215 guid_bytes [i] = read_hex (out error);
2220 if (get_char () != '}' || get_char () != '"')
2223 // TODO: Any white-spaces count
2228 if (get_char () != '"')
2231 // Any length of checksum
2232 List<byte> checksum_bytes = new List<byte> (16);
2234 var checksum_location = Location;
2236 while (c != '"' && c != -1) {
2237 checksum_bytes.Add (read_hex (out error));
2245 ReadSingleLineComment ();
2246 } else if (get_char () != '"') {
2250 if (context.Settings.GenerateDebugInfo) {
2251 var chsum = checksum_bytes.ToArray ();
2253 if (file.HasChecksum) {
2254 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2255 // TODO: Report.SymbolRelatedToPreviousError
2256 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2260 file.SetChecksum (guid_bytes, chsum);
2261 current_source.AutoGenerated = true;
2267 bool IsTokenIdentifierEqual (char[] identifier)
2269 for (int i = 0; i < identifier.Length; ++i) {
2270 if (identifier[i] != id_builder[i])
2277 int TokenizeNumber (int value)
2281 decimal_digits (value);
2282 uint ui = (uint) (number_builder[0] - '0');
2285 for (int i = 1; i < number_pos; i++) {
2286 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2290 } catch (OverflowException) {
2291 Error_NumericConstantTooLong ();
2296 string TokenizeFileName (ref int c)
2298 var string_builder = new StringBuilder ();
2299 while (c != -1 && c != '\n') {
2306 string_builder.Append ((char) c);
2309 if (string_builder.Length == 0) {
2310 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2314 return string_builder.ToString ();
2317 int TokenizePragmaNumber (ref int c)
2323 if (c >= '0' && c <= '9') {
2324 number = TokenizeNumber (c);
2328 // skip over white space
2329 while (c == ' ' || c == '\t')
2336 // skip over white space
2337 while (c == ' ' || c == '\t')
2342 ReadSingleLineComment ();
2344 Report.Warning (1692, 1, Location, "Invalid number");
2346 // Read everything till the end of the line or file
2349 } while (c != -1 && c != '\n');
2356 void ReadSingleLineComment ()
2358 if (peek_char () != '/')
2359 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2361 // Read everything till the end of the line or file
2365 } while (c != -1 && c != '\n');
2369 /// Handles #pragma directive
2371 void ParsePragmaDirective (string arg)
2374 int length = TokenizePreprocessorIdentifier (out c);
2375 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2376 length = TokenizePreprocessorIdentifier (out c);
2379 // #pragma warning disable
2380 // #pragma warning restore
2382 if (length == pragma_warning_disable.Length) {
2383 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2384 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2385 // skip over white space
2386 while (c == ' ' || c == '\t')
2391 if (c == '\n' || c == '/') {
2393 ReadSingleLineComment ();
2396 // Disable/Restore all warnings
2399 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2401 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2405 // Disable/Restore a warning or group of warnings
2409 code = TokenizePragmaNumber (ref c);
2412 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2414 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2417 } while (code >= 0 && c != '\n' && c != -1);
2424 Report.Warning (1634, 1, Location, "Expected disable or restore");
2426 // Eat any remaining characters on the line
2427 while (c != '\n' && c != -1)
2436 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2437 if (c != ' ' || !ParsePragmaChecksum ()) {
2438 Report.Warning (1695, 1, Location,
2439 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2445 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2448 bool eval_val (string s)
2455 return source_file.IsConditionalDefined (s);
2458 bool pp_primary (ref string s)
2467 s = s.Substring (1);
2468 bool val = pp_expr (ref s, false);
2469 if (s.Length > 0 && s [0] == ')'){
2470 s = s.Substring (1);
2473 Error_InvalidDirective ();
2477 if (is_identifier_start_character (c)){
2483 if (is_identifier_part_character (c)){
2487 bool v = eval_val (s.Substring (0, j));
2488 s = s.Substring (j);
2491 bool vv = eval_val (s);
2496 Error_InvalidDirective ();
2500 bool pp_unary (ref string s)
2507 if (len > 1 && s [1] == '='){
2508 Error_InvalidDirective ();
2511 s = s.Substring (1);
2512 return ! pp_primary (ref s);
2514 return pp_primary (ref s);
2516 Error_InvalidDirective ();
2521 bool pp_eq (ref string s)
2523 bool va = pp_unary (ref s);
2529 if (len > 2 && s [1] == '='){
2530 s = s.Substring (2);
2531 return va == pp_unary (ref s);
2533 Error_InvalidDirective ();
2536 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2537 s = s.Substring (2);
2539 return va != pp_unary (ref s);
2548 bool pp_and (ref string s)
2550 bool va = pp_eq (ref s);
2556 if (len > 2 && s [1] == '&'){
2557 s = s.Substring (2);
2558 return (va & pp_and (ref s));
2560 Error_InvalidDirective ();
2569 // Evaluates an expression for `#if' or `#elif'
2571 bool pp_expr (ref string s, bool isTerm)
2573 bool va = pp_and (ref s);
2580 if (len > 2 && s [1] == '|'){
2581 s = s.Substring (2);
2582 return va | pp_expr (ref s, isTerm);
2584 Error_InvalidDirective ();
2589 Error_EndLineExpected ();
2597 bool eval (string s)
2599 bool v = pp_expr (ref s, true);
2608 void Error_NumericConstantTooLong ()
2610 Report.Error (1021, Location, "Integral constant is too large");
2613 void Error_InvalidDirective ()
2615 Report.Error (1517, Location, "Invalid preprocessor directive");
2618 void Error_UnexpectedDirective (string extra)
2622 "Unexpected processor directive ({0})", extra);
2625 void Error_TokensSeen ()
2627 Report.Error (1032, Location,
2628 "Cannot define or undefine preprocessor symbols after first token in file");
2631 void Eror_WrongPreprocessorLocation ()
2633 Report.Error (1040, Location,
2634 "Preprocessor directives must appear as the first non-whitespace character on a line");
2637 void Error_EndLineExpected ()
2639 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2643 // Raises a warning when tokenizer found documentation comment
2644 // on unexpected place
2646 void WarningMisplacedComment (Location loc)
2648 if (doc_state != XmlCommentState.Error) {
2649 doc_state = XmlCommentState.Error;
2650 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2655 // if true, then the code continues processing the code
2656 // if false, the code stays in a loop until another directive is
2658 // When caller_is_taking is false we ignore all directives except the ones
2659 // which can help us to identify where the #if block ends
2660 bool ParsePreprocessingDirective (bool caller_is_taking)
2663 bool region_directive = false;
2665 var directive = get_cmd_arg (out arg);
2668 // The first group of pre-processing instructions is always processed
2670 switch (directive) {
2671 case PreprocessorDirective.Region:
2672 region_directive = true;
2674 goto case PreprocessorDirective.If;
2676 case PreprocessorDirective.Endregion:
2677 if (ifstack == null || ifstack.Count == 0){
2678 Error_UnexpectedDirective ("no #region for this #endregion");
2681 int pop = ifstack.Pop ();
2683 if ((pop & REGION) == 0)
2684 Report.Error (1027, Location, "Expected `#endif' directive");
2686 return caller_is_taking;
2688 case PreprocessorDirective.If:
2689 if (ifstack == null)
2690 ifstack = new Stack<int> (2);
2692 int flags = region_directive ? REGION : 0;
2693 if (ifstack.Count == 0){
2694 flags |= PARENT_TAKING;
2696 int state = ifstack.Peek ();
2697 if ((state & TAKING) != 0) {
2698 flags |= PARENT_TAKING;
2702 if (eval (arg) && caller_is_taking) {
2703 ifstack.Push (flags | TAKING);
2706 ifstack.Push (flags);
2709 case PreprocessorDirective.Endif:
2710 if (ifstack == null || ifstack.Count == 0){
2711 Error_UnexpectedDirective ("no #if for this #endif");
2714 pop = ifstack.Pop ();
2716 if ((pop & REGION) != 0)
2717 Report.Error (1038, Location, "#endregion directive expected");
2719 if (arg.Length != 0) {
2720 Error_EndLineExpected ();
2723 if (ifstack.Count == 0)
2726 int state = ifstack.Peek ();
2727 return (state & TAKING) != 0;
2730 case PreprocessorDirective.Elif:
2731 if (ifstack == null || ifstack.Count == 0){
2732 Error_UnexpectedDirective ("no #if for this #elif");
2735 int state = ifstack.Pop ();
2737 if ((state & REGION) != 0) {
2738 Report.Error (1038, Location, "#endregion directive expected");
2742 if ((state & ELSE_SEEN) != 0){
2743 Error_UnexpectedDirective ("#elif not valid after #else");
2747 if ((state & TAKING) != 0) {
2752 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2753 ifstack.Push (state | TAKING);
2757 ifstack.Push (state);
2761 case PreprocessorDirective.Else:
2762 if (ifstack == null || ifstack.Count == 0){
2763 Error_UnexpectedDirective ("no #if for this #else");
2766 int state = ifstack.Peek ();
2768 if ((state & REGION) != 0) {
2769 Report.Error (1038, Location, "#endregion directive expected");
2773 if ((state & ELSE_SEEN) != 0){
2774 Error_UnexpectedDirective ("#else within #else");
2780 if (arg.Length != 0) {
2781 Error_EndLineExpected ();
2786 if ((state & PARENT_TAKING) != 0) {
2787 ret = (state & TAKING) == 0;
2795 ifstack.Push (state | ELSE_SEEN);
2799 case PreprocessorDirective.Define:
2800 if (any_token_seen){
2801 Error_TokensSeen ();
2802 return caller_is_taking;
2804 PreProcessDefinition (true, arg, caller_is_taking);
2805 return caller_is_taking;
2807 case PreprocessorDirective.Undef:
2808 if (any_token_seen){
2809 Error_TokensSeen ();
2810 return caller_is_taking;
2812 PreProcessDefinition (false, arg, caller_is_taking);
2813 return caller_is_taking;
2815 case PreprocessorDirective.Invalid:
2816 Report.Error (1024, Location, "Wrong preprocessor directive");
2821 // These are only processed if we are in a `taking' block
2823 if (!caller_is_taking)
2827 case PreprocessorDirective.Error:
2828 Report.Error (1029, Location, "#error: '{0}'", arg);
2831 case PreprocessorDirective.Warning:
2832 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2835 case PreprocessorDirective.Pragma:
2836 if (context.Settings.Version == LanguageVersion.ISO_1) {
2837 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2840 ParsePragmaDirective (arg);
2843 case PreprocessorDirective.Line:
2844 Location loc = Location;
2845 if (!PreProcessLine ())
2846 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
2848 return caller_is_taking;
2851 throw new NotImplementedException (directive.ToString ());
2854 private int consume_string (bool quoted)
2858 Location start_location = Location;
2860 start_location = start_location - 1;
2863 int reader_pos = reader.Position;
2867 // Cannot use get_char because of \r in quoted strings
2868 if (putback_char != -1) {
2878 if (quoted && peek_char () == '"') {
2879 if (pos == value_builder.Length)
2880 Array.Resize (ref value_builder, pos * 2);
2882 value_builder[pos++] = (char) c;
2891 s = InternIdentifier (value_builder, pos);
2893 s = new string (value_builder, 0, pos);
2895 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2898 res.ParsedValue = quoted ?
2899 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2900 reader.ReadChars (reader_pos - 1, reader.Position);
2903 return Token.LITERAL;
2908 Report.Error (1010, Location, "Newline in constant");
2912 // Don't add \r to string literal
2913 if (pos > 1 && value_builder [pos - 1] == '\r')
2916 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2917 return Token.LITERAL;
2921 } else if (c == '\\' && !quoted) {
2923 c = escape (c, out surrogate);
2926 if (surrogate != 0) {
2927 if (pos == value_builder.Length)
2928 Array.Resize (ref value_builder, pos * 2);
2930 value_builder[pos++] = (char) c;
2933 } else if (c == -1) {
2934 Report.Error (1039, Location, "Unterminated string literal");
2940 if (pos == value_builder.Length)
2941 Array.Resize (ref value_builder, pos * 2);
2943 value_builder[pos++] = (char) c;
2947 private int consume_identifier (int s)
2949 int res = consume_identifier (s, false);
2951 if (doc_state == XmlCommentState.Allowed)
2952 doc_state = XmlCommentState.NotAllowed;
2957 int consume_identifier (int c, bool quoted)
2960 // This method is very performance sensitive. It accounts
2961 // for approximately 25% of all parser time
2971 c = escape (c, out surrogate);
2972 if (surrogate != 0) {
2973 id_builder [pos++] = (char) c;
2978 id_builder [pos++] = (char) c;
2984 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2985 id_builder [pos++] = (char) c;
2992 c = escape (c, out surrogate);
2993 if (is_identifier_part_character ((char) c))
2994 id_builder[pos++] = (char) c;
2996 if (surrogate != 0) {
3002 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
3003 id_builder [pos++] = (char) c;
3010 } catch (IndexOutOfRangeException) {
3011 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3019 // Optimization: avoids doing the keyword lookup
3020 // on uppercase letters
3022 if (id_builder [0] >= '_' && !quoted) {
3023 int keyword = GetKeyword (id_builder, pos);
3024 if (keyword != -1) {
3025 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3030 string s = InternIdentifier (id_builder, pos);
3031 val = ltb.Create (s, current_source, ref_line, column);
3032 if (quoted && parsing_attribute_section)
3033 AddEscapedIdentifier (((LocatedToken) val).Location);
3035 return Token.IDENTIFIER;
3038 string InternIdentifier (char[] charBuffer, int length)
3041 // Keep identifiers in an array of hashtables to avoid needless
3044 var identifiers_group = identifiers[length];
3046 if (identifiers_group != null) {
3047 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3051 // TODO: this should be number of files dependant
3052 // corlib compilation peaks at 1000 and System.Core at 150
3053 int capacity = length > 20 ? 10 : 100;
3054 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3055 identifiers[length] = identifiers_group;
3058 char[] chars = new char[length];
3059 Array.Copy (charBuffer, chars, length);
3061 s = new string (charBuffer, 0, length);
3062 identifiers_group.Add (chars, s);
3066 public int xtoken ()
3070 // Whether we have seen comments on the current line
3071 bool comments_seen = false;
3072 while ((c = get_char ()) != -1) {
3075 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3083 case 0xFEFF: // Ignore BOM anywhere in the file
3086 /* This is required for compatibility with .NET
3088 if (peek_char () == 0xBB) {
3091 if (get_char () == 0xBF)
3099 return consume_identifier (c);
3102 val = ltb.Create (current_source, ref_line, col);
3103 return Token.OPEN_BRACE;
3105 val = ltb.Create (current_source, ref_line, col);
3106 return Token.CLOSE_BRACE;
3108 // To block doccomment inside attribute declaration.
3109 if (doc_state == XmlCommentState.Allowed)
3110 doc_state = XmlCommentState.NotAllowed;
3112 val = ltb.Create (current_source, ref_line, col);
3114 if (parsing_block == 0 || lambda_arguments_parsing)
3115 return Token.OPEN_BRACKET;
3117 int next = peek_char ();
3121 return Token.OPEN_BRACKET;
3129 next = peek_token ();
3130 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3131 return Token.OPEN_BRACKET;
3133 return Token.OPEN_BRACKET_EXPR;
3135 return Token.OPEN_BRACKET_EXPR;
3138 ltb.CreateOptional (current_source, ref_line, col, ref val);
3139 return Token.CLOSE_BRACKET;
3141 val = ltb.Create (current_source, ref_line, col);
3143 // An expression versions of parens can appear in block context only
3145 if (parsing_block != 0 && !lambda_arguments_parsing) {
3148 // Optmize most common case where we know that parens
3151 switch (current_token) {
3152 case Token.IDENTIFIER:
3160 case Token.DELEGATE:
3161 case Token.OP_GENERICS_GT:
3162 return Token.OPEN_PARENS;
3165 // Optimize using peek
3166 int xx = peek_char ();
3173 return Token.OPEN_PARENS;
3176 lambda_arguments_parsing = true;
3178 d = TokenizeOpenParens ();
3180 lambda_arguments_parsing = false;
3184 return Token.OPEN_PARENS;
3186 ltb.CreateOptional (current_source, ref_line, col, ref val);
3187 return Token.CLOSE_PARENS;
3189 ltb.CreateOptional (current_source, ref_line, col, ref val);
3192 ltb.CreateOptional (current_source, ref_line, col, ref val);
3193 return Token.SEMICOLON;
3195 val = ltb.Create (current_source, ref_line, col);
3198 val = ltb.Create (current_source, ref_line, col);
3199 return TokenizePossibleNullableType ();
3201 val = ltb.Create (current_source, ref_line, col);
3202 if (parsing_generic_less_than++ > 0)
3203 return Token.OP_GENERICS_LT;
3205 return TokenizeLessThan ();
3208 val = ltb.Create (current_source, ref_line, col);
3216 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3217 parsing_generic_less_than--;
3218 return Token.OP_GENERICS_GT;
3227 return Token.OP_SHIFT_RIGHT_ASSIGN;
3229 return Token.OP_SHIFT_RIGHT;
3235 val = ltb.Create (current_source, ref_line, col);
3239 } else if (d == '=') {
3240 d = Token.OP_ADD_ASSIGN;
3248 val = ltb.Create (current_source, ref_line, col);
3252 } else if (d == '=')
3253 d = Token.OP_SUB_ASSIGN;
3263 val = ltb.Create (current_source, ref_line, col);
3264 if (peek_char () == '='){
3271 val = ltb.Create (current_source, ref_line, col);
3282 return Token.ASSIGN;
3285 val = ltb.Create (current_source, ref_line, col);
3289 return Token.OP_AND;
3293 return Token.OP_AND_ASSIGN;
3295 return Token.BITWISE_AND;
3298 val = ltb.Create (current_source, ref_line, col);
3306 return Token.OP_OR_ASSIGN;
3308 return Token.BITWISE_OR;
3311 val = ltb.Create (current_source, ref_line, col);
3312 if (peek_char () == '='){
3314 return Token.OP_MULT_ASSIGN;
3321 val = ltb.Create (current_source, ref_line, col);
3323 return Token.OP_DIV_ASSIGN;
3326 // Handle double-slash comments.
3329 if (doc_processing) {
3330 if (peek_char () == '/') {
3332 // Don't allow ////.
3333 if ((d = peek_char ()) != '/') {
3334 if (doc_state == XmlCommentState.Allowed)
3335 handle_one_line_xml_comment ();
3336 else if (doc_state == XmlCommentState.NotAllowed)
3337 WarningMisplacedComment (Location - 3);
3340 if (xml_comment_buffer.Length > 0)
3341 doc_state = XmlCommentState.NotAllowed;
3345 while ((d = get_char ()) != -1 && d != '\n');
3347 any_token_seen |= tokens_seen;
3348 tokens_seen = false;
3349 comments_seen = false;
3351 } else if (d == '*'){
3353 bool docAppend = false;
3354 if (doc_processing && peek_char () == '*') {
3356 // But when it is /**/, just do nothing.
3357 if (peek_char () == '/') {
3361 if (doc_state == XmlCommentState.Allowed)
3363 else if (doc_state == XmlCommentState.NotAllowed) {
3364 WarningMisplacedComment (Location - 2);
3368 int current_comment_start = 0;
3370 current_comment_start = xml_comment_buffer.Length;
3371 xml_comment_buffer.Append (Environment.NewLine);
3374 while ((d = get_char ()) != -1){
3375 if (d == '*' && peek_char () == '/'){
3377 comments_seen = true;
3381 xml_comment_buffer.Append ((char) d);
3384 any_token_seen |= tokens_seen;
3385 tokens_seen = false;
3387 // Reset 'comments_seen' just to be consistent.
3388 // It doesn't matter either way, here.
3390 comments_seen = false;
3394 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3397 update_formatted_doc_comment (current_comment_start);
3400 val = ltb.Create (current_source, ref_line, col);
3404 val = ltb.Create (current_source, ref_line, col);
3405 if (peek_char () == '='){
3407 return Token.OP_MOD_ASSIGN;
3409 return Token.PERCENT;
3412 val = ltb.Create (current_source, ref_line, col);
3413 if (peek_char () == '='){
3415 return Token.OP_XOR_ASSIGN;
3417 return Token.CARRET;
3420 val = ltb.Create (current_source, ref_line, col);
3421 if (peek_char () == ':') {
3423 return Token.DOUBLE_COLON;
3427 case '0': case '1': case '2': case '3': case '4':
3428 case '5': case '6': case '7': case '8': case '9':
3430 return is_number (c);
3432 case '\n': // white space
3433 any_token_seen |= tokens_seen;
3434 tokens_seen = false;
3435 comments_seen = false;
3441 if (d >= '0' && d <= '9')
3442 return is_number (c);
3444 ltb.CreateOptional (current_source, ref_line, col, ref val);
3448 if (tokens_seen || comments_seen) {
3449 Eror_WrongPreprocessorLocation ();
3453 if (ParsePreprocessingDirective (true))
3456 bool directive_expected = false;
3457 while ((c = get_char ()) != -1) {
3459 directive_expected = true;
3460 } else if (!directive_expected) {
3461 // TODO: Implement comment support for disabled code and uncomment this code
3463 // Eror_WrongPreprocessorLocation ();
3464 // return Token.ERROR;
3469 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3473 if (ParsePreprocessingDirective (false))
3476 directive_expected = false;
3480 tokens_seen = false;
3487 return consume_string (false);
3490 return TokenizeBackslash ();
3496 return consume_string (true);
3499 if (is_identifier_start_character (c)){
3500 return consume_identifier (c, true);
3503 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3506 case EvalStatementParserCharacter:
3507 return Token.EVAL_STATEMENT_PARSER;
3508 case EvalCompilationUnitParserCharacter:
3509 return Token.EVAL_COMPILATION_UNIT_PARSER;
3510 case EvalUsingDeclarationsParserCharacter:
3511 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3512 case DocumentationXref:
3513 return Token.DOC_SEE;
3516 if (is_identifier_start_character (c)) {
3518 return consume_identifier (c);
3521 if (char.IsWhiteSpace ((char) c))
3524 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3529 return Token.COMPLETE_COMPLETION;
3532 return Token.GENERATE_COMPLETION;
3539 int TokenizeBackslash ()
3542 int read_start = reader.Position;
3544 Location start_location = Location;
3545 int c = get_char ();
3548 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3549 Report.Error (1011, start_location, "Empty character literal");
3550 return Token.LITERAL;
3554 Report.Error (1010, start_location, "Newline in constant");
3559 c = escape (c, out d);
3563 throw new NotImplementedException ();
3565 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3570 Report.Error (1012, start_location, "Too many characters in character literal");
3572 // Try to recover, read until newline or next "'"
3573 while ((c = get_char ()) != -1) {
3574 if (c == '\n' || c == '\'')
3580 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3583 return Token.LITERAL;
3586 int TokenizeLessThan ()
3589 if (handle_typeof) {
3591 if (parse_generic_dimension (out d)) {
3594 return Token.GENERIC_DIMENSION;
3599 // Save current position and parse next token.
3601 if (parse_less_than ()) {
3602 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3603 d = Token.OP_GENERICS_LT_DECL;
3605 d = Token.OP_GENERICS_LT;
3612 parsing_generic_less_than = 0;
3621 return Token.OP_SHIFT_LEFT_ASSIGN;
3623 return Token.OP_SHIFT_LEFT;
3634 // Handles one line xml comment
3636 private void handle_one_line_xml_comment ()
3639 while ((c = peek_char ()) == ' ')
3640 get_char (); // skip heading whitespaces.
3641 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3642 xml_comment_buffer.Append ((char) get_char ());
3644 if (c == '\r' || c == '\n')
3645 xml_comment_buffer.Append (Environment.NewLine);
3649 // Remove heading "*" in Javadoc-like xml documentation.
3651 private void update_formatted_doc_comment (int current_comment_start)
3653 int length = xml_comment_buffer.Length - current_comment_start;
3654 string [] lines = xml_comment_buffer.ToString (
3655 current_comment_start,
3656 length).Replace ("\r", "").Split ('\n');
3658 // The first line starts with /**, thus it is not target
3659 // for the format check.
3660 for (int i = 1; i < lines.Length; i++) {
3661 string s = lines [i];
3662 int idx = s.IndexOf ('*');
3665 if (i < lines.Length - 1)
3669 head = s.Substring (0, idx);
3670 foreach (char c in head)
3673 lines [i] = s.Substring (idx + 1);
3675 xml_comment_buffer.Remove (current_comment_start, length);
3676 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3680 // Checks if there was incorrect doc comments and raise
3683 public void check_incorrect_doc_comment ()
3685 if (xml_comment_buffer.Length > 0)
3686 WarningMisplacedComment (Location);
3690 // Consumes the saved xml comment lines (if any)
3691 // as for current target member or type.
3693 public string consume_doc_comment ()
3695 if (xml_comment_buffer.Length > 0) {
3696 string ret = xml_comment_buffer.ToString ();
3697 reset_doc_comment ();
3704 get { return context.Report; }
3707 void reset_doc_comment ()
3709 xml_comment_buffer.Length = 0;
3712 public void cleanup ()
3714 if (ifstack != null && ifstack.Count >= 1) {
3715 int state = ifstack.Pop ();
3716 if ((state & REGION) != 0)
3717 Report.Error (1038, Location, "#endregion directive expected");
3719 Report.Error (1027, Location, "Expected `#endif' directive");
3725 // Indicates whether it accepts XML documentation or not.
3727 public enum XmlCommentState {
3728 // comment is allowed in this state.
3730 // comment is not allowed in this state.
3732 // once comments appeared when it is NotAllowed, then the
3733 // state is changed to it, until the state is changed to