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 CompilationSourceFile 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 List<Location> escaped_identifiers;
182 int parsing_generic_less_than;
183 readonly bool doc_processing;
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;
209 public bool parsing_attribute_section;
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.
259 static readonly KeywordEntry<int>[][] keywords;
260 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
261 static readonly Dictionary<string, object> keyword_strings; // TODO: HashSet
262 static readonly NumberStyles styles;
263 static readonly NumberFormatInfo csharp_format_info;
266 static readonly char[] pragma_warning = "warning".ToCharArray ();
267 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
268 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
269 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
271 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
273 public bool PropertyParsing {
274 get { return handle_get_set; }
275 set { handle_get_set = value; }
278 public bool EventParsing {
279 get { return handle_remove_add; }
280 set { handle_remove_add = value; }
283 public bool ConstraintsParsing {
284 get { return handle_where; }
285 set { handle_where = value; }
288 public bool TypeOfParsing {
289 get { return handle_typeof; }
290 set { handle_typeof = value; }
294 get { return tab_size; }
295 set { tab_size = value; }
298 public XmlCommentState doc_state {
299 get { return xml_doc_state; }
301 if (value == XmlCommentState.Allowed) {
302 check_incorrect_doc_comment ();
303 reset_doc_comment ();
305 xml_doc_state = value;
310 // This is used to trigger completion generation on the parser
311 public bool CompleteOnEOF;
313 void AddEscapedIdentifier (Location loc)
315 if (escaped_identifiers == null)
316 escaped_identifiers = new List<Location> ();
318 escaped_identifiers.Add (loc);
321 public bool IsEscapedIdentifier (MemberName name)
323 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
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 readonly 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 char[] value_builder = new char[256];
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 Tokenizer (SeekableStreamReader input, CompilationSourceFile file, CompilerContext ctx)
409 this.ref_name = file;
410 this.file_name = file;
416 xml_comment_buffer = new StringBuilder ();
417 doc_processing = ctx.Settings.Documentation != null;
419 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
425 // FIXME: This could be `Location.Push' but we have to
426 // find out why the MS compiler allows this
428 Mono.CSharp.Location.Push (file, file);
431 public void PushPosition ()
433 position_stack.Push (new Position (this));
436 public void PopPosition ()
438 Position p = position_stack.Pop ();
440 reader.Position = p.position;
441 ref_line = p.ref_line;
445 putback_char = p.putback_char;
446 previous_col = p.previous_col;
448 parsing_generic_less_than = p.parsing_generic_less_than;
449 current_token = p.current_token;
453 // Do not reset the position, ignore it.
454 public void DiscardPosition ()
456 position_stack.Pop ();
459 static void AddKeyword (string kw, int token)
461 keyword_strings.Add (kw, null);
463 AddKeyword (keywords, kw, token);
466 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
468 AddKeyword (keywords_preprocessor, kw, directive);
471 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
473 int length = kw.Length;
474 if (keywords[length] == null) {
475 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
478 int char_index = kw[0] - '_';
479 var kwe = keywords[length][char_index];
481 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
485 while (kwe.Next != null) {
489 kwe.Next = new KeywordEntry<T> (kw, token);
497 keyword_strings = new Dictionary<string, object> ();
499 // 11 is the length of the longest keyword for now
500 keywords = new KeywordEntry<int>[11][];
502 AddKeyword ("__arglist", Token.ARGLIST);
503 AddKeyword ("__makeref", Token.MAKEREF);
504 AddKeyword ("__reftype", Token.REFTYPE);
505 AddKeyword ("__refvalue", Token.REFVALUE);
506 AddKeyword ("abstract", Token.ABSTRACT);
507 AddKeyword ("as", Token.AS);
508 AddKeyword ("add", Token.ADD);
509 AddKeyword ("base", Token.BASE);
510 AddKeyword ("bool", Token.BOOL);
511 AddKeyword ("break", Token.BREAK);
512 AddKeyword ("byte", Token.BYTE);
513 AddKeyword ("case", Token.CASE);
514 AddKeyword ("catch", Token.CATCH);
515 AddKeyword ("char", Token.CHAR);
516 AddKeyword ("checked", Token.CHECKED);
517 AddKeyword ("class", Token.CLASS);
518 AddKeyword ("const", Token.CONST);
519 AddKeyword ("continue", Token.CONTINUE);
520 AddKeyword ("decimal", Token.DECIMAL);
521 AddKeyword ("default", Token.DEFAULT);
522 AddKeyword ("delegate", Token.DELEGATE);
523 AddKeyword ("do", Token.DO);
524 AddKeyword ("double", Token.DOUBLE);
525 AddKeyword ("else", Token.ELSE);
526 AddKeyword ("enum", Token.ENUM);
527 AddKeyword ("event", Token.EVENT);
528 AddKeyword ("explicit", Token.EXPLICIT);
529 AddKeyword ("extern", Token.EXTERN);
530 AddKeyword ("false", Token.FALSE);
531 AddKeyword ("finally", Token.FINALLY);
532 AddKeyword ("fixed", Token.FIXED);
533 AddKeyword ("float", Token.FLOAT);
534 AddKeyword ("for", Token.FOR);
535 AddKeyword ("foreach", Token.FOREACH);
536 AddKeyword ("goto", Token.GOTO);
537 AddKeyword ("get", Token.GET);
538 AddKeyword ("if", Token.IF);
539 AddKeyword ("implicit", Token.IMPLICIT);
540 AddKeyword ("in", Token.IN);
541 AddKeyword ("int", Token.INT);
542 AddKeyword ("interface", Token.INTERFACE);
543 AddKeyword ("internal", Token.INTERNAL);
544 AddKeyword ("is", Token.IS);
545 AddKeyword ("lock", Token.LOCK);
546 AddKeyword ("long", Token.LONG);
547 AddKeyword ("namespace", Token.NAMESPACE);
548 AddKeyword ("new", Token.NEW);
549 AddKeyword ("null", Token.NULL);
550 AddKeyword ("object", Token.OBJECT);
551 AddKeyword ("operator", Token.OPERATOR);
552 AddKeyword ("out", Token.OUT);
553 AddKeyword ("override", Token.OVERRIDE);
554 AddKeyword ("params", Token.PARAMS);
555 AddKeyword ("private", Token.PRIVATE);
556 AddKeyword ("protected", Token.PROTECTED);
557 AddKeyword ("public", Token.PUBLIC);
558 AddKeyword ("readonly", Token.READONLY);
559 AddKeyword ("ref", Token.REF);
560 AddKeyword ("remove", Token.REMOVE);
561 AddKeyword ("return", Token.RETURN);
562 AddKeyword ("sbyte", Token.SBYTE);
563 AddKeyword ("sealed", Token.SEALED);
564 AddKeyword ("set", Token.SET);
565 AddKeyword ("short", Token.SHORT);
566 AddKeyword ("sizeof", Token.SIZEOF);
567 AddKeyword ("stackalloc", Token.STACKALLOC);
568 AddKeyword ("static", Token.STATIC);
569 AddKeyword ("string", Token.STRING);
570 AddKeyword ("struct", Token.STRUCT);
571 AddKeyword ("switch", Token.SWITCH);
572 AddKeyword ("this", Token.THIS);
573 AddKeyword ("throw", Token.THROW);
574 AddKeyword ("true", Token.TRUE);
575 AddKeyword ("try", Token.TRY);
576 AddKeyword ("typeof", Token.TYPEOF);
577 AddKeyword ("uint", Token.UINT);
578 AddKeyword ("ulong", Token.ULONG);
579 AddKeyword ("unchecked", Token.UNCHECKED);
580 AddKeyword ("unsafe", Token.UNSAFE);
581 AddKeyword ("ushort", Token.USHORT);
582 AddKeyword ("using", Token.USING);
583 AddKeyword ("virtual", Token.VIRTUAL);
584 AddKeyword ("void", Token.VOID);
585 AddKeyword ("volatile", Token.VOLATILE);
586 AddKeyword ("while", Token.WHILE);
587 AddKeyword ("partial", Token.PARTIAL);
588 AddKeyword ("where", Token.WHERE);
589 AddKeyword ("async", Token.ASYNC);
592 AddKeyword ("from", Token.FROM);
593 AddKeyword ("join", Token.JOIN);
594 AddKeyword ("on", Token.ON);
595 AddKeyword ("equals", Token.EQUALS);
596 AddKeyword ("select", Token.SELECT);
597 AddKeyword ("group", Token.GROUP);
598 AddKeyword ("by", Token.BY);
599 AddKeyword ("let", Token.LET);
600 AddKeyword ("orderby", Token.ORDERBY);
601 AddKeyword ("ascending", Token.ASCENDING);
602 AddKeyword ("descending", Token.DESCENDING);
603 AddKeyword ("into", Token.INTO);
605 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
607 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
608 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
609 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
610 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
611 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
612 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
613 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
614 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
615 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
616 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
617 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
618 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
620 csharp_format_info = NumberFormatInfo.InvariantInfo;
621 styles = NumberStyles.Float;
623 string_builder = new System.Text.StringBuilder ();
626 int GetKeyword (char[] id, int id_len)
629 // Keywords are stored in an array of arrays grouped by their
630 // length and then by the first character
632 if (id_len >= keywords.Length || keywords [id_len] == null)
635 int first_index = id [0] - '_';
636 if (first_index > 'z' - '_')
639 var kwe = keywords [id_len] [first_index];
646 for (int i = 1; i < id_len; ++i) {
647 if (id [i] != kwe.Value [i]) {
653 } while (res == 0 && kwe != null);
667 if (!handle_remove_add)
671 if (parsing_declaration == 0)
672 res = Token.EXTERN_ALIAS;
675 if (peek_token () == Token.COLON) {
677 res = Token.DEFAULT_COLON;
681 if (!handle_where && !query_parsing)
686 // A query expression is any expression that starts with `from identifier'
687 // followed by any token except ; , =
689 if (!query_parsing) {
690 if (lambda_arguments_parsing) {
696 // HACK: to disable generics micro-parser, because PushPosition does not
697 // store identifiers array
698 parsing_generic_less_than = 1;
700 case Token.IDENTIFIER:
712 next_token = xtoken ();
713 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
716 res = Token.FROM_FIRST;
717 query_parsing = true;
718 if (context.Settings.Version <= LanguageVersion.ISO_2)
719 Report.FeatureIsNotAvailable (context, Location, "query expressions");
722 Expression.Error_VoidInvalidInTheContext (Location, Report);
726 // HACK: A token is not a keyword so we need to restore identifiers buffer
727 // which has been overwritten before we grabbed the identifier
728 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
742 case Token.ASCENDING:
743 case Token.DESCENDING:
750 case Token.NAMESPACE:
751 // TODO: some explanation needed
752 check_incorrect_doc_comment ();
756 if (parsing_block > 0) {
761 // Save current position and parse next token.
764 next_token = token ();
765 bool ok = (next_token == Token.CLASS) ||
766 (next_token == Token.STRUCT) ||
767 (next_token == Token.INTERFACE) ||
768 (next_token == Token.VOID);
773 if (next_token == Token.VOID) {
774 if (context.Settings.Version <= LanguageVersion.ISO_2)
775 Report.FeatureIsNotAvailable (context, Location, "partial methods");
776 } else if (context.Settings.Version == LanguageVersion.ISO_1)
777 Report.FeatureIsNotAvailable (context, Location, "partial types");
782 if (next_token < Token.LAST_KEYWORD) {
783 Report.Error (267, Location,
784 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
792 if (parsing_block > 0 || context.Settings.Version != LanguageVersion.Future) {
802 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
805 // Keywords are stored in an array of arrays grouped by their
806 // length and then by the first character
808 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
809 return PreprocessorDirective.Invalid;
811 int first_index = id[0] - '_';
812 if (first_index > 'z' - '_')
813 return PreprocessorDirective.Invalid;
815 var kwe = keywords_preprocessor[id_len][first_index];
817 return PreprocessorDirective.Invalid;
819 PreprocessorDirective res = PreprocessorDirective.Invalid;
822 for (int i = 1; i < id_len; ++i) {
823 if (id[i] != kwe.Value[i]) {
829 } while (res == PreprocessorDirective.Invalid && kwe != null);
834 public Location Location {
836 return new Location (ref_line, hidden ? -1 : col);
840 static bool is_identifier_start_character (int c)
842 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
845 static bool is_identifier_part_character (char c)
847 if (c >= 'a' && c <= 'z')
850 if (c >= 'A' && c <= 'Z')
853 if (c == '_' || (c >= '0' && c <= '9'))
859 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
862 public static bool IsKeyword (string s)
864 return keyword_strings.ContainsKey (s);
868 // Open parens micro parser. Detects both lambda and cast ambiguity.
870 int TokenizeOpenParens ()
875 int bracket_level = 0;
876 bool is_type = false;
877 bool can_be_type = false;
880 ptoken = current_token;
883 switch (current_token) {
884 case Token.CLOSE_PARENS:
888 // Expression inside parens is lambda, (int i) =>
890 if (current_token == Token.ARROW)
891 return Token.OPEN_PARENS_LAMBDA;
894 // Expression inside parens is single type, (int[])
897 return Token.OPEN_PARENS_CAST;
900 // Expression is possible cast, look at next token, (T)null
903 switch (current_token) {
904 case Token.OPEN_PARENS:
907 case Token.IDENTIFIER:
921 case Token.UNCHECKED:
926 // These can be part of a member access
940 return Token.OPEN_PARENS_CAST;
943 return Token.OPEN_PARENS;
946 case Token.DOUBLE_COLON:
947 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
952 case Token.IDENTIFIER:
955 if (bracket_level == 0) {
961 case Token.OP_GENERICS_LT:
963 case Token.DOUBLE_COLON:
965 if (bracket_level == 0)
969 can_be_type = is_type = false;
989 if (bracket_level == 0)
994 if (bracket_level == 0) {
996 can_be_type = is_type = false;
1000 case Token.OP_GENERICS_LT:
1001 case Token.OPEN_BRACKET:
1002 if (bracket_level++ == 0)
1006 case Token.OP_GENERICS_GT:
1007 case Token.CLOSE_BRACKET:
1011 case Token.INTERR_NULLABLE:
1013 if (bracket_level == 0)
1019 can_be_type = is_type = false;
1023 return Token.OPEN_PARENS;
1028 public static bool IsValidIdentifier (string s)
1030 if (s == null || s.Length == 0)
1033 if (!is_identifier_start_character (s [0]))
1036 for (int i = 1; i < s.Length; i ++)
1037 if (! is_identifier_part_character (s [i]))
1043 bool parse_less_than ()
1046 int the_token = token ();
1047 if (the_token == Token.OPEN_BRACKET) {
1049 the_token = token ();
1050 } while (the_token != Token.CLOSE_BRACKET);
1051 the_token = token ();
1052 } else if (the_token == Token.IN || the_token == Token.OUT) {
1053 the_token = token ();
1055 switch (the_token) {
1056 case Token.IDENTIFIER:
1074 case Token.OP_GENERICS_GT:
1081 the_token = token ();
1083 if (the_token == Token.OP_GENERICS_GT)
1085 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1087 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1089 else if (the_token == Token.OP_GENERICS_LT) {
1090 if (!parse_less_than ())
1093 } else if (the_token == Token.OPEN_BRACKET) {
1095 the_token = token ();
1096 if (the_token == Token.CLOSE_BRACKET)
1098 else if (the_token == Token.COMMA)
1099 goto rank_specifiers;
1106 bool parse_generic_dimension (out int dimension)
1111 int the_token = token ();
1112 if (the_token == Token.OP_GENERICS_GT)
1114 else if (the_token == Token.COMMA) {
1122 public int peek_token ()
1127 the_token = token ();
1134 // Tonizes `?' using custom disambiguous rules to return one
1135 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1137 // Tricky expression look like:
1139 // Foo ? a = x ? b : c;
1141 int TokenizePossibleNullableType ()
1143 if (parsing_block == 0 || parsing_type > 0)
1144 return Token.INTERR_NULLABLE;
1146 int d = peek_char ();
1149 return Token.OP_COALESCING;
1152 switch (current_token) {
1153 case Token.CLOSE_PARENS:
1158 return Token.INTERR;
1162 if (d == ',' || d == ';' || d == '>')
1163 return Token.INTERR_NULLABLE;
1164 if (d == '*' || (d >= '0' && d <= '9'))
1165 return Token.INTERR;
1169 current_token = Token.NONE;
1171 switch (xtoken ()) {
1178 next_token = Token.INTERR;
1181 case Token.SEMICOLON:
1183 case Token.CLOSE_PARENS:
1184 case Token.OPEN_BRACKET:
1185 case Token.OP_GENERICS_GT:
1186 next_token = Token.INTERR_NULLABLE;
1194 if (next_token == -1) {
1195 switch (xtoken ()) {
1197 case Token.SEMICOLON:
1198 case Token.OPEN_BRACE:
1199 case Token.CLOSE_PARENS:
1201 next_token = Token.INTERR_NULLABLE;
1205 next_token = Token.INTERR;
1213 // All shorcuts failed, do it hard way
1215 while ((ntoken = xtoken ()) != Token.EOF) {
1216 if (ntoken == Token.SEMICOLON)
1219 if (ntoken == Token.COLON) {
1220 if (++colons == interrs)
1225 if (ntoken == Token.INTERR) {
1231 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1240 bool decimal_digits (int c)
1243 bool seen_digits = false;
1246 if (number_pos == max_number_size)
1247 Error_NumericConstantTooLong ();
1248 number_builder [number_pos++] = (char) c;
1252 // We use peek_char2, because decimal_digits needs to do a
1253 // 2-character look-ahead (5.ToString for example).
1255 while ((d = peek_char2 ()) != -1){
1256 if (d >= '0' && d <= '9'){
1257 if (number_pos == max_number_size)
1258 Error_NumericConstantTooLong ();
1259 number_builder [number_pos++] = (char) d;
1269 static bool is_hex (int e)
1271 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1274 static TypeCode real_type_suffix (int c)
1278 return TypeCode.Single;
1280 return TypeCode.Double;
1282 return TypeCode.Decimal;
1284 return TypeCode.Empty;
1288 int integer_type_suffix (ulong ul, int c)
1290 bool is_unsigned = false;
1291 bool is_long = false;
1294 bool scanning = true;
1307 // if we have not seen anything in between
1308 // report this error
1310 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1330 if (is_long && is_unsigned){
1331 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1332 return Token.LITERAL;
1336 // uint if possible, or ulong else.
1338 if ((ul & 0xffffffff00000000) == 0)
1339 val = new UIntLiteral (context.BuiltinTypes, (uint) ul, Location);
1341 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1342 } else if (is_long){
1343 // long if possible, ulong otherwise
1344 if ((ul & 0x8000000000000000) != 0)
1345 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1347 val = new LongLiteral (context.BuiltinTypes, (long) ul, Location);
1349 // int, uint, long or ulong in that order
1350 if ((ul & 0xffffffff00000000) == 0){
1351 uint ui = (uint) ul;
1353 if ((ui & 0x80000000) != 0)
1354 val = new UIntLiteral (context.BuiltinTypes, ui, Location);
1356 val = new IntLiteral (context.BuiltinTypes, (int) ui, Location);
1358 if ((ul & 0x8000000000000000) != 0)
1359 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1361 val = new LongLiteral (context.BuiltinTypes, (long) ul, Location);
1364 return Token.LITERAL;
1368 // given `c' as the next char in the input decide whether
1369 // we need to convert to a special type, and then choose
1370 // the best representation for the integer
1372 int adjust_int (int c)
1375 if (number_pos > 9){
1376 ulong ul = (uint) (number_builder [0] - '0');
1378 for (int i = 1; i < number_pos; i++){
1379 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1381 return integer_type_suffix (ul, c);
1383 uint ui = (uint) (number_builder [0] - '0');
1385 for (int i = 1; i < number_pos; i++){
1386 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1388 return integer_type_suffix (ui, c);
1390 } catch (OverflowException) {
1391 Error_NumericConstantTooLong ();
1392 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1393 return Token.LITERAL;
1395 catch (FormatException) {
1396 Report.Error (1013, Location, "Invalid number");
1397 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1398 return Token.LITERAL;
1402 int adjust_real (TypeCode t)
1404 string s = new String (number_builder, 0, number_pos);
1405 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1408 case TypeCode.Decimal:
1410 val = new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), Location);
1411 } catch (OverflowException) {
1412 val = new DecimalLiteral (context.BuiltinTypes, 0, Location);
1413 Report.Error (594, Location, error_details, "decimal");
1416 case TypeCode.Single:
1418 val = new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), Location);
1419 } catch (OverflowException) {
1420 val = new FloatLiteral (context.BuiltinTypes, 0, Location);
1421 Report.Error (594, Location, error_details, "float");
1426 val = new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), Location);
1427 } catch (OverflowException) {
1428 val = new DoubleLiteral (context.BuiltinTypes, 0, Location);
1429 Report.Error (594, Location, error_details, "double");
1434 return Token.LITERAL;
1443 while ((d = peek_char ()) != -1){
1445 number_builder [number_pos++] = (char) d;
1451 string s = new String (number_builder, 0, number_pos);
1453 if (number_pos <= 8)
1454 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1456 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1457 } catch (OverflowException){
1458 Error_NumericConstantTooLong ();
1459 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1460 return Token.LITERAL;
1462 catch (FormatException) {
1463 Report.Error (1013, Location, "Invalid number");
1464 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1465 return Token.LITERAL;
1468 return integer_type_suffix (ul, peek_char ());
1472 // Invoked if we know we have .digits or digits
1474 int is_number (int c)
1476 bool is_real = false;
1480 if (c >= '0' && c <= '9'){
1482 int peek = peek_char ();
1484 if (peek == 'x' || peek == 'X')
1485 return handle_hex ();
1492 // We need to handle the case of
1493 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1496 if (decimal_digits ('.')){
1502 return adjust_int (-1);
1506 if (c == 'e' || c == 'E'){
1508 if (number_pos == max_number_size)
1509 Error_NumericConstantTooLong ();
1510 number_builder [number_pos++] = 'e';
1514 if (number_pos == max_number_size)
1515 Error_NumericConstantTooLong ();
1516 number_builder [number_pos++] = '+';
1518 } else if (c == '-') {
1519 if (number_pos == max_number_size)
1520 Error_NumericConstantTooLong ();
1521 number_builder [number_pos++] = '-';
1524 if (number_pos == max_number_size)
1525 Error_NumericConstantTooLong ();
1526 number_builder [number_pos++] = '+';
1533 var type = real_type_suffix (c);
1534 if (type == TypeCode.Empty && !is_real){
1536 return adjust_int (c);
1541 if (type == TypeCode.Empty){
1546 return adjust_real (type);
1548 throw new Exception ("Is Number should never reach this point");
1552 // Accepts exactly count (4 or 8) hex, no more no less
1554 int getHex (int count, out int surrogate, out bool error)
1559 int top = count != -1 ? count : 4;
1564 for (i = 0; i < top; i++){
1567 if (c >= '0' && c <= '9')
1568 c = (int) c - (int) '0';
1569 else if (c >= 'A' && c <= 'F')
1570 c = (int) c - (int) 'A' + 10;
1571 else if (c >= 'a' && c <= 'f')
1572 c = (int) c - (int) 'a' + 10;
1578 total = (total * 16) + c;
1580 int p = peek_char ();
1583 if (!is_hex ((char)p))
1589 if (total > 0x0010FFFF) {
1594 if (total >= 0x00010000) {
1595 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1596 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1603 int escape (int c, out int surrogate)
1639 v = getHex (-1, out surrogate, out error);
1645 return EscapeUnicode (d, out surrogate);
1648 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1657 int EscapeUnicode (int ch, out int surrogate)
1661 ch = getHex (8, out surrogate, out error);
1663 ch = getHex (4, out surrogate, out error);
1667 Report.Error (1009, Location, "Unrecognized escape sequence");
1675 if (putback_char != -1) {
1683 if (peek_char () == '\n') {
1689 } else if (x == '\n') {
1697 void advance_line ()
1707 if (putback_char == -1)
1708 putback_char = reader.Read ();
1709 return putback_char;
1714 if (putback_char != -1)
1715 return putback_char;
1716 return reader.Peek ();
1719 void putback (int c)
1721 if (putback_char != -1){
1722 Console.WriteLine ("Col: " + col);
1723 Console.WriteLine ("Row: " + line);
1724 Console.WriteLine ("Name: " + ref_name.Name);
1725 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1726 throw new Exception ("This should not happen putback on putback");
1728 if (c == '\n' || col == 0) {
1729 // It won't happen though.
1739 public bool advance ()
1741 return peek_char () != -1 || CompleteOnEOF;
1744 public Object Value {
1750 public Object value ()
1757 current_token = xtoken ();
1758 return current_token;
1761 int TokenizePreprocessorIdentifier (out int c)
1763 // skip over white space
1766 } while (c == ' ' || c == '\t');
1770 while (c != -1 && c >= 'a' && c <= 'z') {
1771 id_builder[pos++] = (char) c;
1774 int peek = peek_char ();
1775 if (peek == 'U' || peek == 'u') {
1777 c = EscapeUnicode (c, out surrogate);
1778 if (surrogate != 0) {
1779 if (is_identifier_part_character ((char) c)) {
1780 id_builder[pos++] = (char) c;
1791 PreprocessorDirective get_cmd_arg (out string arg)
1795 tokens_seen = false;
1798 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1800 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1803 // skip over white space
1804 while (c == ' ' || c == '\t')
1807 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1810 while (c != -1 && c != '\n') {
1811 if (c == '\\' && has_identifier_argument >= 0) {
1812 if (has_identifier_argument != 0) {
1813 has_identifier_argument = 1;
1815 int peek = peek_char ();
1816 if (peek == 'U' || peek == 'u') {
1818 c = EscapeUnicode (c, out surrogate);
1819 if (surrogate != 0) {
1820 if (is_identifier_part_character ((char) c)) {
1821 if (pos == value_builder.Length)
1822 Array.Resize (ref value_builder, pos * 2);
1824 value_builder[pos++] = (char) c;
1830 has_identifier_argument = -1;
1832 } else if (c == '/' && peek_char () == '/') {
1834 // Eat single-line comments
1839 } while (c != -1 && c != '\n');
1844 if (pos == value_builder.Length)
1845 Array.Resize (ref value_builder, pos * 2);
1847 value_builder[pos++] = (char) c;
1852 if (pos > max_id_size)
1853 arg = new string (value_builder, 0, pos);
1855 arg = InternIdentifier (value_builder, pos);
1857 // Eat any trailing whitespaces
1858 arg = arg.Trim (simple_whitespaces);
1865 // Handles the #line directive
1867 bool PreProcessLine (string arg)
1869 if (arg.Length == 0)
1872 if (arg == "default"){
1874 ref_name = file_name;
1876 Location.Push (file_name, ref_name);
1878 } else if (arg == "hidden"){
1886 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1887 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1890 char [] quotes = { '\"' };
1892 string name = arg.Substring (pos). Trim (quotes);
1893 ref_name = context.LookupFile (file_name, name);
1894 file_name.AddIncludeFile (ref_name);
1896 Location.Push (file_name, ref_name);
1898 ref_line = System.Int32.Parse (arg);
1909 // Handles #define and #undef
1911 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1913 if (ident.Length == 0 || ident == "true" || ident == "false"){
1914 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1918 if (ident.IndexOfAny (simple_whitespaces) != -1){
1919 Error_EndLineExpected ();
1923 if (!is_identifier_start_character (ident [0]))
1924 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1926 foreach (char c in ident.Substring (1)){
1927 if (!is_identifier_part_character (c)){
1928 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1933 if (!caller_is_taking)
1940 if (context.Settings.IsConditionalSymbolDefined (ident))
1943 file_name.AddDefine (ident);
1948 file_name.AddUndefine (ident);
1952 byte read_hex (out bool error)
1955 int c = get_char ();
1957 if ((c >= '0') && (c <= '9'))
1958 total = (int) c - (int) '0';
1959 else if ((c >= 'A') && (c <= 'F'))
1960 total = (int) c - (int) 'A' + 10;
1961 else if ((c >= 'a') && (c <= 'f'))
1962 total = (int) c - (int) 'a' + 10;
1971 if ((c >= '0') && (c <= '9'))
1972 total += (int) c - (int) '0';
1973 else if ((c >= 'A') && (c <= 'F'))
1974 total += (int) c - (int) 'A' + 10;
1975 else if ((c >= 'a') && (c <= 'f'))
1976 total += (int) c - (int) 'a' + 10;
1983 return (byte) total;
1987 // Parses #pragma checksum
1989 bool ParsePragmaChecksum ()
1992 // The syntax is ` "foo.txt" "{guid}" "hash"'
1994 int c = get_char ();
1999 string_builder.Length = 0;
2000 while (c != -1 && c != '\n') {
2007 string_builder.Append ((char) c);
2010 if (string_builder.Length == 0) {
2011 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2014 // TODO: Any white-spaces count
2018 SourceFile file = context.LookupFile (file_name, string_builder.ToString ());
2020 if (get_char () != '"' || get_char () != '{')
2024 byte[] guid_bytes = new byte [16];
2027 for (; i < 4; i++) {
2028 guid_bytes [i] = read_hex (out error);
2033 if (get_char () != '-')
2036 for (; i < 10; i++) {
2037 guid_bytes [i] = read_hex (out error);
2041 guid_bytes [i++] = read_hex (out error);
2045 if (get_char () != '-')
2049 for (; i < 16; i++) {
2050 guid_bytes [i] = read_hex (out error);
2055 if (get_char () != '}' || get_char () != '"')
2058 // TODO: Any white-spaces count
2063 if (get_char () != '"')
2066 // Any length of checksum
2067 List<byte> checksum_bytes = new List<byte> (16);
2070 while (c != '"' && c != -1) {
2071 checksum_bytes.Add (read_hex (out error));
2079 ReadSingleLineComment ();
2080 } else if (get_char () != '"') {
2084 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2085 ref_name.AutoGenerated = true;
2089 bool IsTokenIdentifierEqual (char[] identifier)
2091 for (int i = 0; i < identifier.Length; ++i) {
2092 if (identifier[i] != id_builder[i])
2099 int TokenizePragmaNumber (ref int c)
2105 if (c >= '0' && c <= '9') {
2107 uint ui = (uint) (number_builder[0] - '0');
2110 for (int i = 1; i < number_pos; i++) {
2111 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2115 } catch (OverflowException) {
2116 Error_NumericConstantTooLong ();
2123 // skip over white space
2124 while (c == ' ' || c == '\t')
2131 // skip over white space
2132 while (c == ' ' || c == '\t')
2137 ReadSingleLineComment ();
2139 Report.Warning (1692, 1, Location, "Invalid number");
2141 // Read everything till the end of the line or file
2144 } while (c != -1 && c != '\n');
2151 void ReadSingleLineComment ()
2153 if (peek_char () != '/')
2154 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2156 // Read everything till the end of the line or file
2160 } while (c != -1 && c != '\n');
2164 /// Handles #pragma directive
2166 void ParsePragmaDirective (string arg)
2169 int length = TokenizePreprocessorIdentifier (out c);
2170 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2171 length = TokenizePreprocessorIdentifier (out c);
2174 // #pragma warning disable
2175 // #pragma warning restore
2177 if (length == pragma_warning_disable.Length) {
2178 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2179 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2180 // skip over white space
2181 while (c == ' ' || c == '\t')
2186 if (c == '\n' || c == '/') {
2188 ReadSingleLineComment ();
2191 // Disable/Restore all warnings
2194 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2196 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2200 // Disable/Restore a warning or group of warnings
2204 code = TokenizePragmaNumber (ref c);
2207 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2209 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2212 } while (code >= 0 && c != '\n' && c != -1);
2219 Report.Warning (1634, 1, Location, "Expected disable or restore");
2226 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2227 if (c != ' ' || !ParsePragmaChecksum ()) {
2228 Report.Warning (1695, 1, Location,
2229 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2235 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2238 bool eval_val (string s)
2245 return file_name.IsConditionalDefined (context, s);
2248 bool pp_primary (ref string s)
2257 s = s.Substring (1);
2258 bool val = pp_expr (ref s, false);
2259 if (s.Length > 0 && s [0] == ')'){
2260 s = s.Substring (1);
2263 Error_InvalidDirective ();
2267 if (is_identifier_start_character (c)){
2273 if (is_identifier_part_character (c)){
2277 bool v = eval_val (s.Substring (0, j));
2278 s = s.Substring (j);
2281 bool vv = eval_val (s);
2286 Error_InvalidDirective ();
2290 bool pp_unary (ref string s)
2297 if (len > 1 && s [1] == '='){
2298 Error_InvalidDirective ();
2301 s = s.Substring (1);
2302 return ! pp_primary (ref s);
2304 return pp_primary (ref s);
2306 Error_InvalidDirective ();
2311 bool pp_eq (ref string s)
2313 bool va = pp_unary (ref s);
2319 if (len > 2 && s [1] == '='){
2320 s = s.Substring (2);
2321 return va == pp_unary (ref s);
2323 Error_InvalidDirective ();
2326 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2327 s = s.Substring (2);
2329 return va != pp_unary (ref s);
2338 bool pp_and (ref string s)
2340 bool va = pp_eq (ref s);
2346 if (len > 2 && s [1] == '&'){
2347 s = s.Substring (2);
2348 return (va & pp_and (ref s));
2350 Error_InvalidDirective ();
2359 // Evaluates an expression for `#if' or `#elif'
2361 bool pp_expr (ref string s, bool isTerm)
2363 bool va = pp_and (ref s);
2370 if (len > 2 && s [1] == '|'){
2371 s = s.Substring (2);
2372 return va | pp_expr (ref s, isTerm);
2374 Error_InvalidDirective ();
2379 Error_EndLineExpected ();
2387 bool eval (string s)
2389 bool v = pp_expr (ref s, true);
2398 void Error_NumericConstantTooLong ()
2400 Report.Error (1021, Location, "Integral constant is too large");
2403 void Error_InvalidDirective ()
2405 Report.Error (1517, Location, "Invalid preprocessor directive");
2408 void Error_UnexpectedDirective (string extra)
2412 "Unexpected processor directive ({0})", extra);
2415 void Error_TokensSeen ()
2417 Report.Error (1032, Location,
2418 "Cannot define or undefine preprocessor symbols after first token in file");
2421 void Eror_WrongPreprocessorLocation ()
2423 Report.Error (1040, Location,
2424 "Preprocessor directives must appear as the first non-whitespace character on a line");
2427 void Error_EndLineExpected ()
2429 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2433 // Raises a warning when tokenizer found documentation comment
2434 // on unexpected place
2436 void WarningMisplacedComment (Location loc)
2438 if (doc_state != XmlCommentState.Error) {
2439 doc_state = XmlCommentState.Error;
2440 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2445 // if true, then the code continues processing the code
2446 // if false, the code stays in a loop until another directive is
2448 // When caller_is_taking is false we ignore all directives except the ones
2449 // which can help us to identify where the #if block ends
2450 bool ParsePreprocessingDirective (bool caller_is_taking)
2453 bool region_directive = false;
2455 var directive = get_cmd_arg (out arg);
2458 // The first group of pre-processing instructions is always processed
2460 switch (directive) {
2461 case PreprocessorDirective.Region:
2462 region_directive = true;
2464 goto case PreprocessorDirective.If;
2466 case PreprocessorDirective.Endregion:
2467 if (ifstack == null || ifstack.Count == 0){
2468 Error_UnexpectedDirective ("no #region for this #endregion");
2471 int pop = ifstack.Pop ();
2473 if ((pop & REGION) == 0)
2474 Report.Error (1027, Location, "Expected `#endif' directive");
2476 return caller_is_taking;
2478 case PreprocessorDirective.If:
2479 if (ifstack == null)
2480 ifstack = new Stack<int> (2);
2482 int flags = region_directive ? REGION : 0;
2483 if (ifstack.Count == 0){
2484 flags |= PARENT_TAKING;
2486 int state = ifstack.Peek ();
2487 if ((state & TAKING) != 0) {
2488 flags |= PARENT_TAKING;
2492 if (eval (arg) && caller_is_taking) {
2493 ifstack.Push (flags | TAKING);
2496 ifstack.Push (flags);
2499 case PreprocessorDirective.Endif:
2500 if (ifstack == null || ifstack.Count == 0){
2501 Error_UnexpectedDirective ("no #if for this #endif");
2504 pop = ifstack.Pop ();
2506 if ((pop & REGION) != 0)
2507 Report.Error (1038, Location, "#endregion directive expected");
2509 if (arg.Length != 0) {
2510 Error_EndLineExpected ();
2513 if (ifstack.Count == 0)
2516 int state = ifstack.Peek ();
2517 return (state & TAKING) != 0;
2520 case PreprocessorDirective.Elif:
2521 if (ifstack == null || ifstack.Count == 0){
2522 Error_UnexpectedDirective ("no #if for this #elif");
2525 int state = ifstack.Pop ();
2527 if ((state & REGION) != 0) {
2528 Report.Error (1038, Location, "#endregion directive expected");
2532 if ((state & ELSE_SEEN) != 0){
2533 Error_UnexpectedDirective ("#elif not valid after #else");
2537 if ((state & TAKING) != 0) {
2542 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2543 ifstack.Push (state | TAKING);
2547 ifstack.Push (state);
2551 case PreprocessorDirective.Else:
2552 if (ifstack == null || ifstack.Count == 0){
2553 Error_UnexpectedDirective ("no #if for this #else");
2556 int state = ifstack.Peek ();
2558 if ((state & REGION) != 0) {
2559 Report.Error (1038, Location, "#endregion directive expected");
2563 if ((state & ELSE_SEEN) != 0){
2564 Error_UnexpectedDirective ("#else within #else");
2570 if (arg.Length != 0) {
2571 Error_EndLineExpected ();
2576 if ((state & PARENT_TAKING) != 0) {
2577 ret = (state & TAKING) == 0;
2585 ifstack.Push (state | ELSE_SEEN);
2589 case PreprocessorDirective.Define:
2590 if (any_token_seen){
2591 Error_TokensSeen ();
2592 return caller_is_taking;
2594 PreProcessDefinition (true, arg, caller_is_taking);
2595 return caller_is_taking;
2597 case PreprocessorDirective.Undef:
2598 if (any_token_seen){
2599 Error_TokensSeen ();
2600 return caller_is_taking;
2602 PreProcessDefinition (false, arg, caller_is_taking);
2603 return caller_is_taking;
2605 case PreprocessorDirective.Invalid:
2606 Report.Error (1024, Location, "Wrong preprocessor directive");
2611 // These are only processed if we are in a `taking' block
2613 if (!caller_is_taking)
2617 case PreprocessorDirective.Error:
2618 Report.Error (1029, Location, "#error: '{0}'", arg);
2621 case PreprocessorDirective.Warning:
2622 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2625 case PreprocessorDirective.Pragma:
2626 if (context.Settings.Version == LanguageVersion.ISO_1) {
2627 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2630 ParsePragmaDirective (arg);
2633 case PreprocessorDirective.Line:
2634 if (!PreProcessLine (arg))
2637 "The line number specified for #line directive is missing or invalid");
2638 return caller_is_taking;
2641 throw new NotImplementedException (directive.ToString ());
2644 private int consume_string (bool quoted)
2648 Location start_location = Location;
2652 if (quoted && peek_char () == '"') {
2653 if (pos == value_builder.Length)
2654 Array.Resize (ref value_builder, pos * 2);
2656 value_builder[pos++] = (char) c;
2665 s = InternIdentifier (value_builder, pos);
2667 s = new string (value_builder, 0, pos);
2669 val = new StringLiteral (context.BuiltinTypes, s, start_location);
2670 return Token.LITERAL;
2675 Report.Error (1010, Location, "Newline in constant");
2676 } else if (c == '\\' && !quoted) {
2678 c = escape (c, out surrogate);
2681 if (surrogate != 0) {
2682 if (pos == value_builder.Length)
2683 Array.Resize (ref value_builder, pos * 2);
2685 value_builder[pos++] = (char) c;
2688 } else if (c == -1) {
2689 Report.Error (1039, Location, "Unterminated string literal");
2693 if (pos == value_builder.Length)
2694 Array.Resize (ref value_builder, pos * 2);
2696 value_builder[pos++] = (char) c;
2700 private int consume_identifier (int s)
2702 int res = consume_identifier (s, false);
2704 if (doc_state == XmlCommentState.Allowed)
2705 doc_state = XmlCommentState.NotAllowed;
2710 int consume_identifier (int c, bool quoted)
2713 // This method is very performance sensitive. It accounts
2714 // for approximately 25% of all parser time
2722 c = escape (c, out surrogate);
2723 if (surrogate != 0) {
2724 id_builder [pos++] = (char) c;
2729 id_builder [pos++] = (char) c;
2735 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2736 id_builder [pos++] = (char) c;
2743 c = escape (c, out surrogate);
2744 if (surrogate != 0) {
2745 if (is_identifier_part_character ((char) c))
2746 id_builder[pos++] = (char) c;
2752 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2753 id_builder [pos++] = (char) c;
2760 } catch (IndexOutOfRangeException) {
2761 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2769 // Optimization: avoids doing the keyword lookup
2770 // on uppercase letters
2772 if (id_builder [0] >= '_' && !quoted) {
2773 int keyword = GetKeyword (id_builder, pos);
2774 if (keyword != -1) {
2775 val = LocatedToken.Create (null, ref_line, column);
2780 string s = InternIdentifier (id_builder, pos);
2781 val = LocatedToken.Create (s, ref_line, column);
2782 if (quoted && parsing_attribute_section)
2783 AddEscapedIdentifier (((LocatedToken) val).Location);
2785 return Token.IDENTIFIER;
2788 static string InternIdentifier (char[] charBuffer, int length)
2791 // Keep identifiers in an array of hashtables to avoid needless
2794 var identifiers_group = identifiers[length];
2796 if (identifiers_group != null) {
2797 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2801 // TODO: this should be number of files dependant
2802 // corlib compilation peaks at 1000 and System.Core at 150
2803 int capacity = length > 20 ? 10 : 100;
2804 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2805 identifiers[length] = identifiers_group;
2808 char[] chars = new char[length];
2809 Array.Copy (charBuffer, chars, length);
2811 s = new string (charBuffer, 0, length);
2812 identifiers_group.Add (chars, s);
2816 public int xtoken ()
2820 // Whether we have seen comments on the current line
2821 bool comments_seen = false;
2822 while ((c = get_char ()) != -1) {
2825 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2833 case 0xFEFF: // Ignore BOM anywhere in the file
2836 /* This is required for compatibility with .NET
2838 if (peek_char () == 0xBB) {
2841 if (get_char () == 0xBF)
2849 return consume_identifier (c);
2852 val = LocatedToken.Create (ref_line, col);
2853 return Token.OPEN_BRACE;
2855 val = LocatedToken.Create (ref_line, col);
2856 return Token.CLOSE_BRACE;
2858 // To block doccomment inside attribute declaration.
2859 if (doc_state == XmlCommentState.Allowed)
2860 doc_state = XmlCommentState.NotAllowed;
2862 val = LocatedToken.Create (ref_line, col);
2864 if (parsing_block == 0 || lambda_arguments_parsing)
2865 return Token.OPEN_BRACKET;
2867 int next = peek_char ();
2871 return Token.OPEN_BRACKET;
2879 next = peek_token ();
2880 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2881 return Token.OPEN_BRACKET;
2883 return Token.OPEN_BRACKET_EXPR;
2885 return Token.OPEN_BRACKET_EXPR;
2888 LocatedToken.CreateOptional (ref_line, col, ref val);
2889 return Token.CLOSE_BRACKET;
2891 val = LocatedToken.Create (ref_line, col);
2893 // An expression versions of parens can appear in block context only
2895 if (parsing_block != 0 && !lambda_arguments_parsing) {
2898 // Optmize most common case where we know that parens
2901 switch (current_token) {
2902 case Token.IDENTIFIER:
2910 case Token.DELEGATE:
2911 case Token.OP_GENERICS_GT:
2912 return Token.OPEN_PARENS;
2915 // Optimize using peek
2916 int xx = peek_char ();
2923 return Token.OPEN_PARENS;
2926 lambda_arguments_parsing = true;
2928 d = TokenizeOpenParens ();
2930 lambda_arguments_parsing = false;
2934 return Token.OPEN_PARENS;
2936 LocatedToken.CreateOptional (ref_line, col, ref val);
2937 return Token.CLOSE_PARENS;
2939 LocatedToken.CreateOptional (ref_line, col, ref val);
2942 LocatedToken.CreateOptional (ref_line, col, ref val);
2943 return Token.SEMICOLON;
2945 val = LocatedToken.Create (ref_line, col);
2948 val = LocatedToken.Create (ref_line, col);
2949 return TokenizePossibleNullableType ();
2951 val = LocatedToken.Create (ref_line, col);
2952 if (parsing_generic_less_than++ > 0)
2953 return Token.OP_GENERICS_LT;
2955 return TokenizeLessThan ();
2958 val = LocatedToken.Create (ref_line, col);
2966 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2967 parsing_generic_less_than--;
2968 return Token.OP_GENERICS_GT;
2977 return Token.OP_SHIFT_RIGHT_ASSIGN;
2979 return Token.OP_SHIFT_RIGHT;
2985 val = LocatedToken.Create (ref_line, col);
2989 } else if (d == '=') {
2990 d = Token.OP_ADD_ASSIGN;
2998 val = LocatedToken.Create (ref_line, col);
3002 } else if (d == '=')
3003 d = Token.OP_SUB_ASSIGN;
3013 val = LocatedToken.Create (ref_line, col);
3014 if (peek_char () == '='){
3021 val = LocatedToken.Create (ref_line, col);
3032 return Token.ASSIGN;
3035 val = LocatedToken.Create (ref_line, col);
3039 return Token.OP_AND;
3043 return Token.OP_AND_ASSIGN;
3045 return Token.BITWISE_AND;
3048 val = LocatedToken.Create (ref_line, col);
3056 return Token.OP_OR_ASSIGN;
3058 return Token.BITWISE_OR;
3061 val = LocatedToken.Create (ref_line, col);
3062 if (peek_char () == '='){
3064 return Token.OP_MULT_ASSIGN;
3071 val = LocatedToken.Create (ref_line, col);
3073 return Token.OP_DIV_ASSIGN;
3076 // Handle double-slash comments.
3079 if (doc_processing) {
3080 if (peek_char () == '/') {
3082 // Don't allow ////.
3083 if ((d = peek_char ()) != '/') {
3084 if (doc_state == XmlCommentState.Allowed)
3085 handle_one_line_xml_comment ();
3086 else if (doc_state == XmlCommentState.NotAllowed)
3087 WarningMisplacedComment (Location - 3);
3090 check_incorrect_doc_comment ();
3094 while ((d = get_char ()) != -1 && d != '\n');
3096 any_token_seen |= tokens_seen;
3097 tokens_seen = false;
3098 comments_seen = false;
3100 } else if (d == '*'){
3102 bool docAppend = false;
3103 if (doc_processing && peek_char () == '*') {
3105 // But when it is /**/, just do nothing.
3106 if (peek_char () == '/') {
3110 if (doc_state == XmlCommentState.Allowed)
3112 else if (doc_state == XmlCommentState.NotAllowed) {
3113 WarningMisplacedComment (Location - 2);
3117 int current_comment_start = 0;
3119 current_comment_start = xml_comment_buffer.Length;
3120 xml_comment_buffer.Append (Environment.NewLine);
3123 while ((d = get_char ()) != -1){
3124 if (d == '*' && peek_char () == '/'){
3126 comments_seen = true;
3130 xml_comment_buffer.Append ((char) d);
3133 any_token_seen |= tokens_seen;
3134 tokens_seen = false;
3136 // Reset 'comments_seen' just to be consistent.
3137 // It doesn't matter either way, here.
3139 comments_seen = false;
3143 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3146 update_formatted_doc_comment (current_comment_start);
3149 val = LocatedToken.Create (ref_line, col);
3153 val = LocatedToken.Create (ref_line, col);
3154 if (peek_char () == '='){
3156 return Token.OP_MOD_ASSIGN;
3158 return Token.PERCENT;
3161 val = LocatedToken.Create (ref_line, col);
3162 if (peek_char () == '='){
3164 return Token.OP_XOR_ASSIGN;
3166 return Token.CARRET;
3169 val = LocatedToken.Create (ref_line, col);
3170 if (peek_char () == ':') {
3172 return Token.DOUBLE_COLON;
3176 case '0': case '1': case '2': case '3': case '4':
3177 case '5': case '6': case '7': case '8': case '9':
3179 return is_number (c);
3181 case '\n': // white space
3182 any_token_seen |= tokens_seen;
3183 tokens_seen = false;
3184 comments_seen = false;
3190 if (d >= '0' && d <= '9')
3191 return is_number (c);
3193 LocatedToken.CreateOptional (ref_line, col, ref val);
3197 if (tokens_seen || comments_seen) {
3198 Eror_WrongPreprocessorLocation ();
3202 if (ParsePreprocessingDirective (true))
3205 bool directive_expected = false;
3206 while ((c = get_char ()) != -1) {
3208 directive_expected = true;
3209 } else if (!directive_expected) {
3210 // TODO: Implement comment support for disabled code and uncomment this code
3212 // Eror_WrongPreprocessorLocation ();
3213 // return Token.ERROR;
3218 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3222 if (ParsePreprocessingDirective (false))
3225 directive_expected = false;
3229 tokens_seen = false;
3236 return consume_string (false);
3239 return TokenizeBackslash ();
3245 return consume_string (true);
3248 if (is_identifier_start_character (c)){
3249 return consume_identifier (c, true);
3252 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3255 case EvalStatementParserCharacter:
3256 return Token.EVAL_STATEMENT_PARSER;
3257 case EvalCompilationUnitParserCharacter:
3258 return Token.EVAL_COMPILATION_UNIT_PARSER;
3259 case EvalUsingDeclarationsParserCharacter:
3260 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3263 if (is_identifier_start_character (c)) {
3265 return consume_identifier (c);
3268 if (char.IsWhiteSpace ((char) c))
3271 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3276 return Token.COMPLETE_COMPLETION;
3279 return Token.GENERATE_COMPLETION;
3286 int TokenizeBackslash ()
3288 int c = get_char ();
3291 val = new CharLiteral (context.BuiltinTypes, (char) c, Location);
3292 Report.Error (1011, Location, "Empty character literal");
3293 return Token.LITERAL;
3297 Report.Error (1010, Location, "Newline in constant");
3302 c = escape (c, out d);
3306 throw new NotImplementedException ();
3308 val = new CharLiteral (context.BuiltinTypes, (char) c, Location);
3312 Report.Error (1012, Location, "Too many characters in character literal");
3314 // Try to recover, read until newline or next "'"
3315 while ((c = get_char ()) != -1) {
3316 if (c == '\n' || c == '\'')
3321 return Token.LITERAL;
3324 int TokenizeLessThan ()
3327 if (handle_typeof) {
3329 if (parse_generic_dimension (out d)) {
3332 return Token.GENERIC_DIMENSION;
3337 // Save current position and parse next token.
3339 if (parse_less_than ()) {
3340 if (parsing_generic_declaration && token () != Token.DOT) {
3341 d = Token.OP_GENERICS_LT_DECL;
3343 d = Token.OP_GENERICS_LT;
3350 parsing_generic_less_than = 0;
3359 return Token.OP_SHIFT_LEFT_ASSIGN;
3361 return Token.OP_SHIFT_LEFT;
3372 // Handles one line xml comment
3374 private void handle_one_line_xml_comment ()
3377 while ((c = peek_char ()) == ' ')
3378 get_char (); // skip heading whitespaces.
3379 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3380 xml_comment_buffer.Append ((char) get_char ());
3382 if (c == '\r' || c == '\n')
3383 xml_comment_buffer.Append (Environment.NewLine);
3387 // Remove heading "*" in Javadoc-like xml documentation.
3389 private void update_formatted_doc_comment (int current_comment_start)
3391 int length = xml_comment_buffer.Length - current_comment_start;
3392 string [] lines = xml_comment_buffer.ToString (
3393 current_comment_start,
3394 length).Replace ("\r", "").Split ('\n');
3396 // The first line starts with /**, thus it is not target
3397 // for the format check.
3398 for (int i = 1; i < lines.Length; i++) {
3399 string s = lines [i];
3400 int idx = s.IndexOf ('*');
3403 if (i < lines.Length - 1)
3407 head = s.Substring (0, idx);
3408 foreach (char c in head)
3411 lines [i] = s.Substring (idx + 1);
3413 xml_comment_buffer.Remove (current_comment_start, length);
3414 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3418 // Checks if there was incorrect doc comments and raise
3421 public void check_incorrect_doc_comment ()
3423 if (xml_comment_buffer.Length > 0)
3424 WarningMisplacedComment (Location);
3428 // Consumes the saved xml comment lines (if any)
3429 // as for current target member or type.
3431 public string consume_doc_comment ()
3433 if (xml_comment_buffer.Length > 0) {
3434 string ret = xml_comment_buffer.ToString ();
3435 reset_doc_comment ();
3442 get { return context.Report; }
3445 void reset_doc_comment ()
3447 xml_comment_buffer.Length = 0;
3450 public void cleanup ()
3452 if (ifstack != null && ifstack.Count >= 1) {
3453 int state = ifstack.Pop ();
3454 if ((state & REGION) != 0)
3455 Report.Error (1038, Location, "#endregion directive expected");
3457 Report.Error (1027, Location, "Expected `#endif' directive");
3463 // Indicates whether it accepts XML documentation or not.
3465 public enum XmlCommentState {
3466 // comment is allowed in this state.
3468 // comment is not allowed in this state.
3470 // once comments appeared when it is NotAllowed, then the
3471 // state is changed to it, until the state is changed to