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;
24 /// Tokenizer for C# source code.
27 public class Tokenizer : yyParser.yyInput
31 public readonly T Token;
32 public KeywordEntry<T> Next;
33 public readonly char[] Value;
35 public KeywordEntry (string value, T token)
37 this.Value = value.ToCharArray ();
42 sealed class IdentifiersComparer : IEqualityComparer<char[]>
46 public IdentifiersComparer (int length)
51 public bool Equals (char[] x, char[] y)
53 for (int i = 0; i < length; ++i)
60 public int GetHashCode (char[] obj)
63 for (int i = 0; i < length; ++i)
64 h = (h << 5) - h + obj [i];
71 // This class has to be used in the parser only, it reuses token
72 // details after each parse
74 public class LocatedToken
79 static LocatedToken[] buffer = new LocatedToken[0];
82 private LocatedToken ()
86 public static LocatedToken Create (int row, int column)
88 return Create (null, row, column);
91 public static LocatedToken Create (string value, Location loc)
93 return Create (value, loc.Row, loc.Column);
96 public static LocatedToken Create (string value, int row, int column)
99 // TODO: I am not very happy about the logic but it's the best
100 // what I could come up with for now.
101 // Ideally we should be using just tiny buffer (256 elements) which
102 // is enough to hold all details for currect stack and recycle elements
103 // poped from the stack but there is a trick needed to recycle
107 if (pos >= buffer.Length) {
108 entry = new LocatedToken ();
110 entry = buffer [pos];
112 entry = new LocatedToken ();
113 buffer [pos] = entry;
120 entry.column = column;
125 // Used for token not required by expression evaluator
127 [Conditional ("FULL_AST")]
128 public static void CreateOptional (int row, int col, ref object token)
130 token = Create (row, col);
133 public static void Initialize ()
136 if (buffer.Length == 0)
137 buffer = new LocatedToken [15000];
142 public override string ToString ()
144 return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
147 public Location Location {
148 get { return new Location (row, column); }
151 public string Value {
152 get { return value; }
156 public enum PreprocessorDirective
162 If = 3 | RequiresArgument,
164 Elif = 5 | RequiresArgument,
166 Define = 7 | RequiresArgument,
167 Undef = 8 | RequiresArgument,
170 Pragma = 11 | CustomArgumentsParsing,
171 Line = 12 | CustomArgumentsParsing,
173 CustomArgumentsParsing = 1 << 10,
174 RequiresArgument = 1 << 11
177 readonly SeekableStreamReader reader;
178 readonly CompilationSourceFile source_file;
179 readonly CompilerContext context;
181 SourceFile current_source;
182 Location hidden_block_start;
188 readonly int tab_size;
189 bool handle_get_set = false;
190 bool handle_remove_add = false;
191 bool handle_where = false;
192 bool handle_typeof = false;
193 bool lambda_arguments_parsing;
194 List<Location> escaped_identifiers;
195 int parsing_generic_less_than;
196 readonly bool doc_processing;
199 // Used mainly for parser optimizations. Some expressions for instance
200 // can appear only in block (including initializer, base initializer)
203 public int parsing_block;
204 internal bool query_parsing;
207 // When parsing type only, useful for ambiguous nullable types
209 public int parsing_type;
212 // Set when parsing generic declaration (type or method header)
214 public bool parsing_generic_declaration;
215 public bool parsing_generic_declaration_doc;
218 // The value indicates that we have not reach any declaration or
221 public int parsing_declaration;
223 public bool parsing_attribute_section;
225 public bool parsing_modifiers;
228 // The special characters to inject on streams to run the unit parser
229 // in the special expression mode. Using private characters from
230 // Plane Sixteen (U+100000 to U+10FFFD)
232 // This character is only tested just before the tokenizer is about to report
233 // an error; So on the regular operation mode, this addition will have no
234 // impact on the tokenizer's performance.
237 public const int EvalStatementParserCharacter = 0x100000;
238 public const int EvalCompilationUnitParserCharacter = 0x100001;
239 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
240 public const int DocumentationXref = 0x100003;
243 // XML documentation buffer. The save point is used to divide
244 // comments on types and comments on members.
246 StringBuilder xml_comment_buffer;
249 // See comment on XmlCommentState enumeration.
251 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
254 // Whether tokens have been seen on this line
256 bool tokens_seen = false;
259 // Set to true once the GENERATE_COMPLETION token has bee
260 // returned. This helps produce one GENERATE_COMPLETION,
261 // as many COMPLETE_COMPLETION as necessary to complete the
262 // AST tree and one final EOF.
267 // Whether a token has been seen on the file
268 // This is needed because `define' is not allowed to be used
269 // after a token has been seen.
276 static readonly KeywordEntry<int>[][] keywords;
277 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
278 static readonly HashSet<string> keyword_strings;
279 static readonly NumberStyles styles;
280 static readonly NumberFormatInfo csharp_format_info;
283 static readonly char[] pragma_warning = "warning".ToCharArray ();
284 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
285 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
286 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
287 static readonly char[] line_hidden = "hidden".ToCharArray ();
288 static readonly char[] line_default = "default".ToCharArray ();
290 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
292 public bool PropertyParsing {
293 get { return handle_get_set; }
294 set { handle_get_set = value; }
297 public bool EventParsing {
298 get { return handle_remove_add; }
299 set { handle_remove_add = value; }
302 public bool ConstraintsParsing {
303 get { return handle_where; }
304 set { handle_where = value; }
307 public bool TypeOfParsing {
308 get { return handle_typeof; }
309 set { handle_typeof = value; }
312 public XmlCommentState doc_state {
313 get { return xml_doc_state; }
315 if (value == XmlCommentState.Allowed) {
316 check_incorrect_doc_comment ();
317 reset_doc_comment ();
319 xml_doc_state = value;
324 // This is used to trigger completion generation on the parser
325 public bool CompleteOnEOF;
327 void AddEscapedIdentifier (Location loc)
329 if (escaped_identifiers == null)
330 escaped_identifiers = new List<Location> ();
332 escaped_identifiers.Add (loc);
335 public bool IsEscapedIdentifier (ATypeNameExpression name)
337 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
341 // Values for the associated token returned
343 internal int putback_char; // Used by repl only
349 const int TAKING = 1;
350 const int ELSE_SEEN = 4;
351 const int PARENT_TAKING = 8;
352 const int REGION = 16;
355 // pre-processor if stack state:
359 const int max_id_size = 512;
360 const int max_number_size = 512;
363 readonly char [] id_builder = new char [max_id_size];
365 Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
367 char [] number_builder = new char [max_number_size];
370 char[] value_builder = new char[256];
372 static readonly char [] id_builder = new char [max_id_size];
374 static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
376 static char [] number_builder = new char [max_number_size];
377 static int number_pos;
379 static char[] value_builder = new char[256];
389 // This is used when the tokenizer needs to save
390 // the current position as it needs to do some parsing
391 // on its own to deamiguate a token in behalf of the
394 Stack<Position> position_stack = new Stack<Position> (2);
401 public Location hidden;
402 public int putback_char;
403 public int previous_col;
404 public Stack<int> ifstack;
405 public int parsing_generic_less_than;
406 public int current_token;
409 public Position (Tokenizer t)
411 position = t.reader.Position;
413 ref_line = t.ref_line;
415 hidden = t.hidden_block_start;
416 putback_char = t.putback_char;
417 previous_col = t.previous_col;
418 if (t.ifstack != null && t.ifstack.Count != 0) {
419 // There is no simple way to clone Stack<T> all
420 // methods reverse the order
421 var clone = t.ifstack.ToArray ();
422 Array.Reverse (clone);
423 ifstack = new Stack<int> (clone);
425 parsing_generic_less_than = t.parsing_generic_less_than;
426 current_token = t.current_token;
431 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file)
433 this.source_file = file;
434 this.context = file.Compiler;
435 this.current_source = file.SourceFile;
441 xml_comment_buffer = new StringBuilder ();
442 doc_processing = context.Settings.DocumentationFile != null;
444 tab_size = context.Settings.TabSize;
446 Mono.CSharp.Location.Push (current_source);
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)
842 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
843 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
849 if (parsing_block == 0)
859 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
862 // Keywords are stored in an array of arrays grouped by their
863 // length and then by the first character
865 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
866 return PreprocessorDirective.Invalid;
868 int first_index = id[0] - '_';
869 if (first_index > 'z' - '_')
870 return PreprocessorDirective.Invalid;
872 var kwe = keywords_preprocessor[id_len][first_index];
874 return PreprocessorDirective.Invalid;
876 PreprocessorDirective res = PreprocessorDirective.Invalid;
879 for (int i = 1; i < id_len; ++i) {
880 if (id[i] != kwe.Value[i]) {
886 } while (res == PreprocessorDirective.Invalid && kwe != null);
891 public Location Location {
893 return new Location (ref_line, col);
897 static bool is_identifier_start_character (int c)
899 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
902 static bool is_identifier_part_character (char c)
904 if (c >= 'a' && c <= 'z')
907 if (c >= 'A' && c <= 'Z')
910 if (c == '_' || (c >= '0' && c <= '9'))
916 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
919 public static bool IsKeyword (string s)
921 return keyword_strings.Contains (s);
925 // Open parens micro parser. Detects both lambda and cast ambiguity.
927 int TokenizeOpenParens ()
932 int bracket_level = 0;
933 bool is_type = false;
934 bool can_be_type = false;
937 ptoken = current_token;
940 switch (current_token) {
941 case Token.CLOSE_PARENS:
945 // Expression inside parens is lambda, (int i) =>
947 if (current_token == Token.ARROW)
948 return Token.OPEN_PARENS_LAMBDA;
951 // Expression inside parens is single type, (int[])
954 return Token.OPEN_PARENS_CAST;
957 // Expression is possible cast, look at next token, (T)null
960 switch (current_token) {
961 case Token.OPEN_PARENS:
964 case Token.IDENTIFIER:
978 case Token.UNCHECKED:
984 // These can be part of a member access
998 return Token.OPEN_PARENS_CAST;
1001 return Token.OPEN_PARENS;
1004 case Token.DOUBLE_COLON:
1005 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1010 case Token.IDENTIFIER:
1013 if (bracket_level == 0) {
1019 case Token.OP_GENERICS_LT:
1021 case Token.DOUBLE_COLON:
1023 if (bracket_level == 0)
1027 can_be_type = is_type = false;
1047 if (bracket_level == 0)
1052 if (bracket_level == 0) {
1053 bracket_level = 100;
1054 can_be_type = is_type = false;
1058 case Token.OP_GENERICS_LT:
1059 case Token.OPEN_BRACKET:
1060 if (bracket_level++ == 0)
1064 case Token.OP_GENERICS_GT:
1065 case Token.CLOSE_BRACKET:
1069 case Token.INTERR_NULLABLE:
1071 if (bracket_level == 0)
1077 can_be_type = is_type = false;
1081 return Token.OPEN_PARENS;
1086 public static bool IsValidIdentifier (string s)
1088 if (s == null || s.Length == 0)
1091 if (!is_identifier_start_character (s [0]))
1094 for (int i = 1; i < s.Length; i ++)
1095 if (! is_identifier_part_character (s [i]))
1101 bool parse_less_than ()
1104 int the_token = token ();
1105 if (the_token == Token.OPEN_BRACKET) {
1107 the_token = token ();
1108 } while (the_token != Token.CLOSE_BRACKET);
1109 the_token = token ();
1110 } else if (the_token == Token.IN || the_token == Token.OUT) {
1111 the_token = token ();
1113 switch (the_token) {
1114 case Token.IDENTIFIER:
1132 case Token.OP_GENERICS_GT:
1141 the_token = token ();
1143 if (the_token == Token.OP_GENERICS_GT)
1145 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1147 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1149 else if (the_token == Token.OP_GENERICS_LT) {
1150 if (!parse_less_than ())
1153 } else if (the_token == Token.OPEN_BRACKET) {
1155 the_token = token ();
1156 if (the_token == Token.CLOSE_BRACKET)
1158 else if (the_token == Token.COMMA)
1159 goto rank_specifiers;
1166 bool parse_generic_dimension (out int dimension)
1171 int the_token = token ();
1172 if (the_token == Token.OP_GENERICS_GT)
1174 else if (the_token == Token.COMMA) {
1182 public int peek_token ()
1187 the_token = token ();
1194 // Tonizes `?' using custom disambiguous rules to return one
1195 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1197 // Tricky expression look like:
1199 // Foo ? a = x ? b : c;
1201 int TokenizePossibleNullableType ()
1203 if (parsing_block == 0 || parsing_type > 0)
1204 return Token.INTERR_NULLABLE;
1206 int d = peek_char ();
1209 return Token.OP_COALESCING;
1212 switch (current_token) {
1213 case Token.CLOSE_PARENS:
1218 return Token.INTERR;
1222 if (d == ',' || d == ';' || d == '>')
1223 return Token.INTERR_NULLABLE;
1224 if (d == '*' || (d >= '0' && d <= '9'))
1225 return Token.INTERR;
1229 current_token = Token.NONE;
1231 switch (xtoken ()) {
1238 next_token = Token.INTERR;
1241 case Token.SEMICOLON:
1243 case Token.CLOSE_PARENS:
1244 case Token.OPEN_BRACKET:
1245 case Token.OP_GENERICS_GT:
1247 next_token = Token.INTERR_NULLABLE;
1255 if (next_token == -1) {
1256 switch (xtoken ()) {
1258 case Token.SEMICOLON:
1259 case Token.OPEN_BRACE:
1260 case Token.CLOSE_PARENS:
1262 next_token = Token.INTERR_NULLABLE;
1266 next_token = Token.INTERR;
1275 // All shorcuts failed, do it hard way
1277 while ((ntoken = xtoken ()) != Token.EOF) {
1278 if (ntoken == Token.OPEN_BRACE) {
1283 if (ntoken == Token.CLOSE_BRACE) {
1291 if (ntoken == Token.SEMICOLON)
1294 if (ntoken == Token.COLON) {
1295 if (++colons == interrs)
1300 if (ntoken == Token.INTERR) {
1306 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1315 bool decimal_digits (int c)
1318 bool seen_digits = false;
1321 if (number_pos == max_number_size)
1322 Error_NumericConstantTooLong ();
1323 number_builder [number_pos++] = (char) c;
1327 // We use peek_char2, because decimal_digits needs to do a
1328 // 2-character look-ahead (5.ToString for example).
1330 while ((d = peek_char2 ()) != -1){
1331 if (d >= '0' && d <= '9'){
1332 if (number_pos == max_number_size)
1333 Error_NumericConstantTooLong ();
1334 number_builder [number_pos++] = (char) d;
1344 static bool is_hex (int e)
1346 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1349 static TypeCode real_type_suffix (int c)
1353 return TypeCode.Single;
1355 return TypeCode.Double;
1357 return TypeCode.Decimal;
1359 return TypeCode.Empty;
1363 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1365 bool is_unsigned = false;
1366 bool is_long = false;
1369 bool scanning = true;
1382 // if we have not seen anything in between
1383 // report this error
1385 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1405 if (is_long && is_unsigned){
1406 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1410 // uint if possible, or ulong else.
1412 if ((ul & 0xffffffff00000000) == 0)
1413 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1415 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1416 } else if (is_long){
1417 // long if possible, ulong otherwise
1418 if ((ul & 0x8000000000000000) != 0)
1419 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1421 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1423 // int, uint, long or ulong in that order
1424 if ((ul & 0xffffffff00000000) == 0){
1425 uint ui = (uint) ul;
1427 if ((ui & 0x80000000) != 0)
1428 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1430 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1432 if ((ul & 0x8000000000000000) != 0)
1433 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1435 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1441 // given `c' as the next char in the input decide whether
1442 // we need to convert to a special type, and then choose
1443 // the best representation for the integer
1445 ILiteralConstant adjust_int (int c, Location loc)
1448 if (number_pos > 9){
1449 ulong ul = (uint) (number_builder [0] - '0');
1451 for (int i = 1; i < number_pos; i++){
1452 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1455 return integer_type_suffix (ul, c, loc);
1457 uint ui = (uint) (number_builder [0] - '0');
1459 for (int i = 1; i < number_pos; i++){
1460 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1463 return integer_type_suffix (ui, c, loc);
1465 } catch (OverflowException) {
1466 Error_NumericConstantTooLong ();
1467 return new IntLiteral (context.BuiltinTypes, 0, loc);
1469 catch (FormatException) {
1470 Report.Error (1013, Location, "Invalid number");
1471 return new IntLiteral (context.BuiltinTypes, 0, loc);
1475 ILiteralConstant adjust_real (TypeCode t, Location loc)
1477 string s = new string (number_builder, 0, number_pos);
1478 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1481 case TypeCode.Decimal:
1483 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1484 } catch (OverflowException) {
1485 Report.Error (594, Location, error_details, "decimal");
1486 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1488 case TypeCode.Single:
1490 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1491 } catch (OverflowException) {
1492 Report.Error (594, Location, error_details, "float");
1493 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1497 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1498 } catch (OverflowException) {
1499 Report.Error (594, loc, error_details, "double");
1500 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1505 ILiteralConstant handle_hex (Location loc)
1511 while ((d = peek_char ()) != -1){
1513 number_builder [number_pos++] = (char) d;
1519 string s = new String (number_builder, 0, number_pos);
1522 if (number_pos <= 8)
1523 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1525 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1527 return integer_type_suffix (ul, peek_char (), loc);
1528 } catch (OverflowException){
1529 Error_NumericConstantTooLong ();
1530 return new IntLiteral (context.BuiltinTypes, 0, loc);
1532 catch (FormatException) {
1533 Report.Error (1013, Location, "Invalid number");
1534 return new IntLiteral (context.BuiltinTypes, 0, loc);
1539 // Invoked if we know we have .digits or digits
1541 int is_number (int c)
1543 ILiteralConstant res;
1546 int read_start = reader.Position - 1;
1549 // Caller did peek_char
1557 if (c >= '0' && c <= '9'){
1559 int peek = peek_char ();
1561 if (peek == 'x' || peek == 'X') {
1562 val = res = handle_hex (loc);
1564 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1567 return Token.LITERAL;
1575 // We need to handle the case of
1576 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1578 bool is_real = false;
1580 if (decimal_digits ('.')){
1586 val = res = adjust_int (-1, loc);
1589 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1591 return Token.LITERAL;
1595 if (c == 'e' || c == 'E'){
1597 if (number_pos == max_number_size)
1598 Error_NumericConstantTooLong ();
1599 number_builder [number_pos++] = (char) c;
1603 if (number_pos == max_number_size)
1604 Error_NumericConstantTooLong ();
1605 number_builder [number_pos++] = '+';
1607 } else if (c == '-') {
1608 if (number_pos == max_number_size)
1609 Error_NumericConstantTooLong ();
1610 number_builder [number_pos++] = '-';
1613 if (number_pos == max_number_size)
1614 Error_NumericConstantTooLong ();
1615 number_builder [number_pos++] = '+';
1622 var type = real_type_suffix (c);
1623 if (type == TypeCode.Empty && !is_real) {
1625 res = adjust_int (c, loc);
1629 if (type == TypeCode.Empty) {
1633 res = adjust_real (type, loc);
1639 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1640 if (chars[chars.Length - 1] == '\r')
1641 Array.Resize (ref chars, chars.Length - 1);
1642 res.ParsedValue = chars;
1645 return Token.LITERAL;
1649 // Accepts exactly count (4 or 8) hex, no more no less
1651 int getHex (int count, out int surrogate, out bool error)
1656 int top = count != -1 ? count : 4;
1661 for (i = 0; i < top; i++){
1664 if (c >= '0' && c <= '9')
1665 c = (int) c - (int) '0';
1666 else if (c >= 'A' && c <= 'F')
1667 c = (int) c - (int) 'A' + 10;
1668 else if (c >= 'a' && c <= 'f')
1669 c = (int) c - (int) 'a' + 10;
1675 total = (total * 16) + c;
1677 int p = peek_char ();
1680 if (!is_hex ((char)p))
1686 if (total > 0x0010FFFF) {
1691 if (total >= 0x00010000) {
1692 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1693 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1700 int escape (int c, out int surrogate)
1736 v = getHex (-1, out surrogate, out error);
1742 return EscapeUnicode (d, out surrogate);
1745 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1754 int EscapeUnicode (int ch, out int surrogate)
1758 ch = getHex (8, out surrogate, out error);
1760 ch = getHex (4, out surrogate, out error);
1764 Report.Error (1009, Location, "Unrecognized escape sequence");
1772 if (putback_char != -1) {
1780 if (peek_char () == '\n') {
1786 } else if (x == '\n') {
1794 void advance_line ()
1804 if (putback_char == -1)
1805 putback_char = reader.Read ();
1806 return putback_char;
1811 if (putback_char != -1)
1812 return putback_char;
1813 return reader.Peek ();
1816 public void putback (int c)
1818 if (putback_char != -1) {
1819 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
1822 if (c == '\n' || col == 0) {
1823 // It won't happen though.
1833 public bool advance ()
1835 return peek_char () != -1 || CompleteOnEOF;
1838 public Object Value {
1844 public Object value ()
1851 current_token = xtoken ();
1852 return current_token;
1855 int TokenizePreprocessorIdentifier (out int c)
1857 // skip over white space
1860 } while (c == ' ' || c == '\t');
1864 while (c != -1 && c >= 'a' && c <= 'z') {
1865 id_builder[pos++] = (char) c;
1868 int peek = peek_char ();
1869 if (peek == 'U' || peek == 'u') {
1871 c = EscapeUnicode (c, out surrogate);
1872 if (surrogate != 0) {
1873 if (is_identifier_part_character ((char) c)) {
1874 id_builder[pos++] = (char) c;
1885 PreprocessorDirective get_cmd_arg (out string arg)
1889 tokens_seen = false;
1892 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1894 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1897 // skip over white space
1898 while (c == ' ' || c == '\t')
1901 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1904 while (c != -1 && c != '\n') {
1905 if (c == '\\' && has_identifier_argument >= 0) {
1906 if (has_identifier_argument != 0) {
1907 has_identifier_argument = 1;
1909 int peek = peek_char ();
1910 if (peek == 'U' || peek == 'u') {
1912 c = EscapeUnicode (c, out surrogate);
1913 if (surrogate != 0) {
1914 if (is_identifier_part_character ((char) c)) {
1915 if (pos == value_builder.Length)
1916 Array.Resize (ref value_builder, pos * 2);
1918 value_builder[pos++] = (char) c;
1924 has_identifier_argument = -1;
1926 } else if (c == '/' && peek_char () == '/') {
1928 // Eat single-line comments
1933 } while (c != -1 && c != '\n');
1938 if (pos == value_builder.Length)
1939 Array.Resize (ref value_builder, pos * 2);
1941 value_builder[pos++] = (char) c;
1946 if (pos > max_id_size)
1947 arg = new string (value_builder, 0, pos);
1949 arg = InternIdentifier (value_builder, pos);
1951 // Eat any trailing whitespaces
1952 arg = arg.Trim (simple_whitespaces);
1959 // Handles the #line directive
1961 bool PreProcessLine ()
1963 Location loc = Location;
1967 int length = TokenizePreprocessorIdentifier (out c);
1968 if (length == line_default.Length) {
1969 if (!IsTokenIdentifierEqual (line_default))
1972 current_source = source_file.SourceFile;
1973 if (!hidden_block_start.IsNull) {
1974 current_source.RegisterHiddenScope (hidden_block_start, loc);
1975 hidden_block_start = Location.Null;
1979 Location.Push (current_source);
1983 if (length == line_hidden.Length) {
1984 if (!IsTokenIdentifierEqual (line_hidden))
1987 if (hidden_block_start.IsNull)
1988 hidden_block_start = loc;
1993 if (length != 0 || c < '0' || c > '9') {
1995 // Eat any remaining characters to continue parsing on next line
1997 while (c != -1 && c != '\n') {
2004 int new_line = TokenizeNumber (c);
2007 // Eat any remaining characters to continue parsing on next line
2009 while (c != -1 && c != '\n') {
2013 return new_line != 0;
2018 // skip over white space
2021 } while (c == ' ' || c == '\t');
2022 } else if (c == '"') {
2026 if (c != '\n' && c != '/' && c != '"') {
2028 // Eat any remaining characters to continue parsing on next line
2030 while (c != -1 && c != '\n') {
2034 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2038 string new_file_name = null;
2040 new_file_name = TokenizeFileName (ref c);
2042 // skip over white space
2043 while (c == ' ' || c == '\t') {
2049 } else if (c == '/') {
2050 ReadSingleLineComment ();
2053 // Eat any remaining characters to continue parsing on next line
2055 while (c != -1 && c != '\n') {
2059 Error_EndLineExpected ();
2063 if (new_file_name != null) {
2064 current_source = context.LookupFile (source_file, new_file_name);
2065 source_file.AddIncludeFile (current_source);
2066 Location.Push (current_source);
2069 if (!hidden_block_start.IsNull) {
2070 current_source.RegisterHiddenScope (hidden_block_start, loc);
2071 hidden_block_start = Location.Null;
2074 ref_line = new_line;
2079 // Handles #define and #undef
2081 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2083 if (ident.Length == 0 || ident == "true" || ident == "false"){
2084 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2088 if (ident.IndexOfAny (simple_whitespaces) != -1){
2089 Error_EndLineExpected ();
2093 if (!is_identifier_start_character (ident [0]))
2094 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2096 foreach (char c in ident.Substring (1)){
2097 if (!is_identifier_part_character (c)){
2098 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2103 if (!caller_is_taking)
2110 if (context.Settings.IsConditionalSymbolDefined (ident))
2113 source_file.AddDefine (ident);
2118 source_file.AddUndefine (ident);
2122 byte read_hex (out bool error)
2125 int c = get_char ();
2127 if ((c >= '0') && (c <= '9'))
2128 total = (int) c - (int) '0';
2129 else if ((c >= 'A') && (c <= 'F'))
2130 total = (int) c - (int) 'A' + 10;
2131 else if ((c >= 'a') && (c <= 'f'))
2132 total = (int) c - (int) 'a' + 10;
2141 if ((c >= '0') && (c <= '9'))
2142 total += (int) c - (int) '0';
2143 else if ((c >= 'A') && (c <= 'F'))
2144 total += (int) c - (int) 'A' + 10;
2145 else if ((c >= 'a') && (c <= 'f'))
2146 total += (int) c - (int) 'a' + 10;
2153 return (byte) total;
2157 // Parses #pragma checksum
2159 bool ParsePragmaChecksum ()
2162 // The syntax is ` "foo.txt" "{guid}" "hash"'
2164 int c = get_char ();
2169 string file_name = TokenizeFileName (ref c);
2171 // TODO: Any white-spaces count
2175 SourceFile file = context.LookupFile (source_file, file_name);
2177 if (get_char () != '"' || get_char () != '{')
2181 byte[] guid_bytes = new byte [16];
2184 for (; i < 4; i++) {
2185 guid_bytes [i] = read_hex (out error);
2190 if (get_char () != '-')
2193 for (; i < 10; i++) {
2194 guid_bytes [i] = read_hex (out error);
2198 guid_bytes [i++] = read_hex (out error);
2202 if (get_char () != '-')
2206 for (; i < 16; i++) {
2207 guid_bytes [i] = read_hex (out error);
2212 if (get_char () != '}' || get_char () != '"')
2215 // TODO: Any white-spaces count
2220 if (get_char () != '"')
2223 // Any length of checksum
2224 List<byte> checksum_bytes = new List<byte> (16);
2227 while (c != '"' && c != -1) {
2228 checksum_bytes.Add (read_hex (out error));
2236 ReadSingleLineComment ();
2237 } else if (get_char () != '"') {
2241 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2242 current_source.AutoGenerated = true;
2249 bool IsTokenIdentifierEqual (char[] identifier)
2251 for (int i = 0; i < identifier.Length; ++i) {
2252 if (identifier[i] != id_builder[i])
2259 int TokenizeNumber (int value)
2263 decimal_digits (value);
2264 uint ui = (uint) (number_builder[0] - '0');
2267 for (int i = 1; i < number_pos; i++) {
2268 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2272 } catch (OverflowException) {
2273 Error_NumericConstantTooLong ();
2278 string TokenizeFileName (ref int c)
2280 var string_builder = new StringBuilder ();
2281 while (c != -1 && c != '\n') {
2288 string_builder.Append ((char) c);
2291 if (string_builder.Length == 0) {
2292 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2296 return string_builder.ToString ();
2299 int TokenizePragmaNumber (ref int c)
2305 if (c >= '0' && c <= '9') {
2306 number = TokenizeNumber (c);
2310 // skip over white space
2311 while (c == ' ' || c == '\t')
2318 // skip over white space
2319 while (c == ' ' || c == '\t')
2324 ReadSingleLineComment ();
2326 Report.Warning (1692, 1, Location, "Invalid number");
2328 // Read everything till the end of the line or file
2331 } while (c != -1 && c != '\n');
2338 void ReadSingleLineComment ()
2340 if (peek_char () != '/')
2341 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2343 // Read everything till the end of the line or file
2347 } while (c != -1 && c != '\n');
2351 /// Handles #pragma directive
2353 void ParsePragmaDirective (string arg)
2356 int length = TokenizePreprocessorIdentifier (out c);
2357 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2358 length = TokenizePreprocessorIdentifier (out c);
2361 // #pragma warning disable
2362 // #pragma warning restore
2364 if (length == pragma_warning_disable.Length) {
2365 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2366 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2367 // skip over white space
2368 while (c == ' ' || c == '\t')
2373 if (c == '\n' || c == '/') {
2375 ReadSingleLineComment ();
2378 // Disable/Restore all warnings
2381 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2383 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2387 // Disable/Restore a warning or group of warnings
2391 code = TokenizePragmaNumber (ref c);
2394 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2396 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2399 } while (code >= 0 && c != '\n' && c != -1);
2406 Report.Warning (1634, 1, Location, "Expected disable or restore");
2413 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2414 if (c != ' ' || !ParsePragmaChecksum ()) {
2415 Report.Warning (1695, 1, Location,
2416 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2422 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2425 bool eval_val (string s)
2432 return source_file.IsConditionalDefined (s);
2435 bool pp_primary (ref string s)
2444 s = s.Substring (1);
2445 bool val = pp_expr (ref s, false);
2446 if (s.Length > 0 && s [0] == ')'){
2447 s = s.Substring (1);
2450 Error_InvalidDirective ();
2454 if (is_identifier_start_character (c)){
2460 if (is_identifier_part_character (c)){
2464 bool v = eval_val (s.Substring (0, j));
2465 s = s.Substring (j);
2468 bool vv = eval_val (s);
2473 Error_InvalidDirective ();
2477 bool pp_unary (ref string s)
2484 if (len > 1 && s [1] == '='){
2485 Error_InvalidDirective ();
2488 s = s.Substring (1);
2489 return ! pp_primary (ref s);
2491 return pp_primary (ref s);
2493 Error_InvalidDirective ();
2498 bool pp_eq (ref string s)
2500 bool va = pp_unary (ref s);
2506 if (len > 2 && s [1] == '='){
2507 s = s.Substring (2);
2508 return va == pp_unary (ref s);
2510 Error_InvalidDirective ();
2513 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2514 s = s.Substring (2);
2516 return va != pp_unary (ref s);
2525 bool pp_and (ref string s)
2527 bool va = pp_eq (ref s);
2533 if (len > 2 && s [1] == '&'){
2534 s = s.Substring (2);
2535 return (va & pp_and (ref s));
2537 Error_InvalidDirective ();
2546 // Evaluates an expression for `#if' or `#elif'
2548 bool pp_expr (ref string s, bool isTerm)
2550 bool va = pp_and (ref s);
2557 if (len > 2 && s [1] == '|'){
2558 s = s.Substring (2);
2559 return va | pp_expr (ref s, isTerm);
2561 Error_InvalidDirective ();
2566 Error_EndLineExpected ();
2574 bool eval (string s)
2576 bool v = pp_expr (ref s, true);
2585 void Error_NumericConstantTooLong ()
2587 Report.Error (1021, Location, "Integral constant is too large");
2590 void Error_InvalidDirective ()
2592 Report.Error (1517, Location, "Invalid preprocessor directive");
2595 void Error_UnexpectedDirective (string extra)
2599 "Unexpected processor directive ({0})", extra);
2602 void Error_TokensSeen ()
2604 Report.Error (1032, Location,
2605 "Cannot define or undefine preprocessor symbols after first token in file");
2608 void Eror_WrongPreprocessorLocation ()
2610 Report.Error (1040, Location,
2611 "Preprocessor directives must appear as the first non-whitespace character on a line");
2614 void Error_EndLineExpected ()
2616 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2620 // Raises a warning when tokenizer found documentation comment
2621 // on unexpected place
2623 void WarningMisplacedComment (Location loc)
2625 if (doc_state != XmlCommentState.Error) {
2626 doc_state = XmlCommentState.Error;
2627 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2632 // if true, then the code continues processing the code
2633 // if false, the code stays in a loop until another directive is
2635 // When caller_is_taking is false we ignore all directives except the ones
2636 // which can help us to identify where the #if block ends
2637 bool ParsePreprocessingDirective (bool caller_is_taking)
2640 bool region_directive = false;
2642 var directive = get_cmd_arg (out arg);
2645 // The first group of pre-processing instructions is always processed
2647 switch (directive) {
2648 case PreprocessorDirective.Region:
2649 region_directive = true;
2651 goto case PreprocessorDirective.If;
2653 case PreprocessorDirective.Endregion:
2654 if (ifstack == null || ifstack.Count == 0){
2655 Error_UnexpectedDirective ("no #region for this #endregion");
2658 int pop = ifstack.Pop ();
2660 if ((pop & REGION) == 0)
2661 Report.Error (1027, Location, "Expected `#endif' directive");
2663 return caller_is_taking;
2665 case PreprocessorDirective.If:
2666 if (ifstack == null)
2667 ifstack = new Stack<int> (2);
2669 int flags = region_directive ? REGION : 0;
2670 if (ifstack.Count == 0){
2671 flags |= PARENT_TAKING;
2673 int state = ifstack.Peek ();
2674 if ((state & TAKING) != 0) {
2675 flags |= PARENT_TAKING;
2679 if (eval (arg) && caller_is_taking) {
2680 ifstack.Push (flags | TAKING);
2683 ifstack.Push (flags);
2686 case PreprocessorDirective.Endif:
2687 if (ifstack == null || ifstack.Count == 0){
2688 Error_UnexpectedDirective ("no #if for this #endif");
2691 pop = ifstack.Pop ();
2693 if ((pop & REGION) != 0)
2694 Report.Error (1038, Location, "#endregion directive expected");
2696 if (arg.Length != 0) {
2697 Error_EndLineExpected ();
2700 if (ifstack.Count == 0)
2703 int state = ifstack.Peek ();
2704 return (state & TAKING) != 0;
2707 case PreprocessorDirective.Elif:
2708 if (ifstack == null || ifstack.Count == 0){
2709 Error_UnexpectedDirective ("no #if for this #elif");
2712 int state = ifstack.Pop ();
2714 if ((state & REGION) != 0) {
2715 Report.Error (1038, Location, "#endregion directive expected");
2719 if ((state & ELSE_SEEN) != 0){
2720 Error_UnexpectedDirective ("#elif not valid after #else");
2724 if ((state & TAKING) != 0) {
2729 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2730 ifstack.Push (state | TAKING);
2734 ifstack.Push (state);
2738 case PreprocessorDirective.Else:
2739 if (ifstack == null || ifstack.Count == 0){
2740 Error_UnexpectedDirective ("no #if for this #else");
2743 int state = ifstack.Peek ();
2745 if ((state & REGION) != 0) {
2746 Report.Error (1038, Location, "#endregion directive expected");
2750 if ((state & ELSE_SEEN) != 0){
2751 Error_UnexpectedDirective ("#else within #else");
2757 if (arg.Length != 0) {
2758 Error_EndLineExpected ();
2763 if ((state & PARENT_TAKING) != 0) {
2764 ret = (state & TAKING) == 0;
2772 ifstack.Push (state | ELSE_SEEN);
2776 case PreprocessorDirective.Define:
2777 if (any_token_seen){
2778 Error_TokensSeen ();
2779 return caller_is_taking;
2781 PreProcessDefinition (true, arg, caller_is_taking);
2782 return caller_is_taking;
2784 case PreprocessorDirective.Undef:
2785 if (any_token_seen){
2786 Error_TokensSeen ();
2787 return caller_is_taking;
2789 PreProcessDefinition (false, arg, caller_is_taking);
2790 return caller_is_taking;
2792 case PreprocessorDirective.Invalid:
2793 Report.Error (1024, Location, "Wrong preprocessor directive");
2798 // These are only processed if we are in a `taking' block
2800 if (!caller_is_taking)
2804 case PreprocessorDirective.Error:
2805 Report.Error (1029, Location, "#error: '{0}'", arg);
2808 case PreprocessorDirective.Warning:
2809 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2812 case PreprocessorDirective.Pragma:
2813 if (context.Settings.Version == LanguageVersion.ISO_1) {
2814 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2817 ParsePragmaDirective (arg);
2820 case PreprocessorDirective.Line:
2821 Location loc = Location;
2822 if (!PreProcessLine ())
2823 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
2825 return caller_is_taking;
2828 throw new NotImplementedException (directive.ToString ());
2831 private int consume_string (bool quoted)
2835 Location start_location = Location;
2837 start_location = start_location - 1;
2840 int reader_pos = reader.Position;
2846 if (quoted && peek_char () == '"') {
2847 if (pos == value_builder.Length)
2848 Array.Resize (ref value_builder, pos * 2);
2850 value_builder[pos++] = (char) c;
2859 s = InternIdentifier (value_builder, pos);
2861 s = new string (value_builder, 0, pos);
2863 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2866 res.ParsedValue = quoted ?
2867 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2868 reader.ReadChars (reader_pos - 1, reader.Position);
2871 return Token.LITERAL;
2876 Report.Error (1010, Location, "Newline in constant");
2877 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2878 return Token.LITERAL;
2880 } else if (c == '\\' && !quoted) {
2882 c = escape (c, out surrogate);
2885 if (surrogate != 0) {
2886 if (pos == value_builder.Length)
2887 Array.Resize (ref value_builder, pos * 2);
2889 value_builder[pos++] = (char) c;
2892 } else if (c == -1) {
2893 Report.Error (1039, Location, "Unterminated string literal");
2897 if (pos == value_builder.Length)
2898 Array.Resize (ref value_builder, pos * 2);
2900 value_builder[pos++] = (char) c;
2904 private int consume_identifier (int s)
2906 int res = consume_identifier (s, false);
2908 if (doc_state == XmlCommentState.Allowed)
2909 doc_state = XmlCommentState.NotAllowed;
2914 int consume_identifier (int c, bool quoted)
2917 // This method is very performance sensitive. It accounts
2918 // for approximately 25% of all parser time
2928 c = escape (c, out surrogate);
2929 if (surrogate != 0) {
2930 id_builder [pos++] = (char) c;
2935 id_builder [pos++] = (char) c;
2941 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2942 id_builder [pos++] = (char) c;
2949 c = escape (c, out surrogate);
2950 if (is_identifier_part_character ((char) c))
2951 id_builder[pos++] = (char) c;
2953 if (surrogate != 0) {
2959 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2960 id_builder [pos++] = (char) c;
2967 } catch (IndexOutOfRangeException) {
2968 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2976 // Optimization: avoids doing the keyword lookup
2977 // on uppercase letters
2979 if (id_builder [0] >= '_' && !quoted) {
2980 int keyword = GetKeyword (id_builder, pos);
2981 if (keyword != -1) {
2982 val = LocatedToken.Create (keyword == Token.AWAIT ? "await" : null, ref_line, column);
2987 string s = InternIdentifier (id_builder, pos);
2988 val = LocatedToken.Create (s, ref_line, column);
2989 if (quoted && parsing_attribute_section)
2990 AddEscapedIdentifier (((LocatedToken) val).Location);
2992 return Token.IDENTIFIER;
2998 string InternIdentifier (char[] charBuffer, int length)
3001 // Keep identifiers in an array of hashtables to avoid needless
3004 var identifiers_group = identifiers[length];
3006 if (identifiers_group != null) {
3007 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3011 // TODO: this should be number of files dependant
3012 // corlib compilation peaks at 1000 and System.Core at 150
3013 int capacity = length > 20 ? 10 : 100;
3014 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3015 identifiers[length] = identifiers_group;
3018 char[] chars = new char[length];
3019 Array.Copy (charBuffer, chars, length);
3021 s = new string (charBuffer, 0, length);
3022 identifiers_group.Add (chars, s);
3026 public int xtoken ()
3030 // Whether we have seen comments on the current line
3031 bool comments_seen = false;
3032 while ((c = get_char ()) != -1) {
3035 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3043 case 0xFEFF: // Ignore BOM anywhere in the file
3046 /* This is required for compatibility with .NET
3048 if (peek_char () == 0xBB) {
3051 if (get_char () == 0xBF)
3059 return consume_identifier (c);
3062 val = LocatedToken.Create (ref_line, col);
3063 return Token.OPEN_BRACE;
3065 val = LocatedToken.Create (ref_line, col);
3066 return Token.CLOSE_BRACE;
3068 // To block doccomment inside attribute declaration.
3069 if (doc_state == XmlCommentState.Allowed)
3070 doc_state = XmlCommentState.NotAllowed;
3072 val = LocatedToken.Create (ref_line, col);
3074 if (parsing_block == 0 || lambda_arguments_parsing)
3075 return Token.OPEN_BRACKET;
3077 int next = peek_char ();
3081 return Token.OPEN_BRACKET;
3089 next = peek_token ();
3090 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3091 return Token.OPEN_BRACKET;
3093 return Token.OPEN_BRACKET_EXPR;
3095 return Token.OPEN_BRACKET_EXPR;
3098 LocatedToken.CreateOptional (ref_line, col, ref val);
3099 return Token.CLOSE_BRACKET;
3101 val = LocatedToken.Create (ref_line, col);
3103 // An expression versions of parens can appear in block context only
3105 if (parsing_block != 0 && !lambda_arguments_parsing) {
3108 // Optmize most common case where we know that parens
3111 switch (current_token) {
3112 case Token.IDENTIFIER:
3120 case Token.DELEGATE:
3121 case Token.OP_GENERICS_GT:
3122 return Token.OPEN_PARENS;
3125 // Optimize using peek
3126 int xx = peek_char ();
3133 return Token.OPEN_PARENS;
3136 lambda_arguments_parsing = true;
3138 d = TokenizeOpenParens ();
3140 lambda_arguments_parsing = false;
3144 return Token.OPEN_PARENS;
3146 LocatedToken.CreateOptional (ref_line, col, ref val);
3147 return Token.CLOSE_PARENS;
3149 LocatedToken.CreateOptional (ref_line, col, ref val);
3152 LocatedToken.CreateOptional (ref_line, col, ref val);
3153 return Token.SEMICOLON;
3155 val = LocatedToken.Create (ref_line, col);
3158 val = LocatedToken.Create (ref_line, col);
3159 return TokenizePossibleNullableType ();
3161 val = LocatedToken.Create (ref_line, col);
3162 if (parsing_generic_less_than++ > 0)
3163 return Token.OP_GENERICS_LT;
3165 return TokenizeLessThan ();
3168 val = LocatedToken.Create (ref_line, col);
3176 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3177 parsing_generic_less_than--;
3178 return Token.OP_GENERICS_GT;
3187 return Token.OP_SHIFT_RIGHT_ASSIGN;
3189 return Token.OP_SHIFT_RIGHT;
3195 val = LocatedToken.Create (ref_line, col);
3199 } else if (d == '=') {
3200 d = Token.OP_ADD_ASSIGN;
3208 val = LocatedToken.Create (ref_line, col);
3212 } else if (d == '=')
3213 d = Token.OP_SUB_ASSIGN;
3223 val = LocatedToken.Create (ref_line, col);
3224 if (peek_char () == '='){
3231 val = LocatedToken.Create (ref_line, col);
3242 return Token.ASSIGN;
3245 val = LocatedToken.Create (ref_line, col);
3249 return Token.OP_AND;
3253 return Token.OP_AND_ASSIGN;
3255 return Token.BITWISE_AND;
3258 val = LocatedToken.Create (ref_line, col);
3266 return Token.OP_OR_ASSIGN;
3268 return Token.BITWISE_OR;
3271 val = LocatedToken.Create (ref_line, col);
3272 if (peek_char () == '='){
3274 return Token.OP_MULT_ASSIGN;
3281 val = LocatedToken.Create (ref_line, col);
3283 return Token.OP_DIV_ASSIGN;
3286 // Handle double-slash comments.
3289 if (doc_processing) {
3290 if (peek_char () == '/') {
3292 // Don't allow ////.
3293 if ((d = peek_char ()) != '/') {
3294 if (doc_state == XmlCommentState.Allowed)
3295 handle_one_line_xml_comment ();
3296 else if (doc_state == XmlCommentState.NotAllowed)
3297 WarningMisplacedComment (Location - 3);
3300 if (xml_comment_buffer.Length > 0)
3301 doc_state = XmlCommentState.NotAllowed;
3305 while ((d = get_char ()) != -1 && d != '\n');
3307 any_token_seen |= tokens_seen;
3308 tokens_seen = false;
3309 comments_seen = false;
3311 } else if (d == '*'){
3313 bool docAppend = false;
3314 if (doc_processing && peek_char () == '*') {
3316 // But when it is /**/, just do nothing.
3317 if (peek_char () == '/') {
3321 if (doc_state == XmlCommentState.Allowed)
3323 else if (doc_state == XmlCommentState.NotAllowed) {
3324 WarningMisplacedComment (Location - 2);
3328 int current_comment_start = 0;
3330 current_comment_start = xml_comment_buffer.Length;
3331 xml_comment_buffer.Append (Environment.NewLine);
3334 while ((d = get_char ()) != -1){
3335 if (d == '*' && peek_char () == '/'){
3337 comments_seen = true;
3341 xml_comment_buffer.Append ((char) d);
3344 any_token_seen |= tokens_seen;
3345 tokens_seen = false;
3347 // Reset 'comments_seen' just to be consistent.
3348 // It doesn't matter either way, here.
3350 comments_seen = false;
3354 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3357 update_formatted_doc_comment (current_comment_start);
3360 val = LocatedToken.Create (ref_line, col);
3364 val = LocatedToken.Create (ref_line, col);
3365 if (peek_char () == '='){
3367 return Token.OP_MOD_ASSIGN;
3369 return Token.PERCENT;
3372 val = LocatedToken.Create (ref_line, col);
3373 if (peek_char () == '='){
3375 return Token.OP_XOR_ASSIGN;
3377 return Token.CARRET;
3380 val = LocatedToken.Create (ref_line, col);
3381 if (peek_char () == ':') {
3383 return Token.DOUBLE_COLON;
3387 case '0': case '1': case '2': case '3': case '4':
3388 case '5': case '6': case '7': case '8': case '9':
3390 return is_number (c);
3392 case '\n': // white space
3393 any_token_seen |= tokens_seen;
3394 tokens_seen = false;
3395 comments_seen = false;
3401 if (d >= '0' && d <= '9')
3402 return is_number (c);
3404 LocatedToken.CreateOptional (ref_line, col, ref val);
3408 if (tokens_seen || comments_seen) {
3409 Eror_WrongPreprocessorLocation ();
3413 if (ParsePreprocessingDirective (true))
3416 bool directive_expected = false;
3417 while ((c = get_char ()) != -1) {
3419 directive_expected = true;
3420 } else if (!directive_expected) {
3421 // TODO: Implement comment support for disabled code and uncomment this code
3423 // Eror_WrongPreprocessorLocation ();
3424 // return Token.ERROR;
3429 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3433 if (ParsePreprocessingDirective (false))
3436 directive_expected = false;
3440 tokens_seen = false;
3447 return consume_string (false);
3450 return TokenizeBackslash ();
3456 return consume_string (true);
3459 if (is_identifier_start_character (c)){
3460 return consume_identifier (c, true);
3463 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3466 case EvalStatementParserCharacter:
3467 return Token.EVAL_STATEMENT_PARSER;
3468 case EvalCompilationUnitParserCharacter:
3469 return Token.EVAL_COMPILATION_UNIT_PARSER;
3470 case EvalUsingDeclarationsParserCharacter:
3471 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3472 case DocumentationXref:
3473 return Token.DOC_SEE;
3476 if (is_identifier_start_character (c)) {
3478 return consume_identifier (c);
3481 if (char.IsWhiteSpace ((char) c))
3484 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3489 return Token.COMPLETE_COMPLETION;
3492 return Token.GENERATE_COMPLETION;
3499 int TokenizeBackslash ()
3502 int read_start = reader.Position;
3504 Location start_location = Location;
3505 int c = get_char ();
3508 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3509 Report.Error (1011, start_location, "Empty character literal");
3510 return Token.LITERAL;
3514 Report.Error (1010, start_location, "Newline in constant");
3519 c = escape (c, out d);
3523 throw new NotImplementedException ();
3525 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3530 Report.Error (1012, start_location, "Too many characters in character literal");
3532 // Try to recover, read until newline or next "'"
3533 while ((c = get_char ()) != -1) {
3534 if (c == '\n' || c == '\'')
3540 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3543 return Token.LITERAL;
3546 int TokenizeLessThan ()
3549 if (handle_typeof) {
3551 if (parse_generic_dimension (out d)) {
3554 return Token.GENERIC_DIMENSION;
3559 // Save current position and parse next token.
3561 if (parse_less_than ()) {
3562 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3563 d = Token.OP_GENERICS_LT_DECL;
3565 d = Token.OP_GENERICS_LT;
3572 parsing_generic_less_than = 0;
3581 return Token.OP_SHIFT_LEFT_ASSIGN;
3583 return Token.OP_SHIFT_LEFT;
3594 // Handles one line xml comment
3596 private void handle_one_line_xml_comment ()
3599 while ((c = peek_char ()) == ' ')
3600 get_char (); // skip heading whitespaces.
3601 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3602 xml_comment_buffer.Append ((char) get_char ());
3604 if (c == '\r' || c == '\n')
3605 xml_comment_buffer.Append (Environment.NewLine);
3609 // Remove heading "*" in Javadoc-like xml documentation.
3611 private void update_formatted_doc_comment (int current_comment_start)
3613 int length = xml_comment_buffer.Length - current_comment_start;
3614 string [] lines = xml_comment_buffer.ToString (
3615 current_comment_start,
3616 length).Replace ("\r", "").Split ('\n');
3618 // The first line starts with /**, thus it is not target
3619 // for the format check.
3620 for (int i = 1; i < lines.Length; i++) {
3621 string s = lines [i];
3622 int idx = s.IndexOf ('*');
3625 if (i < lines.Length - 1)
3629 head = s.Substring (0, idx);
3630 foreach (char c in head)
3633 lines [i] = s.Substring (idx + 1);
3635 xml_comment_buffer.Remove (current_comment_start, length);
3636 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3640 // Checks if there was incorrect doc comments and raise
3643 public void check_incorrect_doc_comment ()
3645 if (xml_comment_buffer.Length > 0)
3646 WarningMisplacedComment (Location);
3650 // Consumes the saved xml comment lines (if any)
3651 // as for current target member or type.
3653 public string consume_doc_comment ()
3655 if (xml_comment_buffer.Length > 0) {
3656 string ret = xml_comment_buffer.ToString ();
3657 reset_doc_comment ();
3664 get { return context.Report; }
3667 void reset_doc_comment ()
3669 xml_comment_buffer.Length = 0;
3672 public void cleanup ()
3674 if (ifstack != null && ifstack.Count >= 1) {
3675 int state = ifstack.Pop ();
3676 if ((state & REGION) != 0)
3677 Report.Error (1038, Location, "#endregion directive expected");
3679 Report.Error (1027, Location, "Expected `#endif' directive");
3685 // Indicates whether it accepts XML documentation or not.
3687 public enum XmlCommentState {
3688 // comment is allowed in this state.
3690 // comment is not allowed in this state.
3692 // once comments appeared when it is NotAllowed, then the
3693 // state is changed to it, until the state is changed to