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 ();
365 // This is used when the tokenizer needs to save
366 // the current position as it needs to do some parsing
367 // on its own to deamiguate a token in behalf of the
370 Stack<Position> position_stack = new Stack<Position> (2);
378 public int putback_char;
379 public int previous_col;
380 public Stack<int> ifstack;
381 public int parsing_generic_less_than;
382 public int current_token;
385 public Position (Tokenizer t)
387 position = t.reader.Position;
389 ref_line = t.ref_line;
392 putback_char = t.putback_char;
393 previous_col = t.previous_col;
394 if (t.ifstack != null && t.ifstack.Count != 0) {
395 // There is no simple way to clone Stack<T> all
396 // methods reverse the order
397 var clone = t.ifstack.ToArray ();
398 Array.Reverse (clone);
399 ifstack = new Stack<int> (clone);
401 parsing_generic_less_than = t.parsing_generic_less_than;
402 current_token = t.current_token;
407 public void PushPosition ()
409 position_stack.Push (new Position (this));
412 public void PopPosition ()
414 Position p = position_stack.Pop ();
416 reader.Position = p.position;
417 ref_line = p.ref_line;
421 putback_char = p.putback_char;
422 previous_col = p.previous_col;
424 parsing_generic_less_than = p.parsing_generic_less_than;
425 current_token = p.current_token;
429 // Do not reset the position, ignore it.
430 public void DiscardPosition ()
432 position_stack.Pop ();
435 static void AddKeyword (string kw, int token)
437 keyword_strings.Add (kw, null);
439 AddKeyword (keywords, kw, token);
442 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
444 AddKeyword (keywords_preprocessor, kw, directive);
447 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
449 int length = kw.Length;
450 if (keywords[length] == null) {
451 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
454 int char_index = kw[0] - '_';
455 var kwe = keywords[length][char_index];
457 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
461 while (kwe.Next != null) {
465 kwe.Next = new KeywordEntry<T> (kw, token);
468 static void InitTokens ()
470 keyword_strings = new Dictionary<string, object> ();
472 // 11 is the length of the longest keyword for now
473 keywords = new KeywordEntry<int> [11] [];
475 AddKeyword ("__arglist", Token.ARGLIST);
476 AddKeyword ("abstract", Token.ABSTRACT);
477 AddKeyword ("as", Token.AS);
478 AddKeyword ("add", Token.ADD);
479 AddKeyword ("base", Token.BASE);
480 AddKeyword ("bool", Token.BOOL);
481 AddKeyword ("break", Token.BREAK);
482 AddKeyword ("byte", Token.BYTE);
483 AddKeyword ("case", Token.CASE);
484 AddKeyword ("catch", Token.CATCH);
485 AddKeyword ("char", Token.CHAR);
486 AddKeyword ("checked", Token.CHECKED);
487 AddKeyword ("class", Token.CLASS);
488 AddKeyword ("const", Token.CONST);
489 AddKeyword ("continue", Token.CONTINUE);
490 AddKeyword ("decimal", Token.DECIMAL);
491 AddKeyword ("default", Token.DEFAULT);
492 AddKeyword ("delegate", Token.DELEGATE);
493 AddKeyword ("do", Token.DO);
494 AddKeyword ("double", Token.DOUBLE);
495 AddKeyword ("else", Token.ELSE);
496 AddKeyword ("enum", Token.ENUM);
497 AddKeyword ("event", Token.EVENT);
498 AddKeyword ("explicit", Token.EXPLICIT);
499 AddKeyword ("extern", Token.EXTERN);
500 AddKeyword ("false", Token.FALSE);
501 AddKeyword ("finally", Token.FINALLY);
502 AddKeyword ("fixed", Token.FIXED);
503 AddKeyword ("float", Token.FLOAT);
504 AddKeyword ("for", Token.FOR);
505 AddKeyword ("foreach", Token.FOREACH);
506 AddKeyword ("goto", Token.GOTO);
507 AddKeyword ("get", Token.GET);
508 AddKeyword ("if", Token.IF);
509 AddKeyword ("implicit", Token.IMPLICIT);
510 AddKeyword ("in", Token.IN);
511 AddKeyword ("int", Token.INT);
512 AddKeyword ("interface", Token.INTERFACE);
513 AddKeyword ("internal", Token.INTERNAL);
514 AddKeyword ("is", Token.IS);
515 AddKeyword ("lock", Token.LOCK);
516 AddKeyword ("long", Token.LONG);
517 AddKeyword ("namespace", Token.NAMESPACE);
518 AddKeyword ("new", Token.NEW);
519 AddKeyword ("null", Token.NULL);
520 AddKeyword ("object", Token.OBJECT);
521 AddKeyword ("operator", Token.OPERATOR);
522 AddKeyword ("out", Token.OUT);
523 AddKeyword ("override", Token.OVERRIDE);
524 AddKeyword ("params", Token.PARAMS);
525 AddKeyword ("private", Token.PRIVATE);
526 AddKeyword ("protected", Token.PROTECTED);
527 AddKeyword ("public", Token.PUBLIC);
528 AddKeyword ("readonly", Token.READONLY);
529 AddKeyword ("ref", Token.REF);
530 AddKeyword ("remove", Token.REMOVE);
531 AddKeyword ("return", Token.RETURN);
532 AddKeyword ("sbyte", Token.SBYTE);
533 AddKeyword ("sealed", Token.SEALED);
534 AddKeyword ("set", Token.SET);
535 AddKeyword ("short", Token.SHORT);
536 AddKeyword ("sizeof", Token.SIZEOF);
537 AddKeyword ("stackalloc", Token.STACKALLOC);
538 AddKeyword ("static", Token.STATIC);
539 AddKeyword ("string", Token.STRING);
540 AddKeyword ("struct", Token.STRUCT);
541 AddKeyword ("switch", Token.SWITCH);
542 AddKeyword ("this", Token.THIS);
543 AddKeyword ("throw", Token.THROW);
544 AddKeyword ("true", Token.TRUE);
545 AddKeyword ("try", Token.TRY);
546 AddKeyword ("typeof", Token.TYPEOF);
547 AddKeyword ("uint", Token.UINT);
548 AddKeyword ("ulong", Token.ULONG);
549 AddKeyword ("unchecked", Token.UNCHECKED);
550 AddKeyword ("unsafe", Token.UNSAFE);
551 AddKeyword ("ushort", Token.USHORT);
552 AddKeyword ("using", Token.USING);
553 AddKeyword ("virtual", Token.VIRTUAL);
554 AddKeyword ("void", Token.VOID);
555 AddKeyword ("volatile", Token.VOLATILE);
556 AddKeyword ("while", Token.WHILE);
557 AddKeyword ("partial", Token.PARTIAL);
558 AddKeyword ("where", Token.WHERE);
561 AddKeyword ("from", Token.FROM);
562 AddKeyword ("join", Token.JOIN);
563 AddKeyword ("on", Token.ON);
564 AddKeyword ("equals", Token.EQUALS);
565 AddKeyword ("select", Token.SELECT);
566 AddKeyword ("group", Token.GROUP);
567 AddKeyword ("by", Token.BY);
568 AddKeyword ("let", Token.LET);
569 AddKeyword ("orderby", Token.ORDERBY);
570 AddKeyword ("ascending", Token.ASCENDING);
571 AddKeyword ("descending", Token.DESCENDING);
572 AddKeyword ("into", Token.INTO);
574 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
576 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
577 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
578 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
579 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
580 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
581 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
582 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
583 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
584 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
585 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
586 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
587 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
596 csharp_format_info = NumberFormatInfo.InvariantInfo;
597 styles = NumberStyles.Float;
599 string_builder = new System.Text.StringBuilder ();
602 int GetKeyword (char[] id, int id_len)
605 // Keywords are stored in an array of arrays grouped by their
606 // length and then by the first character
608 if (id_len >= keywords.Length || keywords [id_len] == null)
611 int first_index = id [0] - '_';
612 if (first_index > 'z' - '_')
615 var kwe = keywords [id_len] [first_index];
622 for (int i = 1; i < id_len; ++i) {
623 if (id [i] != kwe.Value [i]) {
629 } while (res == 0 && kwe != null);
643 if (!handle_remove_add)
647 if (parsing_declaration == 0)
648 res = Token.EXTERN_ALIAS;
651 if (peek_token () == Token.COLON) {
653 res = Token.DEFAULT_COLON;
657 if (!handle_where && !query_parsing)
662 // A query expression is any expression that starts with `from identifier'
663 // followed by any token except ; , =
665 if (!query_parsing) {
666 if (lambda_arguments_parsing) {
672 // HACK: to disable generics micro-parser, because PushPosition does not
673 // store identifiers array
674 parsing_generic_less_than = 1;
676 case Token.IDENTIFIER:
688 next_token = xtoken ();
689 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
692 res = Token.FROM_FIRST;
693 query_parsing = true;
694 if (RootContext.Version <= LanguageVersion.ISO_2)
695 Report.FeatureIsNotAvailable (Location, "query expressions");
698 Expression.Error_VoidInvalidInTheContext (Location, Report);
702 // HACK: A token is not a keyword so we need to restore identifiers buffer
703 // which has been overwritten before we grabbed the identifier
704 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
718 case Token.ASCENDING:
719 case Token.DESCENDING:
726 case Token.NAMESPACE:
727 // TODO: some explanation needed
728 check_incorrect_doc_comment ();
732 if (parsing_block > 0) {
737 // Save current position and parse next token.
740 next_token = token ();
741 bool ok = (next_token == Token.CLASS) ||
742 (next_token == Token.STRUCT) ||
743 (next_token == Token.INTERFACE) ||
744 (next_token == Token.VOID);
749 if (next_token == Token.VOID) {
750 if (RootContext.Version == LanguageVersion.ISO_1 ||
751 RootContext.Version == LanguageVersion.ISO_2)
752 Report.FeatureIsNotAvailable (Location, "partial methods");
753 } else if (RootContext.Version == LanguageVersion.ISO_1)
754 Report.FeatureIsNotAvailable (Location, "partial types");
759 if (next_token < Token.LAST_KEYWORD) {
760 Report.Error (267, Location,
761 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
772 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
775 // Keywords are stored in an array of arrays grouped by their
776 // length and then by the first character
778 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
779 return PreprocessorDirective.Invalid;
781 int first_index = id[0] - '_';
782 if (first_index > 'z' - '_')
783 return PreprocessorDirective.Invalid;
785 var kwe = keywords_preprocessor[id_len][first_index];
787 return PreprocessorDirective.Invalid;
789 PreprocessorDirective res = PreprocessorDirective.Invalid;
792 for (int i = 1; i < id_len; ++i) {
793 if (id[i] != kwe.Value[i]) {
799 } while (res == PreprocessorDirective.Invalid && kwe != null);
804 public Location Location {
806 return new Location (ref_line, hidden ? -1 : col);
810 public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
812 this.ref_name = file;
813 this.file_name = file;
819 xml_comment_buffer = new StringBuilder ();
821 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
827 // FIXME: This could be `Location.Push' but we have to
828 // find out why the MS compiler allows this
830 Mono.CSharp.Location.Push (file, file);
833 static bool is_identifier_start_character (int c)
835 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
838 static bool is_identifier_part_character (char c)
840 if (c >= 'a' && c <= 'z')
843 if (c >= 'A' && c <= 'Z')
846 if (c == '_' || (c >= '0' && c <= '9'))
852 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
855 public static bool IsKeyword (string s)
857 return keyword_strings.ContainsKey (s);
861 // Open parens micro parser. Detects both lambda and cast ambiguity.
863 int TokenizeOpenParens ()
868 int bracket_level = 0;
869 bool is_type = false;
870 bool can_be_type = false;
873 ptoken = current_token;
876 switch (current_token) {
877 case Token.CLOSE_PARENS:
881 // Expression inside parens is lambda, (int i) =>
883 if (current_token == Token.ARROW)
884 return Token.OPEN_PARENS_LAMBDA;
887 // Expression inside parens is single type, (int[])
890 return Token.OPEN_PARENS_CAST;
893 // Expression is possible cast, look at next token, (T)null
896 switch (current_token) {
897 case Token.OPEN_PARENS:
900 case Token.IDENTIFIER:
914 case Token.UNCHECKED:
919 // These can be part of a member access
933 return Token.OPEN_PARENS_CAST;
936 return Token.OPEN_PARENS;
939 case Token.DOUBLE_COLON:
940 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
945 case Token.IDENTIFIER:
948 if (bracket_level == 0) {
954 case Token.OP_GENERICS_LT:
956 case Token.DOUBLE_COLON:
958 if (bracket_level == 0)
962 can_be_type = is_type = false;
982 if (bracket_level == 0)
987 if (bracket_level == 0) {
989 can_be_type = is_type = false;
993 case Token.OP_GENERICS_LT:
994 case Token.OPEN_BRACKET:
995 if (bracket_level++ == 0)
999 case Token.OP_GENERICS_GT:
1000 case Token.CLOSE_BRACKET:
1004 case Token.INTERR_NULLABLE:
1006 if (bracket_level == 0)
1012 can_be_type = is_type = false;
1016 return Token.OPEN_PARENS;
1021 public static bool IsValidIdentifier (string s)
1023 if (s == null || s.Length == 0)
1026 if (!is_identifier_start_character (s [0]))
1029 for (int i = 1; i < s.Length; i ++)
1030 if (! is_identifier_part_character (s [i]))
1036 bool parse_less_than ()
1039 int the_token = token ();
1040 if (the_token == Token.OPEN_BRACKET) {
1042 the_token = token ();
1043 } while (the_token != Token.CLOSE_BRACKET);
1044 the_token = token ();
1045 } else if (the_token == Token.IN || the_token == Token.OUT) {
1046 the_token = token ();
1048 switch (the_token) {
1049 case Token.IDENTIFIER:
1067 case Token.OP_GENERICS_GT:
1074 the_token = token ();
1076 if (the_token == Token.OP_GENERICS_GT)
1078 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1080 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1082 else if (the_token == Token.OP_GENERICS_LT) {
1083 if (!parse_less_than ())
1086 } else if (the_token == Token.OPEN_BRACKET) {
1088 the_token = token ();
1089 if (the_token == Token.CLOSE_BRACKET)
1091 else if (the_token == Token.COMMA)
1092 goto rank_specifiers;
1099 bool parse_generic_dimension (out int dimension)
1104 int the_token = token ();
1105 if (the_token == Token.OP_GENERICS_GT)
1107 else if (the_token == Token.COMMA) {
1115 public int peek_token ()
1120 the_token = token ();
1127 // Tonizes `?' using custom disambiguous rules to return one
1128 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1130 // Tricky expression look like:
1132 // Foo ? a = x ? b : c;
1134 int TokenizePossibleNullableType ()
1136 if (parsing_block == 0 || parsing_type > 0)
1137 return Token.INTERR_NULLABLE;
1139 int d = peek_char ();
1142 return Token.OP_COALESCING;
1145 switch (current_token) {
1146 case Token.CLOSE_PARENS:
1151 return Token.INTERR;
1155 if (d == ',' || d == ';' || d == '>')
1156 return Token.INTERR_NULLABLE;
1157 if (d == '*' || (d >= '0' && d <= '9'))
1158 return Token.INTERR;
1162 current_token = Token.NONE;
1164 switch (xtoken ()) {
1171 next_token = Token.INTERR;
1174 case Token.SEMICOLON:
1176 case Token.CLOSE_PARENS:
1177 case Token.OPEN_BRACKET:
1178 case Token.OP_GENERICS_GT:
1179 next_token = Token.INTERR_NULLABLE;
1187 if (next_token == -1) {
1188 switch (xtoken ()) {
1190 case Token.SEMICOLON:
1191 case Token.OPEN_BRACE:
1192 case Token.CLOSE_PARENS:
1194 next_token = Token.INTERR_NULLABLE;
1198 next_token = Token.INTERR;
1206 // All shorcuts failed, do it hard way
1208 while ((ntoken = xtoken ()) != Token.EOF) {
1209 if (ntoken == Token.SEMICOLON)
1212 if (ntoken == Token.COLON) {
1213 if (++colons == interrs)
1218 if (ntoken == Token.INTERR) {
1224 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1233 bool decimal_digits (int c)
1236 bool seen_digits = false;
1239 if (number_pos == max_number_size)
1240 Error_NumericConstantTooLong ();
1241 number_builder [number_pos++] = (char) c;
1245 // We use peek_char2, because decimal_digits needs to do a
1246 // 2-character look-ahead (5.ToString for example).
1248 while ((d = peek_char2 ()) != -1){
1249 if (d >= '0' && d <= '9'){
1250 if (number_pos == max_number_size)
1251 Error_NumericConstantTooLong ();
1252 number_builder [number_pos++] = (char) d;
1262 static bool is_hex (int e)
1264 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1267 static TypeCode real_type_suffix (int c)
1271 return TypeCode.Single;
1273 return TypeCode.Double;
1275 return TypeCode.Decimal;
1277 return TypeCode.Empty;
1281 int integer_type_suffix (ulong ul, int c)
1283 bool is_unsigned = false;
1284 bool is_long = false;
1287 bool scanning = true;
1300 // if we have not seen anything in between
1301 // report this error
1303 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1323 if (is_long && is_unsigned){
1324 val = new ULongLiteral (ul, Location);
1325 return Token.LITERAL;
1329 // uint if possible, or ulong else.
1331 if ((ul & 0xffffffff00000000) == 0)
1332 val = new UIntLiteral ((uint) ul, Location);
1334 val = new ULongLiteral (ul, Location);
1335 } else if (is_long){
1336 // long if possible, ulong otherwise
1337 if ((ul & 0x8000000000000000) != 0)
1338 val = new ULongLiteral (ul, Location);
1340 val = new LongLiteral ((long) ul, Location);
1342 // int, uint, long or ulong in that order
1343 if ((ul & 0xffffffff00000000) == 0){
1344 uint ui = (uint) ul;
1346 if ((ui & 0x80000000) != 0)
1347 val = new UIntLiteral (ui, Location);
1349 val = new IntLiteral ((int) ui, Location);
1351 if ((ul & 0x8000000000000000) != 0)
1352 val = new ULongLiteral (ul, Location);
1354 val = new LongLiteral ((long) ul, Location);
1357 return Token.LITERAL;
1361 // given `c' as the next char in the input decide whether
1362 // we need to convert to a special type, and then choose
1363 // the best representation for the integer
1365 int adjust_int (int c)
1368 if (number_pos > 9){
1369 ulong ul = (uint) (number_builder [0] - '0');
1371 for (int i = 1; i < number_pos; i++){
1372 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1374 return integer_type_suffix (ul, c);
1376 uint ui = (uint) (number_builder [0] - '0');
1378 for (int i = 1; i < number_pos; i++){
1379 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1381 return integer_type_suffix (ui, c);
1383 } catch (OverflowException) {
1384 Error_NumericConstantTooLong ();
1385 val = new IntLiteral (0, Location);
1386 return Token.LITERAL;
1388 catch (FormatException) {
1389 Report.Error (1013, Location, "Invalid number");
1390 val = new IntLiteral (0, Location);
1391 return Token.LITERAL;
1395 int adjust_real (TypeCode t)
1397 string s = new String (number_builder, 0, number_pos);
1398 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1401 case TypeCode.Decimal:
1403 val = new DecimalLiteral (decimal.Parse (s, styles, csharp_format_info), Location);
1404 } catch (OverflowException) {
1405 val = new DecimalLiteral (0, Location);
1406 Report.Error (594, Location, error_details, "decimal");
1409 case TypeCode.Single:
1411 val = new FloatLiteral (float.Parse (s, styles, csharp_format_info), Location);
1412 } catch (OverflowException) {
1413 val = new FloatLiteral (0, Location);
1414 Report.Error (594, Location, error_details, "float");
1419 val = new DoubleLiteral (double.Parse (s, styles, csharp_format_info), Location);
1420 } catch (OverflowException) {
1421 val = new DoubleLiteral (0, Location);
1422 Report.Error (594, Location, error_details, "double");
1427 return Token.LITERAL;
1436 while ((d = peek_char ()) != -1){
1438 number_builder [number_pos++] = (char) d;
1444 string s = new String (number_builder, 0, number_pos);
1446 if (number_pos <= 8)
1447 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1449 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1450 } catch (OverflowException){
1451 Error_NumericConstantTooLong ();
1452 val = new IntLiteral (0, Location);
1453 return Token.LITERAL;
1455 catch (FormatException) {
1456 Report.Error (1013, Location, "Invalid number");
1457 val = new IntLiteral (0, Location);
1458 return Token.LITERAL;
1461 return integer_type_suffix (ul, peek_char ());
1465 // Invoked if we know we have .digits or digits
1467 int is_number (int c)
1469 bool is_real = false;
1473 if (c >= '0' && c <= '9'){
1475 int peek = peek_char ();
1477 if (peek == 'x' || peek == 'X')
1478 return handle_hex ();
1485 // We need to handle the case of
1486 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1489 if (decimal_digits ('.')){
1495 return adjust_int (-1);
1499 if (c == 'e' || c == 'E'){
1501 if (number_pos == max_number_size)
1502 Error_NumericConstantTooLong ();
1503 number_builder [number_pos++] = 'e';
1507 if (number_pos == max_number_size)
1508 Error_NumericConstantTooLong ();
1509 number_builder [number_pos++] = '+';
1511 } else if (c == '-') {
1512 if (number_pos == max_number_size)
1513 Error_NumericConstantTooLong ();
1514 number_builder [number_pos++] = '-';
1517 if (number_pos == max_number_size)
1518 Error_NumericConstantTooLong ();
1519 number_builder [number_pos++] = '+';
1526 var type = real_type_suffix (c);
1527 if (type == TypeCode.Empty && !is_real){
1529 return adjust_int (c);
1534 if (type == TypeCode.Empty){
1539 return adjust_real (type);
1541 throw new Exception ("Is Number should never reach this point");
1545 // Accepts exactly count (4 or 8) hex, no more no less
1547 int getHex (int count, out int surrogate, out bool error)
1552 int top = count != -1 ? count : 4;
1557 for (i = 0; i < top; i++){
1560 if (c >= '0' && c <= '9')
1561 c = (int) c - (int) '0';
1562 else if (c >= 'A' && c <= 'F')
1563 c = (int) c - (int) 'A' + 10;
1564 else if (c >= 'a' && c <= 'f')
1565 c = (int) c - (int) 'a' + 10;
1571 total = (total * 16) + c;
1573 int p = peek_char ();
1576 if (!is_hex ((char)p))
1582 if (total > 0x0010FFFF) {
1587 if (total >= 0x00010000) {
1588 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1589 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1596 int escape (int c, out int surrogate)
1632 v = getHex (-1, out surrogate, out error);
1638 return EscapeUnicode (d, out surrogate);
1641 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1650 int EscapeUnicode (int ch, out int surrogate)
1654 ch = getHex (8, out surrogate, out error);
1656 ch = getHex (4, out surrogate, out error);
1660 Report.Error (1009, Location, "Unrecognized escape sequence");
1668 if (putback_char != -1) {
1681 void advance_line ()
1691 if (putback_char == -1)
1692 putback_char = reader.Read ();
1693 return putback_char;
1698 if (putback_char != -1)
1699 return putback_char;
1700 return reader.Peek ();
1703 void putback (int c)
1705 if (putback_char != -1){
1706 Console.WriteLine ("Col: " + col);
1707 Console.WriteLine ("Row: " + line);
1708 Console.WriteLine ("Name: " + ref_name.Name);
1709 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1710 throw new Exception ("This should not happen putback on putback");
1712 if (c == '\n' || col == 0) {
1713 // It won't happen though.
1723 public bool advance ()
1725 return peek_char () != -1 || CompleteOnEOF;
1728 public Object Value {
1734 public Object value ()
1741 current_token = xtoken ();
1742 return current_token;
1745 int TokenizePreprocessorIdentifier (out int c)
1747 // skip over white space
1750 } while (c == '\r' || c == ' ' || c == '\t');
1754 while (c != -1 && c >= 'a' && c <= 'z') {
1755 id_builder[pos++] = (char) c;
1758 int peek = peek_char ();
1759 if (peek == 'U' || peek == 'u') {
1761 c = EscapeUnicode (c, out surrogate);
1762 if (surrogate != 0) {
1763 if (is_identifier_part_character ((char) c)) {
1764 id_builder[pos++] = (char) c;
1775 PreprocessorDirective get_cmd_arg (out string arg)
1779 tokens_seen = false;
1782 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1784 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1787 // skip over white space
1788 while (c == '\r' || c == ' ' || c == '\t')
1791 static_cmd_arg.Length = 0;
1792 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1794 while (c != -1 && c != '\n' && c != '\r') {
1795 if (c == '\\' && has_identifier_argument >= 0) {
1796 if (has_identifier_argument != 0) {
1797 has_identifier_argument = 1;
1799 int peek = peek_char ();
1800 if (peek == 'U' || peek == 'u') {
1802 c = EscapeUnicode (c, out surrogate);
1803 if (surrogate != 0) {
1804 if (is_identifier_part_character ((char) c))
1805 static_cmd_arg.Append ((char) c);
1810 has_identifier_argument = -1;
1813 static_cmd_arg.Append ((char) c);
1817 if (static_cmd_arg.Length != 0) {
1818 arg = static_cmd_arg.ToString ();
1820 // Eat any trailing whitespaces and single-line comments
1821 if (arg.IndexOf ("//") != -1) {
1822 arg = arg.Substring (0, arg.IndexOf ("//"));
1825 arg = arg.Trim (simple_whitespaces);
1832 // Handles the #line directive
1834 bool PreProcessLine (string arg)
1836 if (arg.Length == 0)
1839 if (arg == "default"){
1841 ref_name = file_name;
1843 Location.Push (file_name, ref_name);
1845 } else if (arg == "hidden"){
1853 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1854 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1857 char [] quotes = { '\"' };
1859 string name = arg.Substring (pos). Trim (quotes);
1860 ref_name = Location.LookupFile (file_name, name);
1861 file_name.AddFile (ref_name);
1863 Location.Push (file_name, ref_name);
1865 ref_line = System.Int32.Parse (arg);
1876 // Handles #define and #undef
1878 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1880 if (ident.Length == 0 || ident == "true" || ident == "false"){
1881 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1885 if (ident.IndexOfAny (simple_whitespaces) != -1){
1886 Error_EndLineExpected ();
1890 if (!is_identifier_start_character (ident [0]))
1891 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1893 foreach (char c in ident.Substring (1)){
1894 if (!is_identifier_part_character (c)){
1895 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1900 if (!caller_is_taking)
1907 if (RootContext.IsConditionalDefined (ident))
1910 file_name.AddDefine (ident);
1915 file_name.AddUndefine (ident);
1919 byte read_hex (out bool error)
1922 int c = get_char ();
1924 if ((c >= '0') && (c <= '9'))
1925 total = (int) c - (int) '0';
1926 else if ((c >= 'A') && (c <= 'F'))
1927 total = (int) c - (int) 'A' + 10;
1928 else if ((c >= 'a') && (c <= 'f'))
1929 total = (int) c - (int) 'a' + 10;
1938 if ((c >= '0') && (c <= '9'))
1939 total += (int) c - (int) '0';
1940 else if ((c >= 'A') && (c <= 'F'))
1941 total += (int) c - (int) 'A' + 10;
1942 else if ((c >= 'a') && (c <= 'f'))
1943 total += (int) c - (int) 'a' + 10;
1950 return (byte) total;
1954 // Parses #pragma checksum
1956 bool ParsePragmaChecksum ()
1959 // The syntax is ` "foo.txt" "{guid}" "hash"'
1961 int c = get_char ();
1966 string_builder.Length = 0;
1967 while (c != -1 && c != '\n') {
1974 string_builder.Append ((char) c);
1977 if (string_builder.Length == 0) {
1978 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
1981 // TODO: Any white-spaces count
1985 SourceFile file = Location.LookupFile (file_name, string_builder.ToString ());
1987 if (get_char () != '"' || get_char () != '{')
1991 byte[] guid_bytes = new byte [16];
1994 for (; i < 4; i++) {
1995 guid_bytes [i] = read_hex (out error);
2000 if (get_char () != '-')
2003 for (; i < 10; i++) {
2004 guid_bytes [i] = read_hex (out error);
2008 guid_bytes [i++] = read_hex (out error);
2012 if (get_char () != '-')
2016 for (; i < 16; i++) {
2017 guid_bytes [i] = read_hex (out error);
2022 if (get_char () != '}' || get_char () != '"')
2025 // TODO: Any white-spaces count
2030 if (get_char () != '"')
2033 // Any length of checksum
2034 List<byte> checksum_bytes = new List<byte> (16);
2037 while (c != '"' && c != -1) {
2038 checksum_bytes.Add (read_hex (out error));
2046 ReadSingleLineComment ();
2047 } else if (get_char () != '"') {
2051 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2052 ref_name.AutoGenerated = true;
2056 bool IsTokenIdentifierEqual (char[] identifier)
2058 for (int i = 0; i < identifier.Length; ++i) {
2059 if (identifier[i] != id_builder[i])
2066 int TokenizePragmaNumber (ref int c)
2072 if (c >= '0' && c <= '9') {
2074 uint ui = (uint) (number_builder[0] - '0');
2077 for (int i = 1; i < number_pos; i++) {
2078 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2082 } catch (OverflowException) {
2083 Error_NumericConstantTooLong ();
2090 // skip over white space
2091 while (c == '\r' || c == ' ' || c == '\t')
2098 // skip over white space
2099 while (c == '\r' || c == ' ' || c == '\t')
2104 ReadSingleLineComment ();
2106 Report.Warning (1692, 1, Location, "Invalid number");
2108 // Read everything till the end of the line or file
2111 } while (c != -1 && c != '\n');
2118 void ReadSingleLineComment ()
2120 if (peek_char () != '/')
2121 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2123 // Read everything till the end of the line or file
2127 } while (c != -1 && c != '\n');
2131 /// Handles #pragma directive
2133 void ParsePragmaDirective (string arg)
2136 int length = TokenizePreprocessorIdentifier (out c);
2137 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2138 length = TokenizePreprocessorIdentifier (out c);
2141 // #pragma warning disable
2142 // #pragma warning restore
2144 if (length == pragma_warning_disable.Length) {
2145 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2146 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2147 // skip over white space
2148 while (c == '\r' || c == ' ' || c == '\t')
2153 if (c == '\n' || c == '/') {
2155 ReadSingleLineComment ();
2158 // Disable/Restore all warnings
2161 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2163 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2167 // Disable/Restore a warning or group of warnings
2171 code = TokenizePragmaNumber (ref c);
2174 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2176 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2179 } while (code >= 0 && c != '\n');
2186 Report.Warning (1634, 1, Location, "Expected disable or restore");
2193 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2194 if (c != ' ' || !ParsePragmaChecksum ()) {
2195 Report.Warning (1695, 1, Location,
2196 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2202 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2205 bool eval_val (string s)
2212 return file_name.IsConditionalDefined (s);
2215 bool pp_primary (ref string s)
2224 s = s.Substring (1);
2225 bool val = pp_expr (ref s, false);
2226 if (s.Length > 0 && s [0] == ')'){
2227 s = s.Substring (1);
2230 Error_InvalidDirective ();
2234 if (is_identifier_start_character (c)){
2240 if (is_identifier_part_character (c)){
2244 bool v = eval_val (s.Substring (0, j));
2245 s = s.Substring (j);
2248 bool vv = eval_val (s);
2253 Error_InvalidDirective ();
2257 bool pp_unary (ref string s)
2264 if (len > 1 && s [1] == '='){
2265 Error_InvalidDirective ();
2268 s = s.Substring (1);
2269 return ! pp_primary (ref s);
2271 return pp_primary (ref s);
2273 Error_InvalidDirective ();
2278 bool pp_eq (ref string s)
2280 bool va = pp_unary (ref s);
2286 if (len > 2 && s [1] == '='){
2287 s = s.Substring (2);
2288 return va == pp_unary (ref s);
2290 Error_InvalidDirective ();
2293 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2294 s = s.Substring (2);
2296 return va != pp_unary (ref s);
2305 bool pp_and (ref string s)
2307 bool va = pp_eq (ref s);
2313 if (len > 2 && s [1] == '&'){
2314 s = s.Substring (2);
2315 return (va & pp_and (ref s));
2317 Error_InvalidDirective ();
2326 // Evaluates an expression for `#if' or `#elif'
2328 bool pp_expr (ref string s, bool isTerm)
2330 bool va = pp_and (ref s);
2337 if (len > 2 && s [1] == '|'){
2338 s = s.Substring (2);
2339 return va | pp_expr (ref s, isTerm);
2341 Error_InvalidDirective ();
2346 Error_EndLineExpected ();
2354 bool eval (string s)
2356 bool v = pp_expr (ref s, true);
2365 void Error_NumericConstantTooLong ()
2367 Report.Error (1021, Location, "Integral constant is too large");
2370 void Error_InvalidDirective ()
2372 Report.Error (1517, Location, "Invalid preprocessor directive");
2375 void Error_UnexpectedDirective (string extra)
2379 "Unexpected processor directive ({0})", extra);
2382 void Error_TokensSeen ()
2384 Report.Error (1032, Location,
2385 "Cannot define or undefine preprocessor symbols after first token in file");
2388 void Eror_WrongPreprocessorLocation ()
2390 Report.Error (1040, Location,
2391 "Preprocessor directives must appear as the first non-whitespace character on a line");
2394 void Error_EndLineExpected ()
2396 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2400 // if true, then the code continues processing the code
2401 // if false, the code stays in a loop until another directive is
2403 // When caller_is_taking is false we ignore all directives except the ones
2404 // which can help us to identify where the #if block ends
2405 bool ParsePreprocessingDirective (bool caller_is_taking)
2408 bool region_directive = false;
2410 var directive = get_cmd_arg (out arg);
2413 // The first group of pre-processing instructions is always processed
2415 switch (directive) {
2416 case PreprocessorDirective.Region:
2417 region_directive = true;
2419 goto case PreprocessorDirective.If;
2421 case PreprocessorDirective.Endregion:
2422 if (ifstack == null || ifstack.Count == 0){
2423 Error_UnexpectedDirective ("no #region for this #endregion");
2426 int pop = ifstack.Pop ();
2428 if ((pop & REGION) == 0)
2429 Report.Error (1027, Location, "Expected `#endif' directive");
2431 return caller_is_taking;
2433 case PreprocessorDirective.If:
2434 if (ifstack == null)
2435 ifstack = new Stack<int> (2);
2437 int flags = region_directive ? REGION : 0;
2438 if (ifstack.Count == 0){
2439 flags |= PARENT_TAKING;
2441 int state = ifstack.Peek ();
2442 if ((state & TAKING) != 0) {
2443 flags |= PARENT_TAKING;
2447 if (caller_is_taking && eval (arg)) {
2448 ifstack.Push (flags | TAKING);
2451 ifstack.Push (flags);
2454 case PreprocessorDirective.Endif:
2455 if (ifstack == null || ifstack.Count == 0){
2456 Error_UnexpectedDirective ("no #if for this #endif");
2459 pop = ifstack.Pop ();
2461 if ((pop & REGION) != 0)
2462 Report.Error (1038, Location, "#endregion directive expected");
2464 if (arg.Length != 0) {
2465 Error_EndLineExpected ();
2468 if (ifstack.Count == 0)
2471 int state = ifstack.Peek ();
2472 return (state & TAKING) != 0;
2475 case PreprocessorDirective.Elif:
2476 if (ifstack == null || ifstack.Count == 0){
2477 Error_UnexpectedDirective ("no #if for this #elif");
2480 int state = ifstack.Pop ();
2482 if ((state & REGION) != 0) {
2483 Report.Error (1038, Location, "#endregion directive expected");
2487 if ((state & ELSE_SEEN) != 0){
2488 Error_UnexpectedDirective ("#elif not valid after #else");
2492 if ((state & TAKING) != 0) {
2497 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2498 ifstack.Push (state | TAKING);
2502 ifstack.Push (state);
2506 case PreprocessorDirective.Else:
2507 if (ifstack == null || ifstack.Count == 0){
2508 Error_UnexpectedDirective ("no #if for this #else");
2511 int state = ifstack.Peek ();
2513 if ((state & REGION) != 0) {
2514 Report.Error (1038, Location, "#endregion directive expected");
2518 if ((state & ELSE_SEEN) != 0){
2519 Error_UnexpectedDirective ("#else within #else");
2525 if (arg.Length != 0) {
2526 Error_EndLineExpected ();
2531 if ((state & PARENT_TAKING) != 0) {
2532 ret = (state & TAKING) == 0;
2540 ifstack.Push (state | ELSE_SEEN);
2544 case PreprocessorDirective.Define:
2545 if (any_token_seen){
2546 Error_TokensSeen ();
2547 return caller_is_taking;
2549 PreProcessDefinition (true, arg, caller_is_taking);
2550 return caller_is_taking;
2552 case PreprocessorDirective.Undef:
2553 if (any_token_seen){
2554 Error_TokensSeen ();
2555 return caller_is_taking;
2557 PreProcessDefinition (false, arg, caller_is_taking);
2558 return caller_is_taking;
2560 case PreprocessorDirective.Invalid:
2561 Report.Error (1024, Location, "Wrong preprocessor directive");
2566 // These are only processed if we are in a `taking' block
2568 if (!caller_is_taking)
2572 case PreprocessorDirective.Error:
2573 Report.Error (1029, Location, "#error: '{0}'", arg);
2576 case PreprocessorDirective.Warning:
2577 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2580 case PreprocessorDirective.Pragma:
2581 if (RootContext.Version == LanguageVersion.ISO_1) {
2582 Report.FeatureIsNotAvailable (Location, "#pragma");
2585 ParsePragmaDirective (arg);
2588 case PreprocessorDirective.Line:
2589 if (!PreProcessLine (arg))
2592 "The line number specified for #line directive is missing or invalid");
2593 return caller_is_taking;
2596 throw new NotImplementedException (directive.ToString ());
2599 private int consume_string (bool quoted)
2602 string_builder.Length = 0;
2607 if (quoted && peek_char () == '"') {
2608 string_builder.Append ((char) c);
2613 val = new StringLiteral (string_builder.ToString (), Location);
2614 return Token.LITERAL;
2619 Report.Error (1010, Location, "Newline in constant");
2620 } else if (c == '\\' && !quoted) {
2622 c = escape (c, out surrogate);
2625 if (surrogate != 0) {
2626 string_builder.Append ((char) c);
2629 } else if (c == -1) {
2630 Report.Error (1039, Location, "Unterminated string literal");
2634 string_builder.Append ((char) c);
2638 private int consume_identifier (int s)
2640 int res = consume_identifier (s, false);
2642 if (doc_state == XmlCommentState.Allowed)
2643 doc_state = XmlCommentState.NotAllowed;
2648 int consume_identifier (int c, bool quoted)
2651 // This method is very performance sensitive. It accounts
2652 // for approximately 25% of all parser time
2660 c = escape (c, out surrogate);
2661 if (surrogate != 0) {
2662 id_builder [pos++] = (char) c;
2667 id_builder [pos++] = (char) c;
2673 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2674 id_builder [pos++] = (char) c;
2681 c = escape (c, out surrogate);
2682 if (surrogate != 0) {
2683 if (is_identifier_part_character ((char) c))
2684 id_builder[pos++] = (char) c;
2690 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2691 id_builder [pos++] = (char) c;
2698 } catch (IndexOutOfRangeException) {
2699 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2707 // Optimization: avoids doing the keyword lookup
2708 // on uppercase letters
2710 if (id_builder [0] >= '_' && !quoted) {
2711 int keyword = GetKeyword (id_builder, pos);
2712 if (keyword != -1) {
2713 val = LocatedToken.Create (null, ref_line, column);
2719 // Keep identifiers in an array of hashtables to avoid needless
2722 var identifiers_group = identifiers [pos];
2724 if (identifiers_group != null) {
2725 if (identifiers_group.TryGetValue (id_builder, out s)) {
2726 val = LocatedToken.Create (s, ref_line, column);
2728 AddEscapedIdentifier (((LocatedToken) val).Location);
2729 return Token.IDENTIFIER;
2732 // TODO: this should be number of files dependant
2733 // corlib compilation peaks at 1000 and System.Core at 150
2734 int capacity = pos > 20 ? 10 : 100;
2735 identifiers_group = new Dictionary<char[],string> (capacity, new IdentifiersComparer (pos));
2736 identifiers [pos] = identifiers_group;
2739 char [] chars = new char [pos];
2740 Array.Copy (id_builder, chars, pos);
2742 s = new string (id_builder, 0, pos);
2743 identifiers_group.Add (chars, s);
2745 val = LocatedToken.Create (s, ref_line, column);
2747 AddEscapedIdentifier (((LocatedToken) val).Location);
2749 return Token.IDENTIFIER;
2752 public int xtoken ()
2756 // Whether we have seen comments on the current line
2757 bool comments_seen = false;
2758 while ((c = get_char ()) != -1) {
2761 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2769 case 0xFEFF: // Ignore BOM anywhere in the file
2772 /* This is required for compatibility with .NET
2774 if (peek_char () == 0xBB) {
2777 if (get_char () == 0xBF)
2784 if (peek_char () != '\n')
2789 any_token_seen |= tokens_seen;
2790 tokens_seen = false;
2791 comments_seen = false;
2796 return consume_identifier (c);
2799 val = LocatedToken.Create (ref_line, col);
2800 return Token.OPEN_BRACE;
2802 val = LocatedToken.Create (ref_line, col);
2803 return Token.CLOSE_BRACE;
2805 // To block doccomment inside attribute declaration.
2806 if (doc_state == XmlCommentState.Allowed)
2807 doc_state = XmlCommentState.NotAllowed;
2809 val = LocatedToken.Create (ref_line, col);
2811 if (parsing_block == 0 || lambda_arguments_parsing)
2812 return Token.OPEN_BRACKET;
2814 int next = peek_char ();
2818 return Token.OPEN_BRACKET;
2826 next = peek_token ();
2827 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2828 return Token.OPEN_BRACKET;
2830 return Token.OPEN_BRACKET_EXPR;
2832 return Token.OPEN_BRACKET_EXPR;
2835 LocatedToken.CreateOptional (ref_line, col, ref val);
2836 return Token.CLOSE_BRACKET;
2838 val = LocatedToken.Create (ref_line, col);
2840 // An expression versions of parens can appear in block context only
2842 if (parsing_block != 0 && !lambda_arguments_parsing) {
2845 // Optmize most common case where we know that parens
2848 switch (current_token) {
2849 case Token.IDENTIFIER:
2857 case Token.DELEGATE:
2858 case Token.OP_GENERICS_GT:
2859 return Token.OPEN_PARENS;
2862 // Optimize using peek
2863 int xx = peek_char ();
2870 return Token.OPEN_PARENS;
2873 lambda_arguments_parsing = true;
2875 d = TokenizeOpenParens ();
2877 lambda_arguments_parsing = false;
2881 return Token.OPEN_PARENS;
2883 LocatedToken.CreateOptional (ref_line, col, ref val);
2884 return Token.CLOSE_PARENS;
2886 LocatedToken.CreateOptional (ref_line, col, ref val);
2889 LocatedToken.CreateOptional (ref_line, col, ref val);
2890 return Token.SEMICOLON;
2892 val = LocatedToken.Create (ref_line, col);
2895 val = LocatedToken.Create (ref_line, col);
2896 return TokenizePossibleNullableType ();
2898 val = LocatedToken.Create (ref_line, col);
2899 if (parsing_generic_less_than++ > 0)
2900 return Token.OP_GENERICS_LT;
2902 return TokenizeLessThan ();
2905 val = LocatedToken.Create (ref_line, col);
2913 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2914 parsing_generic_less_than--;
2915 return Token.OP_GENERICS_GT;
2924 return Token.OP_SHIFT_RIGHT_ASSIGN;
2926 return Token.OP_SHIFT_RIGHT;
2932 val = LocatedToken.Create (ref_line, col);
2936 } else if (d == '=') {
2937 d = Token.OP_ADD_ASSIGN;
2945 val = LocatedToken.Create (ref_line, col);
2949 } else if (d == '=')
2950 d = Token.OP_SUB_ASSIGN;
2960 val = LocatedToken.Create (ref_line, col);
2961 if (peek_char () == '='){
2968 val = LocatedToken.Create (ref_line, col);
2979 return Token.ASSIGN;
2982 val = LocatedToken.Create (ref_line, col);
2986 return Token.OP_AND;
2990 return Token.OP_AND_ASSIGN;
2992 return Token.BITWISE_AND;
2995 val = LocatedToken.Create (ref_line, col);
3003 return Token.OP_OR_ASSIGN;
3005 return Token.BITWISE_OR;
3008 val = LocatedToken.Create (ref_line, col);
3009 if (peek_char () == '='){
3011 return Token.OP_MULT_ASSIGN;
3018 val = LocatedToken.Create (ref_line, col);
3020 return Token.OP_DIV_ASSIGN;
3023 // Handle double-slash comments.
3026 if (RootContext.Documentation != null && peek_char () == '/') {
3028 // Don't allow ////.
3029 if ((d = peek_char ()) != '/') {
3030 update_comment_location ();
3031 if (doc_state == XmlCommentState.Allowed)
3032 handle_one_line_xml_comment ();
3033 else if (doc_state == XmlCommentState.NotAllowed)
3034 warn_incorrect_doc_comment ();
3037 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
3039 any_token_seen |= tokens_seen;
3040 tokens_seen = false;
3041 comments_seen = false;
3043 } else if (d == '*'){
3045 bool docAppend = false;
3046 if (RootContext.Documentation != null && peek_char () == '*') {
3048 update_comment_location ();
3049 // But when it is /**/, just do nothing.
3050 if (peek_char () == '/') {
3054 if (doc_state == XmlCommentState.Allowed)
3056 else if (doc_state == XmlCommentState.NotAllowed)
3057 warn_incorrect_doc_comment ();
3060 int current_comment_start = 0;
3062 current_comment_start = xml_comment_buffer.Length;
3063 xml_comment_buffer.Append (Environment.NewLine);
3066 while ((d = get_char ()) != -1){
3067 if (d == '*' && peek_char () == '/'){
3069 comments_seen = true;
3073 xml_comment_buffer.Append ((char) d);
3076 any_token_seen |= tokens_seen;
3077 tokens_seen = false;
3079 // Reset 'comments_seen' just to be consistent.
3080 // It doesn't matter either way, here.
3082 comments_seen = false;
3086 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3089 update_formatted_doc_comment (current_comment_start);
3092 val = LocatedToken.Create (ref_line, col);
3096 val = LocatedToken.Create (ref_line, col);
3097 if (peek_char () == '='){
3099 return Token.OP_MOD_ASSIGN;
3101 return Token.PERCENT;
3104 val = LocatedToken.Create (ref_line, col);
3105 if (peek_char () == '='){
3107 return Token.OP_XOR_ASSIGN;
3109 return Token.CARRET;
3112 val = LocatedToken.Create (ref_line, col);
3113 if (peek_char () == ':') {
3115 return Token.DOUBLE_COLON;
3119 case '0': case '1': case '2': case '3': case '4':
3120 case '5': case '6': case '7': case '8': case '9':
3122 return is_number (c);
3124 case '\n': // white space
3125 any_token_seen |= tokens_seen;
3126 tokens_seen = false;
3127 comments_seen = false;
3133 if (d >= '0' && d <= '9')
3134 return is_number (c);
3136 LocatedToken.CreateOptional (ref_line, col, ref val);
3140 if (tokens_seen || comments_seen) {
3141 Eror_WrongPreprocessorLocation ();
3145 if (ParsePreprocessingDirective (true))
3148 bool directive_expected = false;
3149 while ((c = get_char ()) != -1) {
3151 directive_expected = true;
3152 } else if (!directive_expected) {
3153 // TODO: Implement comment support for disabled code and uncomment this code
3155 // Eror_WrongPreprocessorLocation ();
3156 // return Token.ERROR;
3161 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
3165 if (ParsePreprocessingDirective (false))
3168 directive_expected = false;
3172 tokens_seen = false;
3179 return consume_string (false);
3182 return TokenizeBackslash ();
3188 return consume_string (true);
3191 if (is_identifier_start_character (c)){
3192 return consume_identifier (c, true);
3195 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3198 case EvalStatementParserCharacter:
3199 return Token.EVAL_STATEMENT_PARSER;
3200 case EvalCompilationUnitParserCharacter:
3201 return Token.EVAL_COMPILATION_UNIT_PARSER;
3202 case EvalUsingDeclarationsParserCharacter:
3203 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3206 if (is_identifier_start_character (c)) {
3208 return consume_identifier (c);
3211 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3216 return Token.COMPLETE_COMPLETION;
3219 return Token.GENERATE_COMPLETION;
3226 int TokenizeBackslash ()
3228 int c = get_char ();
3231 val = new CharLiteral ((char) c, Location);
3232 Report.Error (1011, Location, "Empty character literal");
3233 return Token.LITERAL;
3236 if (c == '\r' || c == '\n') {
3237 Report.Error (1010, Location, "Newline in constant");
3242 c = escape (c, out d);
3246 throw new NotImplementedException ();
3248 val = new CharLiteral ((char) c, Location);
3252 Report.Error (1012, Location, "Too many characters in character literal");
3254 // Try to recover, read until newline or next "'"
3255 while ((c = get_char ()) != -1) {
3256 if (c == '\n' || c == '\'')
3261 return Token.LITERAL;
3264 int TokenizeLessThan ()
3267 if (handle_typeof) {
3269 if (parse_generic_dimension (out d)) {
3272 return Token.GENERIC_DIMENSION;
3277 // Save current position and parse next token.
3279 if (parse_less_than ()) {
3280 if (parsing_generic_declaration && token () != Token.DOT) {
3281 d = Token.OP_GENERICS_LT_DECL;
3283 d = Token.OP_GENERICS_LT;
3290 parsing_generic_less_than = 0;
3299 return Token.OP_SHIFT_LEFT_ASSIGN;
3301 return Token.OP_SHIFT_LEFT;
3312 // Handles one line xml comment
3314 private void handle_one_line_xml_comment ()
3317 while ((c = peek_char ()) == ' ')
3318 get_char (); // skip heading whitespaces.
3319 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3320 xml_comment_buffer.Append ((char) get_char ());
3322 if (c == '\r' || c == '\n')
3323 xml_comment_buffer.Append (Environment.NewLine);
3327 // Remove heading "*" in Javadoc-like xml documentation.
3329 private void update_formatted_doc_comment (int current_comment_start)
3331 int length = xml_comment_buffer.Length - current_comment_start;
3332 string [] lines = xml_comment_buffer.ToString (
3333 current_comment_start,
3334 length).Replace ("\r", "").Split ('\n');
3336 // The first line starts with /**, thus it is not target
3337 // for the format check.
3338 for (int i = 1; i < lines.Length; i++) {
3339 string s = lines [i];
3340 int idx = s.IndexOf ('*');
3343 if (i < lines.Length - 1)
3347 head = s.Substring (0, idx);
3348 foreach (char c in head)
3351 lines [i] = s.Substring (idx + 1);
3353 xml_comment_buffer.Remove (current_comment_start, length);
3354 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3358 // Updates current comment location.
3360 private void update_comment_location ()
3362 if (current_comment_location.IsNull) {
3363 // "-2" is for heading "//" or "/*"
3364 current_comment_location =
3365 new Location (ref_line, hidden ? -1 : col - 2);
3370 // Checks if there was incorrect doc comments and raise
3373 public void check_incorrect_doc_comment ()
3375 if (xml_comment_buffer.Length > 0)
3376 warn_incorrect_doc_comment ();
3380 // Raises a warning when tokenizer found incorrect doccomment
3383 private void warn_incorrect_doc_comment ()
3385 if (doc_state != XmlCommentState.Error) {
3386 doc_state = XmlCommentState.Error;
3387 // in csc, it is 'XML comment is not placed on
3388 // a valid language element'. But that does not
3390 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3395 // Consumes the saved xml comment lines (if any)
3396 // as for current target member or type.
3398 public string consume_doc_comment ()
3400 if (xml_comment_buffer.Length > 0) {
3401 string ret = xml_comment_buffer.ToString ();
3402 reset_doc_comment ();
3409 get { return context.Report; }
3412 void reset_doc_comment ()
3414 xml_comment_buffer.Length = 0;
3415 current_comment_location = Location.Null;
3418 public void cleanup ()
3420 if (ifstack != null && ifstack.Count >= 1) {
3421 int state = ifstack.Pop ();
3422 if ((state & REGION) != 0)
3423 Report.Error (1038, Location, "#endregion directive expected");
3425 Report.Error (1027, Location, "Expected `#endif' directive");
3431 // Indicates whether it accepts XML documentation or not.
3433 public enum XmlCommentState {
3434 // comment is allowed in this state.
3436 // comment is not allowed in this state.
3438 // once comments appeared when it is NotAllowed, then the
3439 // state is changed to it, until the state is changed to