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@seznam.cz)
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
17 using System.Collections.Generic;
19 using System.Globalization;
20 using System.Reflection;
21 using System.Diagnostics;
26 /// Tokenizer for C# source code.
29 public class Tokenizer : yyParser.yyInput
33 public readonly T Token;
34 public KeywordEntry<T> Next;
35 public readonly char[] Value;
37 public KeywordEntry (string value, T token)
39 this.Value = value.ToCharArray ();
44 sealed class IdentifiersComparer : IEqualityComparer<char[]>
48 public IdentifiersComparer (int length)
53 public bool Equals (char[] x, char[] y)
55 for (int i = 0; i < length; ++i)
62 public int GetHashCode (char[] obj)
65 for (int i = 0; i < length; ++i)
66 h = (h << 5) - h + obj [i];
73 // This class has to be used in the parser only, it reuses token
74 // details after each parse
76 public class LocatedToken
81 static LocatedToken[] buffer;
84 private LocatedToken ()
88 public static LocatedToken Create (int row, int column)
90 return Create (null, row, column);
93 public static LocatedToken Create (string value, int row, int column)
96 // TODO: I am not very happy about the logic but it's the best
97 // what I could come up with for now.
98 // Ideally we should be using just tiny buffer (256 elements) which
99 // is enough to hold all details for currect stack and recycle elements
100 // poped from the stack but there is a trick needed to recycle
104 if (pos >= buffer.Length) {
105 entry = new LocatedToken ();
107 entry = buffer [pos];
109 entry = new LocatedToken ();
110 buffer [pos] = entry;
117 entry.column = column;
122 // Used for token not required by expression evaluator
124 [Conditional ("FULL_AST")]
125 public static void CreateOptional (int row, int col, ref object token)
127 token = Create (row, col);
130 public static void Initialize ()
133 buffer = new LocatedToken [10000];
137 public Location Location {
138 get { return new Location (row, column); }
141 public string Value {
142 get { return value; }
146 enum PreprocessorDirective
152 If = 3 | RequiresArgument,
154 Elif = 5 | RequiresArgument,
156 Define = 7 | RequiresArgument,
157 Undef = 8 | RequiresArgument,
160 Pragma = 11 | CustomArgumentsParsing,
163 CustomArgumentsParsing = 1 << 10,
164 RequiresArgument = 1 << 11
167 SeekableStreamReader reader;
169 CompilationUnit file_name;
170 CompilerContext context;
178 bool handle_get_set = false;
179 bool handle_remove_add = false;
180 bool handle_where = false;
181 bool handle_typeof = false;
182 bool lambda_arguments_parsing;
183 Location current_comment_location = Location.Null;
184 List<Location> escaped_identifiers;
185 int parsing_generic_less_than;
188 // Used mainly for parser optimizations. Some expressions for instance
189 // can appear only in block (including initializer, base initializer)
192 public int parsing_block;
193 internal bool query_parsing;
196 // When parsing type only, useful for ambiguous nullable types
198 public int parsing_type;
201 // Set when parsing generic declaration (type or method header)
203 public bool parsing_generic_declaration;
206 // The value indicates that we have not reach any declaration or
209 public int parsing_declaration;
212 // The special character to inject on streams to trigger the EXPRESSION_PARSE
213 // token to be returned. It just happens to be a Unicode character that
214 // would never be part of a program (can not be an identifier).
216 // This character is only tested just before the tokenizer is about to report
217 // an error; So on the regular operation mode, this addition will have no
218 // impact on the tokenizer's performance.
221 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
222 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
223 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
226 // XML documentation buffer. The save point is used to divide
227 // comments on types and comments on members.
229 StringBuilder xml_comment_buffer;
232 // See comment on XmlCommentState enumeration.
234 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
237 // Whether tokens have been seen on this line
239 bool tokens_seen = false;
242 // Set to true once the GENERATE_COMPLETION token has bee
243 // returned. This helps produce one GENERATE_COMPLETION,
244 // as many COMPLETE_COMPLETION as necessary to complete the
245 // AST tree and one final EOF.
250 // Whether a token has been seen on the file
251 // This is needed because `define' is not allowed to be used
252 // after a token has been seen.
254 bool any_token_seen = false;
256 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
258 public bool PropertyParsing {
259 get { return handle_get_set; }
260 set { handle_get_set = value; }
263 public bool EventParsing {
264 get { return handle_remove_add; }
265 set { handle_remove_add = value; }
268 public bool ConstraintsParsing {
269 get { return handle_where; }
270 set { handle_where = value; }
273 public bool TypeOfParsing {
274 get { return handle_typeof; }
275 set { handle_typeof = value; }
279 get { return tab_size; }
280 set { tab_size = value; }
283 public XmlCommentState doc_state {
284 get { return xml_doc_state; }
286 if (value == XmlCommentState.Allowed) {
287 check_incorrect_doc_comment ();
288 reset_doc_comment ();
290 xml_doc_state = value;
295 // This is used to trigger completion generation on the parser
296 public bool CompleteOnEOF;
298 void AddEscapedIdentifier (Location loc)
300 if (escaped_identifiers == null)
301 escaped_identifiers = new List<Location> ();
303 escaped_identifiers.Add (loc);
306 public bool IsEscapedIdentifier (MemberName name)
308 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
314 static KeywordEntry<int>[][] keywords;
315 static KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
316 static Dictionary<string, object> keyword_strings; // TODO: HashSet
317 static NumberStyles styles;
318 static NumberFormatInfo csharp_format_info;
321 static readonly char[] pragma_warning = "warning".ToCharArray ();
322 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
323 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
324 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
327 // Values for the associated token returned
329 internal int putback_char; // Used by repl only
335 const int TAKING = 1;
336 const int ELSE_SEEN = 4;
337 const int PARENT_TAKING = 8;
338 const int REGION = 16;
341 // pre-processor if stack state:
345 static System.Text.StringBuilder string_builder;
347 const int max_id_size = 512;
348 static char [] id_builder = new char [max_id_size];
350 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
352 const int max_number_size = 512;
353 static char [] number_builder = new char [max_number_size];
354 static int number_pos;
356 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
359 // Details about the error encoutered by the tokenizer
361 string error_details;
363 public string error {
365 return error_details;
376 // This is used when the tokenizer needs to save
377 // the current position as it needs to do some parsing
378 // on its own to deamiguate a token in behalf of the
381 Stack<Position> position_stack = new Stack<Position> (2);
389 public int putback_char;
390 public int previous_col;
391 public Stack<int> ifstack;
392 public int parsing_generic_less_than;
393 public int current_token;
396 public Position (Tokenizer t)
398 position = t.reader.Position;
400 ref_line = t.ref_line;
403 putback_char = t.putback_char;
404 previous_col = t.previous_col;
405 if (t.ifstack != null && t.ifstack.Count != 0) {
406 // There is no simple way to clone Stack<T> all
407 // methods reverse the order
408 var clone = t.ifstack.ToArray ();
409 Array.Reverse (clone);
410 ifstack = new Stack<int> (clone);
412 parsing_generic_less_than = t.parsing_generic_less_than;
413 current_token = t.current_token;
418 public void PushPosition ()
420 position_stack.Push (new Position (this));
423 public void PopPosition ()
425 Position p = position_stack.Pop ();
427 reader.Position = p.position;
428 ref_line = p.ref_line;
432 putback_char = p.putback_char;
433 previous_col = p.previous_col;
435 parsing_generic_less_than = p.parsing_generic_less_than;
436 current_token = p.current_token;
440 // Do not reset the position, ignore it.
441 public void DiscardPosition ()
443 position_stack.Pop ();
446 static void AddKeyword (string kw, int token)
448 keyword_strings.Add (kw, null);
450 AddKeyword (keywords, kw, token);
453 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
455 AddKeyword (keywords_preprocessor, kw, directive);
458 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
460 int length = kw.Length;
461 if (keywords[length] == null) {
462 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
465 int char_index = kw[0] - '_';
466 var kwe = keywords[length][char_index];
468 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
472 while (kwe.Next != null) {
476 kwe.Next = new KeywordEntry<T> (kw, token);
479 static void InitTokens ()
481 keyword_strings = new Dictionary<string, object> ();
483 // 11 is the length of the longest keyword for now
484 keywords = new KeywordEntry<int> [11] [];
486 AddKeyword ("__arglist", Token.ARGLIST);
487 AddKeyword ("abstract", Token.ABSTRACT);
488 AddKeyword ("as", Token.AS);
489 AddKeyword ("add", Token.ADD);
490 AddKeyword ("base", Token.BASE);
491 AddKeyword ("bool", Token.BOOL);
492 AddKeyword ("break", Token.BREAK);
493 AddKeyword ("byte", Token.BYTE);
494 AddKeyword ("case", Token.CASE);
495 AddKeyword ("catch", Token.CATCH);
496 AddKeyword ("char", Token.CHAR);
497 AddKeyword ("checked", Token.CHECKED);
498 AddKeyword ("class", Token.CLASS);
499 AddKeyword ("const", Token.CONST);
500 AddKeyword ("continue", Token.CONTINUE);
501 AddKeyword ("decimal", Token.DECIMAL);
502 AddKeyword ("default", Token.DEFAULT);
503 AddKeyword ("delegate", Token.DELEGATE);
504 AddKeyword ("do", Token.DO);
505 AddKeyword ("double", Token.DOUBLE);
506 AddKeyword ("else", Token.ELSE);
507 AddKeyword ("enum", Token.ENUM);
508 AddKeyword ("event", Token.EVENT);
509 AddKeyword ("explicit", Token.EXPLICIT);
510 AddKeyword ("extern", Token.EXTERN);
511 AddKeyword ("false", Token.FALSE);
512 AddKeyword ("finally", Token.FINALLY);
513 AddKeyword ("fixed", Token.FIXED);
514 AddKeyword ("float", Token.FLOAT);
515 AddKeyword ("for", Token.FOR);
516 AddKeyword ("foreach", Token.FOREACH);
517 AddKeyword ("goto", Token.GOTO);
518 AddKeyword ("get", Token.GET);
519 AddKeyword ("if", Token.IF);
520 AddKeyword ("implicit", Token.IMPLICIT);
521 AddKeyword ("in", Token.IN);
522 AddKeyword ("int", Token.INT);
523 AddKeyword ("interface", Token.INTERFACE);
524 AddKeyword ("internal", Token.INTERNAL);
525 AddKeyword ("is", Token.IS);
526 AddKeyword ("lock", Token.LOCK);
527 AddKeyword ("long", Token.LONG);
528 AddKeyword ("namespace", Token.NAMESPACE);
529 AddKeyword ("new", Token.NEW);
530 AddKeyword ("null", Token.NULL);
531 AddKeyword ("object", Token.OBJECT);
532 AddKeyword ("operator", Token.OPERATOR);
533 AddKeyword ("out", Token.OUT);
534 AddKeyword ("override", Token.OVERRIDE);
535 AddKeyword ("params", Token.PARAMS);
536 AddKeyword ("private", Token.PRIVATE);
537 AddKeyword ("protected", Token.PROTECTED);
538 AddKeyword ("public", Token.PUBLIC);
539 AddKeyword ("readonly", Token.READONLY);
540 AddKeyword ("ref", Token.REF);
541 AddKeyword ("remove", Token.REMOVE);
542 AddKeyword ("return", Token.RETURN);
543 AddKeyword ("sbyte", Token.SBYTE);
544 AddKeyword ("sealed", Token.SEALED);
545 AddKeyword ("set", Token.SET);
546 AddKeyword ("short", Token.SHORT);
547 AddKeyword ("sizeof", Token.SIZEOF);
548 AddKeyword ("stackalloc", Token.STACKALLOC);
549 AddKeyword ("static", Token.STATIC);
550 AddKeyword ("string", Token.STRING);
551 AddKeyword ("struct", Token.STRUCT);
552 AddKeyword ("switch", Token.SWITCH);
553 AddKeyword ("this", Token.THIS);
554 AddKeyword ("throw", Token.THROW);
555 AddKeyword ("true", Token.TRUE);
556 AddKeyword ("try", Token.TRY);
557 AddKeyword ("typeof", Token.TYPEOF);
558 AddKeyword ("uint", Token.UINT);
559 AddKeyword ("ulong", Token.ULONG);
560 AddKeyword ("unchecked", Token.UNCHECKED);
561 AddKeyword ("unsafe", Token.UNSAFE);
562 AddKeyword ("ushort", Token.USHORT);
563 AddKeyword ("using", Token.USING);
564 AddKeyword ("virtual", Token.VIRTUAL);
565 AddKeyword ("void", Token.VOID);
566 AddKeyword ("volatile", Token.VOLATILE);
567 AddKeyword ("while", Token.WHILE);
568 AddKeyword ("partial", Token.PARTIAL);
569 AddKeyword ("where", Token.WHERE);
572 AddKeyword ("from", Token.FROM);
573 AddKeyword ("join", Token.JOIN);
574 AddKeyword ("on", Token.ON);
575 AddKeyword ("equals", Token.EQUALS);
576 AddKeyword ("select", Token.SELECT);
577 AddKeyword ("group", Token.GROUP);
578 AddKeyword ("by", Token.BY);
579 AddKeyword ("let", Token.LET);
580 AddKeyword ("orderby", Token.ORDERBY);
581 AddKeyword ("ascending", Token.ASCENDING);
582 AddKeyword ("descending", Token.DESCENDING);
583 AddKeyword ("into", Token.INTO);
585 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
587 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
588 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
589 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
590 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
591 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
592 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
593 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
594 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
595 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
596 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
597 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
598 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
607 csharp_format_info = NumberFormatInfo.InvariantInfo;
608 styles = NumberStyles.Float;
610 string_builder = new System.Text.StringBuilder ();
613 int GetKeyword (char[] id, int id_len)
616 // Keywords are stored in an array of arrays grouped by their
617 // length and then by the first character
619 if (id_len >= keywords.Length || keywords [id_len] == null)
622 int first_index = id [0] - '_';
623 if (first_index > 'z' - '_')
626 var kwe = keywords [id_len] [first_index];
633 for (int i = 1; i < id_len; ++i) {
634 if (id [i] != kwe.Value [i]) {
640 } while (res == 0 && kwe != null);
654 if (!handle_remove_add)
658 if (parsing_declaration == 0)
659 res = Token.EXTERN_ALIAS;
662 if (peek_token () == Token.COLON) {
664 res = Token.DEFAULT_COLON;
668 if (!handle_where && !query_parsing)
673 // A query expression is any expression that starts with `from identifier'
674 // followed by any token except ; , =
676 if (!query_parsing) {
677 if (lambda_arguments_parsing) {
683 // HACK: to disable generics micro-parser, because PushPosition does not
684 // store identifiers array
685 parsing_generic_less_than = 1;
687 case Token.IDENTIFIER:
699 next_token = xtoken ();
700 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
703 res = Token.FROM_FIRST;
704 query_parsing = true;
705 if (RootContext.Version <= LanguageVersion.ISO_2)
706 Report.FeatureIsNotAvailable (Location, "query expressions");
709 Expression.Error_VoidInvalidInTheContext (Location, Report);
713 // HACK: A token is not a keyword so we need to restore identifiers buffer
714 // which has been overwritten before we grabbed the identifier
715 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
729 case Token.ASCENDING:
730 case Token.DESCENDING:
737 case Token.NAMESPACE:
738 // TODO: some explanation needed
739 check_incorrect_doc_comment ();
743 if (parsing_block > 0) {
748 // Save current position and parse next token.
751 next_token = token ();
752 bool ok = (next_token == Token.CLASS) ||
753 (next_token == Token.STRUCT) ||
754 (next_token == Token.INTERFACE) ||
755 (next_token == Token.VOID);
760 if (next_token == Token.VOID) {
761 if (RootContext.Version == LanguageVersion.ISO_1 ||
762 RootContext.Version == LanguageVersion.ISO_2)
763 Report.FeatureIsNotAvailable (Location, "partial methods");
764 } else if (RootContext.Version == LanguageVersion.ISO_1)
765 Report.FeatureIsNotAvailable (Location, "partial types");
770 if (next_token < Token.LAST_KEYWORD) {
771 Report.Error (267, Location,
772 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
783 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
786 // Keywords are stored in an array of arrays grouped by their
787 // length and then by the first character
789 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
790 return PreprocessorDirective.Invalid;
792 int first_index = id[0] - '_';
793 if (first_index > 'z' - '_')
794 return PreprocessorDirective.Invalid;
796 var kwe = keywords_preprocessor[id_len][first_index];
798 return PreprocessorDirective.Invalid;
800 PreprocessorDirective res = PreprocessorDirective.Invalid;
803 for (int i = 1; i < id_len; ++i) {
804 if (id[i] != kwe.Value[i]) {
810 } while (res == PreprocessorDirective.Invalid && kwe != null);
815 public Location Location {
817 return new Location (ref_line, hidden ? -1 : col);
821 public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
823 this.ref_name = file;
824 this.file_name = file;
830 xml_comment_buffer = new StringBuilder ();
832 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
838 // FIXME: This could be `Location.Push' but we have to
839 // find out why the MS compiler allows this
841 Mono.CSharp.Location.Push (file, file);
844 static bool is_identifier_start_character (int c)
846 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
849 static bool is_identifier_part_character (char c)
851 if (c >= 'a' && c <= 'z')
854 if (c >= 'A' && c <= 'Z')
857 if (c == '_' || (c >= '0' && c <= '9'))
863 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
866 public static bool IsKeyword (string s)
868 return keyword_strings.ContainsKey (s);
872 // Open parens micro parser. Detects both lambda and cast ambiguity.
874 int TokenizeOpenParens ()
879 int bracket_level = 0;
880 bool is_type = false;
881 bool can_be_type = false;
884 ptoken = current_token;
887 switch (current_token) {
888 case Token.CLOSE_PARENS:
892 // Expression inside parens is lambda, (int i) =>
894 if (current_token == Token.ARROW)
895 return Token.OPEN_PARENS_LAMBDA;
898 // Expression inside parens is single type, (int[])
901 return Token.OPEN_PARENS_CAST;
904 // Expression is possible cast, look at next token, (T)null
907 switch (current_token) {
908 case Token.OPEN_PARENS:
911 case Token.IDENTIFIER:
925 case Token.UNCHECKED:
930 // These can be part of a member access
944 return Token.OPEN_PARENS_CAST;
947 return Token.OPEN_PARENS;
950 case Token.DOUBLE_COLON:
951 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
956 case Token.IDENTIFIER:
959 case Token.OP_GENERICS_LT:
961 case Token.DOUBLE_COLON:
963 if (bracket_level == 0)
967 can_be_type = is_type = false;
987 if (bracket_level == 0)
992 if (bracket_level == 0) {
994 can_be_type = is_type = false;
998 case Token.OP_GENERICS_LT:
999 case Token.OPEN_BRACKET:
1000 if (bracket_level++ == 0)
1004 case Token.OP_GENERICS_GT:
1005 case Token.CLOSE_BRACKET:
1009 case Token.INTERR_NULLABLE:
1011 if (bracket_level == 0)
1017 can_be_type = is_type = false;
1021 return Token.OPEN_PARENS;
1026 public static bool IsValidIdentifier (string s)
1028 if (s == null || s.Length == 0)
1031 if (!is_identifier_start_character (s [0]))
1034 for (int i = 1; i < s.Length; i ++)
1035 if (! is_identifier_part_character (s [i]))
1041 bool parse_less_than ()
1044 int the_token = token ();
1045 if (the_token == Token.OPEN_BRACKET) {
1047 the_token = token ();
1048 } while (the_token != Token.CLOSE_BRACKET);
1049 the_token = token ();
1050 } else if (the_token == Token.IN || the_token == Token.OUT) {
1051 the_token = token ();
1053 switch (the_token) {
1054 case Token.IDENTIFIER:
1072 case Token.OP_GENERICS_GT:
1079 the_token = token ();
1081 if (the_token == Token.OP_GENERICS_GT)
1083 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1085 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1087 else if (the_token == Token.OP_GENERICS_LT) {
1088 if (!parse_less_than ())
1091 } else if (the_token == Token.OPEN_BRACKET) {
1093 the_token = token ();
1094 if (the_token == Token.CLOSE_BRACKET)
1096 else if (the_token == Token.COMMA)
1097 goto rank_specifiers;
1104 bool parse_generic_dimension (out int dimension)
1109 int the_token = token ();
1110 if (the_token == Token.OP_GENERICS_GT)
1112 else if (the_token == Token.COMMA) {
1120 public int peek_token ()
1125 the_token = token ();
1132 // Tonizes `?' using custom disambiguous rules to return one
1133 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1135 // Tricky expression look like:
1137 // Foo ? a = x ? b : c;
1139 int TokenizePossibleNullableType ()
1141 if (parsing_block == 0 || parsing_type > 0)
1142 return Token.INTERR_NULLABLE;
1144 int d = peek_char ();
1147 return Token.OP_COALESCING;
1150 switch (current_token) {
1151 case Token.CLOSE_PARENS:
1156 return Token.INTERR;
1160 if (d == ',' || d == ';' || d == '>')
1161 return Token.INTERR_NULLABLE;
1162 if (d == '*' || (d >= '0' && d <= '9'))
1163 return Token.INTERR;
1167 current_token = Token.NONE;
1169 switch (xtoken ()) {
1176 next_token = Token.INTERR;
1179 case Token.SEMICOLON:
1181 case Token.CLOSE_PARENS:
1182 case Token.OPEN_BRACKET:
1183 case Token.OP_GENERICS_GT:
1184 next_token = Token.INTERR_NULLABLE;
1192 if (next_token == -1) {
1193 switch (xtoken ()) {
1195 case Token.SEMICOLON:
1196 case Token.OPEN_BRACE:
1197 case Token.CLOSE_PARENS:
1199 next_token = Token.INTERR_NULLABLE;
1203 next_token = Token.INTERR;
1211 // All shorcuts failed, do it hard way
1213 while ((ntoken = xtoken ()) != Token.EOF) {
1214 if (ntoken == Token.SEMICOLON)
1217 if (ntoken == Token.COLON) {
1218 if (++colons == interrs)
1223 if (ntoken == Token.INTERR) {
1229 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1238 bool decimal_digits (int c)
1241 bool seen_digits = false;
1244 if (number_pos == max_number_size)
1245 Error_NumericConstantTooLong ();
1246 number_builder [number_pos++] = (char) c;
1250 // We use peek_char2, because decimal_digits needs to do a
1251 // 2-character look-ahead (5.ToString for example).
1253 while ((d = peek_char2 ()) != -1){
1254 if (d >= '0' && d <= '9'){
1255 if (number_pos == max_number_size)
1256 Error_NumericConstantTooLong ();
1257 number_builder [number_pos++] = (char) d;
1267 static bool is_hex (int e)
1269 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1272 static TypeCode real_type_suffix (int c)
1276 return TypeCode.Single;
1278 return TypeCode.Double;
1280 return TypeCode.Decimal;
1282 return TypeCode.Empty;
1286 int integer_type_suffix (ulong ul, int c)
1288 bool is_unsigned = false;
1289 bool is_long = false;
1292 bool scanning = true;
1305 // if we have not seen anything in between
1306 // report this error
1308 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1328 if (is_long && is_unsigned){
1329 val = new ULongLiteral (ul, Location);
1330 return Token.LITERAL;
1334 // uint if possible, or ulong else.
1336 if ((ul & 0xffffffff00000000) == 0)
1337 val = new UIntLiteral ((uint) ul, Location);
1339 val = new ULongLiteral (ul, Location);
1340 } else if (is_long){
1341 // long if possible, ulong otherwise
1342 if ((ul & 0x8000000000000000) != 0)
1343 val = new ULongLiteral (ul, Location);
1345 val = new LongLiteral ((long) ul, Location);
1347 // int, uint, long or ulong in that order
1348 if ((ul & 0xffffffff00000000) == 0){
1349 uint ui = (uint) ul;
1351 if ((ui & 0x80000000) != 0)
1352 val = new UIntLiteral (ui, Location);
1354 val = new IntLiteral ((int) ui, Location);
1356 if ((ul & 0x8000000000000000) != 0)
1357 val = new ULongLiteral (ul, Location);
1359 val = new LongLiteral ((long) ul, Location);
1362 return Token.LITERAL;
1366 // given `c' as the next char in the input decide whether
1367 // we need to convert to a special type, and then choose
1368 // the best representation for the integer
1370 int adjust_int (int c)
1373 if (number_pos > 9){
1374 ulong ul = (uint) (number_builder [0] - '0');
1376 for (int i = 1; i < number_pos; i++){
1377 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1379 return integer_type_suffix (ul, c);
1381 uint ui = (uint) (number_builder [0] - '0');
1383 for (int i = 1; i < number_pos; i++){
1384 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1386 return integer_type_suffix (ui, c);
1388 } catch (OverflowException) {
1389 Error_NumericConstantTooLong ();
1390 val = new IntLiteral (0, Location);
1391 return Token.LITERAL;
1393 catch (FormatException) {
1394 Report.Error (1013, Location, "Invalid number");
1395 val = new IntLiteral (0, Location);
1396 return Token.LITERAL;
1400 int adjust_real (TypeCode t)
1402 string s = new String (number_builder, 0, number_pos);
1403 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1406 case TypeCode.Decimal:
1408 val = new DecimalLiteral (decimal.Parse (s, styles, csharp_format_info), Location);
1409 } catch (OverflowException) {
1410 val = new DecimalLiteral (0, Location);
1411 Report.Error (594, Location, error_details, "decimal");
1414 case TypeCode.Single:
1416 val = new FloatLiteral (float.Parse (s, styles, csharp_format_info), Location);
1417 } catch (OverflowException) {
1418 val = new FloatLiteral (0, Location);
1419 Report.Error (594, Location, error_details, "float");
1424 val = new DoubleLiteral (double.Parse (s, styles, csharp_format_info), Location);
1425 } catch (OverflowException) {
1426 val = new DoubleLiteral (0, Location);
1427 Report.Error (594, Location, error_details, "double");
1432 return Token.LITERAL;
1441 while ((d = peek_char ()) != -1){
1443 number_builder [number_pos++] = (char) d;
1449 string s = new String (number_builder, 0, number_pos);
1451 if (number_pos <= 8)
1452 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1454 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1455 } catch (OverflowException){
1456 Error_NumericConstantTooLong ();
1457 val = new IntLiteral (0, Location);
1458 return Token.LITERAL;
1460 catch (FormatException) {
1461 Report.Error (1013, Location, "Invalid number");
1462 val = new IntLiteral (0, Location);
1463 return Token.LITERAL;
1466 return integer_type_suffix (ul, peek_char ());
1470 // Invoked if we know we have .digits or digits
1472 int is_number (int c)
1474 bool is_real = false;
1478 if (c >= '0' && c <= '9'){
1480 int peek = peek_char ();
1482 if (peek == 'x' || peek == 'X')
1483 return handle_hex ();
1490 // We need to handle the case of
1491 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1494 if (decimal_digits ('.')){
1500 return adjust_int (-1);
1504 if (c == 'e' || c == 'E'){
1506 if (number_pos == max_number_size)
1507 Error_NumericConstantTooLong ();
1508 number_builder [number_pos++] = 'e';
1512 if (number_pos == max_number_size)
1513 Error_NumericConstantTooLong ();
1514 number_builder [number_pos++] = '+';
1516 } else if (c == '-') {
1517 if (number_pos == max_number_size)
1518 Error_NumericConstantTooLong ();
1519 number_builder [number_pos++] = '-';
1522 if (number_pos == max_number_size)
1523 Error_NumericConstantTooLong ();
1524 number_builder [number_pos++] = '+';
1531 var type = real_type_suffix (c);
1532 if (type == TypeCode.Empty && !is_real){
1534 return adjust_int (c);
1539 if (type == TypeCode.Empty){
1544 return adjust_real (type);
1546 throw new Exception ("Is Number should never reach this point");
1550 // Accepts exactly count (4 or 8) hex, no more no less
1552 int getHex (int count, out int surrogate, out bool error)
1557 int top = count != -1 ? count : 4;
1562 for (i = 0; i < top; i++){
1565 if (c >= '0' && c <= '9')
1566 c = (int) c - (int) '0';
1567 else if (c >= 'A' && c <= 'F')
1568 c = (int) c - (int) 'A' + 10;
1569 else if (c >= 'a' && c <= 'f')
1570 c = (int) c - (int) 'a' + 10;
1576 total = (total * 16) + c;
1578 int p = peek_char ();
1581 if (!is_hex ((char)p))
1587 if (total > 0x0010FFFF) {
1592 if (total >= 0x00010000) {
1593 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1594 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1601 int escape (int c, out int surrogate)
1637 v = getHex (-1, out surrogate, out error);
1643 return EscapeUnicode (d, out surrogate);
1646 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1655 int EscapeUnicode (int ch, out int surrogate)
1659 ch = getHex (8, out surrogate, out error);
1661 ch = getHex (4, out surrogate, out error);
1665 Report.Error (1009, Location, "Unrecognized escape sequence");
1673 if (putback_char != -1) {
1686 void advance_line ()
1696 if (putback_char == -1)
1697 putback_char = reader.Read ();
1698 return putback_char;
1703 if (putback_char != -1)
1704 return putback_char;
1705 return reader.Peek ();
1708 void putback (int c)
1710 if (putback_char != -1){
1711 Console.WriteLine ("Col: " + col);
1712 Console.WriteLine ("Row: " + line);
1713 Console.WriteLine ("Name: " + ref_name.Name);
1714 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1715 throw new Exception ("This should not happen putback on putback");
1717 if (c == '\n' || col == 0) {
1718 // It won't happen though.
1728 public bool advance ()
1730 return peek_char () != -1 || CompleteOnEOF;
1733 public Object Value {
1739 public Object value ()
1746 current_token = xtoken ();
1747 return current_token;
1750 int TokenizePreprocessorIdentifier (out int c)
1752 // skip over white space
1755 } while (c == '\r' || c == ' ' || c == '\t');
1759 while (c != -1 && c >= 'a' && c <= 'z') {
1760 id_builder[pos++] = (char) c;
1763 int peek = peek_char ();
1764 if (peek == 'U' || peek == 'u') {
1766 c = EscapeUnicode (c, out surrogate);
1767 if (surrogate != 0) {
1768 if (is_identifier_part_character ((char) c)) {
1769 id_builder[pos++] = (char) c;
1780 PreprocessorDirective get_cmd_arg (out string arg)
1784 tokens_seen = false;
1787 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1789 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1792 // skip over white space
1793 while (c == '\r' || c == ' ' || c == '\t')
1796 static_cmd_arg.Length = 0;
1797 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1799 while (c != -1 && c != '\n' && c != '\r') {
1800 if (c == '\\' && has_identifier_argument >= 0) {
1801 if (has_identifier_argument != 0) {
1802 has_identifier_argument = 1;
1804 int peek = peek_char ();
1805 if (peek == 'U' || peek == 'u') {
1807 c = EscapeUnicode (c, out surrogate);
1808 if (surrogate != 0) {
1809 if (is_identifier_part_character ((char) c))
1810 static_cmd_arg.Append ((char) c);
1815 has_identifier_argument = -1;
1818 static_cmd_arg.Append ((char) c);
1822 if (static_cmd_arg.Length != 0) {
1823 arg = static_cmd_arg.ToString ();
1825 // Eat any trailing whitespaces and single-line comments
1826 if (arg.IndexOf ("//") != -1) {
1827 arg = arg.Substring (0, arg.IndexOf ("//"));
1830 arg = arg.Trim (simple_whitespaces);
1837 // Handles the #line directive
1839 bool PreProcessLine (string arg)
1841 if (arg.Length == 0)
1844 if (arg == "default"){
1846 ref_name = file_name;
1848 Location.Push (file_name, ref_name);
1850 } else if (arg == "hidden"){
1858 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1859 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1862 char [] quotes = { '\"' };
1864 string name = arg.Substring (pos). Trim (quotes);
1865 ref_name = Location.LookupFile (file_name, name);
1866 file_name.AddFile (ref_name);
1868 Location.Push (file_name, ref_name);
1870 ref_line = System.Int32.Parse (arg);
1881 // Handles #define and #undef
1883 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1885 if (ident.Length == 0 || ident == "true" || ident == "false"){
1886 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1890 if (ident.IndexOfAny (simple_whitespaces) != -1){
1891 Error_EndLineExpected ();
1895 if (!is_identifier_start_character (ident [0]))
1896 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1898 foreach (char c in ident.Substring (1)){
1899 if (!is_identifier_part_character (c)){
1900 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1905 if (!caller_is_taking)
1912 if (RootContext.IsConditionalDefined (ident))
1915 file_name.AddDefine (ident);
1920 file_name.AddUndefine (ident);
1924 byte read_hex (out bool error)
1927 int c = get_char ();
1929 if ((c >= '0') && (c <= '9'))
1930 total = (int) c - (int) '0';
1931 else if ((c >= 'A') && (c <= 'F'))
1932 total = (int) c - (int) 'A' + 10;
1933 else if ((c >= 'a') && (c <= 'f'))
1934 total = (int) c - (int) 'a' + 10;
1943 if ((c >= '0') && (c <= '9'))
1944 total += (int) c - (int) '0';
1945 else if ((c >= 'A') && (c <= 'F'))
1946 total += (int) c - (int) 'A' + 10;
1947 else if ((c >= 'a') && (c <= 'f'))
1948 total += (int) c - (int) 'a' + 10;
1955 return (byte) total;
1959 // Parses #pragma checksum
1961 bool ParsePragmaChecksum ()
1964 // The syntax is ` "foo.txt" "{guid}" "hash"'
1966 int c = get_char ();
1971 string_builder.Length = 0;
1972 while (c != -1 && c != '\n') {
1979 string_builder.Append ((char) c);
1982 if (string_builder.Length == 0) {
1983 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
1986 // TODO: Any white-spaces count
1990 SourceFile file = Location.LookupFile (file_name, string_builder.ToString ());
1992 if (get_char () != '"' || get_char () != '{')
1996 byte[] guid_bytes = new byte [16];
1999 for (; i < 4; i++) {
2000 guid_bytes [i] = read_hex (out error);
2005 if (get_char () != '-')
2008 for (; i < 10; i++) {
2009 guid_bytes [i] = read_hex (out error);
2013 guid_bytes [i++] = read_hex (out error);
2017 if (get_char () != '-')
2021 for (; i < 16; i++) {
2022 guid_bytes [i] = read_hex (out error);
2027 if (get_char () != '}' || get_char () != '"')
2030 // TODO: Any white-spaces count
2035 if (get_char () != '"')
2038 // Any length of checksum
2039 List<byte> checksum_bytes = new List<byte> (16);
2042 while (c != '"' && c != -1) {
2043 checksum_bytes.Add (read_hex (out error));
2051 ReadSingleLineComment ();
2052 } else if (get_char () != '"') {
2056 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2057 ref_name.AutoGenerated = true;
2061 bool IsTokenIdentifierEqual (char[] identifier)
2063 for (int i = 0; i < identifier.Length; ++i) {
2064 if (identifier[i] != id_builder[i])
2071 int TokenizePragmaNumber (ref int c)
2077 if (c >= '0' && c <= '9') {
2079 uint ui = (uint) (number_builder[0] - '0');
2082 for (int i = 1; i < number_pos; i++) {
2083 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2087 } catch (OverflowException) {
2088 Error_NumericConstantTooLong ();
2095 // skip over white space
2096 while (c == '\r' || c == ' ' || c == '\t')
2103 // skip over white space
2104 while (c == '\r' || c == ' ' || c == '\t')
2109 ReadSingleLineComment ();
2111 Report.Warning (1692, 1, Location, "Invalid number");
2113 // Read everything till the end of the line or file
2116 } while (c != -1 && c != '\n');
2123 void ReadSingleLineComment ()
2125 if (peek_char () != '/')
2126 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2128 // Read everything till the end of the line or file
2132 } while (c != -1 && c != '\n');
2136 /// Handles #pragma directive
2138 void ParsePragmaDirective (string arg)
2141 int length = TokenizePreprocessorIdentifier (out c);
2142 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2143 length = TokenizePreprocessorIdentifier (out c);
2146 // #pragma warning disable
2147 // #pragma warning restore
2149 if (length == pragma_warning_disable.Length) {
2150 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2151 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2152 // skip over white space
2153 while (c == '\r' || c == ' ' || c == '\t')
2158 if (c == '\n' || c == '/') {
2160 ReadSingleLineComment ();
2163 // Disable/Restore all warnings
2166 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2168 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2172 // Disable/Restore a warning or group of warnings
2176 code = TokenizePragmaNumber (ref c);
2179 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2181 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2184 } while (code >= 0 && c != '\n');
2191 Report.Warning (1634, 1, Location, "Expected disable or restore");
2198 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2199 if (c != ' ' || !ParsePragmaChecksum ()) {
2200 Report.Warning (1695, 1, Location,
2201 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2207 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2210 bool eval_val (string s)
2217 return file_name.IsConditionalDefined (s);
2220 bool pp_primary (ref string s)
2229 s = s.Substring (1);
2230 bool val = pp_expr (ref s, false);
2231 if (s.Length > 0 && s [0] == ')'){
2232 s = s.Substring (1);
2235 Error_InvalidDirective ();
2239 if (is_identifier_start_character (c)){
2245 if (is_identifier_part_character (c)){
2249 bool v = eval_val (s.Substring (0, j));
2250 s = s.Substring (j);
2253 bool vv = eval_val (s);
2258 Error_InvalidDirective ();
2262 bool pp_unary (ref string s)
2269 if (len > 1 && s [1] == '='){
2270 Error_InvalidDirective ();
2273 s = s.Substring (1);
2274 return ! pp_primary (ref s);
2276 return pp_primary (ref s);
2278 Error_InvalidDirective ();
2283 bool pp_eq (ref string s)
2285 bool va = pp_unary (ref s);
2291 if (len > 2 && s [1] == '='){
2292 s = s.Substring (2);
2293 return va == pp_unary (ref s);
2295 Error_InvalidDirective ();
2298 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2299 s = s.Substring (2);
2301 return va != pp_unary (ref s);
2310 bool pp_and (ref string s)
2312 bool va = pp_eq (ref s);
2318 if (len > 2 && s [1] == '&'){
2319 s = s.Substring (2);
2320 return (va & pp_and (ref s));
2322 Error_InvalidDirective ();
2331 // Evaluates an expression for `#if' or `#elif'
2333 bool pp_expr (ref string s, bool isTerm)
2335 bool va = pp_and (ref s);
2342 if (len > 2 && s [1] == '|'){
2343 s = s.Substring (2);
2344 return va | pp_expr (ref s, isTerm);
2346 Error_InvalidDirective ();
2351 Error_EndLineExpected ();
2359 bool eval (string s)
2361 bool v = pp_expr (ref s, true);
2370 void Error_NumericConstantTooLong ()
2372 Report.Error (1021, Location, "Integral constant is too large");
2375 void Error_InvalidDirective ()
2377 Report.Error (1517, Location, "Invalid preprocessor directive");
2380 void Error_UnexpectedDirective (string extra)
2384 "Unexpected processor directive ({0})", extra);
2387 void Error_TokensSeen ()
2389 Report.Error (1032, Location,
2390 "Cannot define or undefine preprocessor symbols after first token in file");
2393 void Eror_WrongPreprocessorLocation ()
2395 Report.Error (1040, Location,
2396 "Preprocessor directives must appear as the first non-whitespace character on a line");
2399 void Error_EndLineExpected ()
2401 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2405 // if true, then the code continues processing the code
2406 // if false, the code stays in a loop until another directive is
2408 // When caller_is_taking is false we ignore all directives except the ones
2409 // which can help us to identify where the #if block ends
2410 bool ParsePreprocessingDirective (bool caller_is_taking)
2413 bool region_directive = false;
2415 var directive = get_cmd_arg (out arg);
2418 // The first group of pre-processing instructions is always processed
2420 switch (directive) {
2421 case PreprocessorDirective.Region:
2422 region_directive = true;
2424 goto case PreprocessorDirective.If;
2426 case PreprocessorDirective.Endregion:
2427 if (ifstack == null || ifstack.Count == 0){
2428 Error_UnexpectedDirective ("no #region for this #endregion");
2431 int pop = ifstack.Pop ();
2433 if ((pop & REGION) == 0)
2434 Report.Error (1027, Location, "Expected `#endif' directive");
2436 return caller_is_taking;
2438 case PreprocessorDirective.If:
2439 if (ifstack == null)
2440 ifstack = new Stack<int> (2);
2442 int flags = region_directive ? REGION : 0;
2443 if (ifstack.Count == 0){
2444 flags |= PARENT_TAKING;
2446 int state = ifstack.Peek ();
2447 if ((state & TAKING) != 0) {
2448 flags |= PARENT_TAKING;
2452 if (caller_is_taking && eval (arg)) {
2453 ifstack.Push (flags | TAKING);
2456 ifstack.Push (flags);
2459 case PreprocessorDirective.Endif:
2460 if (ifstack == null || ifstack.Count == 0){
2461 Error_UnexpectedDirective ("no #if for this #endif");
2464 pop = ifstack.Pop ();
2466 if ((pop & REGION) != 0)
2467 Report.Error (1038, Location, "#endregion directive expected");
2469 if (arg.Length != 0) {
2470 Error_EndLineExpected ();
2473 if (ifstack.Count == 0)
2476 int state = ifstack.Peek ();
2477 return (state & TAKING) != 0;
2480 case PreprocessorDirective.Elif:
2481 if (ifstack == null || ifstack.Count == 0){
2482 Error_UnexpectedDirective ("no #if for this #elif");
2485 int state = ifstack.Pop ();
2487 if ((state & REGION) != 0) {
2488 Report.Error (1038, Location, "#endregion directive expected");
2492 if ((state & ELSE_SEEN) != 0){
2493 Error_UnexpectedDirective ("#elif not valid after #else");
2497 if ((state & TAKING) != 0) {
2502 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2503 ifstack.Push (state | TAKING);
2507 ifstack.Push (state);
2511 case PreprocessorDirective.Else:
2512 if (ifstack == null || ifstack.Count == 0){
2513 Error_UnexpectedDirective ("no #if for this #else");
2516 int state = ifstack.Peek ();
2518 if ((state & REGION) != 0) {
2519 Report.Error (1038, Location, "#endregion directive expected");
2523 if ((state & ELSE_SEEN) != 0){
2524 Error_UnexpectedDirective ("#else within #else");
2530 if (arg.Length != 0) {
2531 Error_EndLineExpected ();
2536 if ((state & PARENT_TAKING) != 0) {
2537 ret = (state & TAKING) == 0;
2545 ifstack.Push (state | ELSE_SEEN);
2549 case PreprocessorDirective.Define:
2550 if (any_token_seen){
2551 Error_TokensSeen ();
2552 return caller_is_taking;
2554 PreProcessDefinition (true, arg, caller_is_taking);
2555 return caller_is_taking;
2557 case PreprocessorDirective.Undef:
2558 if (any_token_seen){
2559 Error_TokensSeen ();
2560 return caller_is_taking;
2562 PreProcessDefinition (false, arg, caller_is_taking);
2563 return caller_is_taking;
2565 case PreprocessorDirective.Invalid:
2566 Report.Error (1024, Location, "Wrong preprocessor directive");
2571 // These are only processed if we are in a `taking' block
2573 if (!caller_is_taking)
2577 case PreprocessorDirective.Error:
2578 Report.Error (1029, Location, "#error: '{0}'", arg);
2581 case PreprocessorDirective.Warning:
2582 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2585 case PreprocessorDirective.Pragma:
2586 if (RootContext.Version == LanguageVersion.ISO_1) {
2587 Report.FeatureIsNotAvailable (Location, "#pragma");
2590 ParsePragmaDirective (arg);
2593 case PreprocessorDirective.Line:
2594 if (!PreProcessLine (arg))
2597 "The line number specified for #line directive is missing or invalid");
2598 return caller_is_taking;
2601 throw new NotImplementedException (directive.ToString ());
2604 private int consume_string (bool quoted)
2607 string_builder.Length = 0;
2612 if (quoted && peek_char () == '"') {
2613 string_builder.Append ((char) c);
2618 val = new StringLiteral (string_builder.ToString (), Location);
2619 return Token.LITERAL;
2624 Report.Error (1010, Location, "Newline in constant");
2625 } else if (c == '\\' && !quoted) {
2627 c = escape (c, out surrogate);
2630 if (surrogate != 0) {
2631 string_builder.Append ((char) c);
2634 } else if (c == -1) {
2635 Report.Error (1039, Location, "Unterminated string literal");
2639 string_builder.Append ((char) c);
2643 private int consume_identifier (int s)
2645 int res = consume_identifier (s, false);
2647 if (doc_state == XmlCommentState.Allowed)
2648 doc_state = XmlCommentState.NotAllowed;
2653 int consume_identifier (int c, bool quoted)
2656 // This method is very performance sensitive. It accounts
2657 // for approximately 25% of all parser time
2665 c = escape (c, out surrogate);
2666 if (surrogate != 0) {
2667 id_builder [pos++] = (char) c;
2672 id_builder [pos++] = (char) c;
2678 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2679 id_builder [pos++] = (char) c;
2686 c = escape (c, out surrogate);
2687 if (surrogate != 0) {
2688 if (is_identifier_part_character ((char) c))
2689 id_builder[pos++] = (char) c;
2695 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2696 id_builder [pos++] = (char) c;
2703 } catch (IndexOutOfRangeException) {
2704 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2712 // Optimization: avoids doing the keyword lookup
2713 // on uppercase letters
2715 if (id_builder [0] >= '_' && !quoted) {
2716 int keyword = GetKeyword (id_builder, pos);
2717 if (keyword != -1) {
2718 val = LocatedToken.Create (null, ref_line, column);
2724 // Keep identifiers in an array of hashtables to avoid needless
2727 var identifiers_group = identifiers [pos];
2729 if (identifiers_group != null) {
2730 if (identifiers_group.TryGetValue (id_builder, out s)) {
2731 val = LocatedToken.Create (s, ref_line, column);
2733 AddEscapedIdentifier (((LocatedToken) val).Location);
2734 return Token.IDENTIFIER;
2737 // TODO: this should be number of files dependant
2738 // corlib compilation peaks at 1000 and System.Core at 150
2739 int capacity = pos > 20 ? 10 : 100;
2740 identifiers_group = new Dictionary<char[],string> (capacity, new IdentifiersComparer (pos));
2741 identifiers [pos] = identifiers_group;
2744 char [] chars = new char [pos];
2745 Array.Copy (id_builder, chars, pos);
2747 s = new string (id_builder, 0, pos);
2748 identifiers_group.Add (chars, s);
2750 val = LocatedToken.Create (s, ref_line, column);
2752 AddEscapedIdentifier (((LocatedToken) val).Location);
2754 return Token.IDENTIFIER;
2757 public int xtoken ()
2761 // Whether we have seen comments on the current line
2762 bool comments_seen = false;
2763 while ((c = get_char ()) != -1) {
2766 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2774 case 0xFEFF: // Ignore BOM anywhere in the file
2777 /* This is required for compatibility with .NET
2779 if (peek_char () == 0xBB) {
2782 if (get_char () == 0xBF)
2789 if (peek_char () != '\n')
2794 any_token_seen |= tokens_seen;
2795 tokens_seen = false;
2796 comments_seen = false;
2801 return consume_identifier (c);
2804 val = LocatedToken.Create (ref_line, col);
2805 return Token.OPEN_BRACE;
2807 val = LocatedToken.Create (ref_line, col);
2808 return Token.CLOSE_BRACE;
2810 // To block doccomment inside attribute declaration.
2811 if (doc_state == XmlCommentState.Allowed)
2812 doc_state = XmlCommentState.NotAllowed;
2814 val = LocatedToken.Create (ref_line, col);
2816 if (parsing_block == 0 || lambda_arguments_parsing)
2817 return Token.OPEN_BRACKET;
2819 int next = peek_char ();
2823 return Token.OPEN_BRACKET;
2831 next = peek_token ();
2832 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2833 return Token.OPEN_BRACKET;
2835 return Token.OPEN_BRACKET_EXPR;
2837 return Token.OPEN_BRACKET_EXPR;
2840 LocatedToken.CreateOptional (ref_line, col, ref val);
2841 return Token.CLOSE_BRACKET;
2843 val = LocatedToken.Create (ref_line, col);
2845 // An expression versions of parens can appear in block context only
2847 if (parsing_block != 0 && !lambda_arguments_parsing) {
2850 // Optmize most common case where we know that parens
2853 switch (current_token) {
2854 case Token.IDENTIFIER:
2862 case Token.DELEGATE:
2863 case Token.OP_GENERICS_GT:
2864 return Token.OPEN_PARENS;
2867 // Optimize using peek
2868 int xx = peek_char ();
2875 return Token.OPEN_PARENS;
2878 lambda_arguments_parsing = true;
2880 d = TokenizeOpenParens ();
2882 lambda_arguments_parsing = false;
2886 return Token.OPEN_PARENS;
2888 LocatedToken.CreateOptional (ref_line, col, ref val);
2889 return Token.CLOSE_PARENS;
2891 LocatedToken.CreateOptional (ref_line, col, ref val);
2894 LocatedToken.CreateOptional (ref_line, col, ref val);
2895 return Token.SEMICOLON;
2897 val = LocatedToken.Create (ref_line, col);
2900 val = LocatedToken.Create (ref_line, col);
2901 return TokenizePossibleNullableType ();
2903 val = LocatedToken.Create (ref_line, col);
2904 if (parsing_generic_less_than++ > 0)
2905 return Token.OP_GENERICS_LT;
2907 return TokenizeLessThan ();
2910 val = LocatedToken.Create (ref_line, col);
2918 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2919 parsing_generic_less_than--;
2920 return Token.OP_GENERICS_GT;
2929 return Token.OP_SHIFT_RIGHT_ASSIGN;
2931 return Token.OP_SHIFT_RIGHT;
2937 val = LocatedToken.Create (ref_line, col);
2941 } else if (d == '=') {
2942 d = Token.OP_ADD_ASSIGN;
2950 val = LocatedToken.Create (ref_line, col);
2954 } else if (d == '=')
2955 d = Token.OP_SUB_ASSIGN;
2965 val = LocatedToken.Create (ref_line, col);
2966 if (peek_char () == '='){
2973 val = LocatedToken.Create (ref_line, col);
2984 return Token.ASSIGN;
2987 val = LocatedToken.Create (ref_line, col);
2991 return Token.OP_AND;
2995 return Token.OP_AND_ASSIGN;
2997 return Token.BITWISE_AND;
3000 val = LocatedToken.Create (ref_line, col);
3008 return Token.OP_OR_ASSIGN;
3010 return Token.BITWISE_OR;
3013 val = LocatedToken.Create (ref_line, col);
3014 if (peek_char () == '='){
3016 return Token.OP_MULT_ASSIGN;
3023 val = LocatedToken.Create (ref_line, col);
3025 return Token.OP_DIV_ASSIGN;
3028 // Handle double-slash comments.
3031 if (RootContext.Documentation != null && peek_char () == '/') {
3033 // Don't allow ////.
3034 if ((d = peek_char ()) != '/') {
3035 update_comment_location ();
3036 if (doc_state == XmlCommentState.Allowed)
3037 handle_one_line_xml_comment ();
3038 else if (doc_state == XmlCommentState.NotAllowed)
3039 warn_incorrect_doc_comment ();
3042 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
3044 any_token_seen |= tokens_seen;
3045 tokens_seen = false;
3046 comments_seen = false;
3048 } else if (d == '*'){
3050 bool docAppend = false;
3051 if (RootContext.Documentation != null && peek_char () == '*') {
3053 update_comment_location ();
3054 // But when it is /**/, just do nothing.
3055 if (peek_char () == '/') {
3059 if (doc_state == XmlCommentState.Allowed)
3061 else if (doc_state == XmlCommentState.NotAllowed)
3062 warn_incorrect_doc_comment ();
3065 int current_comment_start = 0;
3067 current_comment_start = xml_comment_buffer.Length;
3068 xml_comment_buffer.Append (Environment.NewLine);
3071 while ((d = get_char ()) != -1){
3072 if (d == '*' && peek_char () == '/'){
3074 comments_seen = true;
3078 xml_comment_buffer.Append ((char) d);
3081 any_token_seen |= tokens_seen;
3082 tokens_seen = false;
3084 // Reset 'comments_seen' just to be consistent.
3085 // It doesn't matter either way, here.
3087 comments_seen = false;
3091 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3094 update_formatted_doc_comment (current_comment_start);
3097 val = LocatedToken.Create (ref_line, col);
3101 val = LocatedToken.Create (ref_line, col);
3102 if (peek_char () == '='){
3104 return Token.OP_MOD_ASSIGN;
3106 return Token.PERCENT;
3109 val = LocatedToken.Create (ref_line, col);
3110 if (peek_char () == '='){
3112 return Token.OP_XOR_ASSIGN;
3114 return Token.CARRET;
3117 val = LocatedToken.Create (ref_line, col);
3118 if (peek_char () == ':') {
3120 return Token.DOUBLE_COLON;
3124 case '0': case '1': case '2': case '3': case '4':
3125 case '5': case '6': case '7': case '8': case '9':
3127 return is_number (c);
3129 case '\n': // white space
3130 any_token_seen |= tokens_seen;
3131 tokens_seen = false;
3132 comments_seen = false;
3138 if (d >= '0' && d <= '9')
3139 return is_number (c);
3141 LocatedToken.CreateOptional (ref_line, col, ref val);
3145 if (tokens_seen || comments_seen) {
3146 Eror_WrongPreprocessorLocation ();
3150 if (ParsePreprocessingDirective (true))
3153 bool directive_expected = false;
3154 while ((c = get_char ()) != -1) {
3156 directive_expected = true;
3157 } else if (!directive_expected) {
3158 // TODO: Implement comment support for disabled code and uncomment this code
3160 // Eror_WrongPreprocessorLocation ();
3161 // return Token.ERROR;
3166 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
3170 if (ParsePreprocessingDirective (false))
3173 directive_expected = false;
3177 tokens_seen = false;
3184 return consume_string (false);
3187 return TokenizeBackslash ();
3193 return consume_string (true);
3196 if (is_identifier_start_character (c)){
3197 return consume_identifier (c, true);
3200 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3203 case EvalStatementParserCharacter:
3204 return Token.EVAL_STATEMENT_PARSER;
3205 case EvalCompilationUnitParserCharacter:
3206 return Token.EVAL_COMPILATION_UNIT_PARSER;
3207 case EvalUsingDeclarationsParserCharacter:
3208 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3211 if (is_identifier_start_character (c)) {
3213 return consume_identifier (c);
3216 error_details = ((char)c).ToString ();
3222 return Token.COMPLETE_COMPLETION;
3225 return Token.GENERATE_COMPLETION;
3232 int TokenizeBackslash ()
3234 int c = get_char ();
3237 error_details = "Empty character literal";
3238 Report.Error (1011, Location, error_details);
3241 if (c == '\r' || c == '\n') {
3242 Report.Error (1010, Location, "Newline in constant");
3247 c = escape (c, out d);
3251 throw new NotImplementedException ();
3253 val = new CharLiteral ((char) c, Location);
3257 Report.Error (1012, Location, "Too many characters in character literal");
3259 // Try to recover, read until newline or next "'"
3260 while ((c = get_char ()) != -1) {
3261 if (c == '\n' || c == '\'')
3267 return Token.LITERAL;
3270 int TokenizeLessThan ()
3273 if (handle_typeof) {
3275 if (parse_generic_dimension (out d)) {
3278 return Token.GENERIC_DIMENSION;
3283 // Save current position and parse next token.
3285 if (parse_less_than ()) {
3286 if (parsing_generic_declaration && token () != Token.DOT) {
3287 d = Token.OP_GENERICS_LT_DECL;
3289 d = Token.OP_GENERICS_LT;
3296 parsing_generic_less_than = 0;
3305 return Token.OP_SHIFT_LEFT_ASSIGN;
3307 return Token.OP_SHIFT_LEFT;
3318 // Handles one line xml comment
3320 private void handle_one_line_xml_comment ()
3323 while ((c = peek_char ()) == ' ')
3324 get_char (); // skip heading whitespaces.
3325 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3326 xml_comment_buffer.Append ((char) get_char ());
3328 if (c == '\r' || c == '\n')
3329 xml_comment_buffer.Append (Environment.NewLine);
3333 // Remove heading "*" in Javadoc-like xml documentation.
3335 private void update_formatted_doc_comment (int current_comment_start)
3337 int length = xml_comment_buffer.Length - current_comment_start;
3338 string [] lines = xml_comment_buffer.ToString (
3339 current_comment_start,
3340 length).Replace ("\r", "").Split ('\n');
3342 // The first line starts with /**, thus it is not target
3343 // for the format check.
3344 for (int i = 1; i < lines.Length; i++) {
3345 string s = lines [i];
3346 int idx = s.IndexOf ('*');
3349 if (i < lines.Length - 1)
3353 head = s.Substring (0, idx);
3354 foreach (char c in head)
3357 lines [i] = s.Substring (idx + 1);
3359 xml_comment_buffer.Remove (current_comment_start, length);
3360 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3364 // Updates current comment location.
3366 private void update_comment_location ()
3368 if (current_comment_location.IsNull) {
3369 // "-2" is for heading "//" or "/*"
3370 current_comment_location =
3371 new Location (ref_line, hidden ? -1 : col - 2);
3376 // Checks if there was incorrect doc comments and raise
3379 public void check_incorrect_doc_comment ()
3381 if (xml_comment_buffer.Length > 0)
3382 warn_incorrect_doc_comment ();
3386 // Raises a warning when tokenizer found incorrect doccomment
3389 private void warn_incorrect_doc_comment ()
3391 if (doc_state != XmlCommentState.Error) {
3392 doc_state = XmlCommentState.Error;
3393 // in csc, it is 'XML comment is not placed on
3394 // a valid language element'. But that does not
3396 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3401 // Consumes the saved xml comment lines (if any)
3402 // as for current target member or type.
3404 public string consume_doc_comment ()
3406 if (xml_comment_buffer.Length > 0) {
3407 string ret = xml_comment_buffer.ToString ();
3408 reset_doc_comment ();
3415 get { return context.Report; }
3418 void reset_doc_comment ()
3420 xml_comment_buffer.Length = 0;
3421 current_comment_location = Location.Null;
3424 public void cleanup ()
3426 if (ifstack != null && ifstack.Count >= 1) {
3427 int state = ifstack.Pop ();
3428 if ((state & REGION) != 0)
3429 Report.Error (1038, Location, "#endregion directive expected");
3431 Report.Error (1027, Location, "Expected `#endif' directive");
3437 // Indicates whether it accepts XML documentation or not.
3439 public enum XmlCommentState {
3440 // comment is allowed in this state.
3442 // comment is not allowed in this state.
3444 // once comments appeared when it is NotAllowed, then the
3445 // state is changed to it, until the state is changed to