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;
202 public bool parsing_generic_declaration_doc;
205 // The value indicates that we have not reach any declaration or
208 public int parsing_declaration;
210 public bool parsing_attribute_section;
213 // The special characters to inject on streams to run the unit parser
214 // in the special expression mode. Using private characters from
215 // Plane Sixteen (U+100000 to U+10FFFD)
217 // This character is only tested just before the tokenizer is about to report
218 // an error; So on the regular operation mode, this addition will have no
219 // impact on the tokenizer's performance.
222 public const int EvalStatementParserCharacter = 0x100000;
223 public const int EvalCompilationUnitParserCharacter = 0x100001;
224 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
225 public const int DocumentationXref = 0x100003;
228 // XML documentation buffer. The save point is used to divide
229 // comments on types and comments on members.
231 StringBuilder xml_comment_buffer;
234 // See comment on XmlCommentState enumeration.
236 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
239 // Whether tokens have been seen on this line
241 bool tokens_seen = false;
244 // Set to true once the GENERATE_COMPLETION token has bee
245 // returned. This helps produce one GENERATE_COMPLETION,
246 // as many COMPLETE_COMPLETION as necessary to complete the
247 // AST tree and one final EOF.
252 // Whether a token has been seen on the file
253 // This is needed because `define' is not allowed to be used
254 // after a token has been seen.
261 static readonly KeywordEntry<int>[][] keywords;
262 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
263 static readonly Dictionary<string, object> keyword_strings; // TODO: HashSet
264 static readonly NumberStyles styles;
265 static readonly NumberFormatInfo csharp_format_info;
268 static readonly char[] pragma_warning = "warning".ToCharArray ();
269 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
270 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
271 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
273 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
275 public bool PropertyParsing {
276 get { return handle_get_set; }
277 set { handle_get_set = value; }
280 public bool EventParsing {
281 get { return handle_remove_add; }
282 set { handle_remove_add = value; }
285 public bool ConstraintsParsing {
286 get { return handle_where; }
287 set { handle_where = value; }
290 public bool TypeOfParsing {
291 get { return handle_typeof; }
292 set { handle_typeof = value; }
296 get { return tab_size; }
297 set { tab_size = value; }
300 public XmlCommentState doc_state {
301 get { return xml_doc_state; }
303 if (value == XmlCommentState.Allowed) {
304 check_incorrect_doc_comment ();
305 reset_doc_comment ();
307 xml_doc_state = value;
312 // This is used to trigger completion generation on the parser
313 public bool CompleteOnEOF;
315 void AddEscapedIdentifier (Location loc)
317 if (escaped_identifiers == null)
318 escaped_identifiers = new List<Location> ();
320 escaped_identifiers.Add (loc);
323 public bool IsEscapedIdentifier (MemberName name)
325 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
329 // Values for the associated token returned
331 internal int putback_char; // Used by repl only
337 const int TAKING = 1;
338 const int ELSE_SEEN = 4;
339 const int PARENT_TAKING = 8;
340 const int REGION = 16;
343 // pre-processor if stack state:
347 static System.Text.StringBuilder string_builder;
349 const int max_id_size = 512;
350 static readonly char [] id_builder = new char [max_id_size];
352 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
354 const int max_number_size = 512;
355 static char [] number_builder = new char [max_number_size];
356 static int number_pos;
358 static char[] value_builder = new char[256];
367 // This is used when the tokenizer needs to save
368 // the current position as it needs to do some parsing
369 // on its own to deamiguate a token in behalf of the
372 Stack<Position> position_stack = new Stack<Position> (2);
380 public int putback_char;
381 public int previous_col;
382 public Stack<int> ifstack;
383 public int parsing_generic_less_than;
384 public int current_token;
387 public Position (Tokenizer t)
389 position = t.reader.Position;
391 ref_line = t.ref_line;
394 putback_char = t.putback_char;
395 previous_col = t.previous_col;
396 if (t.ifstack != null && t.ifstack.Count != 0) {
397 // There is no simple way to clone Stack<T> all
398 // methods reverse the order
399 var clone = t.ifstack.ToArray ();
400 Array.Reverse (clone);
401 ifstack = new Stack<int> (clone);
403 parsing_generic_less_than = t.parsing_generic_less_than;
404 current_token = t.current_token;
409 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, CompilerContext ctx)
411 this.ref_name = file;
412 this.file_name = file;
418 xml_comment_buffer = new StringBuilder ();
419 doc_processing = ctx.Settings.DocumentationFile != null;
421 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
427 // FIXME: This could be `Location.Push' but we have to
428 // find out why the MS compiler allows this
430 Mono.CSharp.Location.Push (file, file);
433 public void PushPosition ()
435 position_stack.Push (new Position (this));
438 public void PopPosition ()
440 Position p = position_stack.Pop ();
442 reader.Position = p.position;
443 ref_line = p.ref_line;
447 putback_char = p.putback_char;
448 previous_col = p.previous_col;
450 parsing_generic_less_than = p.parsing_generic_less_than;
451 current_token = p.current_token;
455 // Do not reset the position, ignore it.
456 public void DiscardPosition ()
458 position_stack.Pop ();
461 static void AddKeyword (string kw, int token)
463 keyword_strings.Add (kw, null);
465 AddKeyword (keywords, kw, token);
468 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
470 AddKeyword (keywords_preprocessor, kw, directive);
473 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
475 int length = kw.Length;
476 if (keywords[length] == null) {
477 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
480 int char_index = kw[0] - '_';
481 var kwe = keywords[length][char_index];
483 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
487 while (kwe.Next != null) {
491 kwe.Next = new KeywordEntry<T> (kw, token);
499 keyword_strings = new Dictionary<string, object> ();
501 // 11 is the length of the longest keyword for now
502 keywords = new KeywordEntry<int>[11][];
504 AddKeyword ("__arglist", Token.ARGLIST);
505 AddKeyword ("__makeref", Token.MAKEREF);
506 AddKeyword ("__reftype", Token.REFTYPE);
507 AddKeyword ("__refvalue", Token.REFVALUE);
508 AddKeyword ("abstract", Token.ABSTRACT);
509 AddKeyword ("as", Token.AS);
510 AddKeyword ("add", Token.ADD);
511 AddKeyword ("base", Token.BASE);
512 AddKeyword ("bool", Token.BOOL);
513 AddKeyword ("break", Token.BREAK);
514 AddKeyword ("byte", Token.BYTE);
515 AddKeyword ("case", Token.CASE);
516 AddKeyword ("catch", Token.CATCH);
517 AddKeyword ("char", Token.CHAR);
518 AddKeyword ("checked", Token.CHECKED);
519 AddKeyword ("class", Token.CLASS);
520 AddKeyword ("const", Token.CONST);
521 AddKeyword ("continue", Token.CONTINUE);
522 AddKeyword ("decimal", Token.DECIMAL);
523 AddKeyword ("default", Token.DEFAULT);
524 AddKeyword ("delegate", Token.DELEGATE);
525 AddKeyword ("do", Token.DO);
526 AddKeyword ("double", Token.DOUBLE);
527 AddKeyword ("else", Token.ELSE);
528 AddKeyword ("enum", Token.ENUM);
529 AddKeyword ("event", Token.EVENT);
530 AddKeyword ("explicit", Token.EXPLICIT);
531 AddKeyword ("extern", Token.EXTERN);
532 AddKeyword ("false", Token.FALSE);
533 AddKeyword ("finally", Token.FINALLY);
534 AddKeyword ("fixed", Token.FIXED);
535 AddKeyword ("float", Token.FLOAT);
536 AddKeyword ("for", Token.FOR);
537 AddKeyword ("foreach", Token.FOREACH);
538 AddKeyword ("goto", Token.GOTO);
539 AddKeyword ("get", Token.GET);
540 AddKeyword ("if", Token.IF);
541 AddKeyword ("implicit", Token.IMPLICIT);
542 AddKeyword ("in", Token.IN);
543 AddKeyword ("int", Token.INT);
544 AddKeyword ("interface", Token.INTERFACE);
545 AddKeyword ("internal", Token.INTERNAL);
546 AddKeyword ("is", Token.IS);
547 AddKeyword ("lock", Token.LOCK);
548 AddKeyword ("long", Token.LONG);
549 AddKeyword ("namespace", Token.NAMESPACE);
550 AddKeyword ("new", Token.NEW);
551 AddKeyword ("null", Token.NULL);
552 AddKeyword ("object", Token.OBJECT);
553 AddKeyword ("operator", Token.OPERATOR);
554 AddKeyword ("out", Token.OUT);
555 AddKeyword ("override", Token.OVERRIDE);
556 AddKeyword ("params", Token.PARAMS);
557 AddKeyword ("private", Token.PRIVATE);
558 AddKeyword ("protected", Token.PROTECTED);
559 AddKeyword ("public", Token.PUBLIC);
560 AddKeyword ("readonly", Token.READONLY);
561 AddKeyword ("ref", Token.REF);
562 AddKeyword ("remove", Token.REMOVE);
563 AddKeyword ("return", Token.RETURN);
564 AddKeyword ("sbyte", Token.SBYTE);
565 AddKeyword ("sealed", Token.SEALED);
566 AddKeyword ("set", Token.SET);
567 AddKeyword ("short", Token.SHORT);
568 AddKeyword ("sizeof", Token.SIZEOF);
569 AddKeyword ("stackalloc", Token.STACKALLOC);
570 AddKeyword ("static", Token.STATIC);
571 AddKeyword ("string", Token.STRING);
572 AddKeyword ("struct", Token.STRUCT);
573 AddKeyword ("switch", Token.SWITCH);
574 AddKeyword ("this", Token.THIS);
575 AddKeyword ("throw", Token.THROW);
576 AddKeyword ("true", Token.TRUE);
577 AddKeyword ("try", Token.TRY);
578 AddKeyword ("typeof", Token.TYPEOF);
579 AddKeyword ("uint", Token.UINT);
580 AddKeyword ("ulong", Token.ULONG);
581 AddKeyword ("unchecked", Token.UNCHECKED);
582 AddKeyword ("unsafe", Token.UNSAFE);
583 AddKeyword ("ushort", Token.USHORT);
584 AddKeyword ("using", Token.USING);
585 AddKeyword ("virtual", Token.VIRTUAL);
586 AddKeyword ("void", Token.VOID);
587 AddKeyword ("volatile", Token.VOLATILE);
588 AddKeyword ("while", Token.WHILE);
589 AddKeyword ("partial", Token.PARTIAL);
590 AddKeyword ("where", Token.WHERE);
593 AddKeyword ("from", Token.FROM);
594 AddKeyword ("join", Token.JOIN);
595 AddKeyword ("on", Token.ON);
596 AddKeyword ("equals", Token.EQUALS);
597 AddKeyword ("select", Token.SELECT);
598 AddKeyword ("group", Token.GROUP);
599 AddKeyword ("by", Token.BY);
600 AddKeyword ("let", Token.LET);
601 AddKeyword ("orderby", Token.ORDERBY);
602 AddKeyword ("ascending", Token.ASCENDING);
603 AddKeyword ("descending", Token.DESCENDING);
604 AddKeyword ("into", Token.INTO);
606 // Contextual async keywords
607 AddKeyword ("async", Token.ASYNC);
608 AddKeyword ("await", Token.AWAIT);
610 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
612 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
613 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
614 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
615 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
616 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
617 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
618 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
619 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
620 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
621 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
622 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
623 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
625 csharp_format_info = NumberFormatInfo.InvariantInfo;
626 styles = NumberStyles.Float;
628 string_builder = new System.Text.StringBuilder ();
631 int GetKeyword (char[] id, int id_len)
634 // Keywords are stored in an array of arrays grouped by their
635 // length and then by the first character
637 if (id_len >= keywords.Length || keywords [id_len] == null)
640 int first_index = id [0] - '_';
641 if (first_index > 'z' - '_')
644 var kwe = keywords [id_len] [first_index];
651 for (int i = 1; i < id_len; ++i) {
652 if (id [i] != kwe.Value [i]) {
658 } while (res == 0 && kwe != null);
672 if (!handle_remove_add)
676 if (parsing_declaration == 0)
677 res = Token.EXTERN_ALIAS;
680 if (peek_token () == Token.COLON) {
682 res = Token.DEFAULT_COLON;
686 if (!handle_where && !query_parsing)
691 // A query expression is any expression that starts with `from identifier'
692 // followed by any token except ; , =
694 if (!query_parsing) {
695 if (lambda_arguments_parsing) {
701 // HACK: to disable generics micro-parser, because PushPosition does not
702 // store identifiers array
703 parsing_generic_less_than = 1;
705 case Token.IDENTIFIER:
717 next_token = xtoken ();
718 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
721 res = Token.FROM_FIRST;
722 query_parsing = true;
723 if (context.Settings.Version <= LanguageVersion.ISO_2)
724 Report.FeatureIsNotAvailable (context, Location, "query expressions");
727 Expression.Error_VoidInvalidInTheContext (Location, Report);
731 // HACK: A token is not a keyword so we need to restore identifiers buffer
732 // which has been overwritten before we grabbed the identifier
733 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
747 case Token.ASCENDING:
748 case Token.DESCENDING:
755 case Token.NAMESPACE:
756 // TODO: some explanation needed
757 check_incorrect_doc_comment ();
761 if (parsing_block > 0) {
766 // Save current position and parse next token.
769 next_token = token ();
770 bool ok = (next_token == Token.CLASS) ||
771 (next_token == Token.STRUCT) ||
772 (next_token == Token.INTERFACE) ||
773 (next_token == Token.VOID);
778 if (next_token == Token.VOID) {
779 if (context.Settings.Version <= LanguageVersion.ISO_2)
780 Report.FeatureIsNotAvailable (context, Location, "partial methods");
781 } else if (context.Settings.Version == LanguageVersion.ISO_1)
782 Report.FeatureIsNotAvailable (context, Location, "partial types");
787 if (next_token < Token.LAST_KEYWORD) {
788 Report.Error (267, Location,
789 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
796 // TODO: async, it's modifiers context only
798 if (parsing_block > 0 || context.Settings.Version != LanguageVersion.Future) {
803 // TODO: async, it's async block context only
805 if (context.Settings.Version != LanguageVersion.Future) {
816 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
819 // Keywords are stored in an array of arrays grouped by their
820 // length and then by the first character
822 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
823 return PreprocessorDirective.Invalid;
825 int first_index = id[0] - '_';
826 if (first_index > 'z' - '_')
827 return PreprocessorDirective.Invalid;
829 var kwe = keywords_preprocessor[id_len][first_index];
831 return PreprocessorDirective.Invalid;
833 PreprocessorDirective res = PreprocessorDirective.Invalid;
836 for (int i = 1; i < id_len; ++i) {
837 if (id[i] != kwe.Value[i]) {
843 } while (res == PreprocessorDirective.Invalid && kwe != null);
848 public Location Location {
850 return new Location (ref_line, hidden ? -1 : col);
854 static bool is_identifier_start_character (int c)
856 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
859 static bool is_identifier_part_character (char c)
861 if (c >= 'a' && c <= 'z')
864 if (c >= 'A' && c <= 'Z')
867 if (c == '_' || (c >= '0' && c <= '9'))
873 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
876 public static bool IsKeyword (string s)
878 return keyword_strings.ContainsKey (s);
882 // Open parens micro parser. Detects both lambda and cast ambiguity.
884 int TokenizeOpenParens ()
889 int bracket_level = 0;
890 bool is_type = false;
891 bool can_be_type = false;
894 ptoken = current_token;
897 switch (current_token) {
898 case Token.CLOSE_PARENS:
902 // Expression inside parens is lambda, (int i) =>
904 if (current_token == Token.ARROW)
905 return Token.OPEN_PARENS_LAMBDA;
908 // Expression inside parens is single type, (int[])
911 return Token.OPEN_PARENS_CAST;
914 // Expression is possible cast, look at next token, (T)null
917 switch (current_token) {
918 case Token.OPEN_PARENS:
921 case Token.IDENTIFIER:
935 case Token.UNCHECKED:
940 // These can be part of a member access
954 return Token.OPEN_PARENS_CAST;
957 return Token.OPEN_PARENS;
960 case Token.DOUBLE_COLON:
961 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
966 case Token.IDENTIFIER:
969 if (bracket_level == 0) {
975 case Token.OP_GENERICS_LT:
977 case Token.DOUBLE_COLON:
979 if (bracket_level == 0)
983 can_be_type = is_type = false;
1003 if (bracket_level == 0)
1008 if (bracket_level == 0) {
1009 bracket_level = 100;
1010 can_be_type = is_type = false;
1014 case Token.OP_GENERICS_LT:
1015 case Token.OPEN_BRACKET:
1016 if (bracket_level++ == 0)
1020 case Token.OP_GENERICS_GT:
1021 case Token.CLOSE_BRACKET:
1025 case Token.INTERR_NULLABLE:
1027 if (bracket_level == 0)
1033 can_be_type = is_type = false;
1037 return Token.OPEN_PARENS;
1042 public static bool IsValidIdentifier (string s)
1044 if (s == null || s.Length == 0)
1047 if (!is_identifier_start_character (s [0]))
1050 for (int i = 1; i < s.Length; i ++)
1051 if (! is_identifier_part_character (s [i]))
1057 bool parse_less_than ()
1060 int the_token = token ();
1061 if (the_token == Token.OPEN_BRACKET) {
1063 the_token = token ();
1064 } while (the_token != Token.CLOSE_BRACKET);
1065 the_token = token ();
1066 } else if (the_token == Token.IN || the_token == Token.OUT) {
1067 the_token = token ();
1069 switch (the_token) {
1070 case Token.IDENTIFIER:
1088 case Token.OP_GENERICS_GT:
1095 the_token = token ();
1097 if (the_token == Token.OP_GENERICS_GT)
1099 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1101 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1103 else if (the_token == Token.OP_GENERICS_LT) {
1104 if (!parse_less_than ())
1107 } else if (the_token == Token.OPEN_BRACKET) {
1109 the_token = token ();
1110 if (the_token == Token.CLOSE_BRACKET)
1112 else if (the_token == Token.COMMA)
1113 goto rank_specifiers;
1120 bool parse_generic_dimension (out int dimension)
1125 int the_token = token ();
1126 if (the_token == Token.OP_GENERICS_GT)
1128 else if (the_token == Token.COMMA) {
1136 public int peek_token ()
1141 the_token = token ();
1148 // Tonizes `?' using custom disambiguous rules to return one
1149 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1151 // Tricky expression look like:
1153 // Foo ? a = x ? b : c;
1155 int TokenizePossibleNullableType ()
1157 if (parsing_block == 0 || parsing_type > 0)
1158 return Token.INTERR_NULLABLE;
1160 int d = peek_char ();
1163 return Token.OP_COALESCING;
1166 switch (current_token) {
1167 case Token.CLOSE_PARENS:
1172 return Token.INTERR;
1176 if (d == ',' || d == ';' || d == '>')
1177 return Token.INTERR_NULLABLE;
1178 if (d == '*' || (d >= '0' && d <= '9'))
1179 return Token.INTERR;
1183 current_token = Token.NONE;
1185 switch (xtoken ()) {
1192 next_token = Token.INTERR;
1195 case Token.SEMICOLON:
1197 case Token.CLOSE_PARENS:
1198 case Token.OPEN_BRACKET:
1199 case Token.OP_GENERICS_GT:
1201 next_token = Token.INTERR_NULLABLE;
1209 if (next_token == -1) {
1210 switch (xtoken ()) {
1212 case Token.SEMICOLON:
1213 case Token.OPEN_BRACE:
1214 case Token.CLOSE_PARENS:
1216 next_token = Token.INTERR_NULLABLE;
1220 next_token = Token.INTERR;
1228 // All shorcuts failed, do it hard way
1230 while ((ntoken = xtoken ()) != Token.EOF) {
1231 if (ntoken == Token.SEMICOLON)
1234 if (ntoken == Token.COLON) {
1235 if (++colons == interrs)
1240 if (ntoken == Token.INTERR) {
1246 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1255 bool decimal_digits (int c)
1258 bool seen_digits = false;
1261 if (number_pos == max_number_size)
1262 Error_NumericConstantTooLong ();
1263 number_builder [number_pos++] = (char) c;
1267 // We use peek_char2, because decimal_digits needs to do a
1268 // 2-character look-ahead (5.ToString for example).
1270 while ((d = peek_char2 ()) != -1){
1271 if (d >= '0' && d <= '9'){
1272 if (number_pos == max_number_size)
1273 Error_NumericConstantTooLong ();
1274 number_builder [number_pos++] = (char) d;
1284 static bool is_hex (int e)
1286 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1289 static TypeCode real_type_suffix (int c)
1293 return TypeCode.Single;
1295 return TypeCode.Double;
1297 return TypeCode.Decimal;
1299 return TypeCode.Empty;
1303 int integer_type_suffix (ulong ul, int c)
1305 bool is_unsigned = false;
1306 bool is_long = false;
1309 bool scanning = true;
1322 // if we have not seen anything in between
1323 // report this error
1325 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1345 if (is_long && is_unsigned){
1346 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1347 return Token.LITERAL;
1351 // uint if possible, or ulong else.
1353 if ((ul & 0xffffffff00000000) == 0)
1354 val = new UIntLiteral (context.BuiltinTypes, (uint) ul, Location);
1356 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1357 } else if (is_long){
1358 // long if possible, ulong otherwise
1359 if ((ul & 0x8000000000000000) != 0)
1360 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1362 val = new LongLiteral (context.BuiltinTypes, (long) ul, Location);
1364 // int, uint, long or ulong in that order
1365 if ((ul & 0xffffffff00000000) == 0){
1366 uint ui = (uint) ul;
1368 if ((ui & 0x80000000) != 0)
1369 val = new UIntLiteral (context.BuiltinTypes, ui, Location);
1371 val = new IntLiteral (context.BuiltinTypes, (int) ui, Location);
1373 if ((ul & 0x8000000000000000) != 0)
1374 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1376 val = new LongLiteral (context.BuiltinTypes, (long) ul, Location);
1379 return Token.LITERAL;
1383 // given `c' as the next char in the input decide whether
1384 // we need to convert to a special type, and then choose
1385 // the best representation for the integer
1387 int adjust_int (int c)
1390 if (number_pos > 9){
1391 ulong ul = (uint) (number_builder [0] - '0');
1393 for (int i = 1; i < number_pos; i++){
1394 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1396 return integer_type_suffix (ul, c);
1398 uint ui = (uint) (number_builder [0] - '0');
1400 for (int i = 1; i < number_pos; i++){
1401 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1403 return integer_type_suffix (ui, c);
1405 } catch (OverflowException) {
1406 Error_NumericConstantTooLong ();
1407 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1408 return Token.LITERAL;
1410 catch (FormatException) {
1411 Report.Error (1013, Location, "Invalid number");
1412 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1413 return Token.LITERAL;
1417 int adjust_real (TypeCode t)
1419 string s = new String (number_builder, 0, number_pos);
1420 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1423 case TypeCode.Decimal:
1425 val = new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), Location);
1426 } catch (OverflowException) {
1427 val = new DecimalLiteral (context.BuiltinTypes, 0, Location);
1428 Report.Error (594, Location, error_details, "decimal");
1431 case TypeCode.Single:
1433 val = new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), Location);
1434 } catch (OverflowException) {
1435 val = new FloatLiteral (context.BuiltinTypes, 0, Location);
1436 Report.Error (594, Location, error_details, "float");
1441 val = new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), Location);
1442 } catch (OverflowException) {
1443 val = new DoubleLiteral (context.BuiltinTypes, 0, Location);
1444 Report.Error (594, Location, error_details, "double");
1449 return Token.LITERAL;
1458 while ((d = peek_char ()) != -1){
1460 number_builder [number_pos++] = (char) d;
1466 string s = new String (number_builder, 0, number_pos);
1468 if (number_pos <= 8)
1469 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1471 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1472 } catch (OverflowException){
1473 Error_NumericConstantTooLong ();
1474 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1475 return Token.LITERAL;
1477 catch (FormatException) {
1478 Report.Error (1013, Location, "Invalid number");
1479 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1480 return Token.LITERAL;
1483 return integer_type_suffix (ul, peek_char ());
1487 // Invoked if we know we have .digits or digits
1489 int is_number (int c)
1491 bool is_real = false;
1495 if (c >= '0' && c <= '9'){
1497 int peek = peek_char ();
1499 if (peek == 'x' || peek == 'X')
1500 return handle_hex ();
1507 // We need to handle the case of
1508 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1511 if (decimal_digits ('.')){
1517 return adjust_int (-1);
1521 if (c == 'e' || c == 'E'){
1523 if (number_pos == max_number_size)
1524 Error_NumericConstantTooLong ();
1525 number_builder [number_pos++] = 'e';
1529 if (number_pos == max_number_size)
1530 Error_NumericConstantTooLong ();
1531 number_builder [number_pos++] = '+';
1533 } else if (c == '-') {
1534 if (number_pos == max_number_size)
1535 Error_NumericConstantTooLong ();
1536 number_builder [number_pos++] = '-';
1539 if (number_pos == max_number_size)
1540 Error_NumericConstantTooLong ();
1541 number_builder [number_pos++] = '+';
1548 var type = real_type_suffix (c);
1549 if (type == TypeCode.Empty && !is_real){
1551 return adjust_int (c);
1556 if (type == TypeCode.Empty){
1561 return adjust_real (type);
1563 throw new Exception ("Is Number should never reach this point");
1567 // Accepts exactly count (4 or 8) hex, no more no less
1569 int getHex (int count, out int surrogate, out bool error)
1574 int top = count != -1 ? count : 4;
1579 for (i = 0; i < top; i++){
1582 if (c >= '0' && c <= '9')
1583 c = (int) c - (int) '0';
1584 else if (c >= 'A' && c <= 'F')
1585 c = (int) c - (int) 'A' + 10;
1586 else if (c >= 'a' && c <= 'f')
1587 c = (int) c - (int) 'a' + 10;
1593 total = (total * 16) + c;
1595 int p = peek_char ();
1598 if (!is_hex ((char)p))
1604 if (total > 0x0010FFFF) {
1609 if (total >= 0x00010000) {
1610 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1611 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1618 int escape (int c, out int surrogate)
1654 v = getHex (-1, out surrogate, out error);
1660 return EscapeUnicode (d, out surrogate);
1663 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1672 int EscapeUnicode (int ch, out int surrogate)
1676 ch = getHex (8, out surrogate, out error);
1678 ch = getHex (4, out surrogate, out error);
1682 Report.Error (1009, Location, "Unrecognized escape sequence");
1690 if (putback_char != -1) {
1698 if (peek_char () == '\n') {
1704 } else if (x == '\n') {
1712 void advance_line ()
1722 if (putback_char == -1)
1723 putback_char = reader.Read ();
1724 return putback_char;
1729 if (putback_char != -1)
1730 return putback_char;
1731 return reader.Peek ();
1734 void putback (int c)
1736 if (putback_char != -1){
1737 Console.WriteLine ("Col: " + col);
1738 Console.WriteLine ("Row: " + line);
1739 Console.WriteLine ("Name: " + ref_name.Name);
1740 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1741 throw new Exception ("This should not happen putback on putback");
1743 if (c == '\n' || col == 0) {
1744 // It won't happen though.
1754 public bool advance ()
1756 return peek_char () != -1 || CompleteOnEOF;
1759 public Object Value {
1765 public Object value ()
1772 current_token = xtoken ();
1773 return current_token;
1776 int TokenizePreprocessorIdentifier (out int c)
1778 // skip over white space
1781 } while (c == ' ' || c == '\t');
1785 while (c != -1 && c >= 'a' && c <= 'z') {
1786 id_builder[pos++] = (char) c;
1789 int peek = peek_char ();
1790 if (peek == 'U' || peek == 'u') {
1792 c = EscapeUnicode (c, out surrogate);
1793 if (surrogate != 0) {
1794 if (is_identifier_part_character ((char) c)) {
1795 id_builder[pos++] = (char) c;
1806 PreprocessorDirective get_cmd_arg (out string arg)
1810 tokens_seen = false;
1813 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1815 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1818 // skip over white space
1819 while (c == ' ' || c == '\t')
1822 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1825 while (c != -1 && c != '\n') {
1826 if (c == '\\' && has_identifier_argument >= 0) {
1827 if (has_identifier_argument != 0) {
1828 has_identifier_argument = 1;
1830 int peek = peek_char ();
1831 if (peek == 'U' || peek == 'u') {
1833 c = EscapeUnicode (c, out surrogate);
1834 if (surrogate != 0) {
1835 if (is_identifier_part_character ((char) c)) {
1836 if (pos == value_builder.Length)
1837 Array.Resize (ref value_builder, pos * 2);
1839 value_builder[pos++] = (char) c;
1845 has_identifier_argument = -1;
1847 } else if (c == '/' && peek_char () == '/') {
1849 // Eat single-line comments
1854 } while (c != -1 && c != '\n');
1859 if (pos == value_builder.Length)
1860 Array.Resize (ref value_builder, pos * 2);
1862 value_builder[pos++] = (char) c;
1867 if (pos > max_id_size)
1868 arg = new string (value_builder, 0, pos);
1870 arg = InternIdentifier (value_builder, pos);
1872 // Eat any trailing whitespaces
1873 arg = arg.Trim (simple_whitespaces);
1880 // Handles the #line directive
1882 bool PreProcessLine (string arg)
1884 if (arg.Length == 0)
1887 if (arg == "default"){
1889 ref_name = file_name;
1891 Location.Push (file_name, ref_name);
1893 } else if (arg == "hidden"){
1901 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1902 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1905 char [] quotes = { '\"' };
1907 string name = arg.Substring (pos). Trim (quotes);
1908 ref_name = context.LookupFile (file_name, name);
1909 file_name.AddIncludeFile (ref_name);
1911 Location.Push (file_name, ref_name);
1913 ref_line = System.Int32.Parse (arg);
1924 // Handles #define and #undef
1926 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1928 if (ident.Length == 0 || ident == "true" || ident == "false"){
1929 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1933 if (ident.IndexOfAny (simple_whitespaces) != -1){
1934 Error_EndLineExpected ();
1938 if (!is_identifier_start_character (ident [0]))
1939 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1941 foreach (char c in ident.Substring (1)){
1942 if (!is_identifier_part_character (c)){
1943 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1948 if (!caller_is_taking)
1955 if (context.Settings.IsConditionalSymbolDefined (ident))
1958 file_name.AddDefine (ident);
1963 file_name.AddUndefine (ident);
1967 byte read_hex (out bool error)
1970 int c = get_char ();
1972 if ((c >= '0') && (c <= '9'))
1973 total = (int) c - (int) '0';
1974 else if ((c >= 'A') && (c <= 'F'))
1975 total = (int) c - (int) 'A' + 10;
1976 else if ((c >= 'a') && (c <= 'f'))
1977 total = (int) c - (int) 'a' + 10;
1986 if ((c >= '0') && (c <= '9'))
1987 total += (int) c - (int) '0';
1988 else if ((c >= 'A') && (c <= 'F'))
1989 total += (int) c - (int) 'A' + 10;
1990 else if ((c >= 'a') && (c <= 'f'))
1991 total += (int) c - (int) 'a' + 10;
1998 return (byte) total;
2002 // Parses #pragma checksum
2004 bool ParsePragmaChecksum ()
2007 // The syntax is ` "foo.txt" "{guid}" "hash"'
2009 int c = get_char ();
2014 string_builder.Length = 0;
2015 while (c != -1 && c != '\n') {
2022 string_builder.Append ((char) c);
2025 if (string_builder.Length == 0) {
2026 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2029 // TODO: Any white-spaces count
2033 SourceFile file = context.LookupFile (file_name, string_builder.ToString ());
2035 if (get_char () != '"' || get_char () != '{')
2039 byte[] guid_bytes = new byte [16];
2042 for (; i < 4; i++) {
2043 guid_bytes [i] = read_hex (out error);
2048 if (get_char () != '-')
2051 for (; i < 10; i++) {
2052 guid_bytes [i] = read_hex (out error);
2056 guid_bytes [i++] = read_hex (out error);
2060 if (get_char () != '-')
2064 for (; i < 16; i++) {
2065 guid_bytes [i] = read_hex (out error);
2070 if (get_char () != '}' || get_char () != '"')
2073 // TODO: Any white-spaces count
2078 if (get_char () != '"')
2081 // Any length of checksum
2082 List<byte> checksum_bytes = new List<byte> (16);
2085 while (c != '"' && c != -1) {
2086 checksum_bytes.Add (read_hex (out error));
2094 ReadSingleLineComment ();
2095 } else if (get_char () != '"') {
2099 file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2100 ref_name.AutoGenerated = true;
2104 bool IsTokenIdentifierEqual (char[] identifier)
2106 for (int i = 0; i < identifier.Length; ++i) {
2107 if (identifier[i] != id_builder[i])
2114 int TokenizePragmaNumber (ref int c)
2120 if (c >= '0' && c <= '9') {
2122 uint ui = (uint) (number_builder[0] - '0');
2125 for (int i = 1; i < number_pos; i++) {
2126 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2130 } catch (OverflowException) {
2131 Error_NumericConstantTooLong ();
2138 // skip over white space
2139 while (c == ' ' || c == '\t')
2146 // skip over white space
2147 while (c == ' ' || c == '\t')
2152 ReadSingleLineComment ();
2154 Report.Warning (1692, 1, Location, "Invalid number");
2156 // Read everything till the end of the line or file
2159 } while (c != -1 && c != '\n');
2166 void ReadSingleLineComment ()
2168 if (peek_char () != '/')
2169 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2171 // Read everything till the end of the line or file
2175 } while (c != -1 && c != '\n');
2179 /// Handles #pragma directive
2181 void ParsePragmaDirective (string arg)
2184 int length = TokenizePreprocessorIdentifier (out c);
2185 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2186 length = TokenizePreprocessorIdentifier (out c);
2189 // #pragma warning disable
2190 // #pragma warning restore
2192 if (length == pragma_warning_disable.Length) {
2193 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2194 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2195 // skip over white space
2196 while (c == ' ' || c == '\t')
2201 if (c == '\n' || c == '/') {
2203 ReadSingleLineComment ();
2206 // Disable/Restore all warnings
2209 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2211 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2215 // Disable/Restore a warning or group of warnings
2219 code = TokenizePragmaNumber (ref c);
2222 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2224 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2227 } while (code >= 0 && c != '\n' && c != -1);
2234 Report.Warning (1634, 1, Location, "Expected disable or restore");
2241 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2242 if (c != ' ' || !ParsePragmaChecksum ()) {
2243 Report.Warning (1695, 1, Location,
2244 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2250 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2253 bool eval_val (string s)
2260 return file_name.IsConditionalDefined (context, s);
2263 bool pp_primary (ref string s)
2272 s = s.Substring (1);
2273 bool val = pp_expr (ref s, false);
2274 if (s.Length > 0 && s [0] == ')'){
2275 s = s.Substring (1);
2278 Error_InvalidDirective ();
2282 if (is_identifier_start_character (c)){
2288 if (is_identifier_part_character (c)){
2292 bool v = eval_val (s.Substring (0, j));
2293 s = s.Substring (j);
2296 bool vv = eval_val (s);
2301 Error_InvalidDirective ();
2305 bool pp_unary (ref string s)
2312 if (len > 1 && s [1] == '='){
2313 Error_InvalidDirective ();
2316 s = s.Substring (1);
2317 return ! pp_primary (ref s);
2319 return pp_primary (ref s);
2321 Error_InvalidDirective ();
2326 bool pp_eq (ref string s)
2328 bool va = pp_unary (ref s);
2334 if (len > 2 && s [1] == '='){
2335 s = s.Substring (2);
2336 return va == pp_unary (ref s);
2338 Error_InvalidDirective ();
2341 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2342 s = s.Substring (2);
2344 return va != pp_unary (ref s);
2353 bool pp_and (ref string s)
2355 bool va = pp_eq (ref s);
2361 if (len > 2 && s [1] == '&'){
2362 s = s.Substring (2);
2363 return (va & pp_and (ref s));
2365 Error_InvalidDirective ();
2374 // Evaluates an expression for `#if' or `#elif'
2376 bool pp_expr (ref string s, bool isTerm)
2378 bool va = pp_and (ref s);
2385 if (len > 2 && s [1] == '|'){
2386 s = s.Substring (2);
2387 return va | pp_expr (ref s, isTerm);
2389 Error_InvalidDirective ();
2394 Error_EndLineExpected ();
2402 bool eval (string s)
2404 bool v = pp_expr (ref s, true);
2413 void Error_NumericConstantTooLong ()
2415 Report.Error (1021, Location, "Integral constant is too large");
2418 void Error_InvalidDirective ()
2420 Report.Error (1517, Location, "Invalid preprocessor directive");
2423 void Error_UnexpectedDirective (string extra)
2427 "Unexpected processor directive ({0})", extra);
2430 void Error_TokensSeen ()
2432 Report.Error (1032, Location,
2433 "Cannot define or undefine preprocessor symbols after first token in file");
2436 void Eror_WrongPreprocessorLocation ()
2438 Report.Error (1040, Location,
2439 "Preprocessor directives must appear as the first non-whitespace character on a line");
2442 void Error_EndLineExpected ()
2444 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2448 // Raises a warning when tokenizer found documentation comment
2449 // on unexpected place
2451 void WarningMisplacedComment (Location loc)
2453 if (doc_state != XmlCommentState.Error) {
2454 doc_state = XmlCommentState.Error;
2455 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2460 // if true, then the code continues processing the code
2461 // if false, the code stays in a loop until another directive is
2463 // When caller_is_taking is false we ignore all directives except the ones
2464 // which can help us to identify where the #if block ends
2465 bool ParsePreprocessingDirective (bool caller_is_taking)
2468 bool region_directive = false;
2470 var directive = get_cmd_arg (out arg);
2473 // The first group of pre-processing instructions is always processed
2475 switch (directive) {
2476 case PreprocessorDirective.Region:
2477 region_directive = true;
2479 goto case PreprocessorDirective.If;
2481 case PreprocessorDirective.Endregion:
2482 if (ifstack == null || ifstack.Count == 0){
2483 Error_UnexpectedDirective ("no #region for this #endregion");
2486 int pop = ifstack.Pop ();
2488 if ((pop & REGION) == 0)
2489 Report.Error (1027, Location, "Expected `#endif' directive");
2491 return caller_is_taking;
2493 case PreprocessorDirective.If:
2494 if (ifstack == null)
2495 ifstack = new Stack<int> (2);
2497 int flags = region_directive ? REGION : 0;
2498 if (ifstack.Count == 0){
2499 flags |= PARENT_TAKING;
2501 int state = ifstack.Peek ();
2502 if ((state & TAKING) != 0) {
2503 flags |= PARENT_TAKING;
2507 if (eval (arg) && caller_is_taking) {
2508 ifstack.Push (flags | TAKING);
2511 ifstack.Push (flags);
2514 case PreprocessorDirective.Endif:
2515 if (ifstack == null || ifstack.Count == 0){
2516 Error_UnexpectedDirective ("no #if for this #endif");
2519 pop = ifstack.Pop ();
2521 if ((pop & REGION) != 0)
2522 Report.Error (1038, Location, "#endregion directive expected");
2524 if (arg.Length != 0) {
2525 Error_EndLineExpected ();
2528 if (ifstack.Count == 0)
2531 int state = ifstack.Peek ();
2532 return (state & TAKING) != 0;
2535 case PreprocessorDirective.Elif:
2536 if (ifstack == null || ifstack.Count == 0){
2537 Error_UnexpectedDirective ("no #if for this #elif");
2540 int state = ifstack.Pop ();
2542 if ((state & REGION) != 0) {
2543 Report.Error (1038, Location, "#endregion directive expected");
2547 if ((state & ELSE_SEEN) != 0){
2548 Error_UnexpectedDirective ("#elif not valid after #else");
2552 if ((state & TAKING) != 0) {
2557 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2558 ifstack.Push (state | TAKING);
2562 ifstack.Push (state);
2566 case PreprocessorDirective.Else:
2567 if (ifstack == null || ifstack.Count == 0){
2568 Error_UnexpectedDirective ("no #if for this #else");
2571 int state = ifstack.Peek ();
2573 if ((state & REGION) != 0) {
2574 Report.Error (1038, Location, "#endregion directive expected");
2578 if ((state & ELSE_SEEN) != 0){
2579 Error_UnexpectedDirective ("#else within #else");
2585 if (arg.Length != 0) {
2586 Error_EndLineExpected ();
2591 if ((state & PARENT_TAKING) != 0) {
2592 ret = (state & TAKING) == 0;
2600 ifstack.Push (state | ELSE_SEEN);
2604 case PreprocessorDirective.Define:
2605 if (any_token_seen){
2606 Error_TokensSeen ();
2607 return caller_is_taking;
2609 PreProcessDefinition (true, arg, caller_is_taking);
2610 return caller_is_taking;
2612 case PreprocessorDirective.Undef:
2613 if (any_token_seen){
2614 Error_TokensSeen ();
2615 return caller_is_taking;
2617 PreProcessDefinition (false, arg, caller_is_taking);
2618 return caller_is_taking;
2620 case PreprocessorDirective.Invalid:
2621 Report.Error (1024, Location, "Wrong preprocessor directive");
2626 // These are only processed if we are in a `taking' block
2628 if (!caller_is_taking)
2632 case PreprocessorDirective.Error:
2633 Report.Error (1029, Location, "#error: '{0}'", arg);
2636 case PreprocessorDirective.Warning:
2637 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2640 case PreprocessorDirective.Pragma:
2641 if (context.Settings.Version == LanguageVersion.ISO_1) {
2642 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2645 ParsePragmaDirective (arg);
2648 case PreprocessorDirective.Line:
2649 if (!PreProcessLine (arg))
2652 "The line number specified for #line directive is missing or invalid");
2653 return caller_is_taking;
2656 throw new NotImplementedException (directive.ToString ());
2659 private int consume_string (bool quoted)
2663 Location start_location = Location;
2665 start_location = start_location - 1;
2670 if (quoted && peek_char () == '"') {
2671 if (pos == value_builder.Length)
2672 Array.Resize (ref value_builder, pos * 2);
2674 value_builder[pos++] = (char) c;
2683 s = InternIdentifier (value_builder, pos);
2685 s = new string (value_builder, 0, pos);
2687 val = new StringLiteral (context.BuiltinTypes, s, start_location);
2688 return Token.LITERAL;
2693 Report.Error (1010, Location, "Newline in constant");
2694 } else if (c == '\\' && !quoted) {
2696 c = escape (c, out surrogate);
2699 if (surrogate != 0) {
2700 if (pos == value_builder.Length)
2701 Array.Resize (ref value_builder, pos * 2);
2703 value_builder[pos++] = (char) c;
2706 } else if (c == -1) {
2707 Report.Error (1039, Location, "Unterminated string literal");
2711 if (pos == value_builder.Length)
2712 Array.Resize (ref value_builder, pos * 2);
2714 value_builder[pos++] = (char) c;
2718 private int consume_identifier (int s)
2720 int res = consume_identifier (s, false);
2722 if (doc_state == XmlCommentState.Allowed)
2723 doc_state = XmlCommentState.NotAllowed;
2728 int consume_identifier (int c, bool quoted)
2731 // This method is very performance sensitive. It accounts
2732 // for approximately 25% of all parser time
2742 c = escape (c, out surrogate);
2743 if (surrogate != 0) {
2744 id_builder [pos++] = (char) c;
2749 id_builder [pos++] = (char) c;
2755 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2756 id_builder [pos++] = (char) c;
2763 c = escape (c, out surrogate);
2764 if (is_identifier_part_character ((char) c))
2765 id_builder[pos++] = (char) c;
2767 if (surrogate != 0) {
2773 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2774 id_builder [pos++] = (char) c;
2781 } catch (IndexOutOfRangeException) {
2782 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2790 // Optimization: avoids doing the keyword lookup
2791 // on uppercase letters
2793 if (id_builder [0] >= '_' && !quoted) {
2794 int keyword = GetKeyword (id_builder, pos);
2795 if (keyword != -1) {
2796 val = LocatedToken.Create (null, ref_line, column);
2801 string s = InternIdentifier (id_builder, pos);
2802 val = LocatedToken.Create (s, ref_line, column);
2803 if (quoted && parsing_attribute_section)
2804 AddEscapedIdentifier (((LocatedToken) val).Location);
2806 return Token.IDENTIFIER;
2809 static string InternIdentifier (char[] charBuffer, int length)
2812 // Keep identifiers in an array of hashtables to avoid needless
2815 var identifiers_group = identifiers[length];
2817 if (identifiers_group != null) {
2818 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2822 // TODO: this should be number of files dependant
2823 // corlib compilation peaks at 1000 and System.Core at 150
2824 int capacity = length > 20 ? 10 : 100;
2825 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2826 identifiers[length] = identifiers_group;
2829 char[] chars = new char[length];
2830 Array.Copy (charBuffer, chars, length);
2832 s = new string (charBuffer, 0, length);
2833 identifiers_group.Add (chars, s);
2837 public int xtoken ()
2841 // Whether we have seen comments on the current line
2842 bool comments_seen = false;
2843 while ((c = get_char ()) != -1) {
2846 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2854 case 0xFEFF: // Ignore BOM anywhere in the file
2857 /* This is required for compatibility with .NET
2859 if (peek_char () == 0xBB) {
2862 if (get_char () == 0xBF)
2870 return consume_identifier (c);
2873 val = LocatedToken.Create (ref_line, col);
2874 return Token.OPEN_BRACE;
2876 val = LocatedToken.Create (ref_line, col);
2877 return Token.CLOSE_BRACE;
2879 // To block doccomment inside attribute declaration.
2880 if (doc_state == XmlCommentState.Allowed)
2881 doc_state = XmlCommentState.NotAllowed;
2883 val = LocatedToken.Create (ref_line, col);
2885 if (parsing_block == 0 || lambda_arguments_parsing)
2886 return Token.OPEN_BRACKET;
2888 int next = peek_char ();
2892 return Token.OPEN_BRACKET;
2900 next = peek_token ();
2901 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2902 return Token.OPEN_BRACKET;
2904 return Token.OPEN_BRACKET_EXPR;
2906 return Token.OPEN_BRACKET_EXPR;
2909 LocatedToken.CreateOptional (ref_line, col, ref val);
2910 return Token.CLOSE_BRACKET;
2912 val = LocatedToken.Create (ref_line, col);
2914 // An expression versions of parens can appear in block context only
2916 if (parsing_block != 0 && !lambda_arguments_parsing) {
2919 // Optmize most common case where we know that parens
2922 switch (current_token) {
2923 case Token.IDENTIFIER:
2931 case Token.DELEGATE:
2932 case Token.OP_GENERICS_GT:
2933 return Token.OPEN_PARENS;
2936 // Optimize using peek
2937 int xx = peek_char ();
2944 return Token.OPEN_PARENS;
2947 lambda_arguments_parsing = true;
2949 d = TokenizeOpenParens ();
2951 lambda_arguments_parsing = false;
2955 return Token.OPEN_PARENS;
2957 LocatedToken.CreateOptional (ref_line, col, ref val);
2958 return Token.CLOSE_PARENS;
2960 LocatedToken.CreateOptional (ref_line, col, ref val);
2963 LocatedToken.CreateOptional (ref_line, col, ref val);
2964 return Token.SEMICOLON;
2966 val = LocatedToken.Create (ref_line, col);
2969 val = LocatedToken.Create (ref_line, col);
2970 return TokenizePossibleNullableType ();
2972 val = LocatedToken.Create (ref_line, col);
2973 if (parsing_generic_less_than++ > 0)
2974 return Token.OP_GENERICS_LT;
2976 return TokenizeLessThan ();
2979 val = LocatedToken.Create (ref_line, col);
2987 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2988 parsing_generic_less_than--;
2989 return Token.OP_GENERICS_GT;
2998 return Token.OP_SHIFT_RIGHT_ASSIGN;
3000 return Token.OP_SHIFT_RIGHT;
3006 val = LocatedToken.Create (ref_line, col);
3010 } else if (d == '=') {
3011 d = Token.OP_ADD_ASSIGN;
3019 val = LocatedToken.Create (ref_line, col);
3023 } else if (d == '=')
3024 d = Token.OP_SUB_ASSIGN;
3034 val = LocatedToken.Create (ref_line, col);
3035 if (peek_char () == '='){
3042 val = LocatedToken.Create (ref_line, col);
3053 return Token.ASSIGN;
3056 val = LocatedToken.Create (ref_line, col);
3060 return Token.OP_AND;
3064 return Token.OP_AND_ASSIGN;
3066 return Token.BITWISE_AND;
3069 val = LocatedToken.Create (ref_line, col);
3077 return Token.OP_OR_ASSIGN;
3079 return Token.BITWISE_OR;
3082 val = LocatedToken.Create (ref_line, col);
3083 if (peek_char () == '='){
3085 return Token.OP_MULT_ASSIGN;
3092 val = LocatedToken.Create (ref_line, col);
3094 return Token.OP_DIV_ASSIGN;
3097 // Handle double-slash comments.
3100 if (doc_processing) {
3101 if (peek_char () == '/') {
3103 // Don't allow ////.
3104 if ((d = peek_char ()) != '/') {
3105 if (doc_state == XmlCommentState.Allowed)
3106 handle_one_line_xml_comment ();
3107 else if (doc_state == XmlCommentState.NotAllowed)
3108 WarningMisplacedComment (Location - 3);
3111 if (xml_comment_buffer.Length > 0)
3112 doc_state = XmlCommentState.NotAllowed;
3116 while ((d = get_char ()) != -1 && d != '\n');
3118 any_token_seen |= tokens_seen;
3119 tokens_seen = false;
3120 comments_seen = false;
3122 } else if (d == '*'){
3124 bool docAppend = false;
3125 if (doc_processing && peek_char () == '*') {
3127 // But when it is /**/, just do nothing.
3128 if (peek_char () == '/') {
3132 if (doc_state == XmlCommentState.Allowed)
3134 else if (doc_state == XmlCommentState.NotAllowed) {
3135 WarningMisplacedComment (Location - 2);
3139 int current_comment_start = 0;
3141 current_comment_start = xml_comment_buffer.Length;
3142 xml_comment_buffer.Append (Environment.NewLine);
3145 while ((d = get_char ()) != -1){
3146 if (d == '*' && peek_char () == '/'){
3148 comments_seen = true;
3152 xml_comment_buffer.Append ((char) d);
3155 any_token_seen |= tokens_seen;
3156 tokens_seen = false;
3158 // Reset 'comments_seen' just to be consistent.
3159 // It doesn't matter either way, here.
3161 comments_seen = false;
3165 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3168 update_formatted_doc_comment (current_comment_start);
3171 val = LocatedToken.Create (ref_line, col);
3175 val = LocatedToken.Create (ref_line, col);
3176 if (peek_char () == '='){
3178 return Token.OP_MOD_ASSIGN;
3180 return Token.PERCENT;
3183 val = LocatedToken.Create (ref_line, col);
3184 if (peek_char () == '='){
3186 return Token.OP_XOR_ASSIGN;
3188 return Token.CARRET;
3191 val = LocatedToken.Create (ref_line, col);
3192 if (peek_char () == ':') {
3194 return Token.DOUBLE_COLON;
3198 case '0': case '1': case '2': case '3': case '4':
3199 case '5': case '6': case '7': case '8': case '9':
3201 return is_number (c);
3203 case '\n': // white space
3204 any_token_seen |= tokens_seen;
3205 tokens_seen = false;
3206 comments_seen = false;
3212 if (d >= '0' && d <= '9')
3213 return is_number (c);
3215 LocatedToken.CreateOptional (ref_line, col, ref val);
3219 if (tokens_seen || comments_seen) {
3220 Eror_WrongPreprocessorLocation ();
3224 if (ParsePreprocessingDirective (true))
3227 bool directive_expected = false;
3228 while ((c = get_char ()) != -1) {
3230 directive_expected = true;
3231 } else if (!directive_expected) {
3232 // TODO: Implement comment support for disabled code and uncomment this code
3234 // Eror_WrongPreprocessorLocation ();
3235 // return Token.ERROR;
3240 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3244 if (ParsePreprocessingDirective (false))
3247 directive_expected = false;
3251 tokens_seen = false;
3258 return consume_string (false);
3261 return TokenizeBackslash ();
3267 return consume_string (true);
3270 if (is_identifier_start_character (c)){
3271 return consume_identifier (c, true);
3274 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3277 case EvalStatementParserCharacter:
3278 return Token.EVAL_STATEMENT_PARSER;
3279 case EvalCompilationUnitParserCharacter:
3280 return Token.EVAL_COMPILATION_UNIT_PARSER;
3281 case EvalUsingDeclarationsParserCharacter:
3282 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3283 case DocumentationXref:
3284 return Token.DOC_SEE;
3287 if (is_identifier_start_character (c)) {
3289 return consume_identifier (c);
3292 if (char.IsWhiteSpace ((char) c))
3295 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3300 return Token.COMPLETE_COMPLETION;
3303 return Token.GENERATE_COMPLETION;
3310 int TokenizeBackslash ()
3312 int c = get_char ();
3315 val = new CharLiteral (context.BuiltinTypes, (char) c, Location);
3316 Report.Error (1011, Location, "Empty character literal");
3317 return Token.LITERAL;
3321 Report.Error (1010, Location, "Newline in constant");
3326 c = escape (c, out d);
3330 throw new NotImplementedException ();
3332 val = new CharLiteral (context.BuiltinTypes, (char) c, Location);
3336 Report.Error (1012, Location, "Too many characters in character literal");
3338 // Try to recover, read until newline or next "'"
3339 while ((c = get_char ()) != -1) {
3340 if (c == '\n' || c == '\'')
3345 return Token.LITERAL;
3348 int TokenizeLessThan ()
3351 if (handle_typeof) {
3353 if (parse_generic_dimension (out d)) {
3356 return Token.GENERIC_DIMENSION;
3361 // Save current position and parse next token.
3363 if (parse_less_than ()) {
3364 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3365 d = Token.OP_GENERICS_LT_DECL;
3367 d = Token.OP_GENERICS_LT;
3374 parsing_generic_less_than = 0;
3383 return Token.OP_SHIFT_LEFT_ASSIGN;
3385 return Token.OP_SHIFT_LEFT;
3396 // Handles one line xml comment
3398 private void handle_one_line_xml_comment ()
3401 while ((c = peek_char ()) == ' ')
3402 get_char (); // skip heading whitespaces.
3403 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3404 xml_comment_buffer.Append ((char) get_char ());
3406 if (c == '\r' || c == '\n')
3407 xml_comment_buffer.Append (Environment.NewLine);
3411 // Remove heading "*" in Javadoc-like xml documentation.
3413 private void update_formatted_doc_comment (int current_comment_start)
3415 int length = xml_comment_buffer.Length - current_comment_start;
3416 string [] lines = xml_comment_buffer.ToString (
3417 current_comment_start,
3418 length).Replace ("\r", "").Split ('\n');
3420 // The first line starts with /**, thus it is not target
3421 // for the format check.
3422 for (int i = 1; i < lines.Length; i++) {
3423 string s = lines [i];
3424 int idx = s.IndexOf ('*');
3427 if (i < lines.Length - 1)
3431 head = s.Substring (0, idx);
3432 foreach (char c in head)
3435 lines [i] = s.Substring (idx + 1);
3437 xml_comment_buffer.Remove (current_comment_start, length);
3438 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3442 // Checks if there was incorrect doc comments and raise
3445 public void check_incorrect_doc_comment ()
3447 if (xml_comment_buffer.Length > 0)
3448 WarningMisplacedComment (Location);
3452 // Consumes the saved xml comment lines (if any)
3453 // as for current target member or type.
3455 public string consume_doc_comment ()
3457 if (xml_comment_buffer.Length > 0) {
3458 string ret = xml_comment_buffer.ToString ();
3459 reset_doc_comment ();
3466 get { return context.Report; }
3469 void reset_doc_comment ()
3471 xml_comment_buffer.Length = 0;
3474 public void cleanup ()
3476 if (ifstack != null && ifstack.Count >= 1) {
3477 int state = ifstack.Pop ();
3478 if ((state & REGION) != 0)
3479 Report.Error (1038, Location, "#endregion directive expected");
3481 Report.Error (1027, Location, "Expected `#endif' directive");
3487 // Indicates whether it accepts XML documentation or not.
3489 public enum XmlCommentState {
3490 // comment is allowed in this state.
3492 // comment is not allowed in this state.
3494 // once comments appeared when it is NotAllowed, then the
3495 // state is changed to it, until the state is changed to