2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 // This also implements the preprocessor
5 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
17 using System.Collections.Generic;
18 using System.Globalization;
19 using System.Diagnostics;
24 /// Tokenizer for C# source code.
27 public class Tokenizer : yyParser.yyInput
31 public readonly T Token;
32 public KeywordEntry<T> Next;
33 public readonly char[] Value;
35 public KeywordEntry (string value, T token)
37 this.Value = value.ToCharArray ();
42 sealed class IdentifiersComparer : IEqualityComparer<char[]>
46 public IdentifiersComparer (int length)
51 public bool Equals (char[] x, char[] y)
53 for (int i = 0; i < length; ++i)
60 public int GetHashCode (char[] obj)
63 for (int i = 0; i < length; ++i)
64 h = (h << 5) - h + obj [i];
71 // This class has to be used in the parser only, it reuses token
72 // details after each parse
74 public class LocatedToken
79 static LocatedToken[] buffer = new LocatedToken[0];
82 private LocatedToken ()
86 public static LocatedToken Create (int row, int column)
88 return Create (null, row, column);
91 public static LocatedToken Create (string value, Location loc)
93 return Create (value, loc.Row, loc.Column);
96 public static LocatedToken Create (string value, int row, int column)
99 // TODO: I am not very happy about the logic but it's the best
100 // what I could come up with for now.
101 // Ideally we should be using just tiny buffer (256 elements) which
102 // is enough to hold all details for currect stack and recycle elements
103 // poped from the stack but there is a trick needed to recycle
107 if (pos >= buffer.Length) {
108 entry = new LocatedToken ();
110 entry = buffer [pos];
112 entry = new LocatedToken ();
113 buffer [pos] = entry;
120 entry.column = column;
125 // Used for token not required by expression evaluator
127 [Conditional ("FULL_AST")]
128 public static void CreateOptional (int row, int col, ref object token)
130 token = Create (row, col);
133 public static void Initialize ()
136 if (buffer.Length == 0)
137 buffer = new LocatedToken [15000];
142 public Location Location {
143 get { return new Location (row, column); }
146 public string Value {
147 get { return value; }
151 public enum PreprocessorDirective
157 If = 3 | RequiresArgument,
159 Elif = 5 | RequiresArgument,
161 Define = 7 | RequiresArgument,
162 Undef = 8 | RequiresArgument,
165 Pragma = 11 | CustomArgumentsParsing,
168 CustomArgumentsParsing = 1 << 10,
169 RequiresArgument = 1 << 11
172 readonly SeekableStreamReader reader;
173 readonly CompilationSourceFile source_file;
174 readonly CompilerContext context;
176 SourceFile current_source;
183 readonly int tab_size;
184 bool handle_get_set = false;
185 bool handle_remove_add = false;
186 bool handle_where = false;
187 bool handle_typeof = false;
188 bool lambda_arguments_parsing;
189 List<Location> escaped_identifiers;
190 int parsing_generic_less_than;
191 readonly bool doc_processing;
194 // Used mainly for parser optimizations. Some expressions for instance
195 // can appear only in block (including initializer, base initializer)
198 public int parsing_block;
199 internal bool query_parsing;
202 // When parsing type only, useful for ambiguous nullable types
204 public int parsing_type;
207 // Set when parsing generic declaration (type or method header)
209 public bool parsing_generic_declaration;
210 public bool parsing_generic_declaration_doc;
213 // The value indicates that we have not reach any declaration or
216 public int parsing_declaration;
218 public bool parsing_attribute_section;
220 public bool parsing_modifiers;
223 // The special characters to inject on streams to run the unit parser
224 // in the special expression mode. Using private characters from
225 // Plane Sixteen (U+100000 to U+10FFFD)
227 // This character is only tested just before the tokenizer is about to report
228 // an error; So on the regular operation mode, this addition will have no
229 // impact on the tokenizer's performance.
232 public const int EvalStatementParserCharacter = 0x100000;
233 public const int EvalCompilationUnitParserCharacter = 0x100001;
234 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
235 public const int DocumentationXref = 0x100003;
238 // XML documentation buffer. The save point is used to divide
239 // comments on types and comments on members.
241 StringBuilder xml_comment_buffer;
244 // See comment on XmlCommentState enumeration.
246 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
249 // Whether tokens have been seen on this line
251 bool tokens_seen = false;
254 // Set to true once the GENERATE_COMPLETION token has bee
255 // returned. This helps produce one GENERATE_COMPLETION,
256 // as many COMPLETE_COMPLETION as necessary to complete the
257 // AST tree and one final EOF.
262 // Whether a token has been seen on the file
263 // This is needed because `define' is not allowed to be used
264 // after a token has been seen.
271 static readonly KeywordEntry<int>[][] keywords;
272 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
273 static readonly HashSet<string> keyword_strings;
274 static readonly NumberStyles styles;
275 static readonly NumberFormatInfo csharp_format_info;
278 static readonly char[] pragma_warning = "warning".ToCharArray ();
279 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
280 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
281 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
283 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
285 public bool PropertyParsing {
286 get { return handle_get_set; }
287 set { handle_get_set = value; }
290 public bool EventParsing {
291 get { return handle_remove_add; }
292 set { handle_remove_add = value; }
295 public bool ConstraintsParsing {
296 get { return handle_where; }
297 set { handle_where = value; }
300 public bool TypeOfParsing {
301 get { return handle_typeof; }
302 set { handle_typeof = value; }
305 public XmlCommentState doc_state {
306 get { return xml_doc_state; }
308 if (value == XmlCommentState.Allowed) {
309 check_incorrect_doc_comment ();
310 reset_doc_comment ();
312 xml_doc_state = value;
317 // This is used to trigger completion generation on the parser
318 public bool CompleteOnEOF;
320 void AddEscapedIdentifier (Location loc)
322 if (escaped_identifiers == null)
323 escaped_identifiers = new List<Location> ();
325 escaped_identifiers.Add (loc);
328 public bool IsEscapedIdentifier (ATypeNameExpression name)
330 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
334 // Values for the associated token returned
336 internal int putback_char; // Used by repl only
342 const int TAKING = 1;
343 const int ELSE_SEEN = 4;
344 const int PARENT_TAKING = 8;
345 const int REGION = 16;
348 // pre-processor if stack state:
352 const int max_id_size = 512;
353 const int max_number_size = 512;
356 readonly char [] id_builder = new char [max_id_size];
358 Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
360 char [] number_builder = new char [max_number_size];
363 char[] value_builder = new char[256];
365 static readonly char [] id_builder = new char [max_id_size];
367 static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
369 static char [] number_builder = new char [max_number_size];
370 static int number_pos;
372 static char[] value_builder = new char[256];
382 // This is used when the tokenizer needs to save
383 // the current position as it needs to do some parsing
384 // on its own to deamiguate a token in behalf of the
387 Stack<Position> position_stack = new Stack<Position> (2);
395 public int putback_char;
396 public int previous_col;
397 public Stack<int> ifstack;
398 public int parsing_generic_less_than;
399 public int current_token;
402 public Position (Tokenizer t)
404 position = t.reader.Position;
406 ref_line = t.ref_line;
409 putback_char = t.putback_char;
410 previous_col = t.previous_col;
411 if (t.ifstack != null && t.ifstack.Count != 0) {
412 // There is no simple way to clone Stack<T> all
413 // methods reverse the order
414 var clone = t.ifstack.ToArray ();
415 Array.Reverse (clone);
416 ifstack = new Stack<int> (clone);
418 parsing_generic_less_than = t.parsing_generic_less_than;
419 current_token = t.current_token;
424 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file)
426 this.source_file = file;
427 this.context = file.Compiler;
428 this.current_source = file.SourceFile;
434 xml_comment_buffer = new StringBuilder ();
435 doc_processing = context.Settings.DocumentationFile != null;
437 tab_size = context.Settings.TabSize;
439 Mono.CSharp.Location.Push (current_source);
442 public void PushPosition ()
444 position_stack.Push (new Position (this));
447 public void PopPosition ()
449 Position p = position_stack.Pop ();
451 reader.Position = p.position;
452 ref_line = p.ref_line;
456 putback_char = p.putback_char;
457 previous_col = p.previous_col;
459 parsing_generic_less_than = p.parsing_generic_less_than;
460 current_token = p.current_token;
464 // Do not reset the position, ignore it.
465 public void DiscardPosition ()
467 position_stack.Pop ();
470 static void AddKeyword (string kw, int token)
472 keyword_strings.Add (kw);
474 AddKeyword (keywords, kw, token);
477 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
479 AddKeyword (keywords_preprocessor, kw, directive);
482 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
484 int length = kw.Length;
485 if (keywords[length] == null) {
486 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
489 int char_index = kw[0] - '_';
490 var kwe = keywords[length][char_index];
492 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
496 while (kwe.Next != null) {
500 kwe.Next = new KeywordEntry<T> (kw, token);
508 keyword_strings = new HashSet<string> ();
510 // 11 is the length of the longest keyword for now
511 keywords = new KeywordEntry<int>[11][];
513 AddKeyword ("__arglist", Token.ARGLIST);
514 AddKeyword ("__makeref", Token.MAKEREF);
515 AddKeyword ("__reftype", Token.REFTYPE);
516 AddKeyword ("__refvalue", Token.REFVALUE);
517 AddKeyword ("abstract", Token.ABSTRACT);
518 AddKeyword ("as", Token.AS);
519 AddKeyword ("add", Token.ADD);
520 AddKeyword ("base", Token.BASE);
521 AddKeyword ("bool", Token.BOOL);
522 AddKeyword ("break", Token.BREAK);
523 AddKeyword ("byte", Token.BYTE);
524 AddKeyword ("case", Token.CASE);
525 AddKeyword ("catch", Token.CATCH);
526 AddKeyword ("char", Token.CHAR);
527 AddKeyword ("checked", Token.CHECKED);
528 AddKeyword ("class", Token.CLASS);
529 AddKeyword ("const", Token.CONST);
530 AddKeyword ("continue", Token.CONTINUE);
531 AddKeyword ("decimal", Token.DECIMAL);
532 AddKeyword ("default", Token.DEFAULT);
533 AddKeyword ("delegate", Token.DELEGATE);
534 AddKeyword ("do", Token.DO);
535 AddKeyword ("double", Token.DOUBLE);
536 AddKeyword ("else", Token.ELSE);
537 AddKeyword ("enum", Token.ENUM);
538 AddKeyword ("event", Token.EVENT);
539 AddKeyword ("explicit", Token.EXPLICIT);
540 AddKeyword ("extern", Token.EXTERN);
541 AddKeyword ("false", Token.FALSE);
542 AddKeyword ("finally", Token.FINALLY);
543 AddKeyword ("fixed", Token.FIXED);
544 AddKeyword ("float", Token.FLOAT);
545 AddKeyword ("for", Token.FOR);
546 AddKeyword ("foreach", Token.FOREACH);
547 AddKeyword ("goto", Token.GOTO);
548 AddKeyword ("get", Token.GET);
549 AddKeyword ("if", Token.IF);
550 AddKeyword ("implicit", Token.IMPLICIT);
551 AddKeyword ("in", Token.IN);
552 AddKeyword ("int", Token.INT);
553 AddKeyword ("interface", Token.INTERFACE);
554 AddKeyword ("internal", Token.INTERNAL);
555 AddKeyword ("is", Token.IS);
556 AddKeyword ("lock", Token.LOCK);
557 AddKeyword ("long", Token.LONG);
558 AddKeyword ("namespace", Token.NAMESPACE);
559 AddKeyword ("new", Token.NEW);
560 AddKeyword ("null", Token.NULL);
561 AddKeyword ("object", Token.OBJECT);
562 AddKeyword ("operator", Token.OPERATOR);
563 AddKeyword ("out", Token.OUT);
564 AddKeyword ("override", Token.OVERRIDE);
565 AddKeyword ("params", Token.PARAMS);
566 AddKeyword ("private", Token.PRIVATE);
567 AddKeyword ("protected", Token.PROTECTED);
568 AddKeyword ("public", Token.PUBLIC);
569 AddKeyword ("readonly", Token.READONLY);
570 AddKeyword ("ref", Token.REF);
571 AddKeyword ("remove", Token.REMOVE);
572 AddKeyword ("return", Token.RETURN);
573 AddKeyword ("sbyte", Token.SBYTE);
574 AddKeyword ("sealed", Token.SEALED);
575 AddKeyword ("set", Token.SET);
576 AddKeyword ("short", Token.SHORT);
577 AddKeyword ("sizeof", Token.SIZEOF);
578 AddKeyword ("stackalloc", Token.STACKALLOC);
579 AddKeyword ("static", Token.STATIC);
580 AddKeyword ("string", Token.STRING);
581 AddKeyword ("struct", Token.STRUCT);
582 AddKeyword ("switch", Token.SWITCH);
583 AddKeyword ("this", Token.THIS);
584 AddKeyword ("throw", Token.THROW);
585 AddKeyword ("true", Token.TRUE);
586 AddKeyword ("try", Token.TRY);
587 AddKeyword ("typeof", Token.TYPEOF);
588 AddKeyword ("uint", Token.UINT);
589 AddKeyword ("ulong", Token.ULONG);
590 AddKeyword ("unchecked", Token.UNCHECKED);
591 AddKeyword ("unsafe", Token.UNSAFE);
592 AddKeyword ("ushort", Token.USHORT);
593 AddKeyword ("using", Token.USING);
594 AddKeyword ("virtual", Token.VIRTUAL);
595 AddKeyword ("void", Token.VOID);
596 AddKeyword ("volatile", Token.VOLATILE);
597 AddKeyword ("while", Token.WHILE);
598 AddKeyword ("partial", Token.PARTIAL);
599 AddKeyword ("where", Token.WHERE);
602 AddKeyword ("from", Token.FROM);
603 AddKeyword ("join", Token.JOIN);
604 AddKeyword ("on", Token.ON);
605 AddKeyword ("equals", Token.EQUALS);
606 AddKeyword ("select", Token.SELECT);
607 AddKeyword ("group", Token.GROUP);
608 AddKeyword ("by", Token.BY);
609 AddKeyword ("let", Token.LET);
610 AddKeyword ("orderby", Token.ORDERBY);
611 AddKeyword ("ascending", Token.ASCENDING);
612 AddKeyword ("descending", Token.DESCENDING);
613 AddKeyword ("into", Token.INTO);
615 // Contextual async keywords
616 AddKeyword ("async", Token.ASYNC);
617 AddKeyword ("await", Token.AWAIT);
619 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
621 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
622 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
623 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
624 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
625 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
626 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
627 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
628 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
629 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
630 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
631 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
632 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
634 csharp_format_info = NumberFormatInfo.InvariantInfo;
635 styles = NumberStyles.Float;
638 int GetKeyword (char[] id, int id_len)
641 // Keywords are stored in an array of arrays grouped by their
642 // length and then by the first character
644 if (id_len >= keywords.Length || keywords [id_len] == null)
647 int first_index = id [0] - '_';
648 if (first_index > 'z' - '_')
651 var kwe = keywords [id_len] [first_index];
658 for (int i = 1; i < id_len; ++i) {
659 if (id [i] != kwe.Value [i]) {
665 } while (res == 0 && kwe != null);
679 if (!handle_remove_add)
683 if (parsing_declaration == 0)
684 res = Token.EXTERN_ALIAS;
687 if (peek_token () == Token.COLON) {
689 res = Token.DEFAULT_COLON;
693 if (!handle_where && !query_parsing)
698 // A query expression is any expression that starts with `from identifier'
699 // followed by any token except ; , =
701 if (!query_parsing) {
702 if (lambda_arguments_parsing) {
708 // HACK: to disable generics micro-parser, because PushPosition does not
709 // store identifiers array
710 parsing_generic_less_than = 1;
712 case Token.IDENTIFIER:
724 next_token = xtoken ();
725 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
728 res = Token.FROM_FIRST;
729 query_parsing = true;
730 if (context.Settings.Version <= LanguageVersion.ISO_2)
731 Report.FeatureIsNotAvailable (context, Location, "query expressions");
734 Expression.Error_VoidInvalidInTheContext (Location, Report);
738 // HACK: A token is not a keyword so we need to restore identifiers buffer
739 // which has been overwritten before we grabbed the identifier
740 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
754 case Token.ASCENDING:
755 case Token.DESCENDING:
762 case Token.NAMESPACE:
763 // TODO: some explanation needed
764 check_incorrect_doc_comment ();
768 if (parsing_block > 0) {
773 // Save current position and parse next token.
776 next_token = token ();
777 bool ok = (next_token == Token.CLASS) ||
778 (next_token == Token.STRUCT) ||
779 (next_token == Token.INTERFACE) ||
780 (next_token == Token.VOID);
785 if (next_token == Token.VOID) {
786 if (context.Settings.Version <= LanguageVersion.ISO_2)
787 Report.FeatureIsNotAvailable (context, Location, "partial methods");
788 } else if (context.Settings.Version == LanguageVersion.ISO_1)
789 Report.FeatureIsNotAvailable (context, Location, "partial types");
794 if (next_token < Token.LAST_KEYWORD) {
795 Report.Error (267, Location,
796 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
804 if (parsing_modifiers) {
806 // Skip attributes section or constructor called async
808 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
813 } else if (parsing_block > 0) {
814 switch (peek_token ()) {
816 case Token.OPEN_PARENS_LAMBDA:
819 case Token.IDENTIFIER:
822 if (xtoken () != Token.ARROW)
835 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
836 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
842 if (parsing_block == 0)
852 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
855 // Keywords are stored in an array of arrays grouped by their
856 // length and then by the first character
858 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
859 return PreprocessorDirective.Invalid;
861 int first_index = id[0] - '_';
862 if (first_index > 'z' - '_')
863 return PreprocessorDirective.Invalid;
865 var kwe = keywords_preprocessor[id_len][first_index];
867 return PreprocessorDirective.Invalid;
869 PreprocessorDirective res = PreprocessorDirective.Invalid;
872 for (int i = 1; i < id_len; ++i) {
873 if (id[i] != kwe.Value[i]) {
879 } while (res == PreprocessorDirective.Invalid && kwe != null);
884 public Location Location {
886 return new Location (ref_line, hidden ? -1 : col);
890 static bool is_identifier_start_character (int c)
892 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
895 static bool is_identifier_part_character (char c)
897 if (c >= 'a' && c <= 'z')
900 if (c >= 'A' && c <= 'Z')
903 if (c == '_' || (c >= '0' && c <= '9'))
909 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
912 public static bool IsKeyword (string s)
914 return keyword_strings.Contains (s);
918 // Open parens micro parser. Detects both lambda and cast ambiguity.
920 int TokenizeOpenParens ()
925 int bracket_level = 0;
926 bool is_type = false;
927 bool can_be_type = false;
930 ptoken = current_token;
933 switch (current_token) {
934 case Token.CLOSE_PARENS:
938 // Expression inside parens is lambda, (int i) =>
940 if (current_token == Token.ARROW)
941 return Token.OPEN_PARENS_LAMBDA;
944 // Expression inside parens is single type, (int[])
947 return Token.OPEN_PARENS_CAST;
950 // Expression is possible cast, look at next token, (T)null
953 switch (current_token) {
954 case Token.OPEN_PARENS:
957 case Token.IDENTIFIER:
971 case Token.UNCHECKED:
976 // These can be part of a member access
990 return Token.OPEN_PARENS_CAST;
993 return Token.OPEN_PARENS;
996 case Token.DOUBLE_COLON:
997 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1002 case Token.IDENTIFIER:
1005 if (bracket_level == 0) {
1011 case Token.OP_GENERICS_LT:
1013 case Token.DOUBLE_COLON:
1015 if (bracket_level == 0)
1019 can_be_type = is_type = false;
1039 if (bracket_level == 0)
1044 if (bracket_level == 0) {
1045 bracket_level = 100;
1046 can_be_type = is_type = false;
1050 case Token.OP_GENERICS_LT:
1051 case Token.OPEN_BRACKET:
1052 if (bracket_level++ == 0)
1056 case Token.OP_GENERICS_GT:
1057 case Token.CLOSE_BRACKET:
1061 case Token.INTERR_NULLABLE:
1063 if (bracket_level == 0)
1069 can_be_type = is_type = false;
1073 return Token.OPEN_PARENS;
1078 public static bool IsValidIdentifier (string s)
1080 if (s == null || s.Length == 0)
1083 if (!is_identifier_start_character (s [0]))
1086 for (int i = 1; i < s.Length; i ++)
1087 if (! is_identifier_part_character (s [i]))
1093 bool parse_less_than ()
1096 int the_token = token ();
1097 if (the_token == Token.OPEN_BRACKET) {
1099 the_token = token ();
1100 } while (the_token != Token.CLOSE_BRACKET);
1101 the_token = token ();
1102 } else if (the_token == Token.IN || the_token == Token.OUT) {
1103 the_token = token ();
1105 switch (the_token) {
1106 case Token.IDENTIFIER:
1124 case Token.OP_GENERICS_GT:
1133 the_token = token ();
1135 if (the_token == Token.OP_GENERICS_GT)
1137 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1139 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1141 else if (the_token == Token.OP_GENERICS_LT) {
1142 if (!parse_less_than ())
1145 } else if (the_token == Token.OPEN_BRACKET) {
1147 the_token = token ();
1148 if (the_token == Token.CLOSE_BRACKET)
1150 else if (the_token == Token.COMMA)
1151 goto rank_specifiers;
1158 bool parse_generic_dimension (out int dimension)
1163 int the_token = token ();
1164 if (the_token == Token.OP_GENERICS_GT)
1166 else if (the_token == Token.COMMA) {
1174 public int peek_token ()
1179 the_token = token ();
1186 // Tonizes `?' using custom disambiguous rules to return one
1187 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1189 // Tricky expression look like:
1191 // Foo ? a = x ? b : c;
1193 int TokenizePossibleNullableType ()
1195 if (parsing_block == 0 || parsing_type > 0)
1196 return Token.INTERR_NULLABLE;
1198 int d = peek_char ();
1201 return Token.OP_COALESCING;
1204 switch (current_token) {
1205 case Token.CLOSE_PARENS:
1210 return Token.INTERR;
1214 if (d == ',' || d == ';' || d == '>')
1215 return Token.INTERR_NULLABLE;
1216 if (d == '*' || (d >= '0' && d <= '9'))
1217 return Token.INTERR;
1221 current_token = Token.NONE;
1223 switch (xtoken ()) {
1230 next_token = Token.INTERR;
1233 case Token.SEMICOLON:
1235 case Token.CLOSE_PARENS:
1236 case Token.OPEN_BRACKET:
1237 case Token.OP_GENERICS_GT:
1239 next_token = Token.INTERR_NULLABLE;
1247 if (next_token == -1) {
1248 switch (xtoken ()) {
1250 case Token.SEMICOLON:
1251 case Token.OPEN_BRACE:
1252 case Token.CLOSE_PARENS:
1254 next_token = Token.INTERR_NULLABLE;
1258 next_token = Token.INTERR;
1266 // All shorcuts failed, do it hard way
1268 while ((ntoken = xtoken ()) != Token.EOF) {
1269 if (ntoken == Token.SEMICOLON)
1272 if (ntoken == Token.COLON) {
1273 if (++colons == interrs)
1278 if (ntoken == Token.INTERR) {
1284 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1293 bool decimal_digits (int c)
1296 bool seen_digits = false;
1299 if (number_pos == max_number_size)
1300 Error_NumericConstantTooLong ();
1301 number_builder [number_pos++] = (char) c;
1305 // We use peek_char2, because decimal_digits needs to do a
1306 // 2-character look-ahead (5.ToString for example).
1308 while ((d = peek_char2 ()) != -1){
1309 if (d >= '0' && d <= '9'){
1310 if (number_pos == max_number_size)
1311 Error_NumericConstantTooLong ();
1312 number_builder [number_pos++] = (char) d;
1322 static bool is_hex (int e)
1324 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1327 static TypeCode real_type_suffix (int c)
1331 return TypeCode.Single;
1333 return TypeCode.Double;
1335 return TypeCode.Decimal;
1337 return TypeCode.Empty;
1341 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1343 bool is_unsigned = false;
1344 bool is_long = false;
1347 bool scanning = true;
1360 // if we have not seen anything in between
1361 // report this error
1363 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1383 if (is_long && is_unsigned){
1384 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1388 // uint if possible, or ulong else.
1390 if ((ul & 0xffffffff00000000) == 0)
1391 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1393 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1394 } else if (is_long){
1395 // long if possible, ulong otherwise
1396 if ((ul & 0x8000000000000000) != 0)
1397 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1399 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1401 // int, uint, long or ulong in that order
1402 if ((ul & 0xffffffff00000000) == 0){
1403 uint ui = (uint) ul;
1405 if ((ui & 0x80000000) != 0)
1406 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1408 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1410 if ((ul & 0x8000000000000000) != 0)
1411 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1413 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1419 // given `c' as the next char in the input decide whether
1420 // we need to convert to a special type, and then choose
1421 // the best representation for the integer
1423 ILiteralConstant adjust_int (int c, Location loc)
1426 if (number_pos > 9){
1427 ulong ul = (uint) (number_builder [0] - '0');
1429 for (int i = 1; i < number_pos; i++){
1430 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1433 return integer_type_suffix (ul, c, loc);
1435 uint ui = (uint) (number_builder [0] - '0');
1437 for (int i = 1; i < number_pos; i++){
1438 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1441 return integer_type_suffix (ui, c, loc);
1443 } catch (OverflowException) {
1444 Error_NumericConstantTooLong ();
1445 return new IntLiteral (context.BuiltinTypes, 0, loc);
1447 catch (FormatException) {
1448 Report.Error (1013, Location, "Invalid number");
1449 return new IntLiteral (context.BuiltinTypes, 0, loc);
1453 ILiteralConstant adjust_real (TypeCode t, Location loc)
1455 string s = new string (number_builder, 0, number_pos);
1456 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1459 case TypeCode.Decimal:
1461 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1462 } catch (OverflowException) {
1463 Report.Error (594, Location, error_details, "decimal");
1464 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1466 case TypeCode.Single:
1468 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1469 } catch (OverflowException) {
1470 Report.Error (594, Location, error_details, "float");
1471 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1475 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1476 } catch (OverflowException) {
1477 Report.Error (594, loc, error_details, "double");
1478 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1483 ILiteralConstant handle_hex (Location loc)
1489 while ((d = peek_char ()) != -1){
1491 number_builder [number_pos++] = (char) d;
1497 string s = new String (number_builder, 0, number_pos);
1500 if (number_pos <= 8)
1501 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1503 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1505 return integer_type_suffix (ul, peek_char (), loc);
1506 } catch (OverflowException){
1507 Error_NumericConstantTooLong ();
1508 return new IntLiteral (context.BuiltinTypes, 0, loc);
1510 catch (FormatException) {
1511 Report.Error (1013, Location, "Invalid number");
1512 return new IntLiteral (context.BuiltinTypes, 0, loc);
1517 // Invoked if we know we have .digits or digits
1519 int is_number (int c)
1521 ILiteralConstant res;
1524 int read_start = reader.Position - 1;
1527 // Caller did peek_char
1535 if (c >= '0' && c <= '9'){
1537 int peek = peek_char ();
1539 if (peek == 'x' || peek == 'X') {
1540 val = res = handle_hex (loc);
1542 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1545 return Token.LITERAL;
1553 // We need to handle the case of
1554 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1556 bool is_real = false;
1558 if (decimal_digits ('.')){
1564 val = res = adjust_int (-1, loc);
1567 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1569 return Token.LITERAL;
1573 if (c == 'e' || c == 'E'){
1575 if (number_pos == max_number_size)
1576 Error_NumericConstantTooLong ();
1577 number_builder [number_pos++] = (char) c;
1581 if (number_pos == max_number_size)
1582 Error_NumericConstantTooLong ();
1583 number_builder [number_pos++] = '+';
1585 } else if (c == '-') {
1586 if (number_pos == max_number_size)
1587 Error_NumericConstantTooLong ();
1588 number_builder [number_pos++] = '-';
1591 if (number_pos == max_number_size)
1592 Error_NumericConstantTooLong ();
1593 number_builder [number_pos++] = '+';
1600 var type = real_type_suffix (c);
1601 if (type == TypeCode.Empty && !is_real) {
1603 res = adjust_int (c, loc);
1607 if (type == TypeCode.Empty) {
1611 res = adjust_real (type, loc);
1617 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1618 if (chars[chars.Length - 1] == '\r')
1619 Array.Resize (ref chars, chars.Length - 1);
1620 res.ParsedValue = chars;
1623 return Token.LITERAL;
1627 // Accepts exactly count (4 or 8) hex, no more no less
1629 int getHex (int count, out int surrogate, out bool error)
1634 int top = count != -1 ? count : 4;
1639 for (i = 0; i < top; i++){
1642 if (c >= '0' && c <= '9')
1643 c = (int) c - (int) '0';
1644 else if (c >= 'A' && c <= 'F')
1645 c = (int) c - (int) 'A' + 10;
1646 else if (c >= 'a' && c <= 'f')
1647 c = (int) c - (int) 'a' + 10;
1653 total = (total * 16) + c;
1655 int p = peek_char ();
1658 if (!is_hex ((char)p))
1664 if (total > 0x0010FFFF) {
1669 if (total >= 0x00010000) {
1670 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1671 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1678 int escape (int c, out int surrogate)
1714 v = getHex (-1, out surrogate, out error);
1720 return EscapeUnicode (d, out surrogate);
1723 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1732 int EscapeUnicode (int ch, out int surrogate)
1736 ch = getHex (8, out surrogate, out error);
1738 ch = getHex (4, out surrogate, out error);
1742 Report.Error (1009, Location, "Unrecognized escape sequence");
1750 if (putback_char != -1) {
1758 if (peek_char () == '\n') {
1764 } else if (x == '\n') {
1772 void advance_line ()
1782 if (putback_char == -1)
1783 putback_char = reader.Read ();
1784 return putback_char;
1789 if (putback_char != -1)
1790 return putback_char;
1791 return reader.Peek ();
1794 public void putback (int c)
1796 if (putback_char != -1){
1797 Console.WriteLine ("Col: " + col);
1798 Console.WriteLine ("Row: " + line);
1799 Console.WriteLine ("Name: " + current_source.Name);
1800 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1801 throw new Exception ("This should not happen putback on putback");
1803 if (c == '\n' || col == 0) {
1804 // It won't happen though.
1814 public bool advance ()
1816 return peek_char () != -1 || CompleteOnEOF;
1819 public Object Value {
1825 public Object value ()
1832 current_token = xtoken ();
1833 return current_token;
1836 int TokenizePreprocessorIdentifier (out int c)
1838 // skip over white space
1841 } while (c == ' ' || c == '\t');
1845 while (c != -1 && c >= 'a' && c <= 'z') {
1846 id_builder[pos++] = (char) c;
1849 int peek = peek_char ();
1850 if (peek == 'U' || peek == 'u') {
1852 c = EscapeUnicode (c, out surrogate);
1853 if (surrogate != 0) {
1854 if (is_identifier_part_character ((char) c)) {
1855 id_builder[pos++] = (char) c;
1866 PreprocessorDirective get_cmd_arg (out string arg)
1870 tokens_seen = false;
1873 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1875 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1878 // skip over white space
1879 while (c == ' ' || c == '\t')
1882 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1885 while (c != -1 && c != '\n') {
1886 if (c == '\\' && has_identifier_argument >= 0) {
1887 if (has_identifier_argument != 0) {
1888 has_identifier_argument = 1;
1890 int peek = peek_char ();
1891 if (peek == 'U' || peek == 'u') {
1893 c = EscapeUnicode (c, out surrogate);
1894 if (surrogate != 0) {
1895 if (is_identifier_part_character ((char) c)) {
1896 if (pos == value_builder.Length)
1897 Array.Resize (ref value_builder, pos * 2);
1899 value_builder[pos++] = (char) c;
1905 has_identifier_argument = -1;
1907 } else if (c == '/' && peek_char () == '/') {
1909 // Eat single-line comments
1914 } while (c != -1 && c != '\n');
1919 if (pos == value_builder.Length)
1920 Array.Resize (ref value_builder, pos * 2);
1922 value_builder[pos++] = (char) c;
1927 if (pos > max_id_size)
1928 arg = new string (value_builder, 0, pos);
1930 arg = InternIdentifier (value_builder, pos);
1932 // Eat any trailing whitespaces
1933 arg = arg.Trim (simple_whitespaces);
1940 // Handles the #line directive
1942 bool PreProcessLine (string arg)
1944 if (arg.Length == 0)
1947 if (arg == "default"){
1949 current_source = source_file.SourceFile;
1951 Location.Push (current_source);
1953 } else if (arg == "hidden"){
1961 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1962 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1965 char [] quotes = { '\"' };
1967 string name = arg.Substring (pos).Trim (quotes);
1968 current_source = context.LookupFile (source_file, name);
1969 source_file.AddIncludeFile (current_source);
1971 Location.Push (current_source);
1973 ref_line = System.Int32.Parse (arg);
1984 // Handles #define and #undef
1986 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1988 if (ident.Length == 0 || ident == "true" || ident == "false"){
1989 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1993 if (ident.IndexOfAny (simple_whitespaces) != -1){
1994 Error_EndLineExpected ();
1998 if (!is_identifier_start_character (ident [0]))
1999 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2001 foreach (char c in ident.Substring (1)){
2002 if (!is_identifier_part_character (c)){
2003 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2008 if (!caller_is_taking)
2015 if (context.Settings.IsConditionalSymbolDefined (ident))
2018 source_file.AddDefine (ident);
2023 source_file.AddUndefine (ident);
2027 byte read_hex (out bool error)
2030 int c = get_char ();
2032 if ((c >= '0') && (c <= '9'))
2033 total = (int) c - (int) '0';
2034 else if ((c >= 'A') && (c <= 'F'))
2035 total = (int) c - (int) 'A' + 10;
2036 else if ((c >= 'a') && (c <= 'f'))
2037 total = (int) c - (int) 'a' + 10;
2046 if ((c >= '0') && (c <= '9'))
2047 total += (int) c - (int) '0';
2048 else if ((c >= 'A') && (c <= 'F'))
2049 total += (int) c - (int) 'A' + 10;
2050 else if ((c >= 'a') && (c <= 'f'))
2051 total += (int) c - (int) 'a' + 10;
2058 return (byte) total;
2062 // Parses #pragma checksum
2064 bool ParsePragmaChecksum ()
2067 // The syntax is ` "foo.txt" "{guid}" "hash"'
2069 int c = get_char ();
2074 var string_builder = new StringBuilder ();
2075 while (c != -1 && c != '\n') {
2082 string_builder.Append ((char) c);
2085 if (string_builder.Length == 0) {
2086 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2089 // TODO: Any white-spaces count
2093 SourceFile file = context.LookupFile (source_file, string_builder.ToString ());
2095 if (get_char () != '"' || get_char () != '{')
2099 byte[] guid_bytes = new byte [16];
2102 for (; i < 4; i++) {
2103 guid_bytes [i] = read_hex (out error);
2108 if (get_char () != '-')
2111 for (; i < 10; i++) {
2112 guid_bytes [i] = read_hex (out error);
2116 guid_bytes [i++] = read_hex (out error);
2120 if (get_char () != '-')
2124 for (; i < 16; i++) {
2125 guid_bytes [i] = read_hex (out error);
2130 if (get_char () != '}' || get_char () != '"')
2133 // TODO: Any white-spaces count
2138 if (get_char () != '"')
2141 // Any length of checksum
2142 List<byte> checksum_bytes = new List<byte> (16);
2145 while (c != '"' && c != -1) {
2146 checksum_bytes.Add (read_hex (out error));
2154 ReadSingleLineComment ();
2155 } else if (get_char () != '"') {
2159 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2160 current_source.AutoGenerated = true;
2164 bool IsTokenIdentifierEqual (char[] identifier)
2166 for (int i = 0; i < identifier.Length; ++i) {
2167 if (identifier[i] != id_builder[i])
2174 int TokenizePragmaNumber (ref int c)
2180 if (c >= '0' && c <= '9') {
2182 uint ui = (uint) (number_builder[0] - '0');
2185 for (int i = 1; i < number_pos; i++) {
2186 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2190 } catch (OverflowException) {
2191 Error_NumericConstantTooLong ();
2198 // skip over white space
2199 while (c == ' ' || c == '\t')
2206 // skip over white space
2207 while (c == ' ' || c == '\t')
2212 ReadSingleLineComment ();
2214 Report.Warning (1692, 1, Location, "Invalid number");
2216 // Read everything till the end of the line or file
2219 } while (c != -1 && c != '\n');
2226 void ReadSingleLineComment ()
2228 if (peek_char () != '/')
2229 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2231 // Read everything till the end of the line or file
2235 } while (c != -1 && c != '\n');
2239 /// Handles #pragma directive
2241 void ParsePragmaDirective (string arg)
2244 int length = TokenizePreprocessorIdentifier (out c);
2245 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2246 length = TokenizePreprocessorIdentifier (out c);
2249 // #pragma warning disable
2250 // #pragma warning restore
2252 if (length == pragma_warning_disable.Length) {
2253 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2254 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2255 // skip over white space
2256 while (c == ' ' || c == '\t')
2261 if (c == '\n' || c == '/') {
2263 ReadSingleLineComment ();
2266 // Disable/Restore all warnings
2269 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2271 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2275 // Disable/Restore a warning or group of warnings
2279 code = TokenizePragmaNumber (ref c);
2282 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2284 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2287 } while (code >= 0 && c != '\n' && c != -1);
2294 Report.Warning (1634, 1, Location, "Expected disable or restore");
2301 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2302 if (c != ' ' || !ParsePragmaChecksum ()) {
2303 Report.Warning (1695, 1, Location,
2304 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2310 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2313 bool eval_val (string s)
2320 return source_file.IsConditionalDefined (s);
2323 bool pp_primary (ref string s)
2332 s = s.Substring (1);
2333 bool val = pp_expr (ref s, false);
2334 if (s.Length > 0 && s [0] == ')'){
2335 s = s.Substring (1);
2338 Error_InvalidDirective ();
2342 if (is_identifier_start_character (c)){
2348 if (is_identifier_part_character (c)){
2352 bool v = eval_val (s.Substring (0, j));
2353 s = s.Substring (j);
2356 bool vv = eval_val (s);
2361 Error_InvalidDirective ();
2365 bool pp_unary (ref string s)
2372 if (len > 1 && s [1] == '='){
2373 Error_InvalidDirective ();
2376 s = s.Substring (1);
2377 return ! pp_primary (ref s);
2379 return pp_primary (ref s);
2381 Error_InvalidDirective ();
2386 bool pp_eq (ref string s)
2388 bool va = pp_unary (ref s);
2394 if (len > 2 && s [1] == '='){
2395 s = s.Substring (2);
2396 return va == pp_unary (ref s);
2398 Error_InvalidDirective ();
2401 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2402 s = s.Substring (2);
2404 return va != pp_unary (ref s);
2413 bool pp_and (ref string s)
2415 bool va = pp_eq (ref s);
2421 if (len > 2 && s [1] == '&'){
2422 s = s.Substring (2);
2423 return (va & pp_and (ref s));
2425 Error_InvalidDirective ();
2434 // Evaluates an expression for `#if' or `#elif'
2436 bool pp_expr (ref string s, bool isTerm)
2438 bool va = pp_and (ref s);
2445 if (len > 2 && s [1] == '|'){
2446 s = s.Substring (2);
2447 return va | pp_expr (ref s, isTerm);
2449 Error_InvalidDirective ();
2454 Error_EndLineExpected ();
2462 bool eval (string s)
2464 bool v = pp_expr (ref s, true);
2473 void Error_NumericConstantTooLong ()
2475 Report.Error (1021, Location, "Integral constant is too large");
2478 void Error_InvalidDirective ()
2480 Report.Error (1517, Location, "Invalid preprocessor directive");
2483 void Error_UnexpectedDirective (string extra)
2487 "Unexpected processor directive ({0})", extra);
2490 void Error_TokensSeen ()
2492 Report.Error (1032, Location,
2493 "Cannot define or undefine preprocessor symbols after first token in file");
2496 void Eror_WrongPreprocessorLocation ()
2498 Report.Error (1040, Location,
2499 "Preprocessor directives must appear as the first non-whitespace character on a line");
2502 void Error_EndLineExpected ()
2504 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2508 // Raises a warning when tokenizer found documentation comment
2509 // on unexpected place
2511 void WarningMisplacedComment (Location loc)
2513 if (doc_state != XmlCommentState.Error) {
2514 doc_state = XmlCommentState.Error;
2515 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2520 // if true, then the code continues processing the code
2521 // if false, the code stays in a loop until another directive is
2523 // When caller_is_taking is false we ignore all directives except the ones
2524 // which can help us to identify where the #if block ends
2525 bool ParsePreprocessingDirective (bool caller_is_taking)
2528 bool region_directive = false;
2530 var directive = get_cmd_arg (out arg);
2533 // The first group of pre-processing instructions is always processed
2535 switch (directive) {
2536 case PreprocessorDirective.Region:
2537 region_directive = true;
2539 goto case PreprocessorDirective.If;
2541 case PreprocessorDirective.Endregion:
2542 if (ifstack == null || ifstack.Count == 0){
2543 Error_UnexpectedDirective ("no #region for this #endregion");
2546 int pop = ifstack.Pop ();
2548 if ((pop & REGION) == 0)
2549 Report.Error (1027, Location, "Expected `#endif' directive");
2551 return caller_is_taking;
2553 case PreprocessorDirective.If:
2554 if (ifstack == null)
2555 ifstack = new Stack<int> (2);
2557 int flags = region_directive ? REGION : 0;
2558 if (ifstack.Count == 0){
2559 flags |= PARENT_TAKING;
2561 int state = ifstack.Peek ();
2562 if ((state & TAKING) != 0) {
2563 flags |= PARENT_TAKING;
2567 if (eval (arg) && caller_is_taking) {
2568 ifstack.Push (flags | TAKING);
2571 ifstack.Push (flags);
2574 case PreprocessorDirective.Endif:
2575 if (ifstack == null || ifstack.Count == 0){
2576 Error_UnexpectedDirective ("no #if for this #endif");
2579 pop = ifstack.Pop ();
2581 if ((pop & REGION) != 0)
2582 Report.Error (1038, Location, "#endregion directive expected");
2584 if (arg.Length != 0) {
2585 Error_EndLineExpected ();
2588 if (ifstack.Count == 0)
2591 int state = ifstack.Peek ();
2592 return (state & TAKING) != 0;
2595 case PreprocessorDirective.Elif:
2596 if (ifstack == null || ifstack.Count == 0){
2597 Error_UnexpectedDirective ("no #if for this #elif");
2600 int state = ifstack.Pop ();
2602 if ((state & REGION) != 0) {
2603 Report.Error (1038, Location, "#endregion directive expected");
2607 if ((state & ELSE_SEEN) != 0){
2608 Error_UnexpectedDirective ("#elif not valid after #else");
2612 if ((state & TAKING) != 0) {
2617 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2618 ifstack.Push (state | TAKING);
2622 ifstack.Push (state);
2626 case PreprocessorDirective.Else:
2627 if (ifstack == null || ifstack.Count == 0){
2628 Error_UnexpectedDirective ("no #if for this #else");
2631 int state = ifstack.Peek ();
2633 if ((state & REGION) != 0) {
2634 Report.Error (1038, Location, "#endregion directive expected");
2638 if ((state & ELSE_SEEN) != 0){
2639 Error_UnexpectedDirective ("#else within #else");
2645 if (arg.Length != 0) {
2646 Error_EndLineExpected ();
2651 if ((state & PARENT_TAKING) != 0) {
2652 ret = (state & TAKING) == 0;
2660 ifstack.Push (state | ELSE_SEEN);
2664 case PreprocessorDirective.Define:
2665 if (any_token_seen){
2666 Error_TokensSeen ();
2667 return caller_is_taking;
2669 PreProcessDefinition (true, arg, caller_is_taking);
2670 return caller_is_taking;
2672 case PreprocessorDirective.Undef:
2673 if (any_token_seen){
2674 Error_TokensSeen ();
2675 return caller_is_taking;
2677 PreProcessDefinition (false, arg, caller_is_taking);
2678 return caller_is_taking;
2680 case PreprocessorDirective.Invalid:
2681 Report.Error (1024, Location, "Wrong preprocessor directive");
2686 // These are only processed if we are in a `taking' block
2688 if (!caller_is_taking)
2692 case PreprocessorDirective.Error:
2693 Report.Error (1029, Location, "#error: '{0}'", arg);
2696 case PreprocessorDirective.Warning:
2697 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2700 case PreprocessorDirective.Pragma:
2701 if (context.Settings.Version == LanguageVersion.ISO_1) {
2702 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2705 ParsePragmaDirective (arg);
2708 case PreprocessorDirective.Line:
2709 if (!PreProcessLine (arg))
2712 "The line number specified for #line directive is missing or invalid");
2713 return caller_is_taking;
2716 throw new NotImplementedException (directive.ToString ());
2719 private int consume_string (bool quoted)
2723 Location start_location = Location;
2725 start_location = start_location - 1;
2728 int reader_pos = reader.Position;
2734 if (quoted && peek_char () == '"') {
2735 if (pos == value_builder.Length)
2736 Array.Resize (ref value_builder, pos * 2);
2738 value_builder[pos++] = (char) c;
2747 s = InternIdentifier (value_builder, pos);
2749 s = new string (value_builder, 0, pos);
2751 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2754 res.ParsedValue = quoted ?
2755 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2756 reader.ReadChars (reader_pos - 1, reader.Position);
2759 return Token.LITERAL;
2764 Report.Error (1010, Location, "Newline in constant");
2765 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2766 return Token.LITERAL;
2768 } else if (c == '\\' && !quoted) {
2770 c = escape (c, out surrogate);
2773 if (surrogate != 0) {
2774 if (pos == value_builder.Length)
2775 Array.Resize (ref value_builder, pos * 2);
2777 value_builder[pos++] = (char) c;
2780 } else if (c == -1) {
2781 Report.Error (1039, Location, "Unterminated string literal");
2785 if (pos == value_builder.Length)
2786 Array.Resize (ref value_builder, pos * 2);
2788 value_builder[pos++] = (char) c;
2792 private int consume_identifier (int s)
2794 int res = consume_identifier (s, false);
2796 if (doc_state == XmlCommentState.Allowed)
2797 doc_state = XmlCommentState.NotAllowed;
2802 int consume_identifier (int c, bool quoted)
2805 // This method is very performance sensitive. It accounts
2806 // for approximately 25% of all parser time
2816 c = escape (c, out surrogate);
2817 if (surrogate != 0) {
2818 id_builder [pos++] = (char) c;
2823 id_builder [pos++] = (char) c;
2829 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2830 id_builder [pos++] = (char) c;
2837 c = escape (c, out surrogate);
2838 if (is_identifier_part_character ((char) c))
2839 id_builder[pos++] = (char) c;
2841 if (surrogate != 0) {
2847 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2848 id_builder [pos++] = (char) c;
2855 } catch (IndexOutOfRangeException) {
2856 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2864 // Optimization: avoids doing the keyword lookup
2865 // on uppercase letters
2867 if (id_builder [0] >= '_' && !quoted) {
2868 int keyword = GetKeyword (id_builder, pos);
2869 if (keyword != -1) {
2870 val = LocatedToken.Create (keyword == Token.AWAIT ? "await" : null, ref_line, column);
2875 string s = InternIdentifier (id_builder, pos);
2876 val = LocatedToken.Create (s, ref_line, column);
2877 if (quoted && parsing_attribute_section)
2878 AddEscapedIdentifier (((LocatedToken) val).Location);
2880 return Token.IDENTIFIER;
2883 string InternIdentifier (char[] charBuffer, int length)
2886 // Keep identifiers in an array of hashtables to avoid needless
2889 var identifiers_group = identifiers[length];
2891 if (identifiers_group != null) {
2892 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2896 // TODO: this should be number of files dependant
2897 // corlib compilation peaks at 1000 and System.Core at 150
2898 int capacity = length > 20 ? 10 : 100;
2899 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2900 identifiers[length] = identifiers_group;
2903 char[] chars = new char[length];
2904 Array.Copy (charBuffer, chars, length);
2906 s = new string (charBuffer, 0, length);
2907 identifiers_group.Add (chars, s);
2911 public int xtoken ()
2915 // Whether we have seen comments on the current line
2916 bool comments_seen = false;
2917 while ((c = get_char ()) != -1) {
2920 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2928 case 0xFEFF: // Ignore BOM anywhere in the file
2931 /* This is required for compatibility with .NET
2933 if (peek_char () == 0xBB) {
2936 if (get_char () == 0xBF)
2944 return consume_identifier (c);
2947 val = LocatedToken.Create (ref_line, col);
2948 return Token.OPEN_BRACE;
2950 val = LocatedToken.Create (ref_line, col);
2951 return Token.CLOSE_BRACE;
2953 // To block doccomment inside attribute declaration.
2954 if (doc_state == XmlCommentState.Allowed)
2955 doc_state = XmlCommentState.NotAllowed;
2957 val = LocatedToken.Create (ref_line, col);
2959 if (parsing_block == 0 || lambda_arguments_parsing)
2960 return Token.OPEN_BRACKET;
2962 int next = peek_char ();
2966 return Token.OPEN_BRACKET;
2974 next = peek_token ();
2975 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2976 return Token.OPEN_BRACKET;
2978 return Token.OPEN_BRACKET_EXPR;
2980 return Token.OPEN_BRACKET_EXPR;
2983 LocatedToken.CreateOptional (ref_line, col, ref val);
2984 return Token.CLOSE_BRACKET;
2986 val = LocatedToken.Create (ref_line, col);
2988 // An expression versions of parens can appear in block context only
2990 if (parsing_block != 0 && !lambda_arguments_parsing) {
2993 // Optmize most common case where we know that parens
2996 switch (current_token) {
2997 case Token.IDENTIFIER:
3005 case Token.DELEGATE:
3006 case Token.OP_GENERICS_GT:
3007 return Token.OPEN_PARENS;
3010 // Optimize using peek
3011 int xx = peek_char ();
3018 return Token.OPEN_PARENS;
3021 lambda_arguments_parsing = true;
3023 d = TokenizeOpenParens ();
3025 lambda_arguments_parsing = false;
3029 return Token.OPEN_PARENS;
3031 LocatedToken.CreateOptional (ref_line, col, ref val);
3032 return Token.CLOSE_PARENS;
3034 LocatedToken.CreateOptional (ref_line, col, ref val);
3037 LocatedToken.CreateOptional (ref_line, col, ref val);
3038 return Token.SEMICOLON;
3040 val = LocatedToken.Create (ref_line, col);
3043 val = LocatedToken.Create (ref_line, col);
3044 return TokenizePossibleNullableType ();
3046 val = LocatedToken.Create (ref_line, col);
3047 if (parsing_generic_less_than++ > 0)
3048 return Token.OP_GENERICS_LT;
3050 return TokenizeLessThan ();
3053 val = LocatedToken.Create (ref_line, col);
3061 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3062 parsing_generic_less_than--;
3063 return Token.OP_GENERICS_GT;
3072 return Token.OP_SHIFT_RIGHT_ASSIGN;
3074 return Token.OP_SHIFT_RIGHT;
3080 val = LocatedToken.Create (ref_line, col);
3084 } else if (d == '=') {
3085 d = Token.OP_ADD_ASSIGN;
3093 val = LocatedToken.Create (ref_line, col);
3097 } else if (d == '=')
3098 d = Token.OP_SUB_ASSIGN;
3108 val = LocatedToken.Create (ref_line, col);
3109 if (peek_char () == '='){
3116 val = LocatedToken.Create (ref_line, col);
3127 return Token.ASSIGN;
3130 val = LocatedToken.Create (ref_line, col);
3134 return Token.OP_AND;
3138 return Token.OP_AND_ASSIGN;
3140 return Token.BITWISE_AND;
3143 val = LocatedToken.Create (ref_line, col);
3151 return Token.OP_OR_ASSIGN;
3153 return Token.BITWISE_OR;
3156 val = LocatedToken.Create (ref_line, col);
3157 if (peek_char () == '='){
3159 return Token.OP_MULT_ASSIGN;
3166 val = LocatedToken.Create (ref_line, col);
3168 return Token.OP_DIV_ASSIGN;
3171 // Handle double-slash comments.
3174 if (doc_processing) {
3175 if (peek_char () == '/') {
3177 // Don't allow ////.
3178 if ((d = peek_char ()) != '/') {
3179 if (doc_state == XmlCommentState.Allowed)
3180 handle_one_line_xml_comment ();
3181 else if (doc_state == XmlCommentState.NotAllowed)
3182 WarningMisplacedComment (Location - 3);
3185 if (xml_comment_buffer.Length > 0)
3186 doc_state = XmlCommentState.NotAllowed;
3190 while ((d = get_char ()) != -1 && d != '\n');
3192 any_token_seen |= tokens_seen;
3193 tokens_seen = false;
3194 comments_seen = false;
3196 } else if (d == '*'){
3198 bool docAppend = false;
3199 if (doc_processing && peek_char () == '*') {
3201 // But when it is /**/, just do nothing.
3202 if (peek_char () == '/') {
3206 if (doc_state == XmlCommentState.Allowed)
3208 else if (doc_state == XmlCommentState.NotAllowed) {
3209 WarningMisplacedComment (Location - 2);
3213 int current_comment_start = 0;
3215 current_comment_start = xml_comment_buffer.Length;
3216 xml_comment_buffer.Append (Environment.NewLine);
3219 while ((d = get_char ()) != -1){
3220 if (d == '*' && peek_char () == '/'){
3222 comments_seen = true;
3226 xml_comment_buffer.Append ((char) d);
3229 any_token_seen |= tokens_seen;
3230 tokens_seen = false;
3232 // Reset 'comments_seen' just to be consistent.
3233 // It doesn't matter either way, here.
3235 comments_seen = false;
3239 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3242 update_formatted_doc_comment (current_comment_start);
3245 val = LocatedToken.Create (ref_line, col);
3249 val = LocatedToken.Create (ref_line, col);
3250 if (peek_char () == '='){
3252 return Token.OP_MOD_ASSIGN;
3254 return Token.PERCENT;
3257 val = LocatedToken.Create (ref_line, col);
3258 if (peek_char () == '='){
3260 return Token.OP_XOR_ASSIGN;
3262 return Token.CARRET;
3265 val = LocatedToken.Create (ref_line, col);
3266 if (peek_char () == ':') {
3268 return Token.DOUBLE_COLON;
3272 case '0': case '1': case '2': case '3': case '4':
3273 case '5': case '6': case '7': case '8': case '9':
3275 return is_number (c);
3277 case '\n': // white space
3278 any_token_seen |= tokens_seen;
3279 tokens_seen = false;
3280 comments_seen = false;
3286 if (d >= '0' && d <= '9')
3287 return is_number (c);
3289 LocatedToken.CreateOptional (ref_line, col, ref val);
3293 if (tokens_seen || comments_seen) {
3294 Eror_WrongPreprocessorLocation ();
3298 if (ParsePreprocessingDirective (true))
3301 bool directive_expected = false;
3302 while ((c = get_char ()) != -1) {
3304 directive_expected = true;
3305 } else if (!directive_expected) {
3306 // TODO: Implement comment support for disabled code and uncomment this code
3308 // Eror_WrongPreprocessorLocation ();
3309 // return Token.ERROR;
3314 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3318 if (ParsePreprocessingDirective (false))
3321 directive_expected = false;
3325 tokens_seen = false;
3332 return consume_string (false);
3335 return TokenizeBackslash ();
3341 return consume_string (true);
3344 if (is_identifier_start_character (c)){
3345 return consume_identifier (c, true);
3348 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3351 case EvalStatementParserCharacter:
3352 return Token.EVAL_STATEMENT_PARSER;
3353 case EvalCompilationUnitParserCharacter:
3354 return Token.EVAL_COMPILATION_UNIT_PARSER;
3355 case EvalUsingDeclarationsParserCharacter:
3356 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3357 case DocumentationXref:
3358 return Token.DOC_SEE;
3361 if (is_identifier_start_character (c)) {
3363 return consume_identifier (c);
3366 if (char.IsWhiteSpace ((char) c))
3369 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3374 return Token.COMPLETE_COMPLETION;
3377 return Token.GENERATE_COMPLETION;
3384 int TokenizeBackslash ()
3387 int read_start = reader.Position;
3389 Location start_location = Location;
3390 int c = get_char ();
3393 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3394 Report.Error (1011, start_location, "Empty character literal");
3395 return Token.LITERAL;
3399 Report.Error (1010, start_location, "Newline in constant");
3404 c = escape (c, out d);
3408 throw new NotImplementedException ();
3410 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3415 Report.Error (1012, start_location, "Too many characters in character literal");
3417 // Try to recover, read until newline or next "'"
3418 while ((c = get_char ()) != -1) {
3419 if (c == '\n' || c == '\'')
3425 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3428 return Token.LITERAL;
3431 int TokenizeLessThan ()
3434 if (handle_typeof) {
3436 if (parse_generic_dimension (out d)) {
3439 return Token.GENERIC_DIMENSION;
3444 // Save current position and parse next token.
3446 if (parse_less_than ()) {
3447 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3448 d = Token.OP_GENERICS_LT_DECL;
3450 d = Token.OP_GENERICS_LT;
3457 parsing_generic_less_than = 0;
3466 return Token.OP_SHIFT_LEFT_ASSIGN;
3468 return Token.OP_SHIFT_LEFT;
3479 // Handles one line xml comment
3481 private void handle_one_line_xml_comment ()
3484 while ((c = peek_char ()) == ' ')
3485 get_char (); // skip heading whitespaces.
3486 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3487 xml_comment_buffer.Append ((char) get_char ());
3489 if (c == '\r' || c == '\n')
3490 xml_comment_buffer.Append (Environment.NewLine);
3494 // Remove heading "*" in Javadoc-like xml documentation.
3496 private void update_formatted_doc_comment (int current_comment_start)
3498 int length = xml_comment_buffer.Length - current_comment_start;
3499 string [] lines = xml_comment_buffer.ToString (
3500 current_comment_start,
3501 length).Replace ("\r", "").Split ('\n');
3503 // The first line starts with /**, thus it is not target
3504 // for the format check.
3505 for (int i = 1; i < lines.Length; i++) {
3506 string s = lines [i];
3507 int idx = s.IndexOf ('*');
3510 if (i < lines.Length - 1)
3514 head = s.Substring (0, idx);
3515 foreach (char c in head)
3518 lines [i] = s.Substring (idx + 1);
3520 xml_comment_buffer.Remove (current_comment_start, length);
3521 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3525 // Checks if there was incorrect doc comments and raise
3528 public void check_incorrect_doc_comment ()
3530 if (xml_comment_buffer.Length > 0)
3531 WarningMisplacedComment (Location);
3535 // Consumes the saved xml comment lines (if any)
3536 // as for current target member or type.
3538 public string consume_doc_comment ()
3540 if (xml_comment_buffer.Length > 0) {
3541 string ret = xml_comment_buffer.ToString ();
3542 reset_doc_comment ();
3549 get { return context.Report; }
3552 void reset_doc_comment ()
3554 xml_comment_buffer.Length = 0;
3557 public void cleanup ()
3559 if (ifstack != null && ifstack.Count >= 1) {
3560 int state = ifstack.Pop ();
3561 if ((state & REGION) != 0)
3562 Report.Error (1038, Location, "#endregion directive expected");
3564 Report.Error (1027, Location, "Expected `#endif' directive");
3570 // Indicates whether it accepts XML documentation or not.
3572 public enum XmlCommentState {
3573 // comment is allowed in this state.
3575 // comment is not allowed in this state.
3577 // once comments appeared when it is NotAllowed, then the
3578 // state is changed to it, until the state is changed to