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;
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, int row, int column)
94 // TODO: I am not very happy about the logic but it's the best
95 // what I could come up with for now.
96 // Ideally we should be using just tiny buffer (256 elements) which
97 // is enough to hold all details for currect stack and recycle elements
98 // poped from the stack but there is a trick needed to recycle
102 if (pos >= buffer.Length) {
103 entry = new LocatedToken ();
105 entry = buffer [pos];
107 entry = new LocatedToken ();
108 buffer [pos] = entry;
115 entry.column = column;
120 // Used for token not required by expression evaluator
122 [Conditional ("FULL_AST")]
123 public static void CreateOptional (int row, int col, ref object token)
125 token = Create (row, col);
128 public static void Initialize ()
131 buffer = new LocatedToken [10000];
135 public Location Location {
136 get { return new Location (row, column); }
139 public string Value {
140 get { return value; }
144 enum PreprocessorDirective
150 If = 3 | RequiresArgument,
152 Elif = 5 | RequiresArgument,
154 Define = 7 | RequiresArgument,
155 Undef = 8 | RequiresArgument,
158 Pragma = 11 | CustomArgumentsParsing,
161 CustomArgumentsParsing = 1 << 10,
162 RequiresArgument = 1 << 11
165 SeekableStreamReader reader;
167 CompilationSourceFile file_name;
168 CompilerContext context;
176 bool handle_get_set = false;
177 bool handle_remove_add = false;
178 bool handle_where = false;
179 bool handle_typeof = false;
180 bool lambda_arguments_parsing;
181 List<Location> escaped_identifiers;
182 int parsing_generic_less_than;
183 readonly bool doc_processing;
186 // Used mainly for parser optimizations. Some expressions for instance
187 // can appear only in block (including initializer, base initializer)
190 public int parsing_block;
191 internal bool query_parsing;
194 // When parsing type only, useful for ambiguous nullable types
196 public int parsing_type;
199 // Set when parsing generic declaration (type or method header)
201 public bool parsing_generic_declaration;
202 public bool parsing_generic_declaration_doc;
205 // The value indicates that we have not reach any declaration or
208 public int parsing_declaration;
210 public bool parsing_attribute_section;
212 public bool parsing_modifiers;
214 public bool async_block;
217 // The special characters to inject on streams to run the unit parser
218 // in the special expression mode. Using private characters from
219 // Plane Sixteen (U+100000 to U+10FFFD)
221 // This character is only tested just before the tokenizer is about to report
222 // an error; So on the regular operation mode, this addition will have no
223 // impact on the tokenizer's performance.
226 public const int EvalStatementParserCharacter = 0x100000;
227 public const int EvalCompilationUnitParserCharacter = 0x100001;
228 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
229 public const int DocumentationXref = 0x100003;
232 // XML documentation buffer. The save point is used to divide
233 // comments on types and comments on members.
235 StringBuilder xml_comment_buffer;
238 // See comment on XmlCommentState enumeration.
240 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
243 // Whether tokens have been seen on this line
245 bool tokens_seen = false;
248 // Set to true once the GENERATE_COMPLETION token has bee
249 // returned. This helps produce one GENERATE_COMPLETION,
250 // as many COMPLETE_COMPLETION as necessary to complete the
251 // AST tree and one final EOF.
256 // Whether a token has been seen on the file
257 // This is needed because `define' is not allowed to be used
258 // after a token has been seen.
265 static readonly KeywordEntry<int>[][] keywords;
266 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
267 static readonly Dictionary<string, object> keyword_strings; // TODO: HashSet
268 static readonly NumberStyles styles;
269 static readonly NumberFormatInfo csharp_format_info;
272 static readonly char[] pragma_warning = "warning".ToCharArray ();
273 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
274 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
275 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
277 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
279 public bool PropertyParsing {
280 get { return handle_get_set; }
281 set { handle_get_set = value; }
284 public bool EventParsing {
285 get { return handle_remove_add; }
286 set { handle_remove_add = value; }
289 public bool ConstraintsParsing {
290 get { return handle_where; }
291 set { handle_where = value; }
294 public bool TypeOfParsing {
295 get { return handle_typeof; }
296 set { handle_typeof = value; }
300 get { return tab_size; }
301 set { tab_size = value; }
304 public XmlCommentState doc_state {
305 get { return xml_doc_state; }
307 if (value == XmlCommentState.Allowed) {
308 check_incorrect_doc_comment ();
309 reset_doc_comment ();
311 xml_doc_state = value;
316 // This is used to trigger completion generation on the parser
317 public bool CompleteOnEOF;
319 void AddEscapedIdentifier (Location loc)
321 if (escaped_identifiers == null)
322 escaped_identifiers = new List<Location> ();
324 escaped_identifiers.Add (loc);
327 public bool IsEscapedIdentifier (MemberName name)
329 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
333 // Values for the associated token returned
335 internal int putback_char; // Used by repl only
341 const int TAKING = 1;
342 const int ELSE_SEEN = 4;
343 const int PARENT_TAKING = 8;
344 const int REGION = 16;
347 // pre-processor if stack state:
351 static System.Text.StringBuilder string_builder;
353 const int max_id_size = 512;
354 static readonly char [] id_builder = new char [max_id_size];
356 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
358 const int max_number_size = 512;
359 static char [] number_builder = new char [max_number_size];
360 static int number_pos;
362 static char[] value_builder = new char[256];
371 // This is used when the tokenizer needs to save
372 // the current position as it needs to do some parsing
373 // on its own to deamiguate a token in behalf of the
376 Stack<Position> position_stack = new Stack<Position> (2);
384 public int putback_char;
385 public int previous_col;
386 public Stack<int> ifstack;
387 public int parsing_generic_less_than;
388 public int current_token;
391 public Position (Tokenizer t)
393 position = t.reader.Position;
395 ref_line = t.ref_line;
398 putback_char = t.putback_char;
399 previous_col = t.previous_col;
400 if (t.ifstack != null && t.ifstack.Count != 0) {
401 // There is no simple way to clone Stack<T> all
402 // methods reverse the order
403 var clone = t.ifstack.ToArray ();
404 Array.Reverse (clone);
405 ifstack = new Stack<int> (clone);
407 parsing_generic_less_than = t.parsing_generic_less_than;
408 current_token = t.current_token;
413 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, CompilerContext ctx)
415 this.ref_name = file;
416 this.file_name = file;
422 xml_comment_buffer = new StringBuilder ();
423 doc_processing = ctx.Settings.DocumentationFile != null;
425 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
431 // FIXME: This could be `Location.Push' but we have to
432 // find out why the MS compiler allows this
434 Mono.CSharp.Location.Push (file, file);
437 public void PushPosition ()
439 position_stack.Push (new Position (this));
442 public void PopPosition ()
444 Position p = position_stack.Pop ();
446 reader.Position = p.position;
447 ref_line = p.ref_line;
451 putback_char = p.putback_char;
452 previous_col = p.previous_col;
454 parsing_generic_less_than = p.parsing_generic_less_than;
455 current_token = p.current_token;
459 // Do not reset the position, ignore it.
460 public void DiscardPosition ()
462 position_stack.Pop ();
465 static void AddKeyword (string kw, int token)
467 keyword_strings.Add (kw, null);
469 AddKeyword (keywords, kw, token);
472 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
474 AddKeyword (keywords_preprocessor, kw, directive);
477 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
479 int length = kw.Length;
480 if (keywords[length] == null) {
481 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
484 int char_index = kw[0] - '_';
485 var kwe = keywords[length][char_index];
487 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
491 while (kwe.Next != null) {
495 kwe.Next = new KeywordEntry<T> (kw, token);
503 keyword_strings = new Dictionary<string, object> ();
505 // 11 is the length of the longest keyword for now
506 keywords = new KeywordEntry<int>[11][];
508 AddKeyword ("__arglist", Token.ARGLIST);
509 AddKeyword ("__makeref", Token.MAKEREF);
510 AddKeyword ("__reftype", Token.REFTYPE);
511 AddKeyword ("__refvalue", Token.REFVALUE);
512 AddKeyword ("abstract", Token.ABSTRACT);
513 AddKeyword ("as", Token.AS);
514 AddKeyword ("add", Token.ADD);
515 AddKeyword ("base", Token.BASE);
516 AddKeyword ("bool", Token.BOOL);
517 AddKeyword ("break", Token.BREAK);
518 AddKeyword ("byte", Token.BYTE);
519 AddKeyword ("case", Token.CASE);
520 AddKeyword ("catch", Token.CATCH);
521 AddKeyword ("char", Token.CHAR);
522 AddKeyword ("checked", Token.CHECKED);
523 AddKeyword ("class", Token.CLASS);
524 AddKeyword ("const", Token.CONST);
525 AddKeyword ("continue", Token.CONTINUE);
526 AddKeyword ("decimal", Token.DECIMAL);
527 AddKeyword ("default", Token.DEFAULT);
528 AddKeyword ("delegate", Token.DELEGATE);
529 AddKeyword ("do", Token.DO);
530 AddKeyword ("double", Token.DOUBLE);
531 AddKeyword ("else", Token.ELSE);
532 AddKeyword ("enum", Token.ENUM);
533 AddKeyword ("event", Token.EVENT);
534 AddKeyword ("explicit", Token.EXPLICIT);
535 AddKeyword ("extern", Token.EXTERN);
536 AddKeyword ("false", Token.FALSE);
537 AddKeyword ("finally", Token.FINALLY);
538 AddKeyword ("fixed", Token.FIXED);
539 AddKeyword ("float", Token.FLOAT);
540 AddKeyword ("for", Token.FOR);
541 AddKeyword ("foreach", Token.FOREACH);
542 AddKeyword ("goto", Token.GOTO);
543 AddKeyword ("get", Token.GET);
544 AddKeyword ("if", Token.IF);
545 AddKeyword ("implicit", Token.IMPLICIT);
546 AddKeyword ("in", Token.IN);
547 AddKeyword ("int", Token.INT);
548 AddKeyword ("interface", Token.INTERFACE);
549 AddKeyword ("internal", Token.INTERNAL);
550 AddKeyword ("is", Token.IS);
551 AddKeyword ("lock", Token.LOCK);
552 AddKeyword ("long", Token.LONG);
553 AddKeyword ("namespace", Token.NAMESPACE);
554 AddKeyword ("new", Token.NEW);
555 AddKeyword ("null", Token.NULL);
556 AddKeyword ("object", Token.OBJECT);
557 AddKeyword ("operator", Token.OPERATOR);
558 AddKeyword ("out", Token.OUT);
559 AddKeyword ("override", Token.OVERRIDE);
560 AddKeyword ("params", Token.PARAMS);
561 AddKeyword ("private", Token.PRIVATE);
562 AddKeyword ("protected", Token.PROTECTED);
563 AddKeyword ("public", Token.PUBLIC);
564 AddKeyword ("readonly", Token.READONLY);
565 AddKeyword ("ref", Token.REF);
566 AddKeyword ("remove", Token.REMOVE);
567 AddKeyword ("return", Token.RETURN);
568 AddKeyword ("sbyte", Token.SBYTE);
569 AddKeyword ("sealed", Token.SEALED);
570 AddKeyword ("set", Token.SET);
571 AddKeyword ("short", Token.SHORT);
572 AddKeyword ("sizeof", Token.SIZEOF);
573 AddKeyword ("stackalloc", Token.STACKALLOC);
574 AddKeyword ("static", Token.STATIC);
575 AddKeyword ("string", Token.STRING);
576 AddKeyword ("struct", Token.STRUCT);
577 AddKeyword ("switch", Token.SWITCH);
578 AddKeyword ("this", Token.THIS);
579 AddKeyword ("throw", Token.THROW);
580 AddKeyword ("true", Token.TRUE);
581 AddKeyword ("try", Token.TRY);
582 AddKeyword ("typeof", Token.TYPEOF);
583 AddKeyword ("uint", Token.UINT);
584 AddKeyword ("ulong", Token.ULONG);
585 AddKeyword ("unchecked", Token.UNCHECKED);
586 AddKeyword ("unsafe", Token.UNSAFE);
587 AddKeyword ("ushort", Token.USHORT);
588 AddKeyword ("using", Token.USING);
589 AddKeyword ("virtual", Token.VIRTUAL);
590 AddKeyword ("void", Token.VOID);
591 AddKeyword ("volatile", Token.VOLATILE);
592 AddKeyword ("while", Token.WHILE);
593 AddKeyword ("partial", Token.PARTIAL);
594 AddKeyword ("where", Token.WHERE);
597 AddKeyword ("from", Token.FROM);
598 AddKeyword ("join", Token.JOIN);
599 AddKeyword ("on", Token.ON);
600 AddKeyword ("equals", Token.EQUALS);
601 AddKeyword ("select", Token.SELECT);
602 AddKeyword ("group", Token.GROUP);
603 AddKeyword ("by", Token.BY);
604 AddKeyword ("let", Token.LET);
605 AddKeyword ("orderby", Token.ORDERBY);
606 AddKeyword ("ascending", Token.ASCENDING);
607 AddKeyword ("descending", Token.DESCENDING);
608 AddKeyword ("into", Token.INTO);
610 // Contextual async keywords
611 AddKeyword ("async", Token.ASYNC);
612 AddKeyword ("await", Token.AWAIT);
614 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
616 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
617 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
618 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
619 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
620 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
621 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
622 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
623 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
624 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
625 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
626 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
627 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
629 csharp_format_info = NumberFormatInfo.InvariantInfo;
630 styles = NumberStyles.Float;
632 string_builder = new System.Text.StringBuilder ();
635 int GetKeyword (char[] id, int id_len)
638 // Keywords are stored in an array of arrays grouped by their
639 // length and then by the first character
641 if (id_len >= keywords.Length || keywords [id_len] == null)
644 int first_index = id [0] - '_';
645 if (first_index > 'z' - '_')
648 var kwe = keywords [id_len] [first_index];
655 for (int i = 1; i < id_len; ++i) {
656 if (id [i] != kwe.Value [i]) {
662 } while (res == 0 && kwe != null);
676 if (!handle_remove_add)
680 if (parsing_declaration == 0)
681 res = Token.EXTERN_ALIAS;
684 if (peek_token () == Token.COLON) {
686 res = Token.DEFAULT_COLON;
690 if (!handle_where && !query_parsing)
695 // A query expression is any expression that starts with `from identifier'
696 // followed by any token except ; , =
698 if (!query_parsing) {
699 if (lambda_arguments_parsing) {
705 // HACK: to disable generics micro-parser, because PushPosition does not
706 // store identifiers array
707 parsing_generic_less_than = 1;
709 case Token.IDENTIFIER:
721 next_token = xtoken ();
722 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
725 res = Token.FROM_FIRST;
726 query_parsing = true;
727 if (context.Settings.Version <= LanguageVersion.ISO_2)
728 Report.FeatureIsNotAvailable (context, Location, "query expressions");
731 Expression.Error_VoidInvalidInTheContext (Location, Report);
735 // HACK: A token is not a keyword so we need to restore identifiers buffer
736 // which has been overwritten before we grabbed the identifier
737 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
751 case Token.ASCENDING:
752 case Token.DESCENDING:
759 case Token.NAMESPACE:
760 // TODO: some explanation needed
761 check_incorrect_doc_comment ();
765 if (parsing_block > 0) {
770 // Save current position and parse next token.
773 next_token = token ();
774 bool ok = (next_token == Token.CLASS) ||
775 (next_token == Token.STRUCT) ||
776 (next_token == Token.INTERFACE) ||
777 (next_token == Token.VOID);
782 if (next_token == Token.VOID) {
783 if (context.Settings.Version <= LanguageVersion.ISO_2)
784 Report.FeatureIsNotAvailable (context, Location, "partial methods");
785 } else if (context.Settings.Version == LanguageVersion.ISO_1)
786 Report.FeatureIsNotAvailable (context, Location, "partial types");
791 if (next_token < Token.LAST_KEYWORD) {
792 Report.Error (267, Location,
793 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
801 if (parsing_modifiers) {
803 // Skip attributes section or constructor called async
805 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
810 } else if (parsing_block > 0) {
811 switch (peek_token ()) {
813 case Token.OPEN_PARENS_LAMBDA:
816 case Token.IDENTIFIER:
819 if (xtoken () != Token.ARROW)
832 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
833 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
849 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
852 // Keywords are stored in an array of arrays grouped by their
853 // length and then by the first character
855 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
856 return PreprocessorDirective.Invalid;
858 int first_index = id[0] - '_';
859 if (first_index > 'z' - '_')
860 return PreprocessorDirective.Invalid;
862 var kwe = keywords_preprocessor[id_len][first_index];
864 return PreprocessorDirective.Invalid;
866 PreprocessorDirective res = PreprocessorDirective.Invalid;
869 for (int i = 1; i < id_len; ++i) {
870 if (id[i] != kwe.Value[i]) {
876 } while (res == PreprocessorDirective.Invalid && kwe != null);
881 public Location Location {
883 return new Location (ref_line, hidden ? -1 : col);
887 static bool is_identifier_start_character (int c)
889 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
892 static bool is_identifier_part_character (char c)
894 if (c >= 'a' && c <= 'z')
897 if (c >= 'A' && c <= 'Z')
900 if (c == '_' || (c >= '0' && c <= '9'))
906 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
909 public static bool IsKeyword (string s)
911 return keyword_strings.ContainsKey (s);
915 // Open parens micro parser. Detects both lambda and cast ambiguity.
917 int TokenizeOpenParens ()
922 int bracket_level = 0;
923 bool is_type = false;
924 bool can_be_type = false;
927 ptoken = current_token;
930 switch (current_token) {
931 case Token.CLOSE_PARENS:
935 // Expression inside parens is lambda, (int i) =>
937 if (current_token == Token.ARROW)
938 return Token.OPEN_PARENS_LAMBDA;
941 // Expression inside parens is single type, (int[])
944 return Token.OPEN_PARENS_CAST;
947 // Expression is possible cast, look at next token, (T)null
950 switch (current_token) {
951 case Token.OPEN_PARENS:
954 case Token.IDENTIFIER:
968 case Token.UNCHECKED:
973 // These can be part of a member access
987 return Token.OPEN_PARENS_CAST;
990 return Token.OPEN_PARENS;
993 case Token.DOUBLE_COLON:
994 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
999 case Token.IDENTIFIER:
1002 if (bracket_level == 0) {
1008 case Token.OP_GENERICS_LT:
1010 case Token.DOUBLE_COLON:
1012 if (bracket_level == 0)
1016 can_be_type = is_type = false;
1036 if (bracket_level == 0)
1041 if (bracket_level == 0) {
1042 bracket_level = 100;
1043 can_be_type = is_type = false;
1047 case Token.OP_GENERICS_LT:
1048 case Token.OPEN_BRACKET:
1049 if (bracket_level++ == 0)
1053 case Token.OP_GENERICS_GT:
1054 case Token.CLOSE_BRACKET:
1058 case Token.INTERR_NULLABLE:
1060 if (bracket_level == 0)
1066 can_be_type = is_type = false;
1070 return Token.OPEN_PARENS;
1075 public static bool IsValidIdentifier (string s)
1077 if (s == null || s.Length == 0)
1080 if (!is_identifier_start_character (s [0]))
1083 for (int i = 1; i < s.Length; i ++)
1084 if (! is_identifier_part_character (s [i]))
1090 bool parse_less_than ()
1093 int the_token = token ();
1094 if (the_token == Token.OPEN_BRACKET) {
1096 the_token = token ();
1097 } while (the_token != Token.CLOSE_BRACKET);
1098 the_token = token ();
1099 } else if (the_token == Token.IN || the_token == Token.OUT) {
1100 the_token = token ();
1102 switch (the_token) {
1103 case Token.IDENTIFIER:
1121 case Token.OP_GENERICS_GT:
1130 the_token = token ();
1132 if (the_token == Token.OP_GENERICS_GT)
1134 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1136 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1138 else if (the_token == Token.OP_GENERICS_LT) {
1139 if (!parse_less_than ())
1142 } else if (the_token == Token.OPEN_BRACKET) {
1144 the_token = token ();
1145 if (the_token == Token.CLOSE_BRACKET)
1147 else if (the_token == Token.COMMA)
1148 goto rank_specifiers;
1155 bool parse_generic_dimension (out int dimension)
1160 int the_token = token ();
1161 if (the_token == Token.OP_GENERICS_GT)
1163 else if (the_token == Token.COMMA) {
1171 public int peek_token ()
1176 the_token = token ();
1183 // Tonizes `?' using custom disambiguous rules to return one
1184 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1186 // Tricky expression look like:
1188 // Foo ? a = x ? b : c;
1190 int TokenizePossibleNullableType ()
1192 if (parsing_block == 0 || parsing_type > 0)
1193 return Token.INTERR_NULLABLE;
1195 int d = peek_char ();
1198 return Token.OP_COALESCING;
1201 switch (current_token) {
1202 case Token.CLOSE_PARENS:
1207 return Token.INTERR;
1211 if (d == ',' || d == ';' || d == '>')
1212 return Token.INTERR_NULLABLE;
1213 if (d == '*' || (d >= '0' && d <= '9'))
1214 return Token.INTERR;
1218 current_token = Token.NONE;
1220 switch (xtoken ()) {
1227 next_token = Token.INTERR;
1230 case Token.SEMICOLON:
1232 case Token.CLOSE_PARENS:
1233 case Token.OPEN_BRACKET:
1234 case Token.OP_GENERICS_GT:
1236 next_token = Token.INTERR_NULLABLE;
1244 if (next_token == -1) {
1245 switch (xtoken ()) {
1247 case Token.SEMICOLON:
1248 case Token.OPEN_BRACE:
1249 case Token.CLOSE_PARENS:
1251 next_token = Token.INTERR_NULLABLE;
1255 next_token = Token.INTERR;
1263 // All shorcuts failed, do it hard way
1265 while ((ntoken = xtoken ()) != Token.EOF) {
1266 if (ntoken == Token.SEMICOLON)
1269 if (ntoken == Token.COLON) {
1270 if (++colons == interrs)
1275 if (ntoken == Token.INTERR) {
1281 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1290 bool decimal_digits (int c)
1293 bool seen_digits = false;
1296 if (number_pos == max_number_size)
1297 Error_NumericConstantTooLong ();
1298 number_builder [number_pos++] = (char) c;
1302 // We use peek_char2, because decimal_digits needs to do a
1303 // 2-character look-ahead (5.ToString for example).
1305 while ((d = peek_char2 ()) != -1){
1306 if (d >= '0' && d <= '9'){
1307 if (number_pos == max_number_size)
1308 Error_NumericConstantTooLong ();
1309 number_builder [number_pos++] = (char) d;
1319 static bool is_hex (int e)
1321 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1324 static TypeCode real_type_suffix (int c)
1328 return TypeCode.Single;
1330 return TypeCode.Double;
1332 return TypeCode.Decimal;
1334 return TypeCode.Empty;
1338 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1340 bool is_unsigned = false;
1341 bool is_long = false;
1344 bool scanning = true;
1357 // if we have not seen anything in between
1358 // report this error
1360 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1380 if (is_long && is_unsigned){
1381 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1385 // uint if possible, or ulong else.
1387 if ((ul & 0xffffffff00000000) == 0)
1388 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1390 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1391 } else if (is_long){
1392 // long if possible, ulong otherwise
1393 if ((ul & 0x8000000000000000) != 0)
1394 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1396 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1398 // int, uint, long or ulong in that order
1399 if ((ul & 0xffffffff00000000) == 0){
1400 uint ui = (uint) ul;
1402 if ((ui & 0x80000000) != 0)
1403 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1405 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1407 if ((ul & 0x8000000000000000) != 0)
1408 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1410 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1416 // given `c' as the next char in the input decide whether
1417 // we need to convert to a special type, and then choose
1418 // the best representation for the integer
1420 ILiteralConstant adjust_int (int c, Location loc)
1423 if (number_pos > 9){
1424 ulong ul = (uint) (number_builder [0] - '0');
1426 for (int i = 1; i < number_pos; i++){
1427 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1430 return integer_type_suffix (ul, c, loc);
1432 uint ui = (uint) (number_builder [0] - '0');
1434 for (int i = 1; i < number_pos; i++){
1435 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1438 return integer_type_suffix (ui, c, loc);
1440 } catch (OverflowException) {
1441 Error_NumericConstantTooLong ();
1442 return new IntLiteral (context.BuiltinTypes, 0, loc);
1444 catch (FormatException) {
1445 Report.Error (1013, Location, "Invalid number");
1446 return new IntLiteral (context.BuiltinTypes, 0, loc);
1450 ILiteralConstant adjust_real (TypeCode t, Location loc)
1452 string s = new string (number_builder, 0, number_pos);
1453 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1456 case TypeCode.Decimal:
1458 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1459 } catch (OverflowException) {
1460 Report.Error (594, Location, error_details, "decimal");
1461 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1463 case TypeCode.Single:
1465 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1466 } catch (OverflowException) {
1467 Report.Error (594, Location, error_details, "float");
1468 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1472 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1473 } catch (OverflowException) {
1474 Report.Error (594, loc, error_details, "double");
1475 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1480 ILiteralConstant handle_hex (Location loc)
1486 while ((d = peek_char ()) != -1){
1488 number_builder [number_pos++] = (char) d;
1494 string s = new String (number_builder, 0, number_pos);
1497 if (number_pos <= 8)
1498 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1500 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1502 return integer_type_suffix (ul, peek_char (), loc);
1503 } catch (OverflowException){
1504 Error_NumericConstantTooLong ();
1505 return new IntLiteral (context.BuiltinTypes, 0, loc);
1507 catch (FormatException) {
1508 Report.Error (1013, Location, "Invalid number");
1509 return new IntLiteral (context.BuiltinTypes, 0, loc);
1514 // Invoked if we know we have .digits or digits
1516 int is_number (int c)
1518 ILiteralConstant res;
1521 int read_start = reader.Position - 1;
1526 if (c >= '0' && c <= '9'){
1528 int peek = peek_char ();
1530 if (peek == 'x' || peek == 'X') {
1531 val = res = handle_hex (loc);
1533 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1536 return Token.LITERAL;
1544 // We need to handle the case of
1545 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1547 bool is_real = false;
1549 if (decimal_digits ('.')){
1555 val = res = adjust_int (-1, loc);
1558 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1560 return Token.LITERAL;
1564 if (c == 'e' || c == 'E'){
1566 if (number_pos == max_number_size)
1567 Error_NumericConstantTooLong ();
1568 number_builder [number_pos++] = (char) c;
1572 if (number_pos == max_number_size)
1573 Error_NumericConstantTooLong ();
1574 number_builder [number_pos++] = '+';
1576 } else if (c == '-') {
1577 if (number_pos == max_number_size)
1578 Error_NumericConstantTooLong ();
1579 number_builder [number_pos++] = '-';
1582 if (number_pos == max_number_size)
1583 Error_NumericConstantTooLong ();
1584 number_builder [number_pos++] = '+';
1591 var type = real_type_suffix (c);
1592 if (type == TypeCode.Empty && !is_real) {
1594 res = adjust_int (c, loc);
1598 if (type == TypeCode.Empty) {
1602 res = adjust_real (type, loc);
1608 res.ParsedValue = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty ? 1 : 0));
1611 return Token.LITERAL;
1615 // Accepts exactly count (4 or 8) hex, no more no less
1617 int getHex (int count, out int surrogate, out bool error)
1622 int top = count != -1 ? count : 4;
1627 for (i = 0; i < top; i++){
1630 if (c >= '0' && c <= '9')
1631 c = (int) c - (int) '0';
1632 else if (c >= 'A' && c <= 'F')
1633 c = (int) c - (int) 'A' + 10;
1634 else if (c >= 'a' && c <= 'f')
1635 c = (int) c - (int) 'a' + 10;
1641 total = (total * 16) + c;
1643 int p = peek_char ();
1646 if (!is_hex ((char)p))
1652 if (total > 0x0010FFFF) {
1657 if (total >= 0x00010000) {
1658 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1659 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1666 int escape (int c, out int surrogate)
1702 v = getHex (-1, out surrogate, out error);
1708 return EscapeUnicode (d, out surrogate);
1711 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1720 int EscapeUnicode (int ch, out int surrogate)
1724 ch = getHex (8, out surrogate, out error);
1726 ch = getHex (4, out surrogate, out error);
1730 Report.Error (1009, Location, "Unrecognized escape sequence");
1738 if (putback_char != -1) {
1746 if (peek_char () == '\n') {
1752 } else if (x == '\n') {
1760 void advance_line ()
1770 if (putback_char == -1)
1771 putback_char = reader.Read ();
1772 return putback_char;
1777 if (putback_char != -1)
1778 return putback_char;
1779 return reader.Peek ();
1782 void putback (int c)
1784 if (putback_char != -1){
1785 Console.WriteLine ("Col: " + col);
1786 Console.WriteLine ("Row: " + line);
1787 Console.WriteLine ("Name: " + ref_name.Name);
1788 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1789 throw new Exception ("This should not happen putback on putback");
1791 if (c == '\n' || col == 0) {
1792 // It won't happen though.
1802 public bool advance ()
1804 return peek_char () != -1 || CompleteOnEOF;
1807 public Object Value {
1813 public Object value ()
1820 current_token = xtoken ();
1821 return current_token;
1824 int TokenizePreprocessorIdentifier (out int c)
1826 // skip over white space
1829 } while (c == ' ' || c == '\t');
1833 while (c != -1 && c >= 'a' && c <= 'z') {
1834 id_builder[pos++] = (char) c;
1837 int peek = peek_char ();
1838 if (peek == 'U' || peek == 'u') {
1840 c = EscapeUnicode (c, out surrogate);
1841 if (surrogate != 0) {
1842 if (is_identifier_part_character ((char) c)) {
1843 id_builder[pos++] = (char) c;
1854 PreprocessorDirective get_cmd_arg (out string arg)
1858 tokens_seen = false;
1861 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1863 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1866 // skip over white space
1867 while (c == ' ' || c == '\t')
1870 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1873 while (c != -1 && c != '\n') {
1874 if (c == '\\' && has_identifier_argument >= 0) {
1875 if (has_identifier_argument != 0) {
1876 has_identifier_argument = 1;
1878 int peek = peek_char ();
1879 if (peek == 'U' || peek == 'u') {
1881 c = EscapeUnicode (c, out surrogate);
1882 if (surrogate != 0) {
1883 if (is_identifier_part_character ((char) c)) {
1884 if (pos == value_builder.Length)
1885 Array.Resize (ref value_builder, pos * 2);
1887 value_builder[pos++] = (char) c;
1893 has_identifier_argument = -1;
1895 } else if (c == '/' && peek_char () == '/') {
1897 // Eat single-line comments
1902 } while (c != -1 && c != '\n');
1907 if (pos == value_builder.Length)
1908 Array.Resize (ref value_builder, pos * 2);
1910 value_builder[pos++] = (char) c;
1915 if (pos > max_id_size)
1916 arg = new string (value_builder, 0, pos);
1918 arg = InternIdentifier (value_builder, pos);
1920 // Eat any trailing whitespaces
1921 arg = arg.Trim (simple_whitespaces);
1928 // Handles the #line directive
1930 bool PreProcessLine (string arg)
1932 if (arg.Length == 0)
1935 if (arg == "default"){
1937 ref_name = file_name;
1939 Location.Push (file_name, ref_name);
1941 } else if (arg == "hidden"){
1949 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1950 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1953 char [] quotes = { '\"' };
1955 string name = arg.Substring (pos). Trim (quotes);
1956 ref_name = context.LookupFile (file_name, name);
1957 file_name.AddIncludeFile (ref_name);
1959 Location.Push (file_name, ref_name);
1961 ref_line = System.Int32.Parse (arg);
1972 // Handles #define and #undef
1974 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1976 if (ident.Length == 0 || ident == "true" || ident == "false"){
1977 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1981 if (ident.IndexOfAny (simple_whitespaces) != -1){
1982 Error_EndLineExpected ();
1986 if (!is_identifier_start_character (ident [0]))
1987 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1989 foreach (char c in ident.Substring (1)){
1990 if (!is_identifier_part_character (c)){
1991 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1996 if (!caller_is_taking)
2003 if (context.Settings.IsConditionalSymbolDefined (ident))
2006 file_name.AddDefine (ident);
2011 file_name.AddUndefine (ident);
2015 byte read_hex (out bool error)
2018 int c = get_char ();
2020 if ((c >= '0') && (c <= '9'))
2021 total = (int) c - (int) '0';
2022 else if ((c >= 'A') && (c <= 'F'))
2023 total = (int) c - (int) 'A' + 10;
2024 else if ((c >= 'a') && (c <= 'f'))
2025 total = (int) c - (int) 'a' + 10;
2034 if ((c >= '0') && (c <= '9'))
2035 total += (int) c - (int) '0';
2036 else if ((c >= 'A') && (c <= 'F'))
2037 total += (int) c - (int) 'A' + 10;
2038 else if ((c >= 'a') && (c <= 'f'))
2039 total += (int) c - (int) 'a' + 10;
2046 return (byte) total;
2050 // Parses #pragma checksum
2052 bool ParsePragmaChecksum ()
2055 // The syntax is ` "foo.txt" "{guid}" "hash"'
2057 int c = get_char ();
2062 string_builder.Length = 0;
2063 while (c != -1 && c != '\n') {
2070 string_builder.Append ((char) c);
2073 if (string_builder.Length == 0) {
2074 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2077 // TODO: Any white-spaces count
2081 SourceFile file = context.LookupFile (file_name, string_builder.ToString ());
2083 if (get_char () != '"' || get_char () != '{')
2087 byte[] guid_bytes = new byte [16];
2090 for (; i < 4; i++) {
2091 guid_bytes [i] = read_hex (out error);
2096 if (get_char () != '-')
2099 for (; i < 10; i++) {
2100 guid_bytes [i] = read_hex (out error);
2104 guid_bytes [i++] = read_hex (out error);
2108 if (get_char () != '-')
2112 for (; i < 16; i++) {
2113 guid_bytes [i] = read_hex (out error);
2118 if (get_char () != '}' || get_char () != '"')
2121 // TODO: Any white-spaces count
2126 if (get_char () != '"')
2129 // Any length of checksum
2130 List<byte> checksum_bytes = new List<byte> (16);
2133 while (c != '"' && c != -1) {
2134 checksum_bytes.Add (read_hex (out error));
2142 ReadSingleLineComment ();
2143 } else if (get_char () != '"') {
2147 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2148 ref_name.AutoGenerated = true;
2152 bool IsTokenIdentifierEqual (char[] identifier)
2154 for (int i = 0; i < identifier.Length; ++i) {
2155 if (identifier[i] != id_builder[i])
2162 int TokenizePragmaNumber (ref int c)
2168 if (c >= '0' && c <= '9') {
2170 uint ui = (uint) (number_builder[0] - '0');
2173 for (int i = 1; i < number_pos; i++) {
2174 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2178 } catch (OverflowException) {
2179 Error_NumericConstantTooLong ();
2186 // skip over white space
2187 while (c == ' ' || c == '\t')
2194 // skip over white space
2195 while (c == ' ' || c == '\t')
2200 ReadSingleLineComment ();
2202 Report.Warning (1692, 1, Location, "Invalid number");
2204 // Read everything till the end of the line or file
2207 } while (c != -1 && c != '\n');
2214 void ReadSingleLineComment ()
2216 if (peek_char () != '/')
2217 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2219 // Read everything till the end of the line or file
2223 } while (c != -1 && c != '\n');
2227 /// Handles #pragma directive
2229 void ParsePragmaDirective (string arg)
2232 int length = TokenizePreprocessorIdentifier (out c);
2233 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2234 length = TokenizePreprocessorIdentifier (out c);
2237 // #pragma warning disable
2238 // #pragma warning restore
2240 if (length == pragma_warning_disable.Length) {
2241 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2242 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2243 // skip over white space
2244 while (c == ' ' || c == '\t')
2249 if (c == '\n' || c == '/') {
2251 ReadSingleLineComment ();
2254 // Disable/Restore all warnings
2257 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2259 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2263 // Disable/Restore a warning or group of warnings
2267 code = TokenizePragmaNumber (ref c);
2270 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2272 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2275 } while (code >= 0 && c != '\n' && c != -1);
2282 Report.Warning (1634, 1, Location, "Expected disable or restore");
2289 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2290 if (c != ' ' || !ParsePragmaChecksum ()) {
2291 Report.Warning (1695, 1, Location,
2292 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2298 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2301 bool eval_val (string s)
2308 return file_name.IsConditionalDefined (context, s);
2311 bool pp_primary (ref string s)
2320 s = s.Substring (1);
2321 bool val = pp_expr (ref s, false);
2322 if (s.Length > 0 && s [0] == ')'){
2323 s = s.Substring (1);
2326 Error_InvalidDirective ();
2330 if (is_identifier_start_character (c)){
2336 if (is_identifier_part_character (c)){
2340 bool v = eval_val (s.Substring (0, j));
2341 s = s.Substring (j);
2344 bool vv = eval_val (s);
2349 Error_InvalidDirective ();
2353 bool pp_unary (ref string s)
2360 if (len > 1 && s [1] == '='){
2361 Error_InvalidDirective ();
2364 s = s.Substring (1);
2365 return ! pp_primary (ref s);
2367 return pp_primary (ref s);
2369 Error_InvalidDirective ();
2374 bool pp_eq (ref string s)
2376 bool va = pp_unary (ref s);
2382 if (len > 2 && s [1] == '='){
2383 s = s.Substring (2);
2384 return va == pp_unary (ref s);
2386 Error_InvalidDirective ();
2389 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2390 s = s.Substring (2);
2392 return va != pp_unary (ref s);
2401 bool pp_and (ref string s)
2403 bool va = pp_eq (ref s);
2409 if (len > 2 && s [1] == '&'){
2410 s = s.Substring (2);
2411 return (va & pp_and (ref s));
2413 Error_InvalidDirective ();
2422 // Evaluates an expression for `#if' or `#elif'
2424 bool pp_expr (ref string s, bool isTerm)
2426 bool va = pp_and (ref s);
2433 if (len > 2 && s [1] == '|'){
2434 s = s.Substring (2);
2435 return va | pp_expr (ref s, isTerm);
2437 Error_InvalidDirective ();
2442 Error_EndLineExpected ();
2450 bool eval (string s)
2452 bool v = pp_expr (ref s, true);
2461 void Error_NumericConstantTooLong ()
2463 Report.Error (1021, Location, "Integral constant is too large");
2466 void Error_InvalidDirective ()
2468 Report.Error (1517, Location, "Invalid preprocessor directive");
2471 void Error_UnexpectedDirective (string extra)
2475 "Unexpected processor directive ({0})", extra);
2478 void Error_TokensSeen ()
2480 Report.Error (1032, Location,
2481 "Cannot define or undefine preprocessor symbols after first token in file");
2484 void Eror_WrongPreprocessorLocation ()
2486 Report.Error (1040, Location,
2487 "Preprocessor directives must appear as the first non-whitespace character on a line");
2490 void Error_EndLineExpected ()
2492 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2496 // Raises a warning when tokenizer found documentation comment
2497 // on unexpected place
2499 void WarningMisplacedComment (Location loc)
2501 if (doc_state != XmlCommentState.Error) {
2502 doc_state = XmlCommentState.Error;
2503 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2508 // if true, then the code continues processing the code
2509 // if false, the code stays in a loop until another directive is
2511 // When caller_is_taking is false we ignore all directives except the ones
2512 // which can help us to identify where the #if block ends
2513 bool ParsePreprocessingDirective (bool caller_is_taking)
2516 bool region_directive = false;
2518 var directive = get_cmd_arg (out arg);
2521 // The first group of pre-processing instructions is always processed
2523 switch (directive) {
2524 case PreprocessorDirective.Region:
2525 region_directive = true;
2527 goto case PreprocessorDirective.If;
2529 case PreprocessorDirective.Endregion:
2530 if (ifstack == null || ifstack.Count == 0){
2531 Error_UnexpectedDirective ("no #region for this #endregion");
2534 int pop = ifstack.Pop ();
2536 if ((pop & REGION) == 0)
2537 Report.Error (1027, Location, "Expected `#endif' directive");
2539 return caller_is_taking;
2541 case PreprocessorDirective.If:
2542 if (ifstack == null)
2543 ifstack = new Stack<int> (2);
2545 int flags = region_directive ? REGION : 0;
2546 if (ifstack.Count == 0){
2547 flags |= PARENT_TAKING;
2549 int state = ifstack.Peek ();
2550 if ((state & TAKING) != 0) {
2551 flags |= PARENT_TAKING;
2555 if (eval (arg) && caller_is_taking) {
2556 ifstack.Push (flags | TAKING);
2559 ifstack.Push (flags);
2562 case PreprocessorDirective.Endif:
2563 if (ifstack == null || ifstack.Count == 0){
2564 Error_UnexpectedDirective ("no #if for this #endif");
2567 pop = ifstack.Pop ();
2569 if ((pop & REGION) != 0)
2570 Report.Error (1038, Location, "#endregion directive expected");
2572 if (arg.Length != 0) {
2573 Error_EndLineExpected ();
2576 if (ifstack.Count == 0)
2579 int state = ifstack.Peek ();
2580 return (state & TAKING) != 0;
2583 case PreprocessorDirective.Elif:
2584 if (ifstack == null || ifstack.Count == 0){
2585 Error_UnexpectedDirective ("no #if for this #elif");
2588 int state = ifstack.Pop ();
2590 if ((state & REGION) != 0) {
2591 Report.Error (1038, Location, "#endregion directive expected");
2595 if ((state & ELSE_SEEN) != 0){
2596 Error_UnexpectedDirective ("#elif not valid after #else");
2600 if ((state & TAKING) != 0) {
2605 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2606 ifstack.Push (state | TAKING);
2610 ifstack.Push (state);
2614 case PreprocessorDirective.Else:
2615 if (ifstack == null || ifstack.Count == 0){
2616 Error_UnexpectedDirective ("no #if for this #else");
2619 int state = ifstack.Peek ();
2621 if ((state & REGION) != 0) {
2622 Report.Error (1038, Location, "#endregion directive expected");
2626 if ((state & ELSE_SEEN) != 0){
2627 Error_UnexpectedDirective ("#else within #else");
2633 if (arg.Length != 0) {
2634 Error_EndLineExpected ();
2639 if ((state & PARENT_TAKING) != 0) {
2640 ret = (state & TAKING) == 0;
2648 ifstack.Push (state | ELSE_SEEN);
2652 case PreprocessorDirective.Define:
2653 if (any_token_seen){
2654 Error_TokensSeen ();
2655 return caller_is_taking;
2657 PreProcessDefinition (true, arg, caller_is_taking);
2658 return caller_is_taking;
2660 case PreprocessorDirective.Undef:
2661 if (any_token_seen){
2662 Error_TokensSeen ();
2663 return caller_is_taking;
2665 PreProcessDefinition (false, arg, caller_is_taking);
2666 return caller_is_taking;
2668 case PreprocessorDirective.Invalid:
2669 Report.Error (1024, Location, "Wrong preprocessor directive");
2674 // These are only processed if we are in a `taking' block
2676 if (!caller_is_taking)
2680 case PreprocessorDirective.Error:
2681 Report.Error (1029, Location, "#error: '{0}'", arg);
2684 case PreprocessorDirective.Warning:
2685 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2688 case PreprocessorDirective.Pragma:
2689 if (context.Settings.Version == LanguageVersion.ISO_1) {
2690 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2693 ParsePragmaDirective (arg);
2696 case PreprocessorDirective.Line:
2697 if (!PreProcessLine (arg))
2700 "The line number specified for #line directive is missing or invalid");
2701 return caller_is_taking;
2704 throw new NotImplementedException (directive.ToString ());
2707 private int consume_string (bool quoted)
2711 Location start_location = Location;
2713 start_location = start_location - 1;
2716 int reader_pos = reader.Position;
2722 if (quoted && peek_char () == '"') {
2723 if (pos == value_builder.Length)
2724 Array.Resize (ref value_builder, pos * 2);
2726 value_builder[pos++] = (char) c;
2735 s = InternIdentifier (value_builder, pos);
2737 s = new string (value_builder, 0, pos);
2739 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2742 res.ParsedValue = quoted ?
2743 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2744 reader.ReadChars (reader_pos - 1, reader.Position);
2747 return Token.LITERAL;
2752 Report.Error (1010, Location, "Newline in constant");
2753 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2754 return Token.LITERAL;
2756 } else if (c == '\\' && !quoted) {
2758 c = escape (c, out surrogate);
2761 if (surrogate != 0) {
2762 if (pos == value_builder.Length)
2763 Array.Resize (ref value_builder, pos * 2);
2765 value_builder[pos++] = (char) c;
2768 } else if (c == -1) {
2769 Report.Error (1039, Location, "Unterminated string literal");
2773 if (pos == value_builder.Length)
2774 Array.Resize (ref value_builder, pos * 2);
2776 value_builder[pos++] = (char) c;
2780 private int consume_identifier (int s)
2782 int res = consume_identifier (s, false);
2784 if (doc_state == XmlCommentState.Allowed)
2785 doc_state = XmlCommentState.NotAllowed;
2790 int consume_identifier (int c, bool quoted)
2793 // This method is very performance sensitive. It accounts
2794 // for approximately 25% of all parser time
2804 c = escape (c, out surrogate);
2805 if (surrogate != 0) {
2806 id_builder [pos++] = (char) c;
2811 id_builder [pos++] = (char) c;
2817 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2818 id_builder [pos++] = (char) c;
2825 c = escape (c, out surrogate);
2826 if (is_identifier_part_character ((char) c))
2827 id_builder[pos++] = (char) c;
2829 if (surrogate != 0) {
2835 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2836 id_builder [pos++] = (char) c;
2843 } catch (IndexOutOfRangeException) {
2844 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2852 // Optimization: avoids doing the keyword lookup
2853 // on uppercase letters
2855 if (id_builder [0] >= '_' && !quoted) {
2856 int keyword = GetKeyword (id_builder, pos);
2857 if (keyword != -1) {
2858 val = LocatedToken.Create (null, ref_line, column);
2863 string s = InternIdentifier (id_builder, pos);
2864 val = LocatedToken.Create (s, ref_line, column);
2865 if (quoted && parsing_attribute_section)
2866 AddEscapedIdentifier (((LocatedToken) val).Location);
2868 return Token.IDENTIFIER;
2871 static string InternIdentifier (char[] charBuffer, int length)
2874 // Keep identifiers in an array of hashtables to avoid needless
2877 var identifiers_group = identifiers[length];
2879 if (identifiers_group != null) {
2880 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2884 // TODO: this should be number of files dependant
2885 // corlib compilation peaks at 1000 and System.Core at 150
2886 int capacity = length > 20 ? 10 : 100;
2887 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2888 identifiers[length] = identifiers_group;
2891 char[] chars = new char[length];
2892 Array.Copy (charBuffer, chars, length);
2894 s = new string (charBuffer, 0, length);
2895 identifiers_group.Add (chars, s);
2899 public int xtoken ()
2903 // Whether we have seen comments on the current line
2904 bool comments_seen = false;
2905 while ((c = get_char ()) != -1) {
2908 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2916 case 0xFEFF: // Ignore BOM anywhere in the file
2919 /* This is required for compatibility with .NET
2921 if (peek_char () == 0xBB) {
2924 if (get_char () == 0xBF)
2932 return consume_identifier (c);
2935 val = LocatedToken.Create (ref_line, col);
2936 return Token.OPEN_BRACE;
2938 val = LocatedToken.Create (ref_line, col);
2939 return Token.CLOSE_BRACE;
2941 // To block doccomment inside attribute declaration.
2942 if (doc_state == XmlCommentState.Allowed)
2943 doc_state = XmlCommentState.NotAllowed;
2945 val = LocatedToken.Create (ref_line, col);
2947 if (parsing_block == 0 || lambda_arguments_parsing)
2948 return Token.OPEN_BRACKET;
2950 int next = peek_char ();
2954 return Token.OPEN_BRACKET;
2962 next = peek_token ();
2963 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2964 return Token.OPEN_BRACKET;
2966 return Token.OPEN_BRACKET_EXPR;
2968 return Token.OPEN_BRACKET_EXPR;
2971 LocatedToken.CreateOptional (ref_line, col, ref val);
2972 return Token.CLOSE_BRACKET;
2974 val = LocatedToken.Create (ref_line, col);
2976 // An expression versions of parens can appear in block context only
2978 if (parsing_block != 0 && !lambda_arguments_parsing) {
2981 // Optmize most common case where we know that parens
2984 switch (current_token) {
2985 case Token.IDENTIFIER:
2993 case Token.DELEGATE:
2994 case Token.OP_GENERICS_GT:
2995 return Token.OPEN_PARENS;
2998 // Optimize using peek
2999 int xx = peek_char ();
3006 return Token.OPEN_PARENS;
3009 lambda_arguments_parsing = true;
3011 d = TokenizeOpenParens ();
3013 lambda_arguments_parsing = false;
3017 return Token.OPEN_PARENS;
3019 LocatedToken.CreateOptional (ref_line, col, ref val);
3020 return Token.CLOSE_PARENS;
3022 LocatedToken.CreateOptional (ref_line, col, ref val);
3025 LocatedToken.CreateOptional (ref_line, col, ref val);
3026 return Token.SEMICOLON;
3028 val = LocatedToken.Create (ref_line, col);
3031 val = LocatedToken.Create (ref_line, col);
3032 return TokenizePossibleNullableType ();
3034 val = LocatedToken.Create (ref_line, col);
3035 if (parsing_generic_less_than++ > 0)
3036 return Token.OP_GENERICS_LT;
3038 return TokenizeLessThan ();
3041 val = LocatedToken.Create (ref_line, col);
3049 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3050 parsing_generic_less_than--;
3051 return Token.OP_GENERICS_GT;
3060 return Token.OP_SHIFT_RIGHT_ASSIGN;
3062 return Token.OP_SHIFT_RIGHT;
3068 val = LocatedToken.Create (ref_line, col);
3072 } else if (d == '=') {
3073 d = Token.OP_ADD_ASSIGN;
3081 val = LocatedToken.Create (ref_line, col);
3085 } else if (d == '=')
3086 d = Token.OP_SUB_ASSIGN;
3096 val = LocatedToken.Create (ref_line, col);
3097 if (peek_char () == '='){
3104 val = LocatedToken.Create (ref_line, col);
3115 return Token.ASSIGN;
3118 val = LocatedToken.Create (ref_line, col);
3122 return Token.OP_AND;
3126 return Token.OP_AND_ASSIGN;
3128 return Token.BITWISE_AND;
3131 val = LocatedToken.Create (ref_line, col);
3139 return Token.OP_OR_ASSIGN;
3141 return Token.BITWISE_OR;
3144 val = LocatedToken.Create (ref_line, col);
3145 if (peek_char () == '='){
3147 return Token.OP_MULT_ASSIGN;
3154 val = LocatedToken.Create (ref_line, col);
3156 return Token.OP_DIV_ASSIGN;
3159 // Handle double-slash comments.
3162 if (doc_processing) {
3163 if (peek_char () == '/') {
3165 // Don't allow ////.
3166 if ((d = peek_char ()) != '/') {
3167 if (doc_state == XmlCommentState.Allowed)
3168 handle_one_line_xml_comment ();
3169 else if (doc_state == XmlCommentState.NotAllowed)
3170 WarningMisplacedComment (Location - 3);
3173 if (xml_comment_buffer.Length > 0)
3174 doc_state = XmlCommentState.NotAllowed;
3178 while ((d = get_char ()) != -1 && d != '\n');
3180 any_token_seen |= tokens_seen;
3181 tokens_seen = false;
3182 comments_seen = false;
3184 } else if (d == '*'){
3186 bool docAppend = false;
3187 if (doc_processing && peek_char () == '*') {
3189 // But when it is /**/, just do nothing.
3190 if (peek_char () == '/') {
3194 if (doc_state == XmlCommentState.Allowed)
3196 else if (doc_state == XmlCommentState.NotAllowed) {
3197 WarningMisplacedComment (Location - 2);
3201 int current_comment_start = 0;
3203 current_comment_start = xml_comment_buffer.Length;
3204 xml_comment_buffer.Append (Environment.NewLine);
3207 while ((d = get_char ()) != -1){
3208 if (d == '*' && peek_char () == '/'){
3210 comments_seen = true;
3214 xml_comment_buffer.Append ((char) d);
3217 any_token_seen |= tokens_seen;
3218 tokens_seen = false;
3220 // Reset 'comments_seen' just to be consistent.
3221 // It doesn't matter either way, here.
3223 comments_seen = false;
3227 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3230 update_formatted_doc_comment (current_comment_start);
3233 val = LocatedToken.Create (ref_line, col);
3237 val = LocatedToken.Create (ref_line, col);
3238 if (peek_char () == '='){
3240 return Token.OP_MOD_ASSIGN;
3242 return Token.PERCENT;
3245 val = LocatedToken.Create (ref_line, col);
3246 if (peek_char () == '='){
3248 return Token.OP_XOR_ASSIGN;
3250 return Token.CARRET;
3253 val = LocatedToken.Create (ref_line, col);
3254 if (peek_char () == ':') {
3256 return Token.DOUBLE_COLON;
3260 case '0': case '1': case '2': case '3': case '4':
3261 case '5': case '6': case '7': case '8': case '9':
3263 return is_number (c);
3265 case '\n': // white space
3266 any_token_seen |= tokens_seen;
3267 tokens_seen = false;
3268 comments_seen = false;
3274 if (d >= '0' && d <= '9')
3275 return is_number (c);
3277 LocatedToken.CreateOptional (ref_line, col, ref val);
3281 if (tokens_seen || comments_seen) {
3282 Eror_WrongPreprocessorLocation ();
3286 if (ParsePreprocessingDirective (true))
3289 bool directive_expected = false;
3290 while ((c = get_char ()) != -1) {
3292 directive_expected = true;
3293 } else if (!directive_expected) {
3294 // TODO: Implement comment support for disabled code and uncomment this code
3296 // Eror_WrongPreprocessorLocation ();
3297 // return Token.ERROR;
3302 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3306 if (ParsePreprocessingDirective (false))
3309 directive_expected = false;
3313 tokens_seen = false;
3320 return consume_string (false);
3323 return TokenizeBackslash ();
3329 return consume_string (true);
3332 if (is_identifier_start_character (c)){
3333 return consume_identifier (c, true);
3336 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3339 case EvalStatementParserCharacter:
3340 return Token.EVAL_STATEMENT_PARSER;
3341 case EvalCompilationUnitParserCharacter:
3342 return Token.EVAL_COMPILATION_UNIT_PARSER;
3343 case EvalUsingDeclarationsParserCharacter:
3344 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3345 case DocumentationXref:
3346 return Token.DOC_SEE;
3349 if (is_identifier_start_character (c)) {
3351 return consume_identifier (c);
3354 if (char.IsWhiteSpace ((char) c))
3357 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3362 return Token.COMPLETE_COMPLETION;
3365 return Token.GENERATE_COMPLETION;
3372 int TokenizeBackslash ()
3374 int c = get_char ();
3377 val = new CharLiteral (context.BuiltinTypes, (char) c, Location);
3378 Report.Error (1011, Location, "Empty character literal");
3379 return Token.LITERAL;
3383 Report.Error (1010, Location, "Newline in constant");
3388 c = escape (c, out d);
3392 throw new NotImplementedException ();
3394 val = new CharLiteral (context.BuiltinTypes, (char) c, Location);
3398 Report.Error (1012, Location, "Too many characters in character literal");
3400 // Try to recover, read until newline or next "'"
3401 while ((c = get_char ()) != -1) {
3402 if (c == '\n' || c == '\'')
3407 return Token.LITERAL;
3410 int TokenizeLessThan ()
3413 if (handle_typeof) {
3415 if (parse_generic_dimension (out d)) {
3418 return Token.GENERIC_DIMENSION;
3423 // Save current position and parse next token.
3425 if (parse_less_than ()) {
3426 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3427 d = Token.OP_GENERICS_LT_DECL;
3429 d = Token.OP_GENERICS_LT;
3436 parsing_generic_less_than = 0;
3445 return Token.OP_SHIFT_LEFT_ASSIGN;
3447 return Token.OP_SHIFT_LEFT;
3458 // Handles one line xml comment
3460 private void handle_one_line_xml_comment ()
3463 while ((c = peek_char ()) == ' ')
3464 get_char (); // skip heading whitespaces.
3465 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3466 xml_comment_buffer.Append ((char) get_char ());
3468 if (c == '\r' || c == '\n')
3469 xml_comment_buffer.Append (Environment.NewLine);
3473 // Remove heading "*" in Javadoc-like xml documentation.
3475 private void update_formatted_doc_comment (int current_comment_start)
3477 int length = xml_comment_buffer.Length - current_comment_start;
3478 string [] lines = xml_comment_buffer.ToString (
3479 current_comment_start,
3480 length).Replace ("\r", "").Split ('\n');
3482 // The first line starts with /**, thus it is not target
3483 // for the format check.
3484 for (int i = 1; i < lines.Length; i++) {
3485 string s = lines [i];
3486 int idx = s.IndexOf ('*');
3489 if (i < lines.Length - 1)
3493 head = s.Substring (0, idx);
3494 foreach (char c in head)
3497 lines [i] = s.Substring (idx + 1);
3499 xml_comment_buffer.Remove (current_comment_start, length);
3500 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3504 // Checks if there was incorrect doc comments and raise
3507 public void check_incorrect_doc_comment ()
3509 if (xml_comment_buffer.Length > 0)
3510 WarningMisplacedComment (Location);
3514 // Consumes the saved xml comment lines (if any)
3515 // as for current target member or type.
3517 public string consume_doc_comment ()
3519 if (xml_comment_buffer.Length > 0) {
3520 string ret = xml_comment_buffer.ToString ();
3521 reset_doc_comment ();
3528 get { return context.Report; }
3531 void reset_doc_comment ()
3533 xml_comment_buffer.Length = 0;
3536 public void cleanup ()
3538 if (ifstack != null && ifstack.Count >= 1) {
3539 int state = ifstack.Pop ();
3540 if ((state & REGION) != 0)
3541 Report.Error (1038, Location, "#endregion directive expected");
3543 Report.Error (1027, Location, "Expected `#endif' directive");
3549 // Indicates whether it accepts XML documentation or not.
3551 public enum XmlCommentState {
3552 // comment is allowed in this state.
3554 // comment is not allowed in this state.
3556 // once comments appeared when it is NotAllowed, then the
3557 // state is changed to it, until the state is changed to