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, 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 buffer = new LocatedToken [10000];
140 public Location Location {
141 get { return new Location (row, column); }
144 public string Value {
145 get { return value; }
149 public enum PreprocessorDirective
155 If = 3 | RequiresArgument,
157 Elif = 5 | RequiresArgument,
159 Define = 7 | RequiresArgument,
160 Undef = 8 | RequiresArgument,
163 Pragma = 11 | CustomArgumentsParsing,
166 CustomArgumentsParsing = 1 << 10,
167 RequiresArgument = 1 << 11
170 SeekableStreamReader reader;
172 CompilationSourceFile file_name;
173 CompilerContext context;
181 bool handle_get_set = false;
182 bool handle_remove_add = false;
183 bool handle_where = false;
184 bool handle_typeof = false;
185 bool lambda_arguments_parsing;
186 List<Location> escaped_identifiers;
187 int parsing_generic_less_than;
188 readonly bool doc_processing;
191 // Used mainly for parser optimizations. Some expressions for instance
192 // can appear only in block (including initializer, base initializer)
195 public int parsing_block;
196 internal bool query_parsing;
199 // When parsing type only, useful for ambiguous nullable types
201 public int parsing_type;
204 // Set when parsing generic declaration (type or method header)
206 public bool parsing_generic_declaration;
207 public bool parsing_generic_declaration_doc;
210 // The value indicates that we have not reach any declaration or
213 public int parsing_declaration;
215 public bool parsing_attribute_section;
217 public bool parsing_modifiers;
220 // The special characters to inject on streams to run the unit parser
221 // in the special expression mode. Using private characters from
222 // Plane Sixteen (U+100000 to U+10FFFD)
224 // This character is only tested just before the tokenizer is about to report
225 // an error; So on the regular operation mode, this addition will have no
226 // impact on the tokenizer's performance.
229 public const int EvalStatementParserCharacter = 0x100000;
230 public const int EvalCompilationUnitParserCharacter = 0x100001;
231 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
232 public const int DocumentationXref = 0x100003;
235 // XML documentation buffer. The save point is used to divide
236 // comments on types and comments on members.
238 StringBuilder xml_comment_buffer;
241 // See comment on XmlCommentState enumeration.
243 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
246 // Whether tokens have been seen on this line
248 bool tokens_seen = false;
251 // Set to true once the GENERATE_COMPLETION token has bee
252 // returned. This helps produce one GENERATE_COMPLETION,
253 // as many COMPLETE_COMPLETION as necessary to complete the
254 // AST tree and one final EOF.
259 // Whether a token has been seen on the file
260 // This is needed because `define' is not allowed to be used
261 // after a token has been seen.
268 static readonly KeywordEntry<int>[][] keywords;
269 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
270 static readonly Dictionary<string, object> keyword_strings; // TODO: HashSet
271 static readonly NumberStyles styles;
272 static readonly NumberFormatInfo csharp_format_info;
275 static readonly char[] pragma_warning = "warning".ToCharArray ();
276 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
277 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
278 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
280 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
282 public bool PropertyParsing {
283 get { return handle_get_set; }
284 set { handle_get_set = value; }
287 public bool EventParsing {
288 get { return handle_remove_add; }
289 set { handle_remove_add = value; }
292 public bool ConstraintsParsing {
293 get { return handle_where; }
294 set { handle_where = value; }
297 public bool TypeOfParsing {
298 get { return handle_typeof; }
299 set { handle_typeof = value; }
303 get { return tab_size; }
304 set { tab_size = value; }
307 public XmlCommentState doc_state {
308 get { return xml_doc_state; }
310 if (value == XmlCommentState.Allowed) {
311 check_incorrect_doc_comment ();
312 reset_doc_comment ();
314 xml_doc_state = value;
319 // This is used to trigger completion generation on the parser
320 public bool CompleteOnEOF;
322 void AddEscapedIdentifier (Location loc)
324 if (escaped_identifiers == null)
325 escaped_identifiers = new List<Location> ();
327 escaped_identifiers.Add (loc);
330 public bool IsEscapedIdentifier (ATypeNameExpression name)
332 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
336 // Values for the associated token returned
338 internal int putback_char; // Used by repl only
344 const int TAKING = 1;
345 const int ELSE_SEEN = 4;
346 const int PARENT_TAKING = 8;
347 const int REGION = 16;
350 // pre-processor if stack state:
354 static System.Text.StringBuilder string_builder;
356 const int max_id_size = 512;
357 static readonly char [] id_builder = new char [max_id_size];
359 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
361 const int max_number_size = 512;
362 static char [] number_builder = new char [max_number_size];
363 static int number_pos;
365 static char[] value_builder = new char[256];
374 // This is used when the tokenizer needs to save
375 // the current position as it needs to do some parsing
376 // on its own to deamiguate a token in behalf of the
379 Stack<Position> position_stack = new Stack<Position> (2);
387 public int putback_char;
388 public int previous_col;
389 public Stack<int> ifstack;
390 public int parsing_generic_less_than;
391 public int current_token;
394 public Position (Tokenizer t)
396 position = t.reader.Position;
398 ref_line = t.ref_line;
401 putback_char = t.putback_char;
402 previous_col = t.previous_col;
403 if (t.ifstack != null && t.ifstack.Count != 0) {
404 // There is no simple way to clone Stack<T> all
405 // methods reverse the order
406 var clone = t.ifstack.ToArray ();
407 Array.Reverse (clone);
408 ifstack = new Stack<int> (clone);
410 parsing_generic_less_than = t.parsing_generic_less_than;
411 current_token = t.current_token;
416 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, CompilerContext ctx)
418 this.ref_name = file;
419 this.file_name = file;
425 xml_comment_buffer = new StringBuilder ();
426 doc_processing = ctx.Settings.DocumentationFile != null;
428 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
433 Mono.CSharp.Location.Push (file, file);
436 public void PushPosition ()
438 position_stack.Push (new Position (this));
441 public void PopPosition ()
443 Position p = position_stack.Pop ();
445 reader.Position = p.position;
446 ref_line = p.ref_line;
450 putback_char = p.putback_char;
451 previous_col = p.previous_col;
453 parsing_generic_less_than = p.parsing_generic_less_than;
454 current_token = p.current_token;
458 // Do not reset the position, ignore it.
459 public void DiscardPosition ()
461 position_stack.Pop ();
464 static void AddKeyword (string kw, int token)
466 keyword_strings.Add (kw, null);
468 AddKeyword (keywords, kw, token);
471 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
473 AddKeyword (keywords_preprocessor, kw, directive);
476 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
478 int length = kw.Length;
479 if (keywords[length] == null) {
480 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
483 int char_index = kw[0] - '_';
484 var kwe = keywords[length][char_index];
486 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
490 while (kwe.Next != null) {
494 kwe.Next = new KeywordEntry<T> (kw, token);
502 keyword_strings = new Dictionary<string, object> ();
504 // 11 is the length of the longest keyword for now
505 keywords = new KeywordEntry<int>[11][];
507 AddKeyword ("__arglist", Token.ARGLIST);
508 AddKeyword ("__makeref", Token.MAKEREF);
509 AddKeyword ("__reftype", Token.REFTYPE);
510 AddKeyword ("__refvalue", Token.REFVALUE);
511 AddKeyword ("abstract", Token.ABSTRACT);
512 AddKeyword ("as", Token.AS);
513 AddKeyword ("add", Token.ADD);
514 AddKeyword ("base", Token.BASE);
515 AddKeyword ("bool", Token.BOOL);
516 AddKeyword ("break", Token.BREAK);
517 AddKeyword ("byte", Token.BYTE);
518 AddKeyword ("case", Token.CASE);
519 AddKeyword ("catch", Token.CATCH);
520 AddKeyword ("char", Token.CHAR);
521 AddKeyword ("checked", Token.CHECKED);
522 AddKeyword ("class", Token.CLASS);
523 AddKeyword ("const", Token.CONST);
524 AddKeyword ("continue", Token.CONTINUE);
525 AddKeyword ("decimal", Token.DECIMAL);
526 AddKeyword ("default", Token.DEFAULT);
527 AddKeyword ("delegate", Token.DELEGATE);
528 AddKeyword ("do", Token.DO);
529 AddKeyword ("double", Token.DOUBLE);
530 AddKeyword ("else", Token.ELSE);
531 AddKeyword ("enum", Token.ENUM);
532 AddKeyword ("event", Token.EVENT);
533 AddKeyword ("explicit", Token.EXPLICIT);
534 AddKeyword ("extern", Token.EXTERN);
535 AddKeyword ("false", Token.FALSE);
536 AddKeyword ("finally", Token.FINALLY);
537 AddKeyword ("fixed", Token.FIXED);
538 AddKeyword ("float", Token.FLOAT);
539 AddKeyword ("for", Token.FOR);
540 AddKeyword ("foreach", Token.FOREACH);
541 AddKeyword ("goto", Token.GOTO);
542 AddKeyword ("get", Token.GET);
543 AddKeyword ("if", Token.IF);
544 AddKeyword ("implicit", Token.IMPLICIT);
545 AddKeyword ("in", Token.IN);
546 AddKeyword ("int", Token.INT);
547 AddKeyword ("interface", Token.INTERFACE);
548 AddKeyword ("internal", Token.INTERNAL);
549 AddKeyword ("is", Token.IS);
550 AddKeyword ("lock", Token.LOCK);
551 AddKeyword ("long", Token.LONG);
552 AddKeyword ("namespace", Token.NAMESPACE);
553 AddKeyword ("new", Token.NEW);
554 AddKeyword ("null", Token.NULL);
555 AddKeyword ("object", Token.OBJECT);
556 AddKeyword ("operator", Token.OPERATOR);
557 AddKeyword ("out", Token.OUT);
558 AddKeyword ("override", Token.OVERRIDE);
559 AddKeyword ("params", Token.PARAMS);
560 AddKeyword ("private", Token.PRIVATE);
561 AddKeyword ("protected", Token.PROTECTED);
562 AddKeyword ("public", Token.PUBLIC);
563 AddKeyword ("readonly", Token.READONLY);
564 AddKeyword ("ref", Token.REF);
565 AddKeyword ("remove", Token.REMOVE);
566 AddKeyword ("return", Token.RETURN);
567 AddKeyword ("sbyte", Token.SBYTE);
568 AddKeyword ("sealed", Token.SEALED);
569 AddKeyword ("set", Token.SET);
570 AddKeyword ("short", Token.SHORT);
571 AddKeyword ("sizeof", Token.SIZEOF);
572 AddKeyword ("stackalloc", Token.STACKALLOC);
573 AddKeyword ("static", Token.STATIC);
574 AddKeyword ("string", Token.STRING);
575 AddKeyword ("struct", Token.STRUCT);
576 AddKeyword ("switch", Token.SWITCH);
577 AddKeyword ("this", Token.THIS);
578 AddKeyword ("throw", Token.THROW);
579 AddKeyword ("true", Token.TRUE);
580 AddKeyword ("try", Token.TRY);
581 AddKeyword ("typeof", Token.TYPEOF);
582 AddKeyword ("uint", Token.UINT);
583 AddKeyword ("ulong", Token.ULONG);
584 AddKeyword ("unchecked", Token.UNCHECKED);
585 AddKeyword ("unsafe", Token.UNSAFE);
586 AddKeyword ("ushort", Token.USHORT);
587 AddKeyword ("using", Token.USING);
588 AddKeyword ("virtual", Token.VIRTUAL);
589 AddKeyword ("void", Token.VOID);
590 AddKeyword ("volatile", Token.VOLATILE);
591 AddKeyword ("while", Token.WHILE);
592 AddKeyword ("partial", Token.PARTIAL);
593 AddKeyword ("where", Token.WHERE);
596 AddKeyword ("from", Token.FROM);
597 AddKeyword ("join", Token.JOIN);
598 AddKeyword ("on", Token.ON);
599 AddKeyword ("equals", Token.EQUALS);
600 AddKeyword ("select", Token.SELECT);
601 AddKeyword ("group", Token.GROUP);
602 AddKeyword ("by", Token.BY);
603 AddKeyword ("let", Token.LET);
604 AddKeyword ("orderby", Token.ORDERBY);
605 AddKeyword ("ascending", Token.ASCENDING);
606 AddKeyword ("descending", Token.DESCENDING);
607 AddKeyword ("into", Token.INTO);
609 // Contextual async keywords
610 AddKeyword ("async", Token.ASYNC);
611 AddKeyword ("await", Token.AWAIT);
613 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
615 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
616 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
617 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
618 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
619 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
620 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
621 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
622 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
623 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
624 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
625 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
626 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
628 csharp_format_info = NumberFormatInfo.InvariantInfo;
629 styles = NumberStyles.Float;
631 string_builder = new System.Text.StringBuilder ();
634 int GetKeyword (char[] id, int id_len)
637 // Keywords are stored in an array of arrays grouped by their
638 // length and then by the first character
640 if (id_len >= keywords.Length || keywords [id_len] == null)
643 int first_index = id [0] - '_';
644 if (first_index > 'z' - '_')
647 var kwe = keywords [id_len] [first_index];
654 for (int i = 1; i < id_len; ++i) {
655 if (id [i] != kwe.Value [i]) {
661 } while (res == 0 && kwe != null);
675 if (!handle_remove_add)
679 if (parsing_declaration == 0)
680 res = Token.EXTERN_ALIAS;
683 if (peek_token () == Token.COLON) {
685 res = Token.DEFAULT_COLON;
689 if (!handle_where && !query_parsing)
694 // A query expression is any expression that starts with `from identifier'
695 // followed by any token except ; , =
697 if (!query_parsing) {
698 if (lambda_arguments_parsing) {
704 // HACK: to disable generics micro-parser, because PushPosition does not
705 // store identifiers array
706 parsing_generic_less_than = 1;
708 case Token.IDENTIFIER:
720 next_token = xtoken ();
721 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
724 res = Token.FROM_FIRST;
725 query_parsing = true;
726 if (context.Settings.Version <= LanguageVersion.ISO_2)
727 Report.FeatureIsNotAvailable (context, Location, "query expressions");
730 Expression.Error_VoidInvalidInTheContext (Location, Report);
734 // HACK: A token is not a keyword so we need to restore identifiers buffer
735 // which has been overwritten before we grabbed the identifier
736 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
750 case Token.ASCENDING:
751 case Token.DESCENDING:
758 case Token.NAMESPACE:
759 // TODO: some explanation needed
760 check_incorrect_doc_comment ();
764 if (parsing_block > 0) {
769 // Save current position and parse next token.
772 next_token = token ();
773 bool ok = (next_token == Token.CLASS) ||
774 (next_token == Token.STRUCT) ||
775 (next_token == Token.INTERFACE) ||
776 (next_token == Token.VOID);
781 if (next_token == Token.VOID) {
782 if (context.Settings.Version <= LanguageVersion.ISO_2)
783 Report.FeatureIsNotAvailable (context, Location, "partial methods");
784 } else if (context.Settings.Version == LanguageVersion.ISO_1)
785 Report.FeatureIsNotAvailable (context, Location, "partial types");
790 if (next_token < Token.LAST_KEYWORD) {
791 Report.Error (267, Location,
792 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
800 if (parsing_modifiers) {
802 // Skip attributes section or constructor called async
804 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
809 } else if (parsing_block > 0) {
810 switch (peek_token ()) {
812 case Token.OPEN_PARENS_LAMBDA:
815 case Token.IDENTIFIER:
818 if (xtoken () != Token.ARROW)
831 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
832 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
838 if (parsing_block == 0)
848 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
851 // Keywords are stored in an array of arrays grouped by their
852 // length and then by the first character
854 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
855 return PreprocessorDirective.Invalid;
857 int first_index = id[0] - '_';
858 if (first_index > 'z' - '_')
859 return PreprocessorDirective.Invalid;
861 var kwe = keywords_preprocessor[id_len][first_index];
863 return PreprocessorDirective.Invalid;
865 PreprocessorDirective res = PreprocessorDirective.Invalid;
868 for (int i = 1; i < id_len; ++i) {
869 if (id[i] != kwe.Value[i]) {
875 } while (res == PreprocessorDirective.Invalid && kwe != null);
880 public Location Location {
882 return new Location (ref_line, hidden ? -1 : col);
886 static bool is_identifier_start_character (int c)
888 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
891 static bool is_identifier_part_character (char c)
893 if (c >= 'a' && c <= 'z')
896 if (c >= 'A' && c <= 'Z')
899 if (c == '_' || (c >= '0' && c <= '9'))
905 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
908 public static bool IsKeyword (string s)
910 return keyword_strings.ContainsKey (s);
914 // Open parens micro parser. Detects both lambda and cast ambiguity.
916 int TokenizeOpenParens ()
921 int bracket_level = 0;
922 bool is_type = false;
923 bool can_be_type = false;
926 ptoken = current_token;
929 switch (current_token) {
930 case Token.CLOSE_PARENS:
934 // Expression inside parens is lambda, (int i) =>
936 if (current_token == Token.ARROW)
937 return Token.OPEN_PARENS_LAMBDA;
940 // Expression inside parens is single type, (int[])
943 return Token.OPEN_PARENS_CAST;
946 // Expression is possible cast, look at next token, (T)null
949 switch (current_token) {
950 case Token.OPEN_PARENS:
953 case Token.IDENTIFIER:
967 case Token.UNCHECKED:
972 // These can be part of a member access
986 return Token.OPEN_PARENS_CAST;
989 return Token.OPEN_PARENS;
992 case Token.DOUBLE_COLON:
993 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
998 case Token.IDENTIFIER:
1001 if (bracket_level == 0) {
1007 case Token.OP_GENERICS_LT:
1009 case Token.DOUBLE_COLON:
1011 if (bracket_level == 0)
1015 can_be_type = is_type = false;
1035 if (bracket_level == 0)
1040 if (bracket_level == 0) {
1041 bracket_level = 100;
1042 can_be_type = is_type = false;
1046 case Token.OP_GENERICS_LT:
1047 case Token.OPEN_BRACKET:
1048 if (bracket_level++ == 0)
1052 case Token.OP_GENERICS_GT:
1053 case Token.CLOSE_BRACKET:
1057 case Token.INTERR_NULLABLE:
1059 if (bracket_level == 0)
1065 can_be_type = is_type = false;
1069 return Token.OPEN_PARENS;
1074 public static bool IsValidIdentifier (string s)
1076 if (s == null || s.Length == 0)
1079 if (!is_identifier_start_character (s [0]))
1082 for (int i = 1; i < s.Length; i ++)
1083 if (! is_identifier_part_character (s [i]))
1089 bool parse_less_than ()
1092 int the_token = token ();
1093 if (the_token == Token.OPEN_BRACKET) {
1095 the_token = token ();
1096 } while (the_token != Token.CLOSE_BRACKET);
1097 the_token = token ();
1098 } else if (the_token == Token.IN || the_token == Token.OUT) {
1099 the_token = token ();
1101 switch (the_token) {
1102 case Token.IDENTIFIER:
1120 case Token.OP_GENERICS_GT:
1129 the_token = token ();
1131 if (the_token == Token.OP_GENERICS_GT)
1133 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1135 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1137 else if (the_token == Token.OP_GENERICS_LT) {
1138 if (!parse_less_than ())
1141 } else if (the_token == Token.OPEN_BRACKET) {
1143 the_token = token ();
1144 if (the_token == Token.CLOSE_BRACKET)
1146 else if (the_token == Token.COMMA)
1147 goto rank_specifiers;
1154 bool parse_generic_dimension (out int dimension)
1159 int the_token = token ();
1160 if (the_token == Token.OP_GENERICS_GT)
1162 else if (the_token == Token.COMMA) {
1170 public int peek_token ()
1175 the_token = token ();
1182 // Tonizes `?' using custom disambiguous rules to return one
1183 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1185 // Tricky expression look like:
1187 // Foo ? a = x ? b : c;
1189 int TokenizePossibleNullableType ()
1191 if (parsing_block == 0 || parsing_type > 0)
1192 return Token.INTERR_NULLABLE;
1194 int d = peek_char ();
1197 return Token.OP_COALESCING;
1200 switch (current_token) {
1201 case Token.CLOSE_PARENS:
1206 return Token.INTERR;
1210 if (d == ',' || d == ';' || d == '>')
1211 return Token.INTERR_NULLABLE;
1212 if (d == '*' || (d >= '0' && d <= '9'))
1213 return Token.INTERR;
1217 current_token = Token.NONE;
1219 switch (xtoken ()) {
1226 next_token = Token.INTERR;
1229 case Token.SEMICOLON:
1231 case Token.CLOSE_PARENS:
1232 case Token.OPEN_BRACKET:
1233 case Token.OP_GENERICS_GT:
1235 next_token = Token.INTERR_NULLABLE;
1243 if (next_token == -1) {
1244 switch (xtoken ()) {
1246 case Token.SEMICOLON:
1247 case Token.OPEN_BRACE:
1248 case Token.CLOSE_PARENS:
1250 next_token = Token.INTERR_NULLABLE;
1254 next_token = Token.INTERR;
1262 // All shorcuts failed, do it hard way
1264 while ((ntoken = xtoken ()) != Token.EOF) {
1265 if (ntoken == Token.SEMICOLON)
1268 if (ntoken == Token.COLON) {
1269 if (++colons == interrs)
1274 if (ntoken == Token.INTERR) {
1280 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1289 bool decimal_digits (int c)
1292 bool seen_digits = false;
1295 if (number_pos == max_number_size)
1296 Error_NumericConstantTooLong ();
1297 number_builder [number_pos++] = (char) c;
1301 // We use peek_char2, because decimal_digits needs to do a
1302 // 2-character look-ahead (5.ToString for example).
1304 while ((d = peek_char2 ()) != -1){
1305 if (d >= '0' && d <= '9'){
1306 if (number_pos == max_number_size)
1307 Error_NumericConstantTooLong ();
1308 number_builder [number_pos++] = (char) d;
1318 static bool is_hex (int e)
1320 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1323 static TypeCode real_type_suffix (int c)
1327 return TypeCode.Single;
1329 return TypeCode.Double;
1331 return TypeCode.Decimal;
1333 return TypeCode.Empty;
1337 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1339 bool is_unsigned = false;
1340 bool is_long = false;
1343 bool scanning = true;
1356 // if we have not seen anything in between
1357 // report this error
1359 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1379 if (is_long && is_unsigned){
1380 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1384 // uint if possible, or ulong else.
1386 if ((ul & 0xffffffff00000000) == 0)
1387 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1389 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1390 } else if (is_long){
1391 // long if possible, ulong otherwise
1392 if ((ul & 0x8000000000000000) != 0)
1393 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1395 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1397 // int, uint, long or ulong in that order
1398 if ((ul & 0xffffffff00000000) == 0){
1399 uint ui = (uint) ul;
1401 if ((ui & 0x80000000) != 0)
1402 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1404 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1406 if ((ul & 0x8000000000000000) != 0)
1407 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1409 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1415 // given `c' as the next char in the input decide whether
1416 // we need to convert to a special type, and then choose
1417 // the best representation for the integer
1419 ILiteralConstant adjust_int (int c, Location loc)
1422 if (number_pos > 9){
1423 ulong ul = (uint) (number_builder [0] - '0');
1425 for (int i = 1; i < number_pos; i++){
1426 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1429 return integer_type_suffix (ul, c, loc);
1431 uint ui = (uint) (number_builder [0] - '0');
1433 for (int i = 1; i < number_pos; i++){
1434 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1437 return integer_type_suffix (ui, c, loc);
1439 } catch (OverflowException) {
1440 Error_NumericConstantTooLong ();
1441 return new IntLiteral (context.BuiltinTypes, 0, loc);
1443 catch (FormatException) {
1444 Report.Error (1013, Location, "Invalid number");
1445 return new IntLiteral (context.BuiltinTypes, 0, loc);
1449 ILiteralConstant adjust_real (TypeCode t, Location loc)
1451 string s = new string (number_builder, 0, number_pos);
1452 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1455 case TypeCode.Decimal:
1457 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1458 } catch (OverflowException) {
1459 Report.Error (594, Location, error_details, "decimal");
1460 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1462 case TypeCode.Single:
1464 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1465 } catch (OverflowException) {
1466 Report.Error (594, Location, error_details, "float");
1467 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1471 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1472 } catch (OverflowException) {
1473 Report.Error (594, loc, error_details, "double");
1474 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1479 ILiteralConstant handle_hex (Location loc)
1485 while ((d = peek_char ()) != -1){
1487 number_builder [number_pos++] = (char) d;
1493 string s = new String (number_builder, 0, number_pos);
1496 if (number_pos <= 8)
1497 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1499 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1501 return integer_type_suffix (ul, peek_char (), loc);
1502 } catch (OverflowException){
1503 Error_NumericConstantTooLong ();
1504 return new IntLiteral (context.BuiltinTypes, 0, loc);
1506 catch (FormatException) {
1507 Report.Error (1013, Location, "Invalid number");
1508 return new IntLiteral (context.BuiltinTypes, 0, loc);
1513 // Invoked if we know we have .digits or digits
1515 int is_number (int c)
1517 ILiteralConstant res;
1520 int read_start = reader.Position - 1;
1525 if (c >= '0' && c <= '9'){
1527 int peek = peek_char ();
1529 if (peek == 'x' || peek == 'X') {
1530 val = res = handle_hex (loc);
1532 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1535 return Token.LITERAL;
1543 // We need to handle the case of
1544 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1546 bool is_real = false;
1548 if (decimal_digits ('.')){
1554 val = res = adjust_int (-1, loc);
1557 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1559 return Token.LITERAL;
1563 if (c == 'e' || c == 'E'){
1565 if (number_pos == max_number_size)
1566 Error_NumericConstantTooLong ();
1567 number_builder [number_pos++] = (char) c;
1571 if (number_pos == max_number_size)
1572 Error_NumericConstantTooLong ();
1573 number_builder [number_pos++] = '+';
1575 } else if (c == '-') {
1576 if (number_pos == max_number_size)
1577 Error_NumericConstantTooLong ();
1578 number_builder [number_pos++] = '-';
1581 if (number_pos == max_number_size)
1582 Error_NumericConstantTooLong ();
1583 number_builder [number_pos++] = '+';
1590 var type = real_type_suffix (c);
1591 if (type == TypeCode.Empty && !is_real) {
1593 res = adjust_int (c, loc);
1597 if (type == TypeCode.Empty) {
1601 res = adjust_real (type, loc);
1607 res.ParsedValue = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty ? 1 : 0));
1610 return Token.LITERAL;
1614 // Accepts exactly count (4 or 8) hex, no more no less
1616 int getHex (int count, out int surrogate, out bool error)
1621 int top = count != -1 ? count : 4;
1626 for (i = 0; i < top; i++){
1629 if (c >= '0' && c <= '9')
1630 c = (int) c - (int) '0';
1631 else if (c >= 'A' && c <= 'F')
1632 c = (int) c - (int) 'A' + 10;
1633 else if (c >= 'a' && c <= 'f')
1634 c = (int) c - (int) 'a' + 10;
1640 total = (total * 16) + c;
1642 int p = peek_char ();
1645 if (!is_hex ((char)p))
1651 if (total > 0x0010FFFF) {
1656 if (total >= 0x00010000) {
1657 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1658 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1665 int escape (int c, out int surrogate)
1701 v = getHex (-1, out surrogate, out error);
1707 return EscapeUnicode (d, out surrogate);
1710 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1719 int EscapeUnicode (int ch, out int surrogate)
1723 ch = getHex (8, out surrogate, out error);
1725 ch = getHex (4, out surrogate, out error);
1729 Report.Error (1009, Location, "Unrecognized escape sequence");
1737 if (putback_char != -1) {
1745 if (peek_char () == '\n') {
1751 } else if (x == '\n') {
1759 void advance_line ()
1769 if (putback_char == -1)
1770 putback_char = reader.Read ();
1771 return putback_char;
1776 if (putback_char != -1)
1777 return putback_char;
1778 return reader.Peek ();
1781 void putback (int c)
1783 if (putback_char != -1){
1784 Console.WriteLine ("Col: " + col);
1785 Console.WriteLine ("Row: " + line);
1786 Console.WriteLine ("Name: " + ref_name.Name);
1787 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1788 throw new Exception ("This should not happen putback on putback");
1790 if (c == '\n' || col == 0) {
1791 // It won't happen though.
1801 public bool advance ()
1803 return peek_char () != -1 || CompleteOnEOF;
1806 public Object Value {
1812 public Object value ()
1819 current_token = xtoken ();
1820 return current_token;
1823 int TokenizePreprocessorIdentifier (out int c)
1825 // skip over white space
1828 } while (c == ' ' || c == '\t');
1832 while (c != -1 && c >= 'a' && c <= 'z') {
1833 id_builder[pos++] = (char) c;
1836 int peek = peek_char ();
1837 if (peek == 'U' || peek == 'u') {
1839 c = EscapeUnicode (c, out surrogate);
1840 if (surrogate != 0) {
1841 if (is_identifier_part_character ((char) c)) {
1842 id_builder[pos++] = (char) c;
1853 PreprocessorDirective get_cmd_arg (out string arg)
1857 tokens_seen = false;
1860 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1862 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1865 // skip over white space
1866 while (c == ' ' || c == '\t')
1869 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1872 while (c != -1 && c != '\n') {
1873 if (c == '\\' && has_identifier_argument >= 0) {
1874 if (has_identifier_argument != 0) {
1875 has_identifier_argument = 1;
1877 int peek = peek_char ();
1878 if (peek == 'U' || peek == 'u') {
1880 c = EscapeUnicode (c, out surrogate);
1881 if (surrogate != 0) {
1882 if (is_identifier_part_character ((char) c)) {
1883 if (pos == value_builder.Length)
1884 Array.Resize (ref value_builder, pos * 2);
1886 value_builder[pos++] = (char) c;
1892 has_identifier_argument = -1;
1894 } else if (c == '/' && peek_char () == '/') {
1896 // Eat single-line comments
1901 } while (c != -1 && c != '\n');
1906 if (pos == value_builder.Length)
1907 Array.Resize (ref value_builder, pos * 2);
1909 value_builder[pos++] = (char) c;
1914 if (pos > max_id_size)
1915 arg = new string (value_builder, 0, pos);
1917 arg = InternIdentifier (value_builder, pos);
1919 // Eat any trailing whitespaces
1920 arg = arg.Trim (simple_whitespaces);
1927 // Handles the #line directive
1929 bool PreProcessLine (string arg)
1931 if (arg.Length == 0)
1934 if (arg == "default"){
1936 ref_name = file_name;
1938 Location.Push (file_name, ref_name);
1940 } else if (arg == "hidden"){
1948 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1949 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1952 char [] quotes = { '\"' };
1954 string name = arg.Substring (pos). Trim (quotes);
1955 ref_name = context.LookupFile (file_name, name);
1956 file_name.AddIncludeFile (ref_name);
1958 Location.Push (file_name, ref_name);
1960 ref_line = System.Int32.Parse (arg);
1971 // Handles #define and #undef
1973 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1975 if (ident.Length == 0 || ident == "true" || ident == "false"){
1976 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1980 if (ident.IndexOfAny (simple_whitespaces) != -1){
1981 Error_EndLineExpected ();
1985 if (!is_identifier_start_character (ident [0]))
1986 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1988 foreach (char c in ident.Substring (1)){
1989 if (!is_identifier_part_character (c)){
1990 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1995 if (!caller_is_taking)
2002 if (context.Settings.IsConditionalSymbolDefined (ident))
2005 file_name.AddDefine (ident);
2010 file_name.AddUndefine (ident);
2014 byte read_hex (out bool error)
2017 int c = get_char ();
2019 if ((c >= '0') && (c <= '9'))
2020 total = (int) c - (int) '0';
2021 else if ((c >= 'A') && (c <= 'F'))
2022 total = (int) c - (int) 'A' + 10;
2023 else if ((c >= 'a') && (c <= 'f'))
2024 total = (int) c - (int) 'a' + 10;
2033 if ((c >= '0') && (c <= '9'))
2034 total += (int) c - (int) '0';
2035 else if ((c >= 'A') && (c <= 'F'))
2036 total += (int) c - (int) 'A' + 10;
2037 else if ((c >= 'a') && (c <= 'f'))
2038 total += (int) c - (int) 'a' + 10;
2045 return (byte) total;
2049 // Parses #pragma checksum
2051 bool ParsePragmaChecksum ()
2054 // The syntax is ` "foo.txt" "{guid}" "hash"'
2056 int c = get_char ();
2061 string_builder.Length = 0;
2062 while (c != -1 && c != '\n') {
2069 string_builder.Append ((char) c);
2072 if (string_builder.Length == 0) {
2073 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2076 // TODO: Any white-spaces count
2080 SourceFile file = context.LookupFile (file_name, string_builder.ToString ());
2082 if (get_char () != '"' || get_char () != '{')
2086 byte[] guid_bytes = new byte [16];
2089 for (; i < 4; i++) {
2090 guid_bytes [i] = read_hex (out error);
2095 if (get_char () != '-')
2098 for (; i < 10; i++) {
2099 guid_bytes [i] = read_hex (out error);
2103 guid_bytes [i++] = read_hex (out error);
2107 if (get_char () != '-')
2111 for (; i < 16; i++) {
2112 guid_bytes [i] = read_hex (out error);
2117 if (get_char () != '}' || get_char () != '"')
2120 // TODO: Any white-spaces count
2125 if (get_char () != '"')
2128 // Any length of checksum
2129 List<byte> checksum_bytes = new List<byte> (16);
2132 while (c != '"' && c != -1) {
2133 checksum_bytes.Add (read_hex (out error));
2141 ReadSingleLineComment ();
2142 } else if (get_char () != '"') {
2146 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2147 ref_name.AutoGenerated = true;
2151 bool IsTokenIdentifierEqual (char[] identifier)
2153 for (int i = 0; i < identifier.Length; ++i) {
2154 if (identifier[i] != id_builder[i])
2161 int TokenizePragmaNumber (ref int c)
2167 if (c >= '0' && c <= '9') {
2169 uint ui = (uint) (number_builder[0] - '0');
2172 for (int i = 1; i < number_pos; i++) {
2173 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2177 } catch (OverflowException) {
2178 Error_NumericConstantTooLong ();
2185 // skip over white space
2186 while (c == ' ' || c == '\t')
2193 // skip over white space
2194 while (c == ' ' || c == '\t')
2199 ReadSingleLineComment ();
2201 Report.Warning (1692, 1, Location, "Invalid number");
2203 // Read everything till the end of the line or file
2206 } while (c != -1 && c != '\n');
2213 void ReadSingleLineComment ()
2215 if (peek_char () != '/')
2216 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2218 // Read everything till the end of the line or file
2222 } while (c != -1 && c != '\n');
2226 /// Handles #pragma directive
2228 void ParsePragmaDirective (string arg)
2231 int length = TokenizePreprocessorIdentifier (out c);
2232 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2233 length = TokenizePreprocessorIdentifier (out c);
2236 // #pragma warning disable
2237 // #pragma warning restore
2239 if (length == pragma_warning_disable.Length) {
2240 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2241 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2242 // skip over white space
2243 while (c == ' ' || c == '\t')
2248 if (c == '\n' || c == '/') {
2250 ReadSingleLineComment ();
2253 // Disable/Restore all warnings
2256 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2258 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2262 // Disable/Restore a warning or group of warnings
2266 code = TokenizePragmaNumber (ref c);
2269 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2271 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2274 } while (code >= 0 && c != '\n' && c != -1);
2281 Report.Warning (1634, 1, Location, "Expected disable or restore");
2288 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2289 if (c != ' ' || !ParsePragmaChecksum ()) {
2290 Report.Warning (1695, 1, Location,
2291 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2297 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2300 bool eval_val (string s)
2307 return file_name.IsConditionalDefined (context, s);
2310 bool pp_primary (ref string s)
2319 s = s.Substring (1);
2320 bool val = pp_expr (ref s, false);
2321 if (s.Length > 0 && s [0] == ')'){
2322 s = s.Substring (1);
2325 Error_InvalidDirective ();
2329 if (is_identifier_start_character (c)){
2335 if (is_identifier_part_character (c)){
2339 bool v = eval_val (s.Substring (0, j));
2340 s = s.Substring (j);
2343 bool vv = eval_val (s);
2348 Error_InvalidDirective ();
2352 bool pp_unary (ref string s)
2359 if (len > 1 && s [1] == '='){
2360 Error_InvalidDirective ();
2363 s = s.Substring (1);
2364 return ! pp_primary (ref s);
2366 return pp_primary (ref s);
2368 Error_InvalidDirective ();
2373 bool pp_eq (ref string s)
2375 bool va = pp_unary (ref s);
2381 if (len > 2 && s [1] == '='){
2382 s = s.Substring (2);
2383 return va == pp_unary (ref s);
2385 Error_InvalidDirective ();
2388 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2389 s = s.Substring (2);
2391 return va != pp_unary (ref s);
2400 bool pp_and (ref string s)
2402 bool va = pp_eq (ref s);
2408 if (len > 2 && s [1] == '&'){
2409 s = s.Substring (2);
2410 return (va & pp_and (ref s));
2412 Error_InvalidDirective ();
2421 // Evaluates an expression for `#if' or `#elif'
2423 bool pp_expr (ref string s, bool isTerm)
2425 bool va = pp_and (ref s);
2432 if (len > 2 && s [1] == '|'){
2433 s = s.Substring (2);
2434 return va | pp_expr (ref s, isTerm);
2436 Error_InvalidDirective ();
2441 Error_EndLineExpected ();
2449 bool eval (string s)
2451 bool v = pp_expr (ref s, true);
2460 void Error_NumericConstantTooLong ()
2462 Report.Error (1021, Location, "Integral constant is too large");
2465 void Error_InvalidDirective ()
2467 Report.Error (1517, Location, "Invalid preprocessor directive");
2470 void Error_UnexpectedDirective (string extra)
2474 "Unexpected processor directive ({0})", extra);
2477 void Error_TokensSeen ()
2479 Report.Error (1032, Location,
2480 "Cannot define or undefine preprocessor symbols after first token in file");
2483 void Eror_WrongPreprocessorLocation ()
2485 Report.Error (1040, Location,
2486 "Preprocessor directives must appear as the first non-whitespace character on a line");
2489 void Error_EndLineExpected ()
2491 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2495 // Raises a warning when tokenizer found documentation comment
2496 // on unexpected place
2498 void WarningMisplacedComment (Location loc)
2500 if (doc_state != XmlCommentState.Error) {
2501 doc_state = XmlCommentState.Error;
2502 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2507 // if true, then the code continues processing the code
2508 // if false, the code stays in a loop until another directive is
2510 // When caller_is_taking is false we ignore all directives except the ones
2511 // which can help us to identify where the #if block ends
2512 bool ParsePreprocessingDirective (bool caller_is_taking)
2515 bool region_directive = false;
2517 var directive = get_cmd_arg (out arg);
2520 // The first group of pre-processing instructions is always processed
2522 switch (directive) {
2523 case PreprocessorDirective.Region:
2524 region_directive = true;
2526 goto case PreprocessorDirective.If;
2528 case PreprocessorDirective.Endregion:
2529 if (ifstack == null || ifstack.Count == 0){
2530 Error_UnexpectedDirective ("no #region for this #endregion");
2533 int pop = ifstack.Pop ();
2535 if ((pop & REGION) == 0)
2536 Report.Error (1027, Location, "Expected `#endif' directive");
2538 return caller_is_taking;
2540 case PreprocessorDirective.If:
2541 if (ifstack == null)
2542 ifstack = new Stack<int> (2);
2544 int flags = region_directive ? REGION : 0;
2545 if (ifstack.Count == 0){
2546 flags |= PARENT_TAKING;
2548 int state = ifstack.Peek ();
2549 if ((state & TAKING) != 0) {
2550 flags |= PARENT_TAKING;
2554 if (eval (arg) && caller_is_taking) {
2555 ifstack.Push (flags | TAKING);
2558 ifstack.Push (flags);
2561 case PreprocessorDirective.Endif:
2562 if (ifstack == null || ifstack.Count == 0){
2563 Error_UnexpectedDirective ("no #if for this #endif");
2566 pop = ifstack.Pop ();
2568 if ((pop & REGION) != 0)
2569 Report.Error (1038, Location, "#endregion directive expected");
2571 if (arg.Length != 0) {
2572 Error_EndLineExpected ();
2575 if (ifstack.Count == 0)
2578 int state = ifstack.Peek ();
2579 return (state & TAKING) != 0;
2582 case PreprocessorDirective.Elif:
2583 if (ifstack == null || ifstack.Count == 0){
2584 Error_UnexpectedDirective ("no #if for this #elif");
2587 int state = ifstack.Pop ();
2589 if ((state & REGION) != 0) {
2590 Report.Error (1038, Location, "#endregion directive expected");
2594 if ((state & ELSE_SEEN) != 0){
2595 Error_UnexpectedDirective ("#elif not valid after #else");
2599 if ((state & TAKING) != 0) {
2604 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2605 ifstack.Push (state | TAKING);
2609 ifstack.Push (state);
2613 case PreprocessorDirective.Else:
2614 if (ifstack == null || ifstack.Count == 0){
2615 Error_UnexpectedDirective ("no #if for this #else");
2618 int state = ifstack.Peek ();
2620 if ((state & REGION) != 0) {
2621 Report.Error (1038, Location, "#endregion directive expected");
2625 if ((state & ELSE_SEEN) != 0){
2626 Error_UnexpectedDirective ("#else within #else");
2632 if (arg.Length != 0) {
2633 Error_EndLineExpected ();
2638 if ((state & PARENT_TAKING) != 0) {
2639 ret = (state & TAKING) == 0;
2647 ifstack.Push (state | ELSE_SEEN);
2651 case PreprocessorDirective.Define:
2652 if (any_token_seen){
2653 Error_TokensSeen ();
2654 return caller_is_taking;
2656 PreProcessDefinition (true, arg, caller_is_taking);
2657 return caller_is_taking;
2659 case PreprocessorDirective.Undef:
2660 if (any_token_seen){
2661 Error_TokensSeen ();
2662 return caller_is_taking;
2664 PreProcessDefinition (false, arg, caller_is_taking);
2665 return caller_is_taking;
2667 case PreprocessorDirective.Invalid:
2668 Report.Error (1024, Location, "Wrong preprocessor directive");
2673 // These are only processed if we are in a `taking' block
2675 if (!caller_is_taking)
2679 case PreprocessorDirective.Error:
2680 Report.Error (1029, Location, "#error: '{0}'", arg);
2683 case PreprocessorDirective.Warning:
2684 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2687 case PreprocessorDirective.Pragma:
2688 if (context.Settings.Version == LanguageVersion.ISO_1) {
2689 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2692 ParsePragmaDirective (arg);
2695 case PreprocessorDirective.Line:
2696 if (!PreProcessLine (arg))
2699 "The line number specified for #line directive is missing or invalid");
2700 return caller_is_taking;
2703 throw new NotImplementedException (directive.ToString ());
2706 private int consume_string (bool quoted)
2710 Location start_location = Location;
2712 start_location = start_location - 1;
2715 int reader_pos = reader.Position;
2721 if (quoted && peek_char () == '"') {
2722 if (pos == value_builder.Length)
2723 Array.Resize (ref value_builder, pos * 2);
2725 value_builder[pos++] = (char) c;
2734 s = InternIdentifier (value_builder, pos);
2736 s = new string (value_builder, 0, pos);
2738 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2741 res.ParsedValue = quoted ?
2742 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2743 reader.ReadChars (reader_pos - 1, reader.Position);
2746 return Token.LITERAL;
2751 Report.Error (1010, Location, "Newline in constant");
2752 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2753 return Token.LITERAL;
2755 } else if (c == '\\' && !quoted) {
2757 c = escape (c, out surrogate);
2760 if (surrogate != 0) {
2761 if (pos == value_builder.Length)
2762 Array.Resize (ref value_builder, pos * 2);
2764 value_builder[pos++] = (char) c;
2767 } else if (c == -1) {
2768 Report.Error (1039, Location, "Unterminated string literal");
2772 if (pos == value_builder.Length)
2773 Array.Resize (ref value_builder, pos * 2);
2775 value_builder[pos++] = (char) c;
2779 private int consume_identifier (int s)
2781 int res = consume_identifier (s, false);
2783 if (doc_state == XmlCommentState.Allowed)
2784 doc_state = XmlCommentState.NotAllowed;
2789 int consume_identifier (int c, bool quoted)
2792 // This method is very performance sensitive. It accounts
2793 // for approximately 25% of all parser time
2803 c = escape (c, out surrogate);
2804 if (surrogate != 0) {
2805 id_builder [pos++] = (char) c;
2810 id_builder [pos++] = (char) c;
2816 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2817 id_builder [pos++] = (char) c;
2824 c = escape (c, out surrogate);
2825 if (is_identifier_part_character ((char) c))
2826 id_builder[pos++] = (char) c;
2828 if (surrogate != 0) {
2834 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2835 id_builder [pos++] = (char) c;
2842 } catch (IndexOutOfRangeException) {
2843 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2851 // Optimization: avoids doing the keyword lookup
2852 // on uppercase letters
2854 if (id_builder [0] >= '_' && !quoted) {
2855 int keyword = GetKeyword (id_builder, pos);
2856 if (keyword != -1) {
2857 val = LocatedToken.Create (keyword == Token.AWAIT ? "await" : null, ref_line, column);
2862 string s = InternIdentifier (id_builder, pos);
2863 val = LocatedToken.Create (s, ref_line, column);
2864 if (quoted && parsing_attribute_section)
2865 AddEscapedIdentifier (((LocatedToken) val).Location);
2867 return Token.IDENTIFIER;
2870 static string InternIdentifier (char[] charBuffer, int length)
2873 // Keep identifiers in an array of hashtables to avoid needless
2876 var identifiers_group = identifiers[length];
2878 if (identifiers_group != null) {
2879 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2883 // TODO: this should be number of files dependant
2884 // corlib compilation peaks at 1000 and System.Core at 150
2885 int capacity = length > 20 ? 10 : 100;
2886 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2887 identifiers[length] = identifiers_group;
2890 char[] chars = new char[length];
2891 Array.Copy (charBuffer, chars, length);
2893 s = new string (charBuffer, 0, length);
2894 identifiers_group.Add (chars, s);
2898 public int xtoken ()
2902 // Whether we have seen comments on the current line
2903 bool comments_seen = false;
2904 while ((c = get_char ()) != -1) {
2907 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2915 case 0xFEFF: // Ignore BOM anywhere in the file
2918 /* This is required for compatibility with .NET
2920 if (peek_char () == 0xBB) {
2923 if (get_char () == 0xBF)
2931 return consume_identifier (c);
2934 val = LocatedToken.Create (ref_line, col);
2935 return Token.OPEN_BRACE;
2937 val = LocatedToken.Create (ref_line, col);
2938 return Token.CLOSE_BRACE;
2940 // To block doccomment inside attribute declaration.
2941 if (doc_state == XmlCommentState.Allowed)
2942 doc_state = XmlCommentState.NotAllowed;
2944 val = LocatedToken.Create (ref_line, col);
2946 if (parsing_block == 0 || lambda_arguments_parsing)
2947 return Token.OPEN_BRACKET;
2949 int next = peek_char ();
2953 return Token.OPEN_BRACKET;
2961 next = peek_token ();
2962 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2963 return Token.OPEN_BRACKET;
2965 return Token.OPEN_BRACKET_EXPR;
2967 return Token.OPEN_BRACKET_EXPR;
2970 LocatedToken.CreateOptional (ref_line, col, ref val);
2971 return Token.CLOSE_BRACKET;
2973 val = LocatedToken.Create (ref_line, col);
2975 // An expression versions of parens can appear in block context only
2977 if (parsing_block != 0 && !lambda_arguments_parsing) {
2980 // Optmize most common case where we know that parens
2983 switch (current_token) {
2984 case Token.IDENTIFIER:
2992 case Token.DELEGATE:
2993 case Token.OP_GENERICS_GT:
2994 return Token.OPEN_PARENS;
2997 // Optimize using peek
2998 int xx = peek_char ();
3005 return Token.OPEN_PARENS;
3008 lambda_arguments_parsing = true;
3010 d = TokenizeOpenParens ();
3012 lambda_arguments_parsing = false;
3016 return Token.OPEN_PARENS;
3018 LocatedToken.CreateOptional (ref_line, col, ref val);
3019 return Token.CLOSE_PARENS;
3021 LocatedToken.CreateOptional (ref_line, col, ref val);
3024 LocatedToken.CreateOptional (ref_line, col, ref val);
3025 return Token.SEMICOLON;
3027 val = LocatedToken.Create (ref_line, col);
3030 val = LocatedToken.Create (ref_line, col);
3031 return TokenizePossibleNullableType ();
3033 val = LocatedToken.Create (ref_line, col);
3034 if (parsing_generic_less_than++ > 0)
3035 return Token.OP_GENERICS_LT;
3037 return TokenizeLessThan ();
3040 val = LocatedToken.Create (ref_line, col);
3048 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3049 parsing_generic_less_than--;
3050 return Token.OP_GENERICS_GT;
3059 return Token.OP_SHIFT_RIGHT_ASSIGN;
3061 return Token.OP_SHIFT_RIGHT;
3067 val = LocatedToken.Create (ref_line, col);
3071 } else if (d == '=') {
3072 d = Token.OP_ADD_ASSIGN;
3080 val = LocatedToken.Create (ref_line, col);
3084 } else if (d == '=')
3085 d = Token.OP_SUB_ASSIGN;
3095 val = LocatedToken.Create (ref_line, col);
3096 if (peek_char () == '='){
3103 val = LocatedToken.Create (ref_line, col);
3114 return Token.ASSIGN;
3117 val = LocatedToken.Create (ref_line, col);
3121 return Token.OP_AND;
3125 return Token.OP_AND_ASSIGN;
3127 return Token.BITWISE_AND;
3130 val = LocatedToken.Create (ref_line, col);
3138 return Token.OP_OR_ASSIGN;
3140 return Token.BITWISE_OR;
3143 val = LocatedToken.Create (ref_line, col);
3144 if (peek_char () == '='){
3146 return Token.OP_MULT_ASSIGN;
3153 val = LocatedToken.Create (ref_line, col);
3155 return Token.OP_DIV_ASSIGN;
3158 // Handle double-slash comments.
3161 if (doc_processing) {
3162 if (peek_char () == '/') {
3164 // Don't allow ////.
3165 if ((d = peek_char ()) != '/') {
3166 if (doc_state == XmlCommentState.Allowed)
3167 handle_one_line_xml_comment ();
3168 else if (doc_state == XmlCommentState.NotAllowed)
3169 WarningMisplacedComment (Location - 3);
3172 if (xml_comment_buffer.Length > 0)
3173 doc_state = XmlCommentState.NotAllowed;
3177 while ((d = get_char ()) != -1 && d != '\n');
3179 any_token_seen |= tokens_seen;
3180 tokens_seen = false;
3181 comments_seen = false;
3183 } else if (d == '*'){
3185 bool docAppend = false;
3186 if (doc_processing && peek_char () == '*') {
3188 // But when it is /**/, just do nothing.
3189 if (peek_char () == '/') {
3193 if (doc_state == XmlCommentState.Allowed)
3195 else if (doc_state == XmlCommentState.NotAllowed) {
3196 WarningMisplacedComment (Location - 2);
3200 int current_comment_start = 0;
3202 current_comment_start = xml_comment_buffer.Length;
3203 xml_comment_buffer.Append (Environment.NewLine);
3206 while ((d = get_char ()) != -1){
3207 if (d == '*' && peek_char () == '/'){
3209 comments_seen = true;
3213 xml_comment_buffer.Append ((char) d);
3216 any_token_seen |= tokens_seen;
3217 tokens_seen = false;
3219 // Reset 'comments_seen' just to be consistent.
3220 // It doesn't matter either way, here.
3222 comments_seen = false;
3226 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3229 update_formatted_doc_comment (current_comment_start);
3232 val = LocatedToken.Create (ref_line, col);
3236 val = LocatedToken.Create (ref_line, col);
3237 if (peek_char () == '='){
3239 return Token.OP_MOD_ASSIGN;
3241 return Token.PERCENT;
3244 val = LocatedToken.Create (ref_line, col);
3245 if (peek_char () == '='){
3247 return Token.OP_XOR_ASSIGN;
3249 return Token.CARRET;
3252 val = LocatedToken.Create (ref_line, col);
3253 if (peek_char () == ':') {
3255 return Token.DOUBLE_COLON;
3259 case '0': case '1': case '2': case '3': case '4':
3260 case '5': case '6': case '7': case '8': case '9':
3262 return is_number (c);
3264 case '\n': // white space
3265 any_token_seen |= tokens_seen;
3266 tokens_seen = false;
3267 comments_seen = false;
3273 if (d >= '0' && d <= '9')
3274 return is_number (c);
3276 LocatedToken.CreateOptional (ref_line, col, ref val);
3280 if (tokens_seen || comments_seen) {
3281 Eror_WrongPreprocessorLocation ();
3285 if (ParsePreprocessingDirective (true))
3288 bool directive_expected = false;
3289 while ((c = get_char ()) != -1) {
3291 directive_expected = true;
3292 } else if (!directive_expected) {
3293 // TODO: Implement comment support for disabled code and uncomment this code
3295 // Eror_WrongPreprocessorLocation ();
3296 // return Token.ERROR;
3301 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3305 if (ParsePreprocessingDirective (false))
3308 directive_expected = false;
3312 tokens_seen = false;
3319 return consume_string (false);
3322 return TokenizeBackslash ();
3328 return consume_string (true);
3331 if (is_identifier_start_character (c)){
3332 return consume_identifier (c, true);
3335 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3338 case EvalStatementParserCharacter:
3339 return Token.EVAL_STATEMENT_PARSER;
3340 case EvalCompilationUnitParserCharacter:
3341 return Token.EVAL_COMPILATION_UNIT_PARSER;
3342 case EvalUsingDeclarationsParserCharacter:
3343 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3344 case DocumentationXref:
3345 return Token.DOC_SEE;
3348 if (is_identifier_start_character (c)) {
3350 return consume_identifier (c);
3353 if (char.IsWhiteSpace ((char) c))
3356 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3361 return Token.COMPLETE_COMPLETION;
3364 return Token.GENERATE_COMPLETION;
3371 int TokenizeBackslash ()
3374 int read_start = reader.Position;
3376 Location start_location = Location;
3377 int c = get_char ();
3380 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3381 Report.Error (1011, start_location, "Empty character literal");
3382 return Token.LITERAL;
3386 Report.Error (1010, start_location, "Newline in constant");
3391 c = escape (c, out d);
3395 throw new NotImplementedException ();
3397 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3402 Report.Error (1012, start_location, "Too many characters in character literal");
3404 // Try to recover, read until newline or next "'"
3405 while ((c = get_char ()) != -1) {
3406 if (c == '\n' || c == '\'')
3412 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3415 return Token.LITERAL;
3418 int TokenizeLessThan ()
3421 if (handle_typeof) {
3423 if (parse_generic_dimension (out d)) {
3426 return Token.GENERIC_DIMENSION;
3431 // Save current position and parse next token.
3433 if (parse_less_than ()) {
3434 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3435 d = Token.OP_GENERICS_LT_DECL;
3437 d = Token.OP_GENERICS_LT;
3444 parsing_generic_less_than = 0;
3453 return Token.OP_SHIFT_LEFT_ASSIGN;
3455 return Token.OP_SHIFT_LEFT;
3466 // Handles one line xml comment
3468 private void handle_one_line_xml_comment ()
3471 while ((c = peek_char ()) == ' ')
3472 get_char (); // skip heading whitespaces.
3473 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3474 xml_comment_buffer.Append ((char) get_char ());
3476 if (c == '\r' || c == '\n')
3477 xml_comment_buffer.Append (Environment.NewLine);
3481 // Remove heading "*" in Javadoc-like xml documentation.
3483 private void update_formatted_doc_comment (int current_comment_start)
3485 int length = xml_comment_buffer.Length - current_comment_start;
3486 string [] lines = xml_comment_buffer.ToString (
3487 current_comment_start,
3488 length).Replace ("\r", "").Split ('\n');
3490 // The first line starts with /**, thus it is not target
3491 // for the format check.
3492 for (int i = 1; i < lines.Length; i++) {
3493 string s = lines [i];
3494 int idx = s.IndexOf ('*');
3497 if (i < lines.Length - 1)
3501 head = s.Substring (0, idx);
3502 foreach (char c in head)
3505 lines [i] = s.Substring (idx + 1);
3507 xml_comment_buffer.Remove (current_comment_start, length);
3508 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3512 // Checks if there was incorrect doc comments and raise
3515 public void check_incorrect_doc_comment ()
3517 if (xml_comment_buffer.Length > 0)
3518 WarningMisplacedComment (Location);
3522 // Consumes the saved xml comment lines (if any)
3523 // as for current target member or type.
3525 public string consume_doc_comment ()
3527 if (xml_comment_buffer.Length > 0) {
3528 string ret = xml_comment_buffer.ToString ();
3529 reset_doc_comment ();
3536 get { return context.Report; }
3539 void reset_doc_comment ()
3541 xml_comment_buffer.Length = 0;
3544 public void cleanup ()
3546 if (ifstack != null && ifstack.Count >= 1) {
3547 int state = ifstack.Pop ();
3548 if ((state & REGION) != 0)
3549 Report.Error (1038, Location, "#endregion directive expected");
3551 Report.Error (1027, Location, "Expected `#endif' directive");
3557 // Indicates whether it accepts XML documentation or not.
3559 public enum XmlCommentState {
3560 // comment is allowed in this state.
3562 // comment is not allowed in this state.
3564 // once comments appeared when it is NotAllowed, then the
3565 // state is changed to it, until the state is changed to