2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 // This also implements the preprocessor
5 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
17 using System.Collections.Generic;
18 using System.Globalization;
19 using System.Diagnostics;
24 /// Tokenizer for C# source code.
27 public class Tokenizer : yyParser.yyInput
31 public readonly T Token;
32 public KeywordEntry<T> Next;
33 public readonly char[] Value;
35 public KeywordEntry (string value, T token)
37 this.Value = value.ToCharArray ();
42 sealed class IdentifiersComparer : IEqualityComparer<char[]>
46 public IdentifiersComparer (int length)
51 public bool Equals (char[] x, char[] y)
53 for (int i = 0; i < length; ++i)
60 public int GetHashCode (char[] obj)
63 for (int i = 0; i < length; ++i)
64 h = (h << 5) - h + obj [i];
71 // This class has to be used in the parser only, it reuses token
72 // details after each parse
74 public class LocatedToken
79 static LocatedToken[] buffer = new LocatedToken[0];
82 private LocatedToken ()
86 public static LocatedToken Create (int row, int column)
88 return Create (null, row, column);
91 public static LocatedToken Create (string value, Location loc)
93 return Create (value, loc.Row, loc.Column);
96 public static LocatedToken Create (string value, int row, int column)
99 // TODO: I am not very happy about the logic but it's the best
100 // what I could come up with for now.
101 // Ideally we should be using just tiny buffer (256 elements) which
102 // is enough to hold all details for currect stack and recycle elements
103 // poped from the stack but there is a trick needed to recycle
107 if (pos >= buffer.Length) {
108 entry = new LocatedToken ();
110 entry = buffer [pos];
112 entry = new LocatedToken ();
113 buffer [pos] = entry;
120 entry.column = column;
125 // Used for token not required by expression evaluator
127 [Conditional ("FULL_AST")]
128 public static void CreateOptional (int row, int col, ref object token)
130 token = Create (row, col);
133 public static void Initialize ()
136 if (buffer.Length == 0)
137 buffer = new LocatedToken [10000];
142 public Location Location {
143 get { return new Location (row, column); }
146 public string Value {
147 get { return value; }
151 public enum PreprocessorDirective
157 If = 3 | RequiresArgument,
159 Elif = 5 | RequiresArgument,
161 Define = 7 | RequiresArgument,
162 Undef = 8 | RequiresArgument,
165 Pragma = 11 | CustomArgumentsParsing,
168 CustomArgumentsParsing = 1 << 10,
169 RequiresArgument = 1 << 11
172 SeekableStreamReader reader;
174 CompilationSourceFile file_name;
175 CompilerContext context;
183 bool handle_get_set = false;
184 bool handle_remove_add = false;
185 bool handle_where = false;
186 bool handle_typeof = false;
187 bool lambda_arguments_parsing;
188 List<Location> escaped_identifiers;
189 int parsing_generic_less_than;
190 readonly bool doc_processing;
193 // Used mainly for parser optimizations. Some expressions for instance
194 // can appear only in block (including initializer, base initializer)
197 public int parsing_block;
198 internal bool query_parsing;
201 // When parsing type only, useful for ambiguous nullable types
203 public int parsing_type;
206 // Set when parsing generic declaration (type or method header)
208 public bool parsing_generic_declaration;
209 public bool parsing_generic_declaration_doc;
212 // The value indicates that we have not reach any declaration or
215 public int parsing_declaration;
217 public bool parsing_attribute_section;
219 public bool parsing_modifiers;
222 // The special characters to inject on streams to run the unit parser
223 // in the special expression mode. Using private characters from
224 // Plane Sixteen (U+100000 to U+10FFFD)
226 // This character is only tested just before the tokenizer is about to report
227 // an error; So on the regular operation mode, this addition will have no
228 // impact on the tokenizer's performance.
231 public const int EvalStatementParserCharacter = 0x100000;
232 public const int EvalCompilationUnitParserCharacter = 0x100001;
233 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
234 public const int DocumentationXref = 0x100003;
237 // XML documentation buffer. The save point is used to divide
238 // comments on types and comments on members.
240 StringBuilder xml_comment_buffer;
243 // See comment on XmlCommentState enumeration.
245 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
248 // Whether tokens have been seen on this line
250 bool tokens_seen = false;
253 // Set to true once the GENERATE_COMPLETION token has bee
254 // returned. This helps produce one GENERATE_COMPLETION,
255 // as many COMPLETE_COMPLETION as necessary to complete the
256 // AST tree and one final EOF.
261 // Whether a token has been seen on the file
262 // This is needed because `define' is not allowed to be used
263 // after a token has been seen.
270 static readonly KeywordEntry<int>[][] keywords;
271 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
272 static readonly HashSet<string> keyword_strings;
273 static readonly NumberStyles styles;
274 static readonly NumberFormatInfo csharp_format_info;
277 static readonly char[] pragma_warning = "warning".ToCharArray ();
278 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
279 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
280 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
282 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
284 public bool PropertyParsing {
285 get { return handle_get_set; }
286 set { handle_get_set = value; }
289 public bool EventParsing {
290 get { return handle_remove_add; }
291 set { handle_remove_add = value; }
294 public bool ConstraintsParsing {
295 get { return handle_where; }
296 set { handle_where = value; }
299 public bool TypeOfParsing {
300 get { return handle_typeof; }
301 set { handle_typeof = value; }
305 get { return tab_size; }
306 set { tab_size = value; }
309 public XmlCommentState doc_state {
310 get { return xml_doc_state; }
312 if (value == XmlCommentState.Allowed) {
313 check_incorrect_doc_comment ();
314 reset_doc_comment ();
316 xml_doc_state = value;
321 // This is used to trigger completion generation on the parser
322 public bool CompleteOnEOF;
324 void AddEscapedIdentifier (Location loc)
326 if (escaped_identifiers == null)
327 escaped_identifiers = new List<Location> ();
329 escaped_identifiers.Add (loc);
332 public bool IsEscapedIdentifier (ATypeNameExpression name)
334 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
338 // Values for the associated token returned
340 internal int putback_char; // Used by repl only
346 const int TAKING = 1;
347 const int ELSE_SEEN = 4;
348 const int PARENT_TAKING = 8;
349 const int REGION = 16;
352 // pre-processor if stack state:
356 const int max_id_size = 512;
357 const int max_number_size = 512;
360 readonly char [] id_builder = new char [max_id_size];
362 Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
364 char [] number_builder = new char [max_number_size];
367 char[] value_builder = new char[256];
369 static readonly char [] id_builder = new char [max_id_size];
371 static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
373 static char [] number_builder = new char [max_number_size];
374 static int number_pos;
376 static char[] value_builder = new char[256];
386 // This is used when the tokenizer needs to save
387 // the current position as it needs to do some parsing
388 // on its own to deamiguate a token in behalf of the
391 Stack<Position> position_stack = new Stack<Position> (2);
399 public int putback_char;
400 public int previous_col;
401 public Stack<int> ifstack;
402 public int parsing_generic_less_than;
403 public int current_token;
406 public Position (Tokenizer t)
408 position = t.reader.Position;
410 ref_line = t.ref_line;
413 putback_char = t.putback_char;
414 previous_col = t.previous_col;
415 if (t.ifstack != null && t.ifstack.Count != 0) {
416 // There is no simple way to clone Stack<T> all
417 // methods reverse the order
418 var clone = t.ifstack.ToArray ();
419 Array.Reverse (clone);
420 ifstack = new Stack<int> (clone);
422 parsing_generic_less_than = t.parsing_generic_less_than;
423 current_token = t.current_token;
428 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, CompilerContext ctx)
430 this.ref_name = file;
431 this.file_name = file;
437 xml_comment_buffer = new StringBuilder ();
438 doc_processing = ctx.Settings.DocumentationFile != null;
440 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
445 Mono.CSharp.Location.Push (file, file);
448 public void PushPosition ()
450 position_stack.Push (new Position (this));
453 public void PopPosition ()
455 Position p = position_stack.Pop ();
457 reader.Position = p.position;
458 ref_line = p.ref_line;
462 putback_char = p.putback_char;
463 previous_col = p.previous_col;
465 parsing_generic_less_than = p.parsing_generic_less_than;
466 current_token = p.current_token;
470 // Do not reset the position, ignore it.
471 public void DiscardPosition ()
473 position_stack.Pop ();
476 static void AddKeyword (string kw, int token)
478 keyword_strings.Add (kw);
480 AddKeyword (keywords, kw, token);
483 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
485 AddKeyword (keywords_preprocessor, kw, directive);
488 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
490 int length = kw.Length;
491 if (keywords[length] == null) {
492 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
495 int char_index = kw[0] - '_';
496 var kwe = keywords[length][char_index];
498 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
502 while (kwe.Next != null) {
506 kwe.Next = new KeywordEntry<T> (kw, token);
514 keyword_strings = new HashSet<string> ();
516 // 11 is the length of the longest keyword for now
517 keywords = new KeywordEntry<int>[11][];
519 AddKeyword ("__arglist", Token.ARGLIST);
520 AddKeyword ("__makeref", Token.MAKEREF);
521 AddKeyword ("__reftype", Token.REFTYPE);
522 AddKeyword ("__refvalue", Token.REFVALUE);
523 AddKeyword ("abstract", Token.ABSTRACT);
524 AddKeyword ("as", Token.AS);
525 AddKeyword ("add", Token.ADD);
526 AddKeyword ("base", Token.BASE);
527 AddKeyword ("bool", Token.BOOL);
528 AddKeyword ("break", Token.BREAK);
529 AddKeyword ("byte", Token.BYTE);
530 AddKeyword ("case", Token.CASE);
531 AddKeyword ("catch", Token.CATCH);
532 AddKeyword ("char", Token.CHAR);
533 AddKeyword ("checked", Token.CHECKED);
534 AddKeyword ("class", Token.CLASS);
535 AddKeyword ("const", Token.CONST);
536 AddKeyword ("continue", Token.CONTINUE);
537 AddKeyword ("decimal", Token.DECIMAL);
538 AddKeyword ("default", Token.DEFAULT);
539 AddKeyword ("delegate", Token.DELEGATE);
540 AddKeyword ("do", Token.DO);
541 AddKeyword ("double", Token.DOUBLE);
542 AddKeyword ("else", Token.ELSE);
543 AddKeyword ("enum", Token.ENUM);
544 AddKeyword ("event", Token.EVENT);
545 AddKeyword ("explicit", Token.EXPLICIT);
546 AddKeyword ("extern", Token.EXTERN);
547 AddKeyword ("false", Token.FALSE);
548 AddKeyword ("finally", Token.FINALLY);
549 AddKeyword ("fixed", Token.FIXED);
550 AddKeyword ("float", Token.FLOAT);
551 AddKeyword ("for", Token.FOR);
552 AddKeyword ("foreach", Token.FOREACH);
553 AddKeyword ("goto", Token.GOTO);
554 AddKeyword ("get", Token.GET);
555 AddKeyword ("if", Token.IF);
556 AddKeyword ("implicit", Token.IMPLICIT);
557 AddKeyword ("in", Token.IN);
558 AddKeyword ("int", Token.INT);
559 AddKeyword ("interface", Token.INTERFACE);
560 AddKeyword ("internal", Token.INTERNAL);
561 AddKeyword ("is", Token.IS);
562 AddKeyword ("lock", Token.LOCK);
563 AddKeyword ("long", Token.LONG);
564 AddKeyword ("namespace", Token.NAMESPACE);
565 AddKeyword ("new", Token.NEW);
566 AddKeyword ("null", Token.NULL);
567 AddKeyword ("object", Token.OBJECT);
568 AddKeyword ("operator", Token.OPERATOR);
569 AddKeyword ("out", Token.OUT);
570 AddKeyword ("override", Token.OVERRIDE);
571 AddKeyword ("params", Token.PARAMS);
572 AddKeyword ("private", Token.PRIVATE);
573 AddKeyword ("protected", Token.PROTECTED);
574 AddKeyword ("public", Token.PUBLIC);
575 AddKeyword ("readonly", Token.READONLY);
576 AddKeyword ("ref", Token.REF);
577 AddKeyword ("remove", Token.REMOVE);
578 AddKeyword ("return", Token.RETURN);
579 AddKeyword ("sbyte", Token.SBYTE);
580 AddKeyword ("sealed", Token.SEALED);
581 AddKeyword ("set", Token.SET);
582 AddKeyword ("short", Token.SHORT);
583 AddKeyword ("sizeof", Token.SIZEOF);
584 AddKeyword ("stackalloc", Token.STACKALLOC);
585 AddKeyword ("static", Token.STATIC);
586 AddKeyword ("string", Token.STRING);
587 AddKeyword ("struct", Token.STRUCT);
588 AddKeyword ("switch", Token.SWITCH);
589 AddKeyword ("this", Token.THIS);
590 AddKeyword ("throw", Token.THROW);
591 AddKeyword ("true", Token.TRUE);
592 AddKeyword ("try", Token.TRY);
593 AddKeyword ("typeof", Token.TYPEOF);
594 AddKeyword ("uint", Token.UINT);
595 AddKeyword ("ulong", Token.ULONG);
596 AddKeyword ("unchecked", Token.UNCHECKED);
597 AddKeyword ("unsafe", Token.UNSAFE);
598 AddKeyword ("ushort", Token.USHORT);
599 AddKeyword ("using", Token.USING);
600 AddKeyword ("virtual", Token.VIRTUAL);
601 AddKeyword ("void", Token.VOID);
602 AddKeyword ("volatile", Token.VOLATILE);
603 AddKeyword ("while", Token.WHILE);
604 AddKeyword ("partial", Token.PARTIAL);
605 AddKeyword ("where", Token.WHERE);
608 AddKeyword ("from", Token.FROM);
609 AddKeyword ("join", Token.JOIN);
610 AddKeyword ("on", Token.ON);
611 AddKeyword ("equals", Token.EQUALS);
612 AddKeyword ("select", Token.SELECT);
613 AddKeyword ("group", Token.GROUP);
614 AddKeyword ("by", Token.BY);
615 AddKeyword ("let", Token.LET);
616 AddKeyword ("orderby", Token.ORDERBY);
617 AddKeyword ("ascending", Token.ASCENDING);
618 AddKeyword ("descending", Token.DESCENDING);
619 AddKeyword ("into", Token.INTO);
621 // Contextual async keywords
622 AddKeyword ("async", Token.ASYNC);
623 AddKeyword ("await", Token.AWAIT);
625 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
627 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
628 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
629 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
630 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
631 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
632 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
633 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
634 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
635 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
636 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
637 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
638 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
640 csharp_format_info = NumberFormatInfo.InvariantInfo;
641 styles = NumberStyles.Float;
644 int GetKeyword (char[] id, int id_len)
647 // Keywords are stored in an array of arrays grouped by their
648 // length and then by the first character
650 if (id_len >= keywords.Length || keywords [id_len] == null)
653 int first_index = id [0] - '_';
654 if (first_index > 'z' - '_')
657 var kwe = keywords [id_len] [first_index];
664 for (int i = 1; i < id_len; ++i) {
665 if (id [i] != kwe.Value [i]) {
671 } while (res == 0 && kwe != null);
685 if (!handle_remove_add)
689 if (parsing_declaration == 0)
690 res = Token.EXTERN_ALIAS;
693 if (peek_token () == Token.COLON) {
695 res = Token.DEFAULT_COLON;
699 if (!handle_where && !query_parsing)
704 // A query expression is any expression that starts with `from identifier'
705 // followed by any token except ; , =
707 if (!query_parsing) {
708 if (lambda_arguments_parsing) {
714 // HACK: to disable generics micro-parser, because PushPosition does not
715 // store identifiers array
716 parsing_generic_less_than = 1;
718 case Token.IDENTIFIER:
730 next_token = xtoken ();
731 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
734 res = Token.FROM_FIRST;
735 query_parsing = true;
736 if (context.Settings.Version <= LanguageVersion.ISO_2)
737 Report.FeatureIsNotAvailable (context, Location, "query expressions");
740 Expression.Error_VoidInvalidInTheContext (Location, Report);
744 // HACK: A token is not a keyword so we need to restore identifiers buffer
745 // which has been overwritten before we grabbed the identifier
746 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
760 case Token.ASCENDING:
761 case Token.DESCENDING:
768 case Token.NAMESPACE:
769 // TODO: some explanation needed
770 check_incorrect_doc_comment ();
774 if (parsing_block > 0) {
779 // Save current position and parse next token.
782 next_token = token ();
783 bool ok = (next_token == Token.CLASS) ||
784 (next_token == Token.STRUCT) ||
785 (next_token == Token.INTERFACE) ||
786 (next_token == Token.VOID);
791 if (next_token == Token.VOID) {
792 if (context.Settings.Version <= LanguageVersion.ISO_2)
793 Report.FeatureIsNotAvailable (context, Location, "partial methods");
794 } else if (context.Settings.Version == LanguageVersion.ISO_1)
795 Report.FeatureIsNotAvailable (context, Location, "partial types");
800 if (next_token < Token.LAST_KEYWORD) {
801 Report.Error (267, Location,
802 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
810 if (parsing_modifiers) {
812 // Skip attributes section or constructor called async
814 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
819 } else if (parsing_block > 0) {
820 switch (peek_token ()) {
822 case Token.OPEN_PARENS_LAMBDA:
825 case Token.IDENTIFIER:
828 if (xtoken () != Token.ARROW)
841 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
842 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
848 if (parsing_block == 0)
858 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
861 // Keywords are stored in an array of arrays grouped by their
862 // length and then by the first character
864 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
865 return PreprocessorDirective.Invalid;
867 int first_index = id[0] - '_';
868 if (first_index > 'z' - '_')
869 return PreprocessorDirective.Invalid;
871 var kwe = keywords_preprocessor[id_len][first_index];
873 return PreprocessorDirective.Invalid;
875 PreprocessorDirective res = PreprocessorDirective.Invalid;
878 for (int i = 1; i < id_len; ++i) {
879 if (id[i] != kwe.Value[i]) {
885 } while (res == PreprocessorDirective.Invalid && kwe != null);
890 public Location Location {
892 return new Location (ref_line, hidden ? -1 : col);
896 static bool is_identifier_start_character (int c)
898 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
901 static bool is_identifier_part_character (char c)
903 if (c >= 'a' && c <= 'z')
906 if (c >= 'A' && c <= 'Z')
909 if (c == '_' || (c >= '0' && c <= '9'))
915 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
918 public static bool IsKeyword (string s)
920 return keyword_strings.Contains (s);
924 // Open parens micro parser. Detects both lambda and cast ambiguity.
926 int TokenizeOpenParens ()
931 int bracket_level = 0;
932 bool is_type = false;
933 bool can_be_type = false;
936 ptoken = current_token;
939 switch (current_token) {
940 case Token.CLOSE_PARENS:
944 // Expression inside parens is lambda, (int i) =>
946 if (current_token == Token.ARROW)
947 return Token.OPEN_PARENS_LAMBDA;
950 // Expression inside parens is single type, (int[])
953 return Token.OPEN_PARENS_CAST;
956 // Expression is possible cast, look at next token, (T)null
959 switch (current_token) {
960 case Token.OPEN_PARENS:
963 case Token.IDENTIFIER:
977 case Token.UNCHECKED:
982 // These can be part of a member access
996 return Token.OPEN_PARENS_CAST;
999 return Token.OPEN_PARENS;
1002 case Token.DOUBLE_COLON:
1003 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1008 case Token.IDENTIFIER:
1011 if (bracket_level == 0) {
1017 case Token.OP_GENERICS_LT:
1019 case Token.DOUBLE_COLON:
1021 if (bracket_level == 0)
1025 can_be_type = is_type = false;
1045 if (bracket_level == 0)
1050 if (bracket_level == 0) {
1051 bracket_level = 100;
1052 can_be_type = is_type = false;
1056 case Token.OP_GENERICS_LT:
1057 case Token.OPEN_BRACKET:
1058 if (bracket_level++ == 0)
1062 case Token.OP_GENERICS_GT:
1063 case Token.CLOSE_BRACKET:
1067 case Token.INTERR_NULLABLE:
1069 if (bracket_level == 0)
1075 can_be_type = is_type = false;
1079 return Token.OPEN_PARENS;
1084 public static bool IsValidIdentifier (string s)
1086 if (s == null || s.Length == 0)
1089 if (!is_identifier_start_character (s [0]))
1092 for (int i = 1; i < s.Length; i ++)
1093 if (! is_identifier_part_character (s [i]))
1099 bool parse_less_than ()
1102 int the_token = token ();
1103 if (the_token == Token.OPEN_BRACKET) {
1105 the_token = token ();
1106 } while (the_token != Token.CLOSE_BRACKET);
1107 the_token = token ();
1108 } else if (the_token == Token.IN || the_token == Token.OUT) {
1109 the_token = token ();
1111 switch (the_token) {
1112 case Token.IDENTIFIER:
1130 case Token.OP_GENERICS_GT:
1139 the_token = token ();
1141 if (the_token == Token.OP_GENERICS_GT)
1143 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1145 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1147 else if (the_token == Token.OP_GENERICS_LT) {
1148 if (!parse_less_than ())
1151 } else if (the_token == Token.OPEN_BRACKET) {
1153 the_token = token ();
1154 if (the_token == Token.CLOSE_BRACKET)
1156 else if (the_token == Token.COMMA)
1157 goto rank_specifiers;
1164 bool parse_generic_dimension (out int dimension)
1169 int the_token = token ();
1170 if (the_token == Token.OP_GENERICS_GT)
1172 else if (the_token == Token.COMMA) {
1180 public int peek_token ()
1185 the_token = token ();
1192 // Tonizes `?' using custom disambiguous rules to return one
1193 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1195 // Tricky expression look like:
1197 // Foo ? a = x ? b : c;
1199 int TokenizePossibleNullableType ()
1201 if (parsing_block == 0 || parsing_type > 0)
1202 return Token.INTERR_NULLABLE;
1204 int d = peek_char ();
1207 return Token.OP_COALESCING;
1210 switch (current_token) {
1211 case Token.CLOSE_PARENS:
1216 return Token.INTERR;
1220 if (d == ',' || d == ';' || d == '>')
1221 return Token.INTERR_NULLABLE;
1222 if (d == '*' || (d >= '0' && d <= '9'))
1223 return Token.INTERR;
1227 current_token = Token.NONE;
1229 switch (xtoken ()) {
1236 next_token = Token.INTERR;
1239 case Token.SEMICOLON:
1241 case Token.CLOSE_PARENS:
1242 case Token.OPEN_BRACKET:
1243 case Token.OP_GENERICS_GT:
1245 next_token = Token.INTERR_NULLABLE;
1253 if (next_token == -1) {
1254 switch (xtoken ()) {
1256 case Token.SEMICOLON:
1257 case Token.OPEN_BRACE:
1258 case Token.CLOSE_PARENS:
1260 next_token = Token.INTERR_NULLABLE;
1264 next_token = Token.INTERR;
1272 // All shorcuts failed, do it hard way
1274 while ((ntoken = xtoken ()) != Token.EOF) {
1275 if (ntoken == Token.SEMICOLON)
1278 if (ntoken == Token.COLON) {
1279 if (++colons == interrs)
1284 if (ntoken == Token.INTERR) {
1290 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1299 bool decimal_digits (int c)
1302 bool seen_digits = false;
1305 if (number_pos == max_number_size)
1306 Error_NumericConstantTooLong ();
1307 number_builder [number_pos++] = (char) c;
1311 // We use peek_char2, because decimal_digits needs to do a
1312 // 2-character look-ahead (5.ToString for example).
1314 while ((d = peek_char2 ()) != -1){
1315 if (d >= '0' && d <= '9'){
1316 if (number_pos == max_number_size)
1317 Error_NumericConstantTooLong ();
1318 number_builder [number_pos++] = (char) d;
1328 static bool is_hex (int e)
1330 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1333 static TypeCode real_type_suffix (int c)
1337 return TypeCode.Single;
1339 return TypeCode.Double;
1341 return TypeCode.Decimal;
1343 return TypeCode.Empty;
1347 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1349 bool is_unsigned = false;
1350 bool is_long = false;
1353 bool scanning = true;
1366 // if we have not seen anything in between
1367 // report this error
1369 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1389 if (is_long && is_unsigned){
1390 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1394 // uint if possible, or ulong else.
1396 if ((ul & 0xffffffff00000000) == 0)
1397 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1399 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1400 } else if (is_long){
1401 // long if possible, ulong otherwise
1402 if ((ul & 0x8000000000000000) != 0)
1403 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1405 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1407 // int, uint, long or ulong in that order
1408 if ((ul & 0xffffffff00000000) == 0){
1409 uint ui = (uint) ul;
1411 if ((ui & 0x80000000) != 0)
1412 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1414 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1416 if ((ul & 0x8000000000000000) != 0)
1417 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1419 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1425 // given `c' as the next char in the input decide whether
1426 // we need to convert to a special type, and then choose
1427 // the best representation for the integer
1429 ILiteralConstant adjust_int (int c, Location loc)
1432 if (number_pos > 9){
1433 ulong ul = (uint) (number_builder [0] - '0');
1435 for (int i = 1; i < number_pos; i++){
1436 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1439 return integer_type_suffix (ul, c, loc);
1441 uint ui = (uint) (number_builder [0] - '0');
1443 for (int i = 1; i < number_pos; i++){
1444 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1447 return integer_type_suffix (ui, c, loc);
1449 } catch (OverflowException) {
1450 Error_NumericConstantTooLong ();
1451 return new IntLiteral (context.BuiltinTypes, 0, loc);
1453 catch (FormatException) {
1454 Report.Error (1013, Location, "Invalid number");
1455 return new IntLiteral (context.BuiltinTypes, 0, loc);
1459 ILiteralConstant adjust_real (TypeCode t, Location loc)
1461 string s = new string (number_builder, 0, number_pos);
1462 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1465 case TypeCode.Decimal:
1467 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1468 } catch (OverflowException) {
1469 Report.Error (594, Location, error_details, "decimal");
1470 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1472 case TypeCode.Single:
1474 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1475 } catch (OverflowException) {
1476 Report.Error (594, Location, error_details, "float");
1477 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1481 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1482 } catch (OverflowException) {
1483 Report.Error (594, loc, error_details, "double");
1484 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1489 ILiteralConstant handle_hex (Location loc)
1495 while ((d = peek_char ()) != -1){
1497 number_builder [number_pos++] = (char) d;
1503 string s = new String (number_builder, 0, number_pos);
1506 if (number_pos <= 8)
1507 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1509 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1511 return integer_type_suffix (ul, peek_char (), loc);
1512 } catch (OverflowException){
1513 Error_NumericConstantTooLong ();
1514 return new IntLiteral (context.BuiltinTypes, 0, loc);
1516 catch (FormatException) {
1517 Report.Error (1013, Location, "Invalid number");
1518 return new IntLiteral (context.BuiltinTypes, 0, loc);
1523 // Invoked if we know we have .digits or digits
1525 int is_number (int c)
1527 ILiteralConstant res;
1530 int read_start = reader.Position - 1;
1533 // Caller did peek_char
1541 if (c >= '0' && c <= '9'){
1543 int peek = peek_char ();
1545 if (peek == 'x' || peek == 'X') {
1546 val = res = handle_hex (loc);
1548 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1551 return Token.LITERAL;
1559 // We need to handle the case of
1560 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1562 bool is_real = false;
1564 if (decimal_digits ('.')){
1570 val = res = adjust_int (-1, loc);
1573 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1575 return Token.LITERAL;
1579 if (c == 'e' || c == 'E'){
1581 if (number_pos == max_number_size)
1582 Error_NumericConstantTooLong ();
1583 number_builder [number_pos++] = (char) c;
1587 if (number_pos == max_number_size)
1588 Error_NumericConstantTooLong ();
1589 number_builder [number_pos++] = '+';
1591 } else if (c == '-') {
1592 if (number_pos == max_number_size)
1593 Error_NumericConstantTooLong ();
1594 number_builder [number_pos++] = '-';
1597 if (number_pos == max_number_size)
1598 Error_NumericConstantTooLong ();
1599 number_builder [number_pos++] = '+';
1606 var type = real_type_suffix (c);
1607 if (type == TypeCode.Empty && !is_real) {
1609 res = adjust_int (c, loc);
1613 if (type == TypeCode.Empty) {
1617 res = adjust_real (type, loc);
1623 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1624 if (chars[chars.Length - 1] == '\r')
1625 Array.Resize (ref chars, chars.Length - 1);
1626 res.ParsedValue = chars;
1629 return Token.LITERAL;
1633 // Accepts exactly count (4 or 8) hex, no more no less
1635 int getHex (int count, out int surrogate, out bool error)
1640 int top = count != -1 ? count : 4;
1645 for (i = 0; i < top; i++){
1648 if (c >= '0' && c <= '9')
1649 c = (int) c - (int) '0';
1650 else if (c >= 'A' && c <= 'F')
1651 c = (int) c - (int) 'A' + 10;
1652 else if (c >= 'a' && c <= 'f')
1653 c = (int) c - (int) 'a' + 10;
1659 total = (total * 16) + c;
1661 int p = peek_char ();
1664 if (!is_hex ((char)p))
1670 if (total > 0x0010FFFF) {
1675 if (total >= 0x00010000) {
1676 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1677 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1684 int escape (int c, out int surrogate)
1720 v = getHex (-1, out surrogate, out error);
1726 return EscapeUnicode (d, out surrogate);
1729 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1738 int EscapeUnicode (int ch, out int surrogate)
1742 ch = getHex (8, out surrogate, out error);
1744 ch = getHex (4, out surrogate, out error);
1748 Report.Error (1009, Location, "Unrecognized escape sequence");
1756 if (putback_char != -1) {
1764 if (peek_char () == '\n') {
1770 } else if (x == '\n') {
1778 void advance_line ()
1788 if (putback_char == -1)
1789 putback_char = reader.Read ();
1790 return putback_char;
1795 if (putback_char != -1)
1796 return putback_char;
1797 return reader.Peek ();
1800 public void putback (int c)
1802 if (putback_char != -1){
1803 Console.WriteLine ("Col: " + col);
1804 Console.WriteLine ("Row: " + line);
1805 Console.WriteLine ("Name: " + ref_name.Name);
1806 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1807 throw new Exception ("This should not happen putback on putback");
1809 if (c == '\n' || col == 0) {
1810 // It won't happen though.
1820 public bool advance ()
1822 return peek_char () != -1 || CompleteOnEOF;
1825 public Object Value {
1831 public Object value ()
1838 current_token = xtoken ();
1839 return current_token;
1842 int TokenizePreprocessorIdentifier (out int c)
1844 // skip over white space
1847 } while (c == ' ' || c == '\t');
1851 while (c != -1 && c >= 'a' && c <= 'z') {
1852 id_builder[pos++] = (char) c;
1855 int peek = peek_char ();
1856 if (peek == 'U' || peek == 'u') {
1858 c = EscapeUnicode (c, out surrogate);
1859 if (surrogate != 0) {
1860 if (is_identifier_part_character ((char) c)) {
1861 id_builder[pos++] = (char) c;
1872 PreprocessorDirective get_cmd_arg (out string arg)
1876 tokens_seen = false;
1879 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1881 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1884 // skip over white space
1885 while (c == ' ' || c == '\t')
1888 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1891 while (c != -1 && c != '\n') {
1892 if (c == '\\' && has_identifier_argument >= 0) {
1893 if (has_identifier_argument != 0) {
1894 has_identifier_argument = 1;
1896 int peek = peek_char ();
1897 if (peek == 'U' || peek == 'u') {
1899 c = EscapeUnicode (c, out surrogate);
1900 if (surrogate != 0) {
1901 if (is_identifier_part_character ((char) c)) {
1902 if (pos == value_builder.Length)
1903 Array.Resize (ref value_builder, pos * 2);
1905 value_builder[pos++] = (char) c;
1911 has_identifier_argument = -1;
1913 } else if (c == '/' && peek_char () == '/') {
1915 // Eat single-line comments
1920 } while (c != -1 && c != '\n');
1925 if (pos == value_builder.Length)
1926 Array.Resize (ref value_builder, pos * 2);
1928 value_builder[pos++] = (char) c;
1933 if (pos > max_id_size)
1934 arg = new string (value_builder, 0, pos);
1936 arg = InternIdentifier (value_builder, pos);
1938 // Eat any trailing whitespaces
1939 arg = arg.Trim (simple_whitespaces);
1946 // Handles the #line directive
1948 bool PreProcessLine (string arg)
1950 if (arg.Length == 0)
1953 if (arg == "default"){
1955 ref_name = file_name;
1957 Location.Push (file_name, ref_name);
1959 } else if (arg == "hidden"){
1967 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1968 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1971 char [] quotes = { '\"' };
1973 string name = arg.Substring (pos).Trim (quotes);
1974 ref_name = context.LookupFile (file_name, name);
1975 file_name.AddIncludeFile (ref_name);
1977 Location.Push (file_name, ref_name);
1979 ref_line = System.Int32.Parse (arg);
1990 // Handles #define and #undef
1992 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1994 if (ident.Length == 0 || ident == "true" || ident == "false"){
1995 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1999 if (ident.IndexOfAny (simple_whitespaces) != -1){
2000 Error_EndLineExpected ();
2004 if (!is_identifier_start_character (ident [0]))
2005 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2007 foreach (char c in ident.Substring (1)){
2008 if (!is_identifier_part_character (c)){
2009 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2014 if (!caller_is_taking)
2021 if (context.Settings.IsConditionalSymbolDefined (ident))
2024 file_name.AddDefine (ident);
2029 file_name.AddUndefine (ident);
2033 byte read_hex (out bool error)
2036 int c = get_char ();
2038 if ((c >= '0') && (c <= '9'))
2039 total = (int) c - (int) '0';
2040 else if ((c >= 'A') && (c <= 'F'))
2041 total = (int) c - (int) 'A' + 10;
2042 else if ((c >= 'a') && (c <= 'f'))
2043 total = (int) c - (int) 'a' + 10;
2052 if ((c >= '0') && (c <= '9'))
2053 total += (int) c - (int) '0';
2054 else if ((c >= 'A') && (c <= 'F'))
2055 total += (int) c - (int) 'A' + 10;
2056 else if ((c >= 'a') && (c <= 'f'))
2057 total += (int) c - (int) 'a' + 10;
2064 return (byte) total;
2068 // Parses #pragma checksum
2070 bool ParsePragmaChecksum ()
2073 // The syntax is ` "foo.txt" "{guid}" "hash"'
2075 int c = get_char ();
2080 var string_builder = new StringBuilder ();
2081 while (c != -1 && c != '\n') {
2088 string_builder.Append ((char) c);
2091 if (string_builder.Length == 0) {
2092 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2095 // TODO: Any white-spaces count
2099 SourceFile file = context.LookupFile (file_name, string_builder.ToString ());
2101 if (get_char () != '"' || get_char () != '{')
2105 byte[] guid_bytes = new byte [16];
2108 for (; i < 4; i++) {
2109 guid_bytes [i] = read_hex (out error);
2114 if (get_char () != '-')
2117 for (; i < 10; i++) {
2118 guid_bytes [i] = read_hex (out error);
2122 guid_bytes [i++] = read_hex (out error);
2126 if (get_char () != '-')
2130 for (; i < 16; i++) {
2131 guid_bytes [i] = read_hex (out error);
2136 if (get_char () != '}' || get_char () != '"')
2139 // TODO: Any white-spaces count
2144 if (get_char () != '"')
2147 // Any length of checksum
2148 List<byte> checksum_bytes = new List<byte> (16);
2151 while (c != '"' && c != -1) {
2152 checksum_bytes.Add (read_hex (out error));
2160 ReadSingleLineComment ();
2161 } else if (get_char () != '"') {
2165 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2166 ref_name.AutoGenerated = true;
2170 bool IsTokenIdentifierEqual (char[] identifier)
2172 for (int i = 0; i < identifier.Length; ++i) {
2173 if (identifier[i] != id_builder[i])
2180 int TokenizePragmaNumber (ref int c)
2186 if (c >= '0' && c <= '9') {
2188 uint ui = (uint) (number_builder[0] - '0');
2191 for (int i = 1; i < number_pos; i++) {
2192 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2196 } catch (OverflowException) {
2197 Error_NumericConstantTooLong ();
2204 // skip over white space
2205 while (c == ' ' || c == '\t')
2212 // skip over white space
2213 while (c == ' ' || c == '\t')
2218 ReadSingleLineComment ();
2220 Report.Warning (1692, 1, Location, "Invalid number");
2222 // Read everything till the end of the line or file
2225 } while (c != -1 && c != '\n');
2232 void ReadSingleLineComment ()
2234 if (peek_char () != '/')
2235 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2237 // Read everything till the end of the line or file
2241 } while (c != -1 && c != '\n');
2245 /// Handles #pragma directive
2247 void ParsePragmaDirective (string arg)
2250 int length = TokenizePreprocessorIdentifier (out c);
2251 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2252 length = TokenizePreprocessorIdentifier (out c);
2255 // #pragma warning disable
2256 // #pragma warning restore
2258 if (length == pragma_warning_disable.Length) {
2259 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2260 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2261 // skip over white space
2262 while (c == ' ' || c == '\t')
2267 if (c == '\n' || c == '/') {
2269 ReadSingleLineComment ();
2272 // Disable/Restore all warnings
2275 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2277 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2281 // Disable/Restore a warning or group of warnings
2285 code = TokenizePragmaNumber (ref c);
2288 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2290 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2293 } while (code >= 0 && c != '\n' && c != -1);
2300 Report.Warning (1634, 1, Location, "Expected disable or restore");
2307 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2308 if (c != ' ' || !ParsePragmaChecksum ()) {
2309 Report.Warning (1695, 1, Location,
2310 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2316 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2319 bool eval_val (string s)
2326 return file_name.IsConditionalDefined (context, s);
2329 bool pp_primary (ref string s)
2338 s = s.Substring (1);
2339 bool val = pp_expr (ref s, false);
2340 if (s.Length > 0 && s [0] == ')'){
2341 s = s.Substring (1);
2344 Error_InvalidDirective ();
2348 if (is_identifier_start_character (c)){
2354 if (is_identifier_part_character (c)){
2358 bool v = eval_val (s.Substring (0, j));
2359 s = s.Substring (j);
2362 bool vv = eval_val (s);
2367 Error_InvalidDirective ();
2371 bool pp_unary (ref string s)
2378 if (len > 1 && s [1] == '='){
2379 Error_InvalidDirective ();
2382 s = s.Substring (1);
2383 return ! pp_primary (ref s);
2385 return pp_primary (ref s);
2387 Error_InvalidDirective ();
2392 bool pp_eq (ref string s)
2394 bool va = pp_unary (ref s);
2400 if (len > 2 && s [1] == '='){
2401 s = s.Substring (2);
2402 return va == pp_unary (ref s);
2404 Error_InvalidDirective ();
2407 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2408 s = s.Substring (2);
2410 return va != pp_unary (ref s);
2419 bool pp_and (ref string s)
2421 bool va = pp_eq (ref s);
2427 if (len > 2 && s [1] == '&'){
2428 s = s.Substring (2);
2429 return (va & pp_and (ref s));
2431 Error_InvalidDirective ();
2440 // Evaluates an expression for `#if' or `#elif'
2442 bool pp_expr (ref string s, bool isTerm)
2444 bool va = pp_and (ref s);
2451 if (len > 2 && s [1] == '|'){
2452 s = s.Substring (2);
2453 return va | pp_expr (ref s, isTerm);
2455 Error_InvalidDirective ();
2460 Error_EndLineExpected ();
2468 bool eval (string s)
2470 bool v = pp_expr (ref s, true);
2479 void Error_NumericConstantTooLong ()
2481 Report.Error (1021, Location, "Integral constant is too large");
2484 void Error_InvalidDirective ()
2486 Report.Error (1517, Location, "Invalid preprocessor directive");
2489 void Error_UnexpectedDirective (string extra)
2493 "Unexpected processor directive ({0})", extra);
2496 void Error_TokensSeen ()
2498 Report.Error (1032, Location,
2499 "Cannot define or undefine preprocessor symbols after first token in file");
2502 void Eror_WrongPreprocessorLocation ()
2504 Report.Error (1040, Location,
2505 "Preprocessor directives must appear as the first non-whitespace character on a line");
2508 void Error_EndLineExpected ()
2510 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2514 // Raises a warning when tokenizer found documentation comment
2515 // on unexpected place
2517 void WarningMisplacedComment (Location loc)
2519 if (doc_state != XmlCommentState.Error) {
2520 doc_state = XmlCommentState.Error;
2521 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2526 // if true, then the code continues processing the code
2527 // if false, the code stays in a loop until another directive is
2529 // When caller_is_taking is false we ignore all directives except the ones
2530 // which can help us to identify where the #if block ends
2531 bool ParsePreprocessingDirective (bool caller_is_taking)
2534 bool region_directive = false;
2536 var directive = get_cmd_arg (out arg);
2539 // The first group of pre-processing instructions is always processed
2541 switch (directive) {
2542 case PreprocessorDirective.Region:
2543 region_directive = true;
2545 goto case PreprocessorDirective.If;
2547 case PreprocessorDirective.Endregion:
2548 if (ifstack == null || ifstack.Count == 0){
2549 Error_UnexpectedDirective ("no #region for this #endregion");
2552 int pop = ifstack.Pop ();
2554 if ((pop & REGION) == 0)
2555 Report.Error (1027, Location, "Expected `#endif' directive");
2557 return caller_is_taking;
2559 case PreprocessorDirective.If:
2560 if (ifstack == null)
2561 ifstack = new Stack<int> (2);
2563 int flags = region_directive ? REGION : 0;
2564 if (ifstack.Count == 0){
2565 flags |= PARENT_TAKING;
2567 int state = ifstack.Peek ();
2568 if ((state & TAKING) != 0) {
2569 flags |= PARENT_TAKING;
2573 if (eval (arg) && caller_is_taking) {
2574 ifstack.Push (flags | TAKING);
2577 ifstack.Push (flags);
2580 case PreprocessorDirective.Endif:
2581 if (ifstack == null || ifstack.Count == 0){
2582 Error_UnexpectedDirective ("no #if for this #endif");
2585 pop = ifstack.Pop ();
2587 if ((pop & REGION) != 0)
2588 Report.Error (1038, Location, "#endregion directive expected");
2590 if (arg.Length != 0) {
2591 Error_EndLineExpected ();
2594 if (ifstack.Count == 0)
2597 int state = ifstack.Peek ();
2598 return (state & TAKING) != 0;
2601 case PreprocessorDirective.Elif:
2602 if (ifstack == null || ifstack.Count == 0){
2603 Error_UnexpectedDirective ("no #if for this #elif");
2606 int state = ifstack.Pop ();
2608 if ((state & REGION) != 0) {
2609 Report.Error (1038, Location, "#endregion directive expected");
2613 if ((state & ELSE_SEEN) != 0){
2614 Error_UnexpectedDirective ("#elif not valid after #else");
2618 if ((state & TAKING) != 0) {
2623 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2624 ifstack.Push (state | TAKING);
2628 ifstack.Push (state);
2632 case PreprocessorDirective.Else:
2633 if (ifstack == null || ifstack.Count == 0){
2634 Error_UnexpectedDirective ("no #if for this #else");
2637 int state = ifstack.Peek ();
2639 if ((state & REGION) != 0) {
2640 Report.Error (1038, Location, "#endregion directive expected");
2644 if ((state & ELSE_SEEN) != 0){
2645 Error_UnexpectedDirective ("#else within #else");
2651 if (arg.Length != 0) {
2652 Error_EndLineExpected ();
2657 if ((state & PARENT_TAKING) != 0) {
2658 ret = (state & TAKING) == 0;
2666 ifstack.Push (state | ELSE_SEEN);
2670 case PreprocessorDirective.Define:
2671 if (any_token_seen){
2672 Error_TokensSeen ();
2673 return caller_is_taking;
2675 PreProcessDefinition (true, arg, caller_is_taking);
2676 return caller_is_taking;
2678 case PreprocessorDirective.Undef:
2679 if (any_token_seen){
2680 Error_TokensSeen ();
2681 return caller_is_taking;
2683 PreProcessDefinition (false, arg, caller_is_taking);
2684 return caller_is_taking;
2686 case PreprocessorDirective.Invalid:
2687 Report.Error (1024, Location, "Wrong preprocessor directive");
2692 // These are only processed if we are in a `taking' block
2694 if (!caller_is_taking)
2698 case PreprocessorDirective.Error:
2699 Report.Error (1029, Location, "#error: '{0}'", arg);
2702 case PreprocessorDirective.Warning:
2703 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2706 case PreprocessorDirective.Pragma:
2707 if (context.Settings.Version == LanguageVersion.ISO_1) {
2708 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2711 ParsePragmaDirective (arg);
2714 case PreprocessorDirective.Line:
2715 if (!PreProcessLine (arg))
2718 "The line number specified for #line directive is missing or invalid");
2719 return caller_is_taking;
2722 throw new NotImplementedException (directive.ToString ());
2725 private int consume_string (bool quoted)
2729 Location start_location = Location;
2731 start_location = start_location - 1;
2734 int reader_pos = reader.Position;
2740 if (quoted && peek_char () == '"') {
2741 if (pos == value_builder.Length)
2742 Array.Resize (ref value_builder, pos * 2);
2744 value_builder[pos++] = (char) c;
2753 s = InternIdentifier (value_builder, pos);
2755 s = new string (value_builder, 0, pos);
2757 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2760 res.ParsedValue = quoted ?
2761 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2762 reader.ReadChars (reader_pos - 1, reader.Position);
2765 return Token.LITERAL;
2770 Report.Error (1010, Location, "Newline in constant");
2771 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2772 return Token.LITERAL;
2774 } else if (c == '\\' && !quoted) {
2776 c = escape (c, out surrogate);
2779 if (surrogate != 0) {
2780 if (pos == value_builder.Length)
2781 Array.Resize (ref value_builder, pos * 2);
2783 value_builder[pos++] = (char) c;
2786 } else if (c == -1) {
2787 Report.Error (1039, Location, "Unterminated string literal");
2791 if (pos == value_builder.Length)
2792 Array.Resize (ref value_builder, pos * 2);
2794 value_builder[pos++] = (char) c;
2798 private int consume_identifier (int s)
2800 int res = consume_identifier (s, false);
2802 if (doc_state == XmlCommentState.Allowed)
2803 doc_state = XmlCommentState.NotAllowed;
2808 int consume_identifier (int c, bool quoted)
2811 // This method is very performance sensitive. It accounts
2812 // for approximately 25% of all parser time
2822 c = escape (c, out surrogate);
2823 if (surrogate != 0) {
2824 id_builder [pos++] = (char) c;
2829 id_builder [pos++] = (char) c;
2835 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2836 id_builder [pos++] = (char) c;
2843 c = escape (c, out surrogate);
2844 if (is_identifier_part_character ((char) c))
2845 id_builder[pos++] = (char) c;
2847 if (surrogate != 0) {
2853 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2854 id_builder [pos++] = (char) c;
2861 } catch (IndexOutOfRangeException) {
2862 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2870 // Optimization: avoids doing the keyword lookup
2871 // on uppercase letters
2873 if (id_builder [0] >= '_' && !quoted) {
2874 int keyword = GetKeyword (id_builder, pos);
2875 if (keyword != -1) {
2876 val = LocatedToken.Create (keyword == Token.AWAIT ? "await" : null, ref_line, column);
2881 string s = InternIdentifier (id_builder, pos);
2882 val = LocatedToken.Create (s, ref_line, column);
2883 if (quoted && parsing_attribute_section)
2884 AddEscapedIdentifier (((LocatedToken) val).Location);
2886 return Token.IDENTIFIER;
2889 string InternIdentifier (char[] charBuffer, int length)
2892 // Keep identifiers in an array of hashtables to avoid needless
2895 var identifiers_group = identifiers[length];
2897 if (identifiers_group != null) {
2898 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2902 // TODO: this should be number of files dependant
2903 // corlib compilation peaks at 1000 and System.Core at 150
2904 int capacity = length > 20 ? 10 : 100;
2905 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2906 identifiers[length] = identifiers_group;
2909 char[] chars = new char[length];
2910 Array.Copy (charBuffer, chars, length);
2912 s = new string (charBuffer, 0, length);
2913 identifiers_group.Add (chars, s);
2917 public int xtoken ()
2921 // Whether we have seen comments on the current line
2922 bool comments_seen = false;
2923 while ((c = get_char ()) != -1) {
2926 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2934 case 0xFEFF: // Ignore BOM anywhere in the file
2937 /* This is required for compatibility with .NET
2939 if (peek_char () == 0xBB) {
2942 if (get_char () == 0xBF)
2950 return consume_identifier (c);
2953 val = LocatedToken.Create (ref_line, col);
2954 return Token.OPEN_BRACE;
2956 val = LocatedToken.Create (ref_line, col);
2957 return Token.CLOSE_BRACE;
2959 // To block doccomment inside attribute declaration.
2960 if (doc_state == XmlCommentState.Allowed)
2961 doc_state = XmlCommentState.NotAllowed;
2963 val = LocatedToken.Create (ref_line, col);
2965 if (parsing_block == 0 || lambda_arguments_parsing)
2966 return Token.OPEN_BRACKET;
2968 int next = peek_char ();
2972 return Token.OPEN_BRACKET;
2980 next = peek_token ();
2981 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2982 return Token.OPEN_BRACKET;
2984 return Token.OPEN_BRACKET_EXPR;
2986 return Token.OPEN_BRACKET_EXPR;
2989 LocatedToken.CreateOptional (ref_line, col, ref val);
2990 return Token.CLOSE_BRACKET;
2992 val = LocatedToken.Create (ref_line, col);
2994 // An expression versions of parens can appear in block context only
2996 if (parsing_block != 0 && !lambda_arguments_parsing) {
2999 // Optmize most common case where we know that parens
3002 switch (current_token) {
3003 case Token.IDENTIFIER:
3011 case Token.DELEGATE:
3012 case Token.OP_GENERICS_GT:
3013 return Token.OPEN_PARENS;
3016 // Optimize using peek
3017 int xx = peek_char ();
3024 return Token.OPEN_PARENS;
3027 lambda_arguments_parsing = true;
3029 d = TokenizeOpenParens ();
3031 lambda_arguments_parsing = false;
3035 return Token.OPEN_PARENS;
3037 LocatedToken.CreateOptional (ref_line, col, ref val);
3038 return Token.CLOSE_PARENS;
3040 LocatedToken.CreateOptional (ref_line, col, ref val);
3043 LocatedToken.CreateOptional (ref_line, col, ref val);
3044 return Token.SEMICOLON;
3046 val = LocatedToken.Create (ref_line, col);
3049 val = LocatedToken.Create (ref_line, col);
3050 return TokenizePossibleNullableType ();
3052 val = LocatedToken.Create (ref_line, col);
3053 if (parsing_generic_less_than++ > 0)
3054 return Token.OP_GENERICS_LT;
3056 return TokenizeLessThan ();
3059 val = LocatedToken.Create (ref_line, col);
3067 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3068 parsing_generic_less_than--;
3069 return Token.OP_GENERICS_GT;
3078 return Token.OP_SHIFT_RIGHT_ASSIGN;
3080 return Token.OP_SHIFT_RIGHT;
3086 val = LocatedToken.Create (ref_line, col);
3090 } else if (d == '=') {
3091 d = Token.OP_ADD_ASSIGN;
3099 val = LocatedToken.Create (ref_line, col);
3103 } else if (d == '=')
3104 d = Token.OP_SUB_ASSIGN;
3114 val = LocatedToken.Create (ref_line, col);
3115 if (peek_char () == '='){
3122 val = LocatedToken.Create (ref_line, col);
3133 return Token.ASSIGN;
3136 val = LocatedToken.Create (ref_line, col);
3140 return Token.OP_AND;
3144 return Token.OP_AND_ASSIGN;
3146 return Token.BITWISE_AND;
3149 val = LocatedToken.Create (ref_line, col);
3157 return Token.OP_OR_ASSIGN;
3159 return Token.BITWISE_OR;
3162 val = LocatedToken.Create (ref_line, col);
3163 if (peek_char () == '='){
3165 return Token.OP_MULT_ASSIGN;
3172 val = LocatedToken.Create (ref_line, col);
3174 return Token.OP_DIV_ASSIGN;
3177 // Handle double-slash comments.
3180 if (doc_processing) {
3181 if (peek_char () == '/') {
3183 // Don't allow ////.
3184 if ((d = peek_char ()) != '/') {
3185 if (doc_state == XmlCommentState.Allowed)
3186 handle_one_line_xml_comment ();
3187 else if (doc_state == XmlCommentState.NotAllowed)
3188 WarningMisplacedComment (Location - 3);
3191 if (xml_comment_buffer.Length > 0)
3192 doc_state = XmlCommentState.NotAllowed;
3196 while ((d = get_char ()) != -1 && d != '\n');
3198 any_token_seen |= tokens_seen;
3199 tokens_seen = false;
3200 comments_seen = false;
3202 } else if (d == '*'){
3204 bool docAppend = false;
3205 if (doc_processing && peek_char () == '*') {
3207 // But when it is /**/, just do nothing.
3208 if (peek_char () == '/') {
3212 if (doc_state == XmlCommentState.Allowed)
3214 else if (doc_state == XmlCommentState.NotAllowed) {
3215 WarningMisplacedComment (Location - 2);
3219 int current_comment_start = 0;
3221 current_comment_start = xml_comment_buffer.Length;
3222 xml_comment_buffer.Append (Environment.NewLine);
3225 while ((d = get_char ()) != -1){
3226 if (d == '*' && peek_char () == '/'){
3228 comments_seen = true;
3232 xml_comment_buffer.Append ((char) d);
3235 any_token_seen |= tokens_seen;
3236 tokens_seen = false;
3238 // Reset 'comments_seen' just to be consistent.
3239 // It doesn't matter either way, here.
3241 comments_seen = false;
3245 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3248 update_formatted_doc_comment (current_comment_start);
3251 val = LocatedToken.Create (ref_line, col);
3255 val = LocatedToken.Create (ref_line, col);
3256 if (peek_char () == '='){
3258 return Token.OP_MOD_ASSIGN;
3260 return Token.PERCENT;
3263 val = LocatedToken.Create (ref_line, col);
3264 if (peek_char () == '='){
3266 return Token.OP_XOR_ASSIGN;
3268 return Token.CARRET;
3271 val = LocatedToken.Create (ref_line, col);
3272 if (peek_char () == ':') {
3274 return Token.DOUBLE_COLON;
3278 case '0': case '1': case '2': case '3': case '4':
3279 case '5': case '6': case '7': case '8': case '9':
3281 return is_number (c);
3283 case '\n': // white space
3284 any_token_seen |= tokens_seen;
3285 tokens_seen = false;
3286 comments_seen = false;
3292 if (d >= '0' && d <= '9')
3293 return is_number (c);
3295 LocatedToken.CreateOptional (ref_line, col, ref val);
3299 if (tokens_seen || comments_seen) {
3300 Eror_WrongPreprocessorLocation ();
3304 if (ParsePreprocessingDirective (true))
3307 bool directive_expected = false;
3308 while ((c = get_char ()) != -1) {
3310 directive_expected = true;
3311 } else if (!directive_expected) {
3312 // TODO: Implement comment support for disabled code and uncomment this code
3314 // Eror_WrongPreprocessorLocation ();
3315 // return Token.ERROR;
3320 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3324 if (ParsePreprocessingDirective (false))
3327 directive_expected = false;
3331 tokens_seen = false;
3338 return consume_string (false);
3341 return TokenizeBackslash ();
3347 return consume_string (true);
3350 if (is_identifier_start_character (c)){
3351 return consume_identifier (c, true);
3354 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3357 case EvalStatementParserCharacter:
3358 return Token.EVAL_STATEMENT_PARSER;
3359 case EvalCompilationUnitParserCharacter:
3360 return Token.EVAL_COMPILATION_UNIT_PARSER;
3361 case EvalUsingDeclarationsParserCharacter:
3362 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3363 case DocumentationXref:
3364 return Token.DOC_SEE;
3367 if (is_identifier_start_character (c)) {
3369 return consume_identifier (c);
3372 if (char.IsWhiteSpace ((char) c))
3375 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3380 return Token.COMPLETE_COMPLETION;
3383 return Token.GENERATE_COMPLETION;
3390 int TokenizeBackslash ()
3393 int read_start = reader.Position;
3395 Location start_location = Location;
3396 int c = get_char ();
3399 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3400 Report.Error (1011, start_location, "Empty character literal");
3401 return Token.LITERAL;
3405 Report.Error (1010, start_location, "Newline in constant");
3410 c = escape (c, out d);
3414 throw new NotImplementedException ();
3416 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3421 Report.Error (1012, start_location, "Too many characters in character literal");
3423 // Try to recover, read until newline or next "'"
3424 while ((c = get_char ()) != -1) {
3425 if (c == '\n' || c == '\'')
3431 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3434 return Token.LITERAL;
3437 int TokenizeLessThan ()
3440 if (handle_typeof) {
3442 if (parse_generic_dimension (out d)) {
3445 return Token.GENERIC_DIMENSION;
3450 // Save current position and parse next token.
3452 if (parse_less_than ()) {
3453 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3454 d = Token.OP_GENERICS_LT_DECL;
3456 d = Token.OP_GENERICS_LT;
3463 parsing_generic_less_than = 0;
3472 return Token.OP_SHIFT_LEFT_ASSIGN;
3474 return Token.OP_SHIFT_LEFT;
3485 // Handles one line xml comment
3487 private void handle_one_line_xml_comment ()
3490 while ((c = peek_char ()) == ' ')
3491 get_char (); // skip heading whitespaces.
3492 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3493 xml_comment_buffer.Append ((char) get_char ());
3495 if (c == '\r' || c == '\n')
3496 xml_comment_buffer.Append (Environment.NewLine);
3500 // Remove heading "*" in Javadoc-like xml documentation.
3502 private void update_formatted_doc_comment (int current_comment_start)
3504 int length = xml_comment_buffer.Length - current_comment_start;
3505 string [] lines = xml_comment_buffer.ToString (
3506 current_comment_start,
3507 length).Replace ("\r", "").Split ('\n');
3509 // The first line starts with /**, thus it is not target
3510 // for the format check.
3511 for (int i = 1; i < lines.Length; i++) {
3512 string s = lines [i];
3513 int idx = s.IndexOf ('*');
3516 if (i < lines.Length - 1)
3520 head = s.Substring (0, idx);
3521 foreach (char c in head)
3524 lines [i] = s.Substring (idx + 1);
3526 xml_comment_buffer.Remove (current_comment_start, length);
3527 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3531 // Checks if there was incorrect doc comments and raise
3534 public void check_incorrect_doc_comment ()
3536 if (xml_comment_buffer.Length > 0)
3537 WarningMisplacedComment (Location);
3541 // Consumes the saved xml comment lines (if any)
3542 // as for current target member or type.
3544 public string consume_doc_comment ()
3546 if (xml_comment_buffer.Length > 0) {
3547 string ret = xml_comment_buffer.ToString ();
3548 reset_doc_comment ();
3555 get { return context.Report; }
3558 void reset_doc_comment ()
3560 xml_comment_buffer.Length = 0;
3563 public void cleanup ()
3565 if (ifstack != null && ifstack.Count >= 1) {
3566 int state = ifstack.Pop ();
3567 if ((state & REGION) != 0)
3568 Report.Error (1038, Location, "#endregion directive expected");
3570 Report.Error (1027, Location, "Expected `#endif' directive");
3576 // Indicates whether it accepts XML documentation or not.
3578 public enum XmlCommentState {
3579 // comment is allowed in this state.
3581 // comment is not allowed in this state.
3583 // once comments appeared when it is NotAllowed, then the
3584 // state is changed to it, until the state is changed to