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;
18 using System.Globalization;
19 using System.Diagnostics;
24 /// Tokenizer for C# source code.
27 public class Tokenizer : yyParser.yyInput
31 public readonly T Token;
32 public KeywordEntry<T> Next;
33 public readonly char[] Value;
35 public KeywordEntry (string value, T token)
37 this.Value = value.ToCharArray ();
42 sealed class IdentifiersComparer : IEqualityComparer<char[]>
46 public IdentifiersComparer (int length)
51 public bool Equals (char[] x, char[] y)
53 for (int i = 0; i < length; ++i)
60 public int GetHashCode (char[] obj)
63 for (int i = 0; i < length; ++i)
64 h = (h << 5) - h + obj [i];
71 // This class has to be used in the parser only, it reuses token
72 // details after each parse
74 public class LocatedToken
79 static LocatedToken[] buffer;
82 private LocatedToken ()
86 public static LocatedToken Create (int row, int column)
88 return Create (null, row, column);
91 public static LocatedToken Create (string value, int row, int column)
94 // TODO: I am not very happy about the logic but it's the best
95 // what I could come up with for now.
96 // Ideally we should be using just tiny buffer (256 elements) which
97 // is enough to hold all details for currect stack and recycle elements
98 // poped from the stack but there is a trick needed to recycle
102 if (pos >= buffer.Length) {
103 entry = new LocatedToken ();
105 entry = buffer [pos];
107 entry = new LocatedToken ();
108 buffer [pos] = entry;
115 entry.column = column;
120 // Used for token not required by expression evaluator
122 [Conditional ("FULL_AST")]
123 public static void CreateOptional (int row, int col, ref object token)
125 token = Create (row, col);
128 public static void Initialize ()
131 buffer = new LocatedToken [10000];
135 public Location Location {
136 get { return new Location (row, column); }
139 public string Value {
140 get { return value; }
144 enum PreprocessorDirective
150 If = 3 | RequiresArgument,
152 Elif = 5 | RequiresArgument,
154 Define = 7 | RequiresArgument,
155 Undef = 8 | RequiresArgument,
158 Pragma = 11 | CustomArgumentsParsing,
161 CustomArgumentsParsing = 1 << 10,
162 RequiresArgument = 1 << 11
165 SeekableStreamReader reader;
167 CompilationUnit file_name;
168 CompilerContext context;
176 bool handle_get_set = false;
177 bool handle_remove_add = false;
178 bool handle_where = false;
179 bool handle_typeof = false;
180 bool lambda_arguments_parsing;
181 Location current_comment_location = Location.Null;
182 List<Location> escaped_identifiers;
183 int parsing_generic_less_than;
186 // Used mainly for parser optimizations. Some expressions for instance
187 // can appear only in block (including initializer, base initializer)
190 public int parsing_block;
191 internal bool query_parsing;
194 // When parsing type only, useful for ambiguous nullable types
196 public int parsing_type;
199 // Set when parsing generic declaration (type or method header)
201 public bool parsing_generic_declaration;
204 // The value indicates that we have not reach any declaration or
207 public int parsing_declaration;
210 // The special character to inject on streams to trigger the EXPRESSION_PARSE
211 // token to be returned. It just happens to be a Unicode character that
212 // would never be part of a program (can not be an identifier).
214 // This character is only tested just before the tokenizer is about to report
215 // an error; So on the regular operation mode, this addition will have no
216 // impact on the tokenizer's performance.
219 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
220 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
221 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
224 // XML documentation buffer. The save point is used to divide
225 // comments on types and comments on members.
227 StringBuilder xml_comment_buffer;
230 // See comment on XmlCommentState enumeration.
232 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
235 // Whether tokens have been seen on this line
237 bool tokens_seen = false;
240 // Set to true once the GENERATE_COMPLETION token has bee
241 // returned. This helps produce one GENERATE_COMPLETION,
242 // as many COMPLETE_COMPLETION as necessary to complete the
243 // AST tree and one final EOF.
248 // Whether a token has been seen on the file
249 // This is needed because `define' is not allowed to be used
250 // after a token has been seen.
252 bool any_token_seen = false;
254 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
256 public bool PropertyParsing {
257 get { return handle_get_set; }
258 set { handle_get_set = value; }
261 public bool EventParsing {
262 get { return handle_remove_add; }
263 set { handle_remove_add = value; }
266 public bool ConstraintsParsing {
267 get { return handle_where; }
268 set { handle_where = value; }
271 public bool TypeOfParsing {
272 get { return handle_typeof; }
273 set { handle_typeof = value; }
277 get { return tab_size; }
278 set { tab_size = value; }
281 public XmlCommentState doc_state {
282 get { return xml_doc_state; }
284 if (value == XmlCommentState.Allowed) {
285 check_incorrect_doc_comment ();
286 reset_doc_comment ();
288 xml_doc_state = value;
293 // This is used to trigger completion generation on the parser
294 public bool CompleteOnEOF;
296 void AddEscapedIdentifier (Location loc)
298 if (escaped_identifiers == null)
299 escaped_identifiers = new List<Location> ();
301 escaped_identifiers.Add (loc);
304 public bool IsEscapedIdentifier (MemberName name)
306 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
312 static KeywordEntry<int>[][] keywords;
313 static KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
314 static Dictionary<string, object> keyword_strings; // TODO: HashSet
315 static NumberStyles styles;
316 static NumberFormatInfo csharp_format_info;
319 static readonly char[] pragma_warning = "warning".ToCharArray ();
320 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
321 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
322 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
325 // Values for the associated token returned
327 internal int putback_char; // Used by repl only
333 const int TAKING = 1;
334 const int ELSE_SEEN = 4;
335 const int PARENT_TAKING = 8;
336 const int REGION = 16;
339 // pre-processor if stack state:
343 static System.Text.StringBuilder string_builder;
345 const int max_id_size = 512;
346 static char [] id_builder = new char [max_id_size];
348 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
350 const int max_number_size = 512;
351 static char [] number_builder = new char [max_number_size];
352 static int number_pos;
354 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
363 // This is used when the tokenizer needs to save
364 // the current position as it needs to do some parsing
365 // on its own to deamiguate a token in behalf of the
368 Stack<Position> position_stack = new Stack<Position> (2);
376 public int putback_char;
377 public int previous_col;
378 public Stack<int> ifstack;
379 public int parsing_generic_less_than;
380 public int current_token;
383 public Position (Tokenizer t)
385 position = t.reader.Position;
387 ref_line = t.ref_line;
390 putback_char = t.putback_char;
391 previous_col = t.previous_col;
392 if (t.ifstack != null && t.ifstack.Count != 0) {
393 // There is no simple way to clone Stack<T> all
394 // methods reverse the order
395 var clone = t.ifstack.ToArray ();
396 Array.Reverse (clone);
397 ifstack = new Stack<int> (clone);
399 parsing_generic_less_than = t.parsing_generic_less_than;
400 current_token = t.current_token;
405 public void PushPosition ()
407 position_stack.Push (new Position (this));
410 public void PopPosition ()
412 Position p = position_stack.Pop ();
414 reader.Position = p.position;
415 ref_line = p.ref_line;
419 putback_char = p.putback_char;
420 previous_col = p.previous_col;
422 parsing_generic_less_than = p.parsing_generic_less_than;
423 current_token = p.current_token;
427 // Do not reset the position, ignore it.
428 public void DiscardPosition ()
430 position_stack.Pop ();
433 static void AddKeyword (string kw, int token)
435 keyword_strings.Add (kw, null);
437 AddKeyword (keywords, kw, token);
440 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
442 AddKeyword (keywords_preprocessor, kw, directive);
445 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
447 int length = kw.Length;
448 if (keywords[length] == null) {
449 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
452 int char_index = kw[0] - '_';
453 var kwe = keywords[length][char_index];
455 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
459 while (kwe.Next != null) {
463 kwe.Next = new KeywordEntry<T> (kw, token);
466 static void InitTokens ()
468 keyword_strings = new Dictionary<string, object> ();
470 // 11 is the length of the longest keyword for now
471 keywords = new KeywordEntry<int> [11] [];
473 AddKeyword ("__arglist", Token.ARGLIST);
474 AddKeyword ("abstract", Token.ABSTRACT);
475 AddKeyword ("as", Token.AS);
476 AddKeyword ("add", Token.ADD);
477 AddKeyword ("base", Token.BASE);
478 AddKeyword ("bool", Token.BOOL);
479 AddKeyword ("break", Token.BREAK);
480 AddKeyword ("byte", Token.BYTE);
481 AddKeyword ("case", Token.CASE);
482 AddKeyword ("catch", Token.CATCH);
483 AddKeyword ("char", Token.CHAR);
484 AddKeyword ("checked", Token.CHECKED);
485 AddKeyword ("class", Token.CLASS);
486 AddKeyword ("const", Token.CONST);
487 AddKeyword ("continue", Token.CONTINUE);
488 AddKeyword ("decimal", Token.DECIMAL);
489 AddKeyword ("default", Token.DEFAULT);
490 AddKeyword ("delegate", Token.DELEGATE);
491 AddKeyword ("do", Token.DO);
492 AddKeyword ("double", Token.DOUBLE);
493 AddKeyword ("else", Token.ELSE);
494 AddKeyword ("enum", Token.ENUM);
495 AddKeyword ("event", Token.EVENT);
496 AddKeyword ("explicit", Token.EXPLICIT);
497 AddKeyword ("extern", Token.EXTERN);
498 AddKeyword ("false", Token.FALSE);
499 AddKeyword ("finally", Token.FINALLY);
500 AddKeyword ("fixed", Token.FIXED);
501 AddKeyword ("float", Token.FLOAT);
502 AddKeyword ("for", Token.FOR);
503 AddKeyword ("foreach", Token.FOREACH);
504 AddKeyword ("goto", Token.GOTO);
505 AddKeyword ("get", Token.GET);
506 AddKeyword ("if", Token.IF);
507 AddKeyword ("implicit", Token.IMPLICIT);
508 AddKeyword ("in", Token.IN);
509 AddKeyword ("int", Token.INT);
510 AddKeyword ("interface", Token.INTERFACE);
511 AddKeyword ("internal", Token.INTERNAL);
512 AddKeyword ("is", Token.IS);
513 AddKeyword ("lock", Token.LOCK);
514 AddKeyword ("long", Token.LONG);
515 AddKeyword ("namespace", Token.NAMESPACE);
516 AddKeyword ("new", Token.NEW);
517 AddKeyword ("null", Token.NULL);
518 AddKeyword ("object", Token.OBJECT);
519 AddKeyword ("operator", Token.OPERATOR);
520 AddKeyword ("out", Token.OUT);
521 AddKeyword ("override", Token.OVERRIDE);
522 AddKeyword ("params", Token.PARAMS);
523 AddKeyword ("private", Token.PRIVATE);
524 AddKeyword ("protected", Token.PROTECTED);
525 AddKeyword ("public", Token.PUBLIC);
526 AddKeyword ("readonly", Token.READONLY);
527 AddKeyword ("ref", Token.REF);
528 AddKeyword ("remove", Token.REMOVE);
529 AddKeyword ("return", Token.RETURN);
530 AddKeyword ("sbyte", Token.SBYTE);
531 AddKeyword ("sealed", Token.SEALED);
532 AddKeyword ("set", Token.SET);
533 AddKeyword ("short", Token.SHORT);
534 AddKeyword ("sizeof", Token.SIZEOF);
535 AddKeyword ("stackalloc", Token.STACKALLOC);
536 AddKeyword ("static", Token.STATIC);
537 AddKeyword ("string", Token.STRING);
538 AddKeyword ("struct", Token.STRUCT);
539 AddKeyword ("switch", Token.SWITCH);
540 AddKeyword ("this", Token.THIS);
541 AddKeyword ("throw", Token.THROW);
542 AddKeyword ("true", Token.TRUE);
543 AddKeyword ("try", Token.TRY);
544 AddKeyword ("typeof", Token.TYPEOF);
545 AddKeyword ("uint", Token.UINT);
546 AddKeyword ("ulong", Token.ULONG);
547 AddKeyword ("unchecked", Token.UNCHECKED);
548 AddKeyword ("unsafe", Token.UNSAFE);
549 AddKeyword ("ushort", Token.USHORT);
550 AddKeyword ("using", Token.USING);
551 AddKeyword ("virtual", Token.VIRTUAL);
552 AddKeyword ("void", Token.VOID);
553 AddKeyword ("volatile", Token.VOLATILE);
554 AddKeyword ("while", Token.WHILE);
555 AddKeyword ("partial", Token.PARTIAL);
556 AddKeyword ("where", Token.WHERE);
557 AddKeyword ("async", Token.ASYNC);
560 AddKeyword ("from", Token.FROM);
561 AddKeyword ("join", Token.JOIN);
562 AddKeyword ("on", Token.ON);
563 AddKeyword ("equals", Token.EQUALS);
564 AddKeyword ("select", Token.SELECT);
565 AddKeyword ("group", Token.GROUP);
566 AddKeyword ("by", Token.BY);
567 AddKeyword ("let", Token.LET);
568 AddKeyword ("orderby", Token.ORDERBY);
569 AddKeyword ("ascending", Token.ASCENDING);
570 AddKeyword ("descending", Token.DESCENDING);
571 AddKeyword ("into", Token.INTO);
573 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
575 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
576 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
577 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
578 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
579 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
580 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
581 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
582 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
583 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
584 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
585 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
586 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
595 csharp_format_info = NumberFormatInfo.InvariantInfo;
596 styles = NumberStyles.Float;
598 string_builder = new System.Text.StringBuilder ();
601 int GetKeyword (char[] id, int id_len)
604 // Keywords are stored in an array of arrays grouped by their
605 // length and then by the first character
607 if (id_len >= keywords.Length || keywords [id_len] == null)
610 int first_index = id [0] - '_';
611 if (first_index > 'z' - '_')
614 var kwe = keywords [id_len] [first_index];
621 for (int i = 1; i < id_len; ++i) {
622 if (id [i] != kwe.Value [i]) {
628 } while (res == 0 && kwe != null);
642 if (!handle_remove_add)
646 if (parsing_declaration == 0)
647 res = Token.EXTERN_ALIAS;
650 if (peek_token () == Token.COLON) {
652 res = Token.DEFAULT_COLON;
656 if (!handle_where && !query_parsing)
661 // A query expression is any expression that starts with `from identifier'
662 // followed by any token except ; , =
664 if (!query_parsing) {
665 if (lambda_arguments_parsing) {
671 // HACK: to disable generics micro-parser, because PushPosition does not
672 // store identifiers array
673 parsing_generic_less_than = 1;
675 case Token.IDENTIFIER:
687 next_token = xtoken ();
688 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
691 res = Token.FROM_FIRST;
692 query_parsing = true;
693 if (context.Settings.Version <= LanguageVersion.ISO_2)
694 Report.FeatureIsNotAvailable (context, Location, "query expressions");
697 Expression.Error_VoidInvalidInTheContext (Location, Report);
701 // HACK: A token is not a keyword so we need to restore identifiers buffer
702 // which has been overwritten before we grabbed the identifier
703 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
717 case Token.ASCENDING:
718 case Token.DESCENDING:
725 case Token.NAMESPACE:
726 // TODO: some explanation needed
727 check_incorrect_doc_comment ();
731 if (parsing_block > 0) {
736 // Save current position and parse next token.
739 next_token = token ();
740 bool ok = (next_token == Token.CLASS) ||
741 (next_token == Token.STRUCT) ||
742 (next_token == Token.INTERFACE) ||
743 (next_token == Token.VOID);
748 if (next_token == Token.VOID) {
749 if (context.Settings.Version <= LanguageVersion.ISO_2)
750 Report.FeatureIsNotAvailable (context, Location, "partial methods");
751 } else if (context.Settings.Version == LanguageVersion.ISO_1)
752 Report.FeatureIsNotAvailable (context, Location, "partial types");
757 if (next_token < Token.LAST_KEYWORD) {
758 Report.Error (267, Location,
759 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
767 if (parsing_block > 0 || context.Settings.Version != LanguageVersion.Future) {
777 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
780 // Keywords are stored in an array of arrays grouped by their
781 // length and then by the first character
783 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
784 return PreprocessorDirective.Invalid;
786 int first_index = id[0] - '_';
787 if (first_index > 'z' - '_')
788 return PreprocessorDirective.Invalid;
790 var kwe = keywords_preprocessor[id_len][first_index];
792 return PreprocessorDirective.Invalid;
794 PreprocessorDirective res = PreprocessorDirective.Invalid;
797 for (int i = 1; i < id_len; ++i) {
798 if (id[i] != kwe.Value[i]) {
804 } while (res == PreprocessorDirective.Invalid && kwe != null);
809 public Location Location {
811 return new Location (ref_line, hidden ? -1 : col);
815 public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
817 this.ref_name = file;
818 this.file_name = file;
824 xml_comment_buffer = new StringBuilder ();
826 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
832 // FIXME: This could be `Location.Push' but we have to
833 // find out why the MS compiler allows this
835 Mono.CSharp.Location.Push (file, file);
838 static bool is_identifier_start_character (int c)
840 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
843 static bool is_identifier_part_character (char c)
845 if (c >= 'a' && c <= 'z')
848 if (c >= 'A' && c <= 'Z')
851 if (c == '_' || (c >= '0' && c <= '9'))
857 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
860 public static bool IsKeyword (string s)
862 return keyword_strings.ContainsKey (s);
866 // Open parens micro parser. Detects both lambda and cast ambiguity.
868 int TokenizeOpenParens ()
873 int bracket_level = 0;
874 bool is_type = false;
875 bool can_be_type = false;
878 ptoken = current_token;
881 switch (current_token) {
882 case Token.CLOSE_PARENS:
886 // Expression inside parens is lambda, (int i) =>
888 if (current_token == Token.ARROW)
889 return Token.OPEN_PARENS_LAMBDA;
892 // Expression inside parens is single type, (int[])
895 return Token.OPEN_PARENS_CAST;
898 // Expression is possible cast, look at next token, (T)null
901 switch (current_token) {
902 case Token.OPEN_PARENS:
905 case Token.IDENTIFIER:
919 case Token.UNCHECKED:
924 // These can be part of a member access
938 return Token.OPEN_PARENS_CAST;
941 return Token.OPEN_PARENS;
944 case Token.DOUBLE_COLON:
945 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
950 case Token.IDENTIFIER:
953 if (bracket_level == 0) {
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) {
1681 if (peek_char () == '\n') {
1687 } else if (x == '\n') {
1695 void advance_line ()
1705 if (putback_char == -1)
1706 putback_char = reader.Read ();
1707 return putback_char;
1712 if (putback_char != -1)
1713 return putback_char;
1714 return reader.Peek ();
1717 void putback (int c)
1719 if (putback_char != -1){
1720 Console.WriteLine ("Col: " + col);
1721 Console.WriteLine ("Row: " + line);
1722 Console.WriteLine ("Name: " + ref_name.Name);
1723 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1724 throw new Exception ("This should not happen putback on putback");
1726 if (c == '\n' || col == 0) {
1727 // It won't happen though.
1737 public bool advance ()
1739 return peek_char () != -1 || CompleteOnEOF;
1742 public Object Value {
1748 public Object value ()
1755 current_token = xtoken ();
1756 return current_token;
1759 int TokenizePreprocessorIdentifier (out int c)
1761 // skip over white space
1764 } while (c == ' ' || c == '\t');
1768 while (c != -1 && c >= 'a' && c <= 'z') {
1769 id_builder[pos++] = (char) c;
1772 int peek = peek_char ();
1773 if (peek == 'U' || peek == 'u') {
1775 c = EscapeUnicode (c, out surrogate);
1776 if (surrogate != 0) {
1777 if (is_identifier_part_character ((char) c)) {
1778 id_builder[pos++] = (char) c;
1789 PreprocessorDirective get_cmd_arg (out string arg)
1793 tokens_seen = false;
1796 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1798 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1801 // skip over white space
1802 while (c == ' ' || c == '\t')
1805 static_cmd_arg.Length = 0;
1806 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1808 while (c != -1 && c != '\n') {
1809 if (c == '\\' && has_identifier_argument >= 0) {
1810 if (has_identifier_argument != 0) {
1811 has_identifier_argument = 1;
1813 int peek = peek_char ();
1814 if (peek == 'U' || peek == 'u') {
1816 c = EscapeUnicode (c, out surrogate);
1817 if (surrogate != 0) {
1818 if (is_identifier_part_character ((char) c))
1819 static_cmd_arg.Append ((char) c);
1824 has_identifier_argument = -1;
1827 static_cmd_arg.Append ((char) c);
1831 if (static_cmd_arg.Length != 0) {
1832 arg = static_cmd_arg.ToString ();
1834 // Eat any trailing whitespaces and single-line comments
1835 if (arg.IndexOf ("//") != -1) {
1836 arg = arg.Substring (0, arg.IndexOf ("//"));
1839 arg = arg.Trim (simple_whitespaces);
1846 // Handles the #line directive
1848 bool PreProcessLine (string arg)
1850 if (arg.Length == 0)
1853 if (arg == "default"){
1855 ref_name = file_name;
1857 Location.Push (file_name, ref_name);
1859 } else if (arg == "hidden"){
1867 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1868 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1871 char [] quotes = { '\"' };
1873 string name = arg.Substring (pos). Trim (quotes);
1874 ref_name = Location.LookupFile (file_name, name);
1875 file_name.AddFile (ref_name);
1877 Location.Push (file_name, ref_name);
1879 ref_line = System.Int32.Parse (arg);
1890 // Handles #define and #undef
1892 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1894 if (ident.Length == 0 || ident == "true" || ident == "false"){
1895 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1899 if (ident.IndexOfAny (simple_whitespaces) != -1){
1900 Error_EndLineExpected ();
1904 if (!is_identifier_start_character (ident [0]))
1905 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1907 foreach (char c in ident.Substring (1)){
1908 if (!is_identifier_part_character (c)){
1909 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1914 if (!caller_is_taking)
1921 if (RootContext.IsConditionalDefined (ident))
1924 file_name.AddDefine (ident);
1929 file_name.AddUndefine (ident);
1933 byte read_hex (out bool error)
1936 int c = get_char ();
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;
1952 if ((c >= '0') && (c <= '9'))
1953 total += (int) c - (int) '0';
1954 else if ((c >= 'A') && (c <= 'F'))
1955 total += (int) c - (int) 'A' + 10;
1956 else if ((c >= 'a') && (c <= 'f'))
1957 total += (int) c - (int) 'a' + 10;
1964 return (byte) total;
1968 // Parses #pragma checksum
1970 bool ParsePragmaChecksum ()
1973 // The syntax is ` "foo.txt" "{guid}" "hash"'
1975 int c = get_char ();
1980 string_builder.Length = 0;
1981 while (c != -1 && c != '\n') {
1988 string_builder.Append ((char) c);
1991 if (string_builder.Length == 0) {
1992 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
1995 // TODO: Any white-spaces count
1999 SourceFile file = Location.LookupFile (file_name, string_builder.ToString ());
2001 if (get_char () != '"' || get_char () != '{')
2005 byte[] guid_bytes = new byte [16];
2008 for (; i < 4; i++) {
2009 guid_bytes [i] = read_hex (out error);
2014 if (get_char () != '-')
2017 for (; i < 10; i++) {
2018 guid_bytes [i] = read_hex (out error);
2022 guid_bytes [i++] = read_hex (out error);
2026 if (get_char () != '-')
2030 for (; i < 16; i++) {
2031 guid_bytes [i] = read_hex (out error);
2036 if (get_char () != '}' || get_char () != '"')
2039 // TODO: Any white-spaces count
2044 if (get_char () != '"')
2047 // Any length of checksum
2048 List<byte> checksum_bytes = new List<byte> (16);
2051 while (c != '"' && c != -1) {
2052 checksum_bytes.Add (read_hex (out error));
2060 ReadSingleLineComment ();
2061 } else if (get_char () != '"') {
2065 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2066 ref_name.AutoGenerated = true;
2070 bool IsTokenIdentifierEqual (char[] identifier)
2072 for (int i = 0; i < identifier.Length; ++i) {
2073 if (identifier[i] != id_builder[i])
2080 int TokenizePragmaNumber (ref int c)
2086 if (c >= '0' && c <= '9') {
2088 uint ui = (uint) (number_builder[0] - '0');
2091 for (int i = 1; i < number_pos; i++) {
2092 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2096 } catch (OverflowException) {
2097 Error_NumericConstantTooLong ();
2104 // skip over white space
2105 while (c == ' ' || c == '\t')
2112 // skip over white space
2113 while (c == ' ' || c == '\t')
2118 ReadSingleLineComment ();
2120 Report.Warning (1692, 1, Location, "Invalid number");
2122 // Read everything till the end of the line or file
2125 } while (c != -1 && c != '\n');
2132 void ReadSingleLineComment ()
2134 if (peek_char () != '/')
2135 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2137 // Read everything till the end of the line or file
2141 } while (c != -1 && c != '\n');
2145 /// Handles #pragma directive
2147 void ParsePragmaDirective (string arg)
2150 int length = TokenizePreprocessorIdentifier (out c);
2151 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2152 length = TokenizePreprocessorIdentifier (out c);
2155 // #pragma warning disable
2156 // #pragma warning restore
2158 if (length == pragma_warning_disable.Length) {
2159 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2160 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2161 // skip over white space
2162 while (c == ' ' || c == '\t')
2167 if (c == '\n' || c == '/') {
2169 ReadSingleLineComment ();
2172 // Disable/Restore all warnings
2175 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2177 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2181 // Disable/Restore a warning or group of warnings
2185 code = TokenizePragmaNumber (ref c);
2188 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2190 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2193 } while (code >= 0 && c != '\n' && c != -1);
2200 Report.Warning (1634, 1, Location, "Expected disable or restore");
2207 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2208 if (c != ' ' || !ParsePragmaChecksum ()) {
2209 Report.Warning (1695, 1, Location,
2210 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2216 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2219 bool eval_val (string s)
2226 return file_name.IsConditionalDefined (s);
2229 bool pp_primary (ref string s)
2238 s = s.Substring (1);
2239 bool val = pp_expr (ref s, false);
2240 if (s.Length > 0 && s [0] == ')'){
2241 s = s.Substring (1);
2244 Error_InvalidDirective ();
2248 if (is_identifier_start_character (c)){
2254 if (is_identifier_part_character (c)){
2258 bool v = eval_val (s.Substring (0, j));
2259 s = s.Substring (j);
2262 bool vv = eval_val (s);
2267 Error_InvalidDirective ();
2271 bool pp_unary (ref string s)
2278 if (len > 1 && s [1] == '='){
2279 Error_InvalidDirective ();
2282 s = s.Substring (1);
2283 return ! pp_primary (ref s);
2285 return pp_primary (ref s);
2287 Error_InvalidDirective ();
2292 bool pp_eq (ref string s)
2294 bool va = pp_unary (ref s);
2300 if (len > 2 && s [1] == '='){
2301 s = s.Substring (2);
2302 return va == pp_unary (ref s);
2304 Error_InvalidDirective ();
2307 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2308 s = s.Substring (2);
2310 return va != pp_unary (ref s);
2319 bool pp_and (ref string s)
2321 bool va = pp_eq (ref s);
2327 if (len > 2 && s [1] == '&'){
2328 s = s.Substring (2);
2329 return (va & pp_and (ref s));
2331 Error_InvalidDirective ();
2340 // Evaluates an expression for `#if' or `#elif'
2342 bool pp_expr (ref string s, bool isTerm)
2344 bool va = pp_and (ref s);
2351 if (len > 2 && s [1] == '|'){
2352 s = s.Substring (2);
2353 return va | pp_expr (ref s, isTerm);
2355 Error_InvalidDirective ();
2360 Error_EndLineExpected ();
2368 bool eval (string s)
2370 bool v = pp_expr (ref s, true);
2379 void Error_NumericConstantTooLong ()
2381 Report.Error (1021, Location, "Integral constant is too large");
2384 void Error_InvalidDirective ()
2386 Report.Error (1517, Location, "Invalid preprocessor directive");
2389 void Error_UnexpectedDirective (string extra)
2393 "Unexpected processor directive ({0})", extra);
2396 void Error_TokensSeen ()
2398 Report.Error (1032, Location,
2399 "Cannot define or undefine preprocessor symbols after first token in file");
2402 void Eror_WrongPreprocessorLocation ()
2404 Report.Error (1040, Location,
2405 "Preprocessor directives must appear as the first non-whitespace character on a line");
2408 void Error_EndLineExpected ()
2410 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2414 // if true, then the code continues processing the code
2415 // if false, the code stays in a loop until another directive is
2417 // When caller_is_taking is false we ignore all directives except the ones
2418 // which can help us to identify where the #if block ends
2419 bool ParsePreprocessingDirective (bool caller_is_taking)
2422 bool region_directive = false;
2424 var directive = get_cmd_arg (out arg);
2427 // The first group of pre-processing instructions is always processed
2429 switch (directive) {
2430 case PreprocessorDirective.Region:
2431 region_directive = true;
2433 goto case PreprocessorDirective.If;
2435 case PreprocessorDirective.Endregion:
2436 if (ifstack == null || ifstack.Count == 0){
2437 Error_UnexpectedDirective ("no #region for this #endregion");
2440 int pop = ifstack.Pop ();
2442 if ((pop & REGION) == 0)
2443 Report.Error (1027, Location, "Expected `#endif' directive");
2445 return caller_is_taking;
2447 case PreprocessorDirective.If:
2448 if (ifstack == null)
2449 ifstack = new Stack<int> (2);
2451 int flags = region_directive ? REGION : 0;
2452 if (ifstack.Count == 0){
2453 flags |= PARENT_TAKING;
2455 int state = ifstack.Peek ();
2456 if ((state & TAKING) != 0) {
2457 flags |= PARENT_TAKING;
2461 if (eval (arg) && caller_is_taking) {
2462 ifstack.Push (flags | TAKING);
2465 ifstack.Push (flags);
2468 case PreprocessorDirective.Endif:
2469 if (ifstack == null || ifstack.Count == 0){
2470 Error_UnexpectedDirective ("no #if for this #endif");
2473 pop = ifstack.Pop ();
2475 if ((pop & REGION) != 0)
2476 Report.Error (1038, Location, "#endregion directive expected");
2478 if (arg.Length != 0) {
2479 Error_EndLineExpected ();
2482 if (ifstack.Count == 0)
2485 int state = ifstack.Peek ();
2486 return (state & TAKING) != 0;
2489 case PreprocessorDirective.Elif:
2490 if (ifstack == null || ifstack.Count == 0){
2491 Error_UnexpectedDirective ("no #if for this #elif");
2494 int state = ifstack.Pop ();
2496 if ((state & REGION) != 0) {
2497 Report.Error (1038, Location, "#endregion directive expected");
2501 if ((state & ELSE_SEEN) != 0){
2502 Error_UnexpectedDirective ("#elif not valid after #else");
2506 if ((state & TAKING) != 0) {
2511 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2512 ifstack.Push (state | TAKING);
2516 ifstack.Push (state);
2520 case PreprocessorDirective.Else:
2521 if (ifstack == null || ifstack.Count == 0){
2522 Error_UnexpectedDirective ("no #if for this #else");
2525 int state = ifstack.Peek ();
2527 if ((state & REGION) != 0) {
2528 Report.Error (1038, Location, "#endregion directive expected");
2532 if ((state & ELSE_SEEN) != 0){
2533 Error_UnexpectedDirective ("#else within #else");
2539 if (arg.Length != 0) {
2540 Error_EndLineExpected ();
2545 if ((state & PARENT_TAKING) != 0) {
2546 ret = (state & TAKING) == 0;
2554 ifstack.Push (state | ELSE_SEEN);
2558 case PreprocessorDirective.Define:
2559 if (any_token_seen){
2560 Error_TokensSeen ();
2561 return caller_is_taking;
2563 PreProcessDefinition (true, arg, caller_is_taking);
2564 return caller_is_taking;
2566 case PreprocessorDirective.Undef:
2567 if (any_token_seen){
2568 Error_TokensSeen ();
2569 return caller_is_taking;
2571 PreProcessDefinition (false, arg, caller_is_taking);
2572 return caller_is_taking;
2574 case PreprocessorDirective.Invalid:
2575 Report.Error (1024, Location, "Wrong preprocessor directive");
2580 // These are only processed if we are in a `taking' block
2582 if (!caller_is_taking)
2586 case PreprocessorDirective.Error:
2587 Report.Error (1029, Location, "#error: '{0}'", arg);
2590 case PreprocessorDirective.Warning:
2591 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2594 case PreprocessorDirective.Pragma:
2595 if (context.Settings.Version == LanguageVersion.ISO_1) {
2596 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2599 ParsePragmaDirective (arg);
2602 case PreprocessorDirective.Line:
2603 if (!PreProcessLine (arg))
2606 "The line number specified for #line directive is missing or invalid");
2607 return caller_is_taking;
2610 throw new NotImplementedException (directive.ToString ());
2613 private int consume_string (bool quoted)
2616 string_builder.Length = 0;
2621 if (quoted && peek_char () == '"') {
2622 string_builder.Append ((char) c);
2627 val = new StringLiteral (string_builder.ToString (), Location);
2628 return Token.LITERAL;
2633 Report.Error (1010, Location, "Newline in constant");
2634 } else if (c == '\\' && !quoted) {
2636 c = escape (c, out surrogate);
2639 if (surrogate != 0) {
2640 string_builder.Append ((char) c);
2643 } else if (c == -1) {
2644 Report.Error (1039, Location, "Unterminated string literal");
2648 string_builder.Append ((char) c);
2652 private int consume_identifier (int s)
2654 int res = consume_identifier (s, false);
2656 if (doc_state == XmlCommentState.Allowed)
2657 doc_state = XmlCommentState.NotAllowed;
2662 int consume_identifier (int c, bool quoted)
2665 // This method is very performance sensitive. It accounts
2666 // for approximately 25% of all parser time
2674 c = escape (c, out surrogate);
2675 if (surrogate != 0) {
2676 id_builder [pos++] = (char) c;
2681 id_builder [pos++] = (char) c;
2687 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2688 id_builder [pos++] = (char) c;
2695 c = escape (c, out surrogate);
2696 if (surrogate != 0) {
2697 if (is_identifier_part_character ((char) c))
2698 id_builder[pos++] = (char) c;
2704 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2705 id_builder [pos++] = (char) c;
2712 } catch (IndexOutOfRangeException) {
2713 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2721 // Optimization: avoids doing the keyword lookup
2722 // on uppercase letters
2724 if (id_builder [0] >= '_' && !quoted) {
2725 int keyword = GetKeyword (id_builder, pos);
2726 if (keyword != -1) {
2727 val = LocatedToken.Create (null, ref_line, column);
2733 // Keep identifiers in an array of hashtables to avoid needless
2736 var identifiers_group = identifiers [pos];
2738 if (identifiers_group != null) {
2739 if (identifiers_group.TryGetValue (id_builder, out s)) {
2740 val = LocatedToken.Create (s, ref_line, column);
2742 AddEscapedIdentifier (((LocatedToken) val).Location);
2743 return Token.IDENTIFIER;
2746 // TODO: this should be number of files dependant
2747 // corlib compilation peaks at 1000 and System.Core at 150
2748 int capacity = pos > 20 ? 10 : 100;
2749 identifiers_group = new Dictionary<char[],string> (capacity, new IdentifiersComparer (pos));
2750 identifiers [pos] = identifiers_group;
2753 char [] chars = new char [pos];
2754 Array.Copy (id_builder, chars, pos);
2756 s = new string (id_builder, 0, pos);
2757 identifiers_group.Add (chars, s);
2759 val = LocatedToken.Create (s, ref_line, column);
2761 AddEscapedIdentifier (((LocatedToken) val).Location);
2763 return Token.IDENTIFIER;
2766 public int xtoken ()
2770 // Whether we have seen comments on the current line
2771 bool comments_seen = false;
2772 while ((c = get_char ()) != -1) {
2775 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2783 case 0xFEFF: // Ignore BOM anywhere in the file
2786 /* This is required for compatibility with .NET
2788 if (peek_char () == 0xBB) {
2791 if (get_char () == 0xBF)
2799 return consume_identifier (c);
2802 val = LocatedToken.Create (ref_line, col);
2803 return Token.OPEN_BRACE;
2805 val = LocatedToken.Create (ref_line, col);
2806 return Token.CLOSE_BRACE;
2808 // To block doccomment inside attribute declaration.
2809 if (doc_state == XmlCommentState.Allowed)
2810 doc_state = XmlCommentState.NotAllowed;
2812 val = LocatedToken.Create (ref_line, col);
2814 if (parsing_block == 0 || lambda_arguments_parsing)
2815 return Token.OPEN_BRACKET;
2817 int next = peek_char ();
2821 return Token.OPEN_BRACKET;
2829 next = peek_token ();
2830 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2831 return Token.OPEN_BRACKET;
2833 return Token.OPEN_BRACKET_EXPR;
2835 return Token.OPEN_BRACKET_EXPR;
2838 LocatedToken.CreateOptional (ref_line, col, ref val);
2839 return Token.CLOSE_BRACKET;
2841 val = LocatedToken.Create (ref_line, col);
2843 // An expression versions of parens can appear in block context only
2845 if (parsing_block != 0 && !lambda_arguments_parsing) {
2848 // Optmize most common case where we know that parens
2851 switch (current_token) {
2852 case Token.IDENTIFIER:
2860 case Token.DELEGATE:
2861 case Token.OP_GENERICS_GT:
2862 return Token.OPEN_PARENS;
2865 // Optimize using peek
2866 int xx = peek_char ();
2873 return Token.OPEN_PARENS;
2876 lambda_arguments_parsing = true;
2878 d = TokenizeOpenParens ();
2880 lambda_arguments_parsing = false;
2884 return Token.OPEN_PARENS;
2886 LocatedToken.CreateOptional (ref_line, col, ref val);
2887 return Token.CLOSE_PARENS;
2889 LocatedToken.CreateOptional (ref_line, col, ref val);
2892 LocatedToken.CreateOptional (ref_line, col, ref val);
2893 return Token.SEMICOLON;
2895 val = LocatedToken.Create (ref_line, col);
2898 val = LocatedToken.Create (ref_line, col);
2899 return TokenizePossibleNullableType ();
2901 val = LocatedToken.Create (ref_line, col);
2902 if (parsing_generic_less_than++ > 0)
2903 return Token.OP_GENERICS_LT;
2905 return TokenizeLessThan ();
2908 val = LocatedToken.Create (ref_line, col);
2916 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2917 parsing_generic_less_than--;
2918 return Token.OP_GENERICS_GT;
2927 return Token.OP_SHIFT_RIGHT_ASSIGN;
2929 return Token.OP_SHIFT_RIGHT;
2935 val = LocatedToken.Create (ref_line, col);
2939 } else if (d == '=') {
2940 d = Token.OP_ADD_ASSIGN;
2948 val = LocatedToken.Create (ref_line, col);
2952 } else if (d == '=')
2953 d = Token.OP_SUB_ASSIGN;
2963 val = LocatedToken.Create (ref_line, col);
2964 if (peek_char () == '='){
2971 val = LocatedToken.Create (ref_line, col);
2982 return Token.ASSIGN;
2985 val = LocatedToken.Create (ref_line, col);
2989 return Token.OP_AND;
2993 return Token.OP_AND_ASSIGN;
2995 return Token.BITWISE_AND;
2998 val = LocatedToken.Create (ref_line, col);
3006 return Token.OP_OR_ASSIGN;
3008 return Token.BITWISE_OR;
3011 val = LocatedToken.Create (ref_line, col);
3012 if (peek_char () == '='){
3014 return Token.OP_MULT_ASSIGN;
3021 val = LocatedToken.Create (ref_line, col);
3023 return Token.OP_DIV_ASSIGN;
3026 // Handle double-slash comments.
3029 if (context.Settings.Documentation != null && peek_char () == '/') {
3031 // Don't allow ////.
3032 if ((d = peek_char ()) != '/') {
3033 update_comment_location ();
3034 if (doc_state == XmlCommentState.Allowed)
3035 handle_one_line_xml_comment ();
3036 else if (doc_state == XmlCommentState.NotAllowed)
3037 warn_incorrect_doc_comment ();
3041 while ((d = get_char ()) != -1 && d != '\n');
3043 any_token_seen |= tokens_seen;
3044 tokens_seen = false;
3045 comments_seen = false;
3047 } else if (d == '*'){
3049 bool docAppend = false;
3050 if (context.Settings.Documentation != null && peek_char () == '*') {
3052 update_comment_location ();
3053 // But when it is /**/, just do nothing.
3054 if (peek_char () == '/') {
3058 if (doc_state == XmlCommentState.Allowed)
3060 else if (doc_state == XmlCommentState.NotAllowed)
3061 warn_incorrect_doc_comment ();
3064 int current_comment_start = 0;
3066 current_comment_start = xml_comment_buffer.Length;
3067 xml_comment_buffer.Append (Environment.NewLine);
3070 while ((d = get_char ()) != -1){
3071 if (d == '*' && peek_char () == '/'){
3073 comments_seen = true;
3077 xml_comment_buffer.Append ((char) d);
3080 any_token_seen |= tokens_seen;
3081 tokens_seen = false;
3083 // Reset 'comments_seen' just to be consistent.
3084 // It doesn't matter either way, here.
3086 comments_seen = false;
3090 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3093 update_formatted_doc_comment (current_comment_start);
3096 val = LocatedToken.Create (ref_line, col);
3100 val = LocatedToken.Create (ref_line, col);
3101 if (peek_char () == '='){
3103 return Token.OP_MOD_ASSIGN;
3105 return Token.PERCENT;
3108 val = LocatedToken.Create (ref_line, col);
3109 if (peek_char () == '='){
3111 return Token.OP_XOR_ASSIGN;
3113 return Token.CARRET;
3116 val = LocatedToken.Create (ref_line, col);
3117 if (peek_char () == ':') {
3119 return Token.DOUBLE_COLON;
3123 case '0': case '1': case '2': case '3': case '4':
3124 case '5': case '6': case '7': case '8': case '9':
3126 return is_number (c);
3128 case '\n': // white space
3129 any_token_seen |= tokens_seen;
3130 tokens_seen = false;
3131 comments_seen = false;
3137 if (d >= '0' && d <= '9')
3138 return is_number (c);
3140 LocatedToken.CreateOptional (ref_line, col, ref val);
3144 if (tokens_seen || comments_seen) {
3145 Eror_WrongPreprocessorLocation ();
3149 if (ParsePreprocessingDirective (true))
3152 bool directive_expected = false;
3153 while ((c = get_char ()) != -1) {
3155 directive_expected = true;
3156 } else if (!directive_expected) {
3157 // TODO: Implement comment support for disabled code and uncomment this code
3159 // Eror_WrongPreprocessorLocation ();
3160 // return Token.ERROR;
3165 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3169 if (ParsePreprocessingDirective (false))
3172 directive_expected = false;
3176 tokens_seen = false;
3183 return consume_string (false);
3186 return TokenizeBackslash ();
3192 return consume_string (true);
3195 if (is_identifier_start_character (c)){
3196 return consume_identifier (c, true);
3199 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3202 case EvalStatementParserCharacter:
3203 return Token.EVAL_STATEMENT_PARSER;
3204 case EvalCompilationUnitParserCharacter:
3205 return Token.EVAL_COMPILATION_UNIT_PARSER;
3206 case EvalUsingDeclarationsParserCharacter:
3207 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3210 if (is_identifier_start_character (c)) {
3212 return consume_identifier (c);
3215 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3220 return Token.COMPLETE_COMPLETION;
3223 return Token.GENERATE_COMPLETION;
3230 int TokenizeBackslash ()
3232 int c = get_char ();
3235 val = new CharLiteral ((char) c, Location);
3236 Report.Error (1011, Location, "Empty character literal");
3237 return Token.LITERAL;
3241 Report.Error (1010, Location, "Newline in constant");
3246 c = escape (c, out d);
3250 throw new NotImplementedException ();
3252 val = new CharLiteral ((char) c, Location);
3256 Report.Error (1012, Location, "Too many characters in character literal");
3258 // Try to recover, read until newline or next "'"
3259 while ((c = get_char ()) != -1) {
3260 if (c == '\n' || c == '\'')
3265 return Token.LITERAL;
3268 int TokenizeLessThan ()
3271 if (handle_typeof) {
3273 if (parse_generic_dimension (out d)) {
3276 return Token.GENERIC_DIMENSION;
3281 // Save current position and parse next token.
3283 if (parse_less_than ()) {
3284 if (parsing_generic_declaration && token () != Token.DOT) {
3285 d = Token.OP_GENERICS_LT_DECL;
3287 d = Token.OP_GENERICS_LT;
3294 parsing_generic_less_than = 0;
3303 return Token.OP_SHIFT_LEFT_ASSIGN;
3305 return Token.OP_SHIFT_LEFT;
3316 // Handles one line xml comment
3318 private void handle_one_line_xml_comment ()
3321 while ((c = peek_char ()) == ' ')
3322 get_char (); // skip heading whitespaces.
3323 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3324 xml_comment_buffer.Append ((char) get_char ());
3326 if (c == '\r' || c == '\n')
3327 xml_comment_buffer.Append (Environment.NewLine);
3331 // Remove heading "*" in Javadoc-like xml documentation.
3333 private void update_formatted_doc_comment (int current_comment_start)
3335 int length = xml_comment_buffer.Length - current_comment_start;
3336 string [] lines = xml_comment_buffer.ToString (
3337 current_comment_start,
3338 length).Replace ("\r", "").Split ('\n');
3340 // The first line starts with /**, thus it is not target
3341 // for the format check.
3342 for (int i = 1; i < lines.Length; i++) {
3343 string s = lines [i];
3344 int idx = s.IndexOf ('*');
3347 if (i < lines.Length - 1)
3351 head = s.Substring (0, idx);
3352 foreach (char c in head)
3355 lines [i] = s.Substring (idx + 1);
3357 xml_comment_buffer.Remove (current_comment_start, length);
3358 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3362 // Updates current comment location.
3364 private void update_comment_location ()
3366 if (current_comment_location.IsNull) {
3367 // "-2" is for heading "//" or "/*"
3368 current_comment_location =
3369 new Location (ref_line, hidden ? -1 : col - 2);
3374 // Checks if there was incorrect doc comments and raise
3377 public void check_incorrect_doc_comment ()
3379 if (xml_comment_buffer.Length > 0)
3380 warn_incorrect_doc_comment ();
3384 // Raises a warning when tokenizer found incorrect doccomment
3387 private void warn_incorrect_doc_comment ()
3389 if (doc_state != XmlCommentState.Error) {
3390 doc_state = XmlCommentState.Error;
3391 // in csc, it is 'XML comment is not placed on
3392 // a valid language element'. But that does not
3394 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3399 // Consumes the saved xml comment lines (if any)
3400 // as for current target member or type.
3402 public string consume_doc_comment ()
3404 if (xml_comment_buffer.Length > 0) {
3405 string ret = xml_comment_buffer.ToString ();
3406 reset_doc_comment ();
3413 get { return context.Report; }
3416 void reset_doc_comment ()
3418 xml_comment_buffer.Length = 0;
3419 current_comment_location = Location.Null;
3422 public void cleanup ()
3424 if (ifstack != null && ifstack.Count >= 1) {
3425 int state = ifstack.Pop ();
3426 if ((state & REGION) != 0)
3427 Report.Error (1038, Location, "#endregion directive expected");
3429 Report.Error (1027, Location, "Expected `#endif' directive");
3435 // Indicates whether it accepts XML documentation or not.
3437 public enum XmlCommentState {
3438 // comment is allowed in this state.
3440 // comment is not allowed in this state.
3442 // once comments appeared when it is NotAllowed, then the
3443 // state is changed to it, until the state is changed to