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;
20 using System.Collections;
25 // This class has to be used by parser only, it reuses token
26 // details once a file is parsed
28 public class LocatedToken
30 public int row, column;
32 public SourceFile file;
34 public LocatedToken ()
38 public LocatedToken (string value, Location loc)
41 file = loc.SourceFile;
46 public override string ToString ()
48 return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
51 public Location Location
53 get { return new Location (file, row, column); }
63 /// Tokenizer for C# source code.
65 public class Tokenizer : yyParser.yyInput
69 public readonly T Token;
70 public KeywordEntry<T> Next;
71 public readonly char[] Value;
73 public KeywordEntry (string value, T token)
75 this.Value = value.ToCharArray ();
80 sealed class IdentifiersComparer : IEqualityComparer<char[]>
84 public IdentifiersComparer (int length)
89 public bool Equals (char[] x, char[] y)
91 for (int i = 0; i < length; ++i)
98 public int GetHashCode (char[] obj)
101 for (int i = 0; i < length; ++i)
102 h = (h << 5) - h + obj [i];
108 public class LocatedTokenBuffer
110 readonly LocatedToken[] buffer;
113 public LocatedTokenBuffer ()
115 buffer = new LocatedToken[0];
118 public LocatedTokenBuffer (LocatedToken[] buffer)
120 this.buffer = buffer ?? new LocatedToken[0];
123 public LocatedToken Create (SourceFile file, int row, int column)
125 return Create (null, file, row, column);
128 public LocatedToken Create (string value, SourceFile file, int row, int column)
131 // TODO: I am not very happy about the logic but it's the best
132 // what I could come up with for now.
133 // Ideally we should be using just tiny buffer (256 elements) which
134 // is enough to hold all details for currect stack and recycle elements
135 // poped from the stack but there is a trick needed to recycle
139 if (pos >= buffer.Length) {
140 entry = new LocatedToken ();
144 entry = new LocatedToken ();
153 entry.column = column;
158 // Used for token not required by expression evaluator
160 [Conditional ("FULL_AST")]
161 public void CreateOptional (SourceFile file, int row, int col, ref object token)
163 token = Create (file, row, col);
167 public enum PreprocessorDirective
173 If = 3 | RequiresArgument,
175 Elif = 5 | RequiresArgument,
177 Define = 7 | RequiresArgument,
178 Undef = 8 | RequiresArgument,
181 Pragma = 11 | CustomArgumentsParsing,
182 Line = 12 | CustomArgumentsParsing,
184 CustomArgumentsParsing = 1 << 10,
185 RequiresArgument = 1 << 11
188 readonly SeekableStreamReader reader;
189 readonly CompilationSourceFile source_file;
190 readonly CompilerContext context;
192 SourceFile current_source;
193 Location hidden_block_start;
199 readonly int tab_size;
200 bool handle_get_set = false;
201 bool handle_remove_add = false;
203 bool handle_typeof = false;
204 bool lambda_arguments_parsing;
205 List<Location> escaped_identifiers;
206 int parsing_generic_less_than;
207 readonly bool doc_processing;
208 readonly LocatedTokenBuffer ltb;
211 // Used mainly for parser optimizations. Some expressions for instance
212 // can appear only in block (including initializer, base initializer)
215 public int parsing_block;
216 internal bool query_parsing;
219 // When parsing type only, useful for ambiguous nullable types
221 public int parsing_type;
224 // Set when parsing generic declaration (type or method header)
226 public bool parsing_generic_declaration;
227 public bool parsing_generic_declaration_doc;
230 // The value indicates that we have not reach any declaration or
233 public int parsing_declaration;
235 public bool parsing_attribute_section;
237 public bool parsing_modifiers;
240 // The special characters to inject on streams to run the unit parser
241 // in the special expression mode. Using private characters from
242 // Plane Sixteen (U+100000 to U+10FFFD)
244 // This character is only tested just before the tokenizer is about to report
245 // an error; So on the regular operation mode, this addition will have no
246 // impact on the tokenizer's performance.
249 public const int EvalStatementParserCharacter = 0x100000;
250 public const int EvalCompilationUnitParserCharacter = 0x100001;
251 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
252 public const int DocumentationXref = 0x100003;
255 // XML documentation buffer. The save point is used to divide
256 // comments on types and comments on members.
258 StringBuilder xml_comment_buffer;
261 // See comment on XmlCommentState enumeration.
263 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
266 // Whether tokens have been seen on this line
268 bool tokens_seen = false;
271 // Set to true once the GENERATE_COMPLETION token has bee
272 // returned. This helps produce one GENERATE_COMPLETION,
273 // as many COMPLETE_COMPLETION as necessary to complete the
274 // AST tree and one final EOF.
279 // Whether a token has been seen on the file
280 // This is needed because `define' is not allowed to be used
281 // after a token has been seen.
288 static readonly KeywordEntry<int>[][] keywords;
289 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
290 static readonly HashSet<string> keyword_strings;
291 static readonly NumberStyles styles;
292 static readonly NumberFormatInfo csharp_format_info;
295 static readonly char[] pragma_warning = "warning".ToCharArray ();
296 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
297 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
298 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
299 static readonly char[] line_hidden = "hidden".ToCharArray ();
300 static readonly char[] line_default = "default".ToCharArray ();
302 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
304 public bool PropertyParsing {
305 get { return handle_get_set; }
306 set { handle_get_set = value; }
309 public bool EventParsing {
310 get { return handle_remove_add; }
311 set { handle_remove_add = value; }
314 public bool ConstraintsParsing {
315 get { return handle_where; }
316 set { handle_where = value; }
319 public bool TypeOfParsing {
320 get { return handle_typeof; }
321 set { handle_typeof = value; }
324 public XmlCommentState doc_state {
325 get { return xml_doc_state; }
327 if (value == XmlCommentState.Allowed) {
328 check_incorrect_doc_comment ();
329 reset_doc_comment ();
331 xml_doc_state = value;
336 // This is used to trigger completion generation on the parser
337 public bool CompleteOnEOF;
339 void AddEscapedIdentifier (Location loc)
341 if (escaped_identifiers == null)
342 escaped_identifiers = new List<Location> ();
344 escaped_identifiers.Add (loc);
347 public bool IsEscapedIdentifier (ATypeNameExpression name)
349 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
353 // Values for the associated token returned
355 internal int putback_char; // Used by repl only
361 const int TAKING = 1;
362 const int ELSE_SEEN = 4;
363 const int PARENT_TAKING = 8;
364 const int REGION = 16;
367 // pre-processor if stack state:
371 public const int MaxIdentifierLength = 512;
372 public const int MaxNumberLength = 512;
374 readonly char[] id_builder;
375 readonly Dictionary<char[], string>[] identifiers;
376 readonly char[] number_builder;
379 char[] value_builder = new char[64];
388 // This is used when the tokenizer needs to save
389 // the current position as it needs to do some parsing
390 // on its own to deamiguate a token in behalf of the
393 Stack<Position> position_stack = new Stack<Position> (2);
400 public Location hidden;
401 public int putback_char;
402 public int previous_col;
403 public Stack<int> ifstack;
404 public int parsing_generic_less_than;
405 public int current_token;
408 public Position (Tokenizer t)
410 position = t.reader.Position;
412 ref_line = t.ref_line;
414 hidden = t.hidden_block_start;
415 putback_char = t.putback_char;
416 previous_col = t.previous_col;
417 if (t.ifstack != null && t.ifstack.Count != 0) {
418 // There is no simple way to clone Stack<T> all
419 // methods reverse the order
420 var clone = t.ifstack.ToArray ();
421 Array.Reverse (clone);
422 ifstack = new Stack<int> (clone);
424 parsing_generic_less_than = t.parsing_generic_less_than;
425 current_token = t.current_token;
430 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session)
432 this.source_file = file;
433 this.context = file.Compiler;
434 this.current_source = file.SourceFile;
435 this.identifiers = session.Identifiers;
436 this.id_builder = session.IDBuilder;
437 this.number_builder = session.NumberBuilder;
438 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
444 xml_comment_buffer = new StringBuilder ();
445 doc_processing = context.Settings.DocumentationFile != null;
447 tab_size = context.Settings.TabSize;
450 public void PushPosition ()
452 position_stack.Push (new Position (this));
455 public void PopPosition ()
457 Position p = position_stack.Pop ();
459 reader.Position = p.position;
460 ref_line = p.ref_line;
463 hidden_block_start = p.hidden;
464 putback_char = p.putback_char;
465 previous_col = p.previous_col;
467 parsing_generic_less_than = p.parsing_generic_less_than;
468 current_token = p.current_token;
472 // Do not reset the position, ignore it.
473 public void DiscardPosition ()
475 position_stack.Pop ();
478 static void AddKeyword (string kw, int token)
480 keyword_strings.Add (kw);
482 AddKeyword (keywords, kw, token);
485 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
487 AddKeyword (keywords_preprocessor, kw, directive);
490 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
492 int length = kw.Length;
493 if (keywords[length] == null) {
494 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
497 int char_index = kw[0] - '_';
498 var kwe = keywords[length][char_index];
500 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
504 while (kwe.Next != null) {
508 kwe.Next = new KeywordEntry<T> (kw, token);
516 keyword_strings = new HashSet<string> ();
518 // 11 is the length of the longest keyword for now
519 keywords = new KeywordEntry<int>[11][];
521 AddKeyword ("__arglist", Token.ARGLIST);
522 AddKeyword ("__makeref", Token.MAKEREF);
523 AddKeyword ("__reftype", Token.REFTYPE);
524 AddKeyword ("__refvalue", Token.REFVALUE);
525 AddKeyword ("abstract", Token.ABSTRACT);
526 AddKeyword ("as", Token.AS);
527 AddKeyword ("add", Token.ADD);
528 AddKeyword ("base", Token.BASE);
529 AddKeyword ("bool", Token.BOOL);
530 AddKeyword ("break", Token.BREAK);
531 AddKeyword ("byte", Token.BYTE);
532 AddKeyword ("case", Token.CASE);
533 AddKeyword ("catch", Token.CATCH);
534 AddKeyword ("char", Token.CHAR);
535 AddKeyword ("checked", Token.CHECKED);
536 AddKeyword ("class", Token.CLASS);
537 AddKeyword ("const", Token.CONST);
538 AddKeyword ("continue", Token.CONTINUE);
539 AddKeyword ("decimal", Token.DECIMAL);
540 AddKeyword ("default", Token.DEFAULT);
541 AddKeyword ("delegate", Token.DELEGATE);
542 AddKeyword ("do", Token.DO);
543 AddKeyword ("double", Token.DOUBLE);
544 AddKeyword ("else", Token.ELSE);
545 AddKeyword ("enum", Token.ENUM);
546 AddKeyword ("event", Token.EVENT);
547 AddKeyword ("explicit", Token.EXPLICIT);
548 AddKeyword ("extern", Token.EXTERN);
549 AddKeyword ("false", Token.FALSE);
550 AddKeyword ("finally", Token.FINALLY);
551 AddKeyword ("fixed", Token.FIXED);
552 AddKeyword ("float", Token.FLOAT);
553 AddKeyword ("for", Token.FOR);
554 AddKeyword ("foreach", Token.FOREACH);
555 AddKeyword ("goto", Token.GOTO);
556 AddKeyword ("get", Token.GET);
557 AddKeyword ("if", Token.IF);
558 AddKeyword ("implicit", Token.IMPLICIT);
559 AddKeyword ("in", Token.IN);
560 AddKeyword ("int", Token.INT);
561 AddKeyword ("interface", Token.INTERFACE);
562 AddKeyword ("internal", Token.INTERNAL);
563 AddKeyword ("is", Token.IS);
564 AddKeyword ("lock", Token.LOCK);
565 AddKeyword ("long", Token.LONG);
566 AddKeyword ("namespace", Token.NAMESPACE);
567 AddKeyword ("new", Token.NEW);
568 AddKeyword ("null", Token.NULL);
569 AddKeyword ("object", Token.OBJECT);
570 AddKeyword ("operator", Token.OPERATOR);
571 AddKeyword ("out", Token.OUT);
572 AddKeyword ("override", Token.OVERRIDE);
573 AddKeyword ("params", Token.PARAMS);
574 AddKeyword ("private", Token.PRIVATE);
575 AddKeyword ("protected", Token.PROTECTED);
576 AddKeyword ("public", Token.PUBLIC);
577 AddKeyword ("readonly", Token.READONLY);
578 AddKeyword ("ref", Token.REF);
579 AddKeyword ("remove", Token.REMOVE);
580 AddKeyword ("return", Token.RETURN);
581 AddKeyword ("sbyte", Token.SBYTE);
582 AddKeyword ("sealed", Token.SEALED);
583 AddKeyword ("set", Token.SET);
584 AddKeyword ("short", Token.SHORT);
585 AddKeyword ("sizeof", Token.SIZEOF);
586 AddKeyword ("stackalloc", Token.STACKALLOC);
587 AddKeyword ("static", Token.STATIC);
588 AddKeyword ("string", Token.STRING);
589 AddKeyword ("struct", Token.STRUCT);
590 AddKeyword ("switch", Token.SWITCH);
591 AddKeyword ("this", Token.THIS);
592 AddKeyword ("throw", Token.THROW);
593 AddKeyword ("true", Token.TRUE);
594 AddKeyword ("try", Token.TRY);
595 AddKeyword ("typeof", Token.TYPEOF);
596 AddKeyword ("uint", Token.UINT);
597 AddKeyword ("ulong", Token.ULONG);
598 AddKeyword ("unchecked", Token.UNCHECKED);
599 AddKeyword ("unsafe", Token.UNSAFE);
600 AddKeyword ("ushort", Token.USHORT);
601 AddKeyword ("using", Token.USING);
602 AddKeyword ("virtual", Token.VIRTUAL);
603 AddKeyword ("void", Token.VOID);
604 AddKeyword ("volatile", Token.VOLATILE);
605 AddKeyword ("while", Token.WHILE);
606 AddKeyword ("partial", Token.PARTIAL);
607 AddKeyword ("where", Token.WHERE);
610 AddKeyword ("from", Token.FROM);
611 AddKeyword ("join", Token.JOIN);
612 AddKeyword ("on", Token.ON);
613 AddKeyword ("equals", Token.EQUALS);
614 AddKeyword ("select", Token.SELECT);
615 AddKeyword ("group", Token.GROUP);
616 AddKeyword ("by", Token.BY);
617 AddKeyword ("let", Token.LET);
618 AddKeyword ("orderby", Token.ORDERBY);
619 AddKeyword ("ascending", Token.ASCENDING);
620 AddKeyword ("descending", Token.DESCENDING);
621 AddKeyword ("into", Token.INTO);
623 // Contextual async keywords
624 AddKeyword ("async", Token.ASYNC);
625 AddKeyword ("await", Token.AWAIT);
627 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
629 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
630 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
631 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
632 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
633 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
634 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
635 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
636 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
637 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
638 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
639 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
640 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
642 csharp_format_info = NumberFormatInfo.InvariantInfo;
643 styles = NumberStyles.Float;
646 int GetKeyword (char[] id, int id_len)
649 // Keywords are stored in an array of arrays grouped by their
650 // length and then by the first character
652 if (id_len >= keywords.Length || keywords [id_len] == null)
655 int first_index = id [0] - '_';
656 if (first_index > 'z' - '_')
659 var kwe = keywords [id_len] [first_index];
666 for (int i = 1; i < id_len; ++i) {
667 if (id [i] != kwe.Value [i]) {
673 } while (res == 0 && kwe != null);
687 if (!handle_remove_add)
691 if (parsing_declaration == 0)
692 res = Token.EXTERN_ALIAS;
695 if (peek_token () == Token.COLON) {
697 res = Token.DEFAULT_COLON;
701 if (!(handle_where && current_token != Token.COLON) && !query_parsing)
706 // A query expression is any expression that starts with `from identifier'
707 // followed by any token except ; , =
709 if (!query_parsing) {
710 if (lambda_arguments_parsing || parsing_block == 0) {
716 // HACK: to disable generics micro-parser, because PushPosition does not
717 // store identifiers array
718 parsing_generic_less_than = 1;
720 case Token.IDENTIFIER:
732 next_token = xtoken ();
733 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
736 res = Token.FROM_FIRST;
737 query_parsing = true;
738 if (context.Settings.Version <= LanguageVersion.ISO_2)
739 Report.FeatureIsNotAvailable (context, Location, "query expressions");
742 Expression.Error_VoidInvalidInTheContext (Location, Report);
746 // HACK: A token is not a keyword so we need to restore identifiers buffer
747 // which has been overwritten before we grabbed the identifier
748 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
762 case Token.ASCENDING:
763 case Token.DESCENDING:
770 case Token.NAMESPACE:
771 // TODO: some explanation needed
772 check_incorrect_doc_comment ();
773 parsing_modifiers = false;
777 if (parsing_block > 0) {
782 // Save current position and parse next token.
785 next_token = token ();
786 bool ok = (next_token == Token.CLASS) ||
787 (next_token == Token.STRUCT) ||
788 (next_token == Token.INTERFACE) ||
789 (next_token == Token.VOID);
794 if (next_token == Token.VOID) {
795 if (context.Settings.Version <= LanguageVersion.ISO_2)
796 Report.FeatureIsNotAvailable (context, Location, "partial methods");
797 } else if (context.Settings.Version == LanguageVersion.ISO_1)
798 Report.FeatureIsNotAvailable (context, Location, "partial types");
803 if (next_token < Token.LAST_KEYWORD) {
804 Report.Error (267, Location,
805 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
809 // HACK: A token is not a keyword so we need to restore identifiers buffer
810 // which has been overwritten before we grabbed the identifier
822 if (parsing_modifiers) {
824 // Skip attributes section or constructor called async
826 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
831 } else if (parsing_block > 0) {
832 switch (peek_token ()) {
834 case Token.OPEN_PARENS_LAMBDA:
837 case Token.IDENTIFIER:
840 if (xtoken () != Token.ARROW) {
848 // peek_token could overwrite id_buffer
849 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
857 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
858 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
864 if (parsing_block == 0)
874 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
877 // Keywords are stored in an array of arrays grouped by their
878 // length and then by the first character
880 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
881 return PreprocessorDirective.Invalid;
883 int first_index = id[0] - '_';
884 if (first_index > 'z' - '_')
885 return PreprocessorDirective.Invalid;
887 var kwe = keywords_preprocessor[id_len][first_index];
889 return PreprocessorDirective.Invalid;
891 PreprocessorDirective res = PreprocessorDirective.Invalid;
894 for (int i = 1; i < id_len; ++i) {
895 if (id[i] != kwe.Value[i]) {
901 } while (res == PreprocessorDirective.Invalid && kwe != null);
906 public Location Location {
908 return new Location (current_source, ref_line, col);
912 static bool is_identifier_start_character (int c)
914 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
917 static bool is_identifier_part_character (char c)
919 if (c >= 'a' && c <= 'z')
922 if (c >= 'A' && c <= 'Z')
925 if (c == '_' || (c >= '0' && c <= '9'))
931 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
934 public static bool IsKeyword (string s)
936 return keyword_strings.Contains (s);
940 // Open parens micro parser. Detects both lambda and cast ambiguity.
942 int TokenizeOpenParens ()
947 int bracket_level = 0;
948 bool is_type = false;
949 bool can_be_type = false;
952 ptoken = current_token;
955 switch (current_token) {
956 case Token.CLOSE_PARENS:
960 // Expression inside parens is lambda, (int i) =>
962 if (current_token == Token.ARROW)
963 return Token.OPEN_PARENS_LAMBDA;
966 // Expression inside parens is single type, (int[])
969 if (current_token == Token.SEMICOLON)
970 return Token.OPEN_PARENS;
972 return Token.OPEN_PARENS_CAST;
976 // Expression is possible cast, look at next token, (T)null
979 switch (current_token) {
980 case Token.OPEN_PARENS:
983 case Token.IDENTIFIER:
997 case Token.UNCHECKED:
1003 // These can be part of a member access
1017 return Token.OPEN_PARENS_CAST;
1020 return Token.OPEN_PARENS;
1023 case Token.DOUBLE_COLON:
1024 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1029 case Token.IDENTIFIER:
1033 if (bracket_level == 0) {
1039 case Token.OP_GENERICS_LT:
1041 case Token.DOUBLE_COLON:
1043 if (bracket_level == 0)
1047 can_be_type = is_type = false;
1067 if (bracket_level == 0)
1072 if (bracket_level == 0) {
1073 bracket_level = 100;
1074 can_be_type = is_type = false;
1078 case Token.OP_GENERICS_LT:
1079 case Token.OPEN_BRACKET:
1080 if (bracket_level++ == 0)
1084 case Token.OP_GENERICS_GT:
1085 case Token.CLOSE_BRACKET:
1089 case Token.INTERR_NULLABLE:
1091 if (bracket_level == 0)
1097 can_be_type = is_type = false;
1101 return Token.OPEN_PARENS;
1106 public static bool IsValidIdentifier (string s)
1108 if (s == null || s.Length == 0)
1111 if (!is_identifier_start_character (s [0]))
1114 for (int i = 1; i < s.Length; i ++)
1115 if (! is_identifier_part_character (s [i]))
1121 bool parse_less_than ()
1124 int the_token = token ();
1125 if (the_token == Token.OPEN_BRACKET) {
1127 the_token = token ();
1128 if (the_token == Token.EOF)
1131 if (the_token == Token.CLOSE_BRACKET)
1134 the_token = token ();
1135 } else if (the_token == Token.IN || the_token == Token.OUT) {
1136 the_token = token ();
1138 switch (the_token) {
1139 case Token.IDENTIFIER:
1157 case Token.OP_GENERICS_GT:
1166 the_token = token ();
1168 if (the_token == Token.OP_GENERICS_GT)
1170 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1172 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1174 else if (the_token == Token.OP_GENERICS_LT) {
1175 if (!parse_less_than ())
1178 } else if (the_token == Token.OPEN_BRACKET) {
1180 the_token = token ();
1181 if (the_token == Token.CLOSE_BRACKET)
1183 else if (the_token == Token.COMMA)
1184 goto rank_specifiers;
1191 bool parse_generic_dimension (out int dimension)
1196 int the_token = token ();
1197 if (the_token == Token.OP_GENERICS_GT)
1199 else if (the_token == Token.COMMA) {
1207 public int peek_token ()
1212 the_token = token ();
1219 // Tonizes `?' using custom disambiguous rules to return one
1220 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1222 // Tricky expression look like:
1224 // Foo ? a = x ? b : c;
1226 int TokenizePossibleNullableType ()
1228 if (parsing_block == 0 || parsing_type > 0)
1229 return Token.INTERR_NULLABLE;
1231 int d = peek_char ();
1234 return Token.OP_COALESCING;
1237 switch (current_token) {
1238 case Token.CLOSE_PARENS:
1243 return Token.INTERR;
1247 if (d == ',' || d == ';' || d == '>')
1248 return Token.INTERR_NULLABLE;
1249 if (d == '*' || (d >= '0' && d <= '9'))
1250 return Token.INTERR;
1254 current_token = Token.NONE;
1256 switch (xtoken ()) {
1263 next_token = Token.INTERR;
1266 case Token.SEMICOLON:
1268 case Token.CLOSE_PARENS:
1269 case Token.OPEN_BRACKET:
1270 case Token.OP_GENERICS_GT:
1272 case Token.OP_COALESCING:
1274 next_token = Token.INTERR_NULLABLE;
1282 if (next_token == -1) {
1283 switch (xtoken ()) {
1285 case Token.SEMICOLON:
1286 case Token.OPEN_BRACE:
1287 case Token.CLOSE_PARENS:
1289 next_token = Token.INTERR_NULLABLE;
1293 next_token = Token.INTERR;
1302 // All shorcuts failed, do it hard way
1304 while ((ntoken = xtoken ()) != Token.EOF) {
1305 if (ntoken == Token.OPEN_BRACE) {
1310 if (ntoken == Token.CLOSE_BRACE) {
1318 if (ntoken == Token.SEMICOLON)
1321 if (ntoken == Token.COLON) {
1322 if (++colons == interrs)
1327 if (ntoken == Token.INTERR) {
1333 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1342 bool decimal_digits (int c)
1345 bool seen_digits = false;
1348 if (number_pos == MaxNumberLength)
1349 Error_NumericConstantTooLong ();
1350 number_builder [number_pos++] = (char) c;
1354 // We use peek_char2, because decimal_digits needs to do a
1355 // 2-character look-ahead (5.ToString for example).
1357 while ((d = peek_char2 ()) != -1){
1358 if (d >= '0' && d <= '9'){
1359 if (number_pos == MaxNumberLength)
1360 Error_NumericConstantTooLong ();
1361 number_builder [number_pos++] = (char) d;
1371 static bool is_hex (int e)
1373 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1376 static TypeCode real_type_suffix (int c)
1380 return TypeCode.Single;
1382 return TypeCode.Double;
1384 return TypeCode.Decimal;
1386 return TypeCode.Empty;
1390 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1392 bool is_unsigned = false;
1393 bool is_long = false;
1396 bool scanning = true;
1409 // if we have not seen anything in between
1410 // report this error
1412 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1432 if (is_long && is_unsigned){
1433 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1437 // uint if possible, or ulong else.
1439 if ((ul & 0xffffffff00000000) == 0)
1440 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1442 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1443 } else if (is_long){
1444 // long if possible, ulong otherwise
1445 if ((ul & 0x8000000000000000) != 0)
1446 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1448 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1450 // int, uint, long or ulong in that order
1451 if ((ul & 0xffffffff00000000) == 0){
1452 uint ui = (uint) ul;
1454 if ((ui & 0x80000000) != 0)
1455 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1457 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1459 if ((ul & 0x8000000000000000) != 0)
1460 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1462 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1468 // given `c' as the next char in the input decide whether
1469 // we need to convert to a special type, and then choose
1470 // the best representation for the integer
1472 ILiteralConstant adjust_int (int c, Location loc)
1475 if (number_pos > 9){
1476 ulong ul = (uint) (number_builder [0] - '0');
1478 for (int i = 1; i < number_pos; i++){
1479 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1482 return integer_type_suffix (ul, c, loc);
1484 uint ui = (uint) (number_builder [0] - '0');
1486 for (int i = 1; i < number_pos; i++){
1487 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1490 return integer_type_suffix (ui, c, loc);
1492 } catch (OverflowException) {
1493 Error_NumericConstantTooLong ();
1494 return new IntLiteral (context.BuiltinTypes, 0, loc);
1496 catch (FormatException) {
1497 Report.Error (1013, Location, "Invalid number");
1498 return new IntLiteral (context.BuiltinTypes, 0, loc);
1502 ILiteralConstant adjust_real (TypeCode t, Location loc)
1504 string s = new string (number_builder, 0, number_pos);
1505 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1508 case TypeCode.Decimal:
1510 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1511 } catch (OverflowException) {
1512 Report.Error (594, Location, error_details, "decimal");
1513 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1515 case TypeCode.Single:
1517 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1518 } catch (OverflowException) {
1519 Report.Error (594, Location, error_details, "float");
1520 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1524 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1525 } catch (OverflowException) {
1526 Report.Error (594, loc, error_details, "double");
1527 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1532 ILiteralConstant handle_hex (Location loc)
1538 while ((d = peek_char ()) != -1){
1540 number_builder [number_pos++] = (char) d;
1546 string s = new String (number_builder, 0, number_pos);
1549 if (number_pos <= 8)
1550 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1552 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1554 return integer_type_suffix (ul, peek_char (), loc);
1555 } catch (OverflowException){
1556 Error_NumericConstantTooLong ();
1557 return new IntLiteral (context.BuiltinTypes, 0, loc);
1559 catch (FormatException) {
1560 Report.Error (1013, Location, "Invalid number");
1561 return new IntLiteral (context.BuiltinTypes, 0, loc);
1566 // Invoked if we know we have .digits or digits
1568 int is_number (int c, bool dotLead)
1570 ILiteralConstant res;
1573 int read_start = reader.Position - 1;
1576 // Caller did peek_char
1586 int peek = peek_char ();
1588 if (peek == 'x' || peek == 'X') {
1589 val = res = handle_hex (loc);
1591 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1594 return Token.LITERAL;
1602 // We need to handle the case of
1603 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1605 bool is_real = false;
1610 if (decimal_digits ('.')){
1616 val = res = adjust_int (-1, loc);
1619 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1621 return Token.LITERAL;
1625 if (c == 'e' || c == 'E'){
1628 if (number_pos == MaxNumberLength)
1629 Error_NumericConstantTooLong ();
1630 number_builder [number_pos++] = (char) c;
1634 if (number_pos == MaxNumberLength)
1635 Error_NumericConstantTooLong ();
1636 number_builder [number_pos++] = '+';
1638 } else if (c == '-') {
1639 if (number_pos == MaxNumberLength)
1640 Error_NumericConstantTooLong ();
1641 number_builder [number_pos++] = '-';
1644 if (number_pos == MaxNumberLength)
1645 Error_NumericConstantTooLong ();
1646 number_builder [number_pos++] = '+';
1653 var type = real_type_suffix (c);
1654 if (type == TypeCode.Empty && !is_real) {
1655 res = adjust_int (c, loc);
1659 if (type != TypeCode.Empty) {
1663 res = adjust_real (type, loc);
1669 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1670 if (chars[chars.Length - 1] == '\r')
1671 Array.Resize (ref chars, chars.Length - 1);
1672 res.ParsedValue = chars;
1675 return Token.LITERAL;
1679 // Accepts exactly count (4 or 8) hex, no more no less
1681 int getHex (int count, out int surrogate, out bool error)
1686 int top = count != -1 ? count : 4;
1691 for (i = 0; i < top; i++){
1694 if (c >= '0' && c <= '9')
1695 c = (int) c - (int) '0';
1696 else if (c >= 'A' && c <= 'F')
1697 c = (int) c - (int) 'A' + 10;
1698 else if (c >= 'a' && c <= 'f')
1699 c = (int) c - (int) 'a' + 10;
1705 total = (total * 16) + c;
1707 int p = peek_char ();
1710 if (!is_hex ((char)p))
1716 if (total > 0x0010FFFF) {
1721 if (total >= 0x00010000) {
1722 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1723 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1730 int escape (int c, out int surrogate)
1766 v = getHex (-1, out surrogate, out error);
1772 return EscapeUnicode (d, out surrogate);
1775 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1784 int EscapeUnicode (int ch, out int surrogate)
1788 ch = getHex (8, out surrogate, out error);
1790 ch = getHex (4, out surrogate, out error);
1794 Report.Error (1009, Location, "Unrecognized escape sequence");
1802 if (putback_char != -1) {
1810 if (peek_char () == '\n') {
1816 } else if (x == '\n') {
1824 void advance_line ()
1834 if (putback_char == -1)
1835 putback_char = reader.Read ();
1836 return putback_char;
1841 if (putback_char != -1)
1842 return putback_char;
1843 return reader.Peek ();
1846 public void putback (int c)
1848 if (putback_char != -1) {
1849 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
1852 if (c == '\n' || col == 0) {
1853 // It won't happen though.
1863 public bool advance ()
1865 return peek_char () != -1 || CompleteOnEOF;
1868 public Object Value {
1874 public Object value ()
1881 current_token = xtoken ();
1882 return current_token;
1885 int TokenizePreprocessorIdentifier (out int c)
1887 // skip over white space
1890 } while (c == ' ' || c == '\t');
1894 while (c != -1 && c >= 'a' && c <= 'z') {
1895 id_builder[pos++] = (char) c;
1898 int peek = peek_char ();
1899 if (peek == 'U' || peek == 'u') {
1901 c = EscapeUnicode (c, out surrogate);
1902 if (surrogate != 0) {
1903 if (is_identifier_part_character ((char) c)) {
1904 id_builder[pos++] = (char) c;
1915 PreprocessorDirective get_cmd_arg (out string arg)
1919 tokens_seen = false;
1922 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1924 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1927 // skip over white space
1928 while (c == ' ' || c == '\t')
1931 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1934 while (c != -1 && c != '\n') {
1935 if (c == '\\' && has_identifier_argument >= 0) {
1936 if (has_identifier_argument != 0) {
1937 has_identifier_argument = 1;
1939 int peek = peek_char ();
1940 if (peek == 'U' || peek == 'u') {
1942 c = EscapeUnicode (c, out surrogate);
1943 if (surrogate != 0) {
1944 if (is_identifier_part_character ((char) c)) {
1945 if (pos == value_builder.Length)
1946 Array.Resize (ref value_builder, pos * 2);
1948 value_builder[pos++] = (char) c;
1954 has_identifier_argument = -1;
1956 } else if (c == '/' && peek_char () == '/') {
1958 // Eat single-line comments
1963 } while (c != -1 && c != '\n');
1968 if (pos == value_builder.Length)
1969 Array.Resize (ref value_builder, pos * 2);
1971 value_builder[pos++] = (char) c;
1976 if (pos > MaxIdentifierLength)
1977 arg = new string (value_builder, 0, pos);
1979 arg = InternIdentifier (value_builder, pos);
1981 // Eat any trailing whitespaces
1982 arg = arg.Trim (simple_whitespaces);
1989 // Handles the #line directive
1991 bool PreProcessLine ()
1993 Location loc = Location;
1997 int length = TokenizePreprocessorIdentifier (out c);
1998 if (length == line_default.Length) {
1999 if (!IsTokenIdentifierEqual (line_default))
2002 current_source = source_file.SourceFile;
2003 if (!hidden_block_start.IsNull) {
2004 current_source.RegisterHiddenScope (hidden_block_start, loc);
2005 hidden_block_start = Location.Null;
2012 if (length == line_hidden.Length) {
2013 if (!IsTokenIdentifierEqual (line_hidden))
2016 if (hidden_block_start.IsNull)
2017 hidden_block_start = loc;
2022 if (length != 0 || c < '0' || c > '9') {
2024 // Eat any remaining characters to continue parsing on next line
2026 while (c != -1 && c != '\n') {
2033 int new_line = TokenizeNumber (c);
2036 // Eat any remaining characters to continue parsing on next line
2038 while (c != -1 && c != '\n') {
2042 return new_line != 0;
2047 // skip over white space
2050 } while (c == ' ' || c == '\t');
2051 } else if (c == '"') {
2055 if (c != '\n' && c != '/' && c != '"') {
2057 // Eat any remaining characters to continue parsing on next line
2059 while (c != -1 && c != '\n') {
2063 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2067 string new_file_name = null;
2069 new_file_name = TokenizeFileName (ref c);
2071 // skip over white space
2072 while (c == ' ' || c == '\t') {
2078 } else if (c == '/') {
2079 ReadSingleLineComment ();
2082 // Eat any remaining characters to continue parsing on next line
2084 while (c != -1 && c != '\n') {
2088 Error_EndLineExpected ();
2092 if (new_file_name != null) {
2093 current_source = context.LookupFile (source_file, new_file_name);
2094 source_file.AddIncludeFile (current_source);
2097 if (!hidden_block_start.IsNull) {
2098 current_source.RegisterHiddenScope (hidden_block_start, loc);
2099 hidden_block_start = Location.Null;
2102 ref_line = new_line;
2107 // Handles #define and #undef
2109 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2111 if (ident.Length == 0 || ident == "true" || ident == "false"){
2112 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2116 if (ident.IndexOfAny (simple_whitespaces) != -1){
2117 Error_EndLineExpected ();
2121 if (!is_identifier_start_character (ident [0]))
2122 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2124 foreach (char c in ident.Substring (1)){
2125 if (!is_identifier_part_character (c)){
2126 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2131 if (!caller_is_taking)
2138 if (context.Settings.IsConditionalSymbolDefined (ident))
2141 source_file.AddDefine (ident);
2146 source_file.AddUndefine (ident);
2150 byte read_hex (out bool error)
2153 int c = get_char ();
2155 if ((c >= '0') && (c <= '9'))
2156 total = (int) c - (int) '0';
2157 else if ((c >= 'A') && (c <= 'F'))
2158 total = (int) c - (int) 'A' + 10;
2159 else if ((c >= 'a') && (c <= 'f'))
2160 total = (int) c - (int) 'a' + 10;
2169 if ((c >= '0') && (c <= '9'))
2170 total += (int) c - (int) '0';
2171 else if ((c >= 'A') && (c <= 'F'))
2172 total += (int) c - (int) 'A' + 10;
2173 else if ((c >= 'a') && (c <= 'f'))
2174 total += (int) c - (int) 'a' + 10;
2181 return (byte) total;
2185 // Parses #pragma checksum
2187 bool ParsePragmaChecksum ()
2190 // The syntax is ` "foo.txt" "{guid}" "hash"'
2192 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2194 int c = get_char ();
2199 string file_name = TokenizeFileName (ref c);
2201 // TODO: Any white-spaces count
2205 SourceFile file = context.LookupFile (source_file, file_name);
2207 if (get_char () != '"' || get_char () != '{')
2211 byte[] guid_bytes = new byte [16];
2214 for (; i < 4; i++) {
2215 guid_bytes [i] = read_hex (out error);
2220 if (get_char () != '-')
2223 for (; i < 10; i++) {
2224 guid_bytes [i] = read_hex (out error);
2228 guid_bytes [i++] = read_hex (out error);
2232 if (get_char () != '-')
2236 for (; i < 16; i++) {
2237 guid_bytes [i] = read_hex (out error);
2242 if (get_char () != '}' || get_char () != '"')
2245 // TODO: Any white-spaces count
2250 if (get_char () != '"')
2253 // Any length of checksum
2254 List<byte> checksum_bytes = new List<byte> (16);
2256 var checksum_location = Location;
2258 while (c != '"' && c != -1) {
2259 checksum_bytes.Add (read_hex (out error));
2267 ReadSingleLineComment ();
2268 } else if (get_char () != '"') {
2272 if (context.Settings.GenerateDebugInfo) {
2273 var chsum = checksum_bytes.ToArray ();
2275 if (file.HasChecksum) {
2276 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2277 // TODO: Report.SymbolRelatedToPreviousError
2278 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2282 file.SetChecksum (guid_bytes, chsum);
2283 current_source.AutoGenerated = true;
2289 bool IsTokenIdentifierEqual (char[] identifier)
2291 for (int i = 0; i < identifier.Length; ++i) {
2292 if (identifier[i] != id_builder[i])
2299 int TokenizeNumber (int value)
2303 decimal_digits (value);
2304 uint ui = (uint) (number_builder[0] - '0');
2307 for (int i = 1; i < number_pos; i++) {
2308 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2312 } catch (OverflowException) {
2313 Error_NumericConstantTooLong ();
2318 string TokenizeFileName (ref int c)
2320 var string_builder = new StringBuilder ();
2321 while (c != -1 && c != '\n') {
2328 string_builder.Append ((char) c);
2331 if (string_builder.Length == 0) {
2332 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2336 return string_builder.ToString ();
2339 int TokenizePragmaNumber (ref int c)
2345 if (c >= '0' && c <= '9') {
2346 number = TokenizeNumber (c);
2350 // skip over white space
2351 while (c == ' ' || c == '\t')
2358 // skip over white space
2359 while (c == ' ' || c == '\t')
2364 ReadSingleLineComment ();
2366 Report.Warning (1692, 1, Location, "Invalid number");
2368 // Read everything till the end of the line or file
2371 } while (c != -1 && c != '\n');
2378 void ReadSingleLineComment ()
2380 if (peek_char () != '/')
2381 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2383 // Read everything till the end of the line or file
2387 } while (c != -1 && c != '\n');
2391 /// Handles #pragma directive
2393 void ParsePragmaDirective (string arg)
2396 int length = TokenizePreprocessorIdentifier (out c);
2397 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2398 length = TokenizePreprocessorIdentifier (out c);
2401 // #pragma warning disable
2402 // #pragma warning restore
2404 if (length == pragma_warning_disable.Length) {
2405 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2406 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2407 // skip over white space
2408 while (c == ' ' || c == '\t')
2413 if (c == '\n' || c == '/') {
2415 ReadSingleLineComment ();
2418 // Disable/Restore all warnings
2421 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2423 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2427 // Disable/Restore a warning or group of warnings
2431 code = TokenizePragmaNumber (ref c);
2434 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2436 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2439 } while (code >= 0 && c != '\n' && c != -1);
2446 Report.Warning (1634, 1, Location, "Expected disable or restore");
2448 // Eat any remaining characters on the line
2449 while (c != '\n' && c != -1)
2458 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2459 if (c != ' ' || !ParsePragmaChecksum ()) {
2460 Report.Warning (1695, 1, Location,
2461 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2467 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2470 bool eval_val (string s)
2477 return source_file.IsConditionalDefined (s);
2480 bool pp_primary (ref string s)
2489 s = s.Substring (1);
2490 bool val = pp_expr (ref s, false);
2491 if (s.Length > 0 && s [0] == ')'){
2492 s = s.Substring (1);
2495 Error_InvalidDirective ();
2499 if (is_identifier_start_character (c)){
2505 if (is_identifier_part_character (c)){
2509 bool v = eval_val (s.Substring (0, j));
2510 s = s.Substring (j);
2513 bool vv = eval_val (s);
2518 Error_InvalidDirective ();
2522 bool pp_unary (ref string s)
2529 if (len > 1 && s [1] == '='){
2530 Error_InvalidDirective ();
2533 s = s.Substring (1);
2534 return ! pp_primary (ref s);
2536 return pp_primary (ref s);
2538 Error_InvalidDirective ();
2543 bool pp_eq (ref string s)
2545 bool va = pp_unary (ref s);
2551 if (len > 2 && s [1] == '='){
2552 s = s.Substring (2);
2553 return va == pp_unary (ref s);
2555 Error_InvalidDirective ();
2558 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2559 s = s.Substring (2);
2561 return va != pp_unary (ref s);
2570 bool pp_and (ref string s)
2572 bool va = pp_eq (ref s);
2578 if (len > 2 && s [1] == '&'){
2579 s = s.Substring (2);
2580 return (va & pp_and (ref s));
2582 Error_InvalidDirective ();
2591 // Evaluates an expression for `#if' or `#elif'
2593 bool pp_expr (ref string s, bool isTerm)
2595 bool va = pp_and (ref s);
2602 if (len > 2 && s [1] == '|'){
2603 s = s.Substring (2);
2604 return va | pp_expr (ref s, isTerm);
2606 Error_InvalidDirective ();
2611 Error_EndLineExpected ();
2619 bool eval (string s)
2621 bool v = pp_expr (ref s, true);
2630 void Error_NumericConstantTooLong ()
2632 Report.Error (1021, Location, "Integral constant is too large");
2635 void Error_InvalidDirective ()
2637 Report.Error (1517, Location, "Invalid preprocessor directive");
2640 void Error_UnexpectedDirective (string extra)
2644 "Unexpected processor directive ({0})", extra);
2647 void Error_TokensSeen ()
2649 Report.Error (1032, Location,
2650 "Cannot define or undefine preprocessor symbols after first token in file");
2653 void Eror_WrongPreprocessorLocation ()
2655 Report.Error (1040, Location,
2656 "Preprocessor directives must appear as the first non-whitespace character on a line");
2659 void Error_EndLineExpected ()
2661 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2665 // Raises a warning when tokenizer found documentation comment
2666 // on unexpected place
2668 void WarningMisplacedComment (Location loc)
2670 if (doc_state != XmlCommentState.Error) {
2671 doc_state = XmlCommentState.Error;
2672 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2677 // if true, then the code continues processing the code
2678 // if false, the code stays in a loop until another directive is
2680 // When caller_is_taking is false we ignore all directives except the ones
2681 // which can help us to identify where the #if block ends
2682 bool ParsePreprocessingDirective (bool caller_is_taking)
2685 bool region_directive = false;
2687 var directive = get_cmd_arg (out arg);
2690 // The first group of pre-processing instructions is always processed
2692 switch (directive) {
2693 case PreprocessorDirective.Region:
2694 region_directive = true;
2696 goto case PreprocessorDirective.If;
2698 case PreprocessorDirective.Endregion:
2699 if (ifstack == null || ifstack.Count == 0){
2700 Error_UnexpectedDirective ("no #region for this #endregion");
2703 int pop = ifstack.Pop ();
2705 if ((pop & REGION) == 0)
2706 Report.Error (1027, Location, "Expected `#endif' directive");
2708 return caller_is_taking;
2710 case PreprocessorDirective.If:
2711 if (ifstack == null)
2712 ifstack = new Stack<int> (2);
2714 int flags = region_directive ? REGION : 0;
2715 if (ifstack.Count == 0){
2716 flags |= PARENT_TAKING;
2718 int state = ifstack.Peek ();
2719 if ((state & TAKING) != 0) {
2720 flags |= PARENT_TAKING;
2724 if (eval (arg) && caller_is_taking) {
2725 ifstack.Push (flags | TAKING);
2728 ifstack.Push (flags);
2731 case PreprocessorDirective.Endif:
2732 if (ifstack == null || ifstack.Count == 0){
2733 Error_UnexpectedDirective ("no #if for this #endif");
2736 pop = ifstack.Pop ();
2738 if ((pop & REGION) != 0)
2739 Report.Error (1038, Location, "#endregion directive expected");
2741 if (arg.Length != 0) {
2742 Error_EndLineExpected ();
2745 if (ifstack.Count == 0)
2748 int state = ifstack.Peek ();
2749 return (state & TAKING) != 0;
2752 case PreprocessorDirective.Elif:
2753 if (ifstack == null || ifstack.Count == 0){
2754 Error_UnexpectedDirective ("no #if for this #elif");
2757 int state = ifstack.Pop ();
2759 if ((state & REGION) != 0) {
2760 Report.Error (1038, Location, "#endregion directive expected");
2764 if ((state & ELSE_SEEN) != 0){
2765 Error_UnexpectedDirective ("#elif not valid after #else");
2769 if ((state & TAKING) != 0) {
2774 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2775 ifstack.Push (state | TAKING);
2779 ifstack.Push (state);
2783 case PreprocessorDirective.Else:
2784 if (ifstack == null || ifstack.Count == 0){
2785 Error_UnexpectedDirective ("no #if for this #else");
2788 int state = ifstack.Peek ();
2790 if ((state & REGION) != 0) {
2791 Report.Error (1038, Location, "#endregion directive expected");
2795 if ((state & ELSE_SEEN) != 0){
2796 Error_UnexpectedDirective ("#else within #else");
2802 if (arg.Length != 0) {
2803 Error_EndLineExpected ();
2808 if ((state & PARENT_TAKING) != 0) {
2809 ret = (state & TAKING) == 0;
2817 ifstack.Push (state | ELSE_SEEN);
2821 case PreprocessorDirective.Define:
2822 if (any_token_seen){
2823 if (caller_is_taking)
2824 Error_TokensSeen ();
2825 return caller_is_taking;
2827 PreProcessDefinition (true, arg, caller_is_taking);
2828 return caller_is_taking;
2830 case PreprocessorDirective.Undef:
2831 if (any_token_seen){
2832 if (caller_is_taking)
2833 Error_TokensSeen ();
2834 return caller_is_taking;
2836 PreProcessDefinition (false, arg, caller_is_taking);
2837 return caller_is_taking;
2839 case PreprocessorDirective.Invalid:
2840 Report.Error (1024, Location, "Wrong preprocessor directive");
2845 // These are only processed if we are in a `taking' block
2847 if (!caller_is_taking)
2851 case PreprocessorDirective.Error:
2852 Report.Error (1029, Location, "#error: '{0}'", arg);
2855 case PreprocessorDirective.Warning:
2856 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2859 case PreprocessorDirective.Pragma:
2860 if (context.Settings.Version == LanguageVersion.ISO_1) {
2861 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2864 ParsePragmaDirective (arg);
2867 case PreprocessorDirective.Line:
2868 Location loc = Location;
2869 if (!PreProcessLine ())
2870 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
2872 return caller_is_taking;
2875 throw new NotImplementedException (directive.ToString ());
2878 private int consume_string (bool quoted)
2882 Location start_location = Location;
2884 start_location = start_location - 1;
2887 int reader_pos = reader.Position;
2891 // Cannot use get_char because of \r in quoted strings
2892 if (putback_char != -1) {
2902 if (quoted && peek_char () == '"') {
2903 if (pos == value_builder.Length)
2904 Array.Resize (ref value_builder, pos * 2);
2906 value_builder[pos++] = (char) c;
2915 s = InternIdentifier (value_builder, pos);
2917 s = new string (value_builder, 0, pos);
2919 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2922 res.ParsedValue = quoted ?
2923 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2924 reader.ReadChars (reader_pos - 1, reader.Position);
2927 return Token.LITERAL;
2932 Report.Error (1010, Location, "Newline in constant");
2936 // Don't add \r to string literal
2937 if (pos > 1 && value_builder [pos - 1] == '\r')
2940 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2941 return Token.LITERAL;
2945 } else if (c == '\\' && !quoted) {
2948 c = escape (c, out surrogate);
2951 if (surrogate != 0) {
2952 if (pos == value_builder.Length)
2953 Array.Resize (ref value_builder, pos * 2);
2955 value_builder[pos++] = (char) c;
2958 } else if (c == -1) {
2959 Report.Error (1039, Location, "Unterminated string literal");
2965 if (pos == value_builder.Length)
2966 Array.Resize (ref value_builder, pos * 2);
2968 value_builder[pos++] = (char) c;
2972 private int consume_identifier (int s)
2974 int res = consume_identifier (s, false);
2976 if (doc_state == XmlCommentState.Allowed)
2977 doc_state = XmlCommentState.NotAllowed;
2982 int consume_identifier (int c, bool quoted)
2985 // This method is very performance sensitive. It accounts
2986 // for approximately 25% of all parser time
2996 c = escape (c, out surrogate);
2997 if (surrogate != 0) {
2998 id_builder [pos++] = (char) c;
3003 id_builder [pos++] = (char) c;
3009 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3010 id_builder [pos++] = (char) c;
3017 c = escape (c, out surrogate);
3018 if (is_identifier_part_character ((char) c))
3019 id_builder[pos++] = (char) c;
3021 if (surrogate != 0) {
3027 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
3028 id_builder [pos++] = (char) c;
3035 } catch (IndexOutOfRangeException) {
3036 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3044 // Optimization: avoids doing the keyword lookup
3045 // on uppercase letters
3047 if (id_builder [0] >= '_' && !quoted) {
3048 int keyword = GetKeyword (id_builder, pos);
3049 if (keyword != -1) {
3050 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3055 string s = InternIdentifier (id_builder, pos);
3056 val = ltb.Create (s, current_source, ref_line, column);
3057 if (quoted && parsing_attribute_section)
3058 AddEscapedIdentifier (((LocatedToken) val).Location);
3060 return Token.IDENTIFIER;
3063 string InternIdentifier (char[] charBuffer, int length)
3066 // Keep identifiers in an array of hashtables to avoid needless
3069 var identifiers_group = identifiers[length];
3071 if (identifiers_group != null) {
3072 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3076 // TODO: this should be number of files dependant
3077 // corlib compilation peaks at 1000 and System.Core at 150
3078 int capacity = length > 20 ? 10 : 100;
3079 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3080 identifiers[length] = identifiers_group;
3083 char[] chars = new char[length];
3084 Array.Copy (charBuffer, chars, length);
3086 s = new string (charBuffer, 0, length);
3087 identifiers_group.Add (chars, s);
3091 public int xtoken ()
3095 // Whether we have seen comments on the current line
3096 bool comments_seen = false;
3097 while ((c = get_char ()) != -1) {
3100 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3108 case 0xFEFF: // Ignore BOM anywhere in the file
3111 /* This is required for compatibility with .NET
3113 if (peek_char () == 0xBB) {
3116 if (get_char () == 0xBF)
3124 return consume_identifier (c);
3127 val = ltb.Create (current_source, ref_line, col);
3128 return Token.OPEN_BRACE;
3130 val = ltb.Create (current_source, ref_line, col);
3131 return Token.CLOSE_BRACE;
3133 // To block doccomment inside attribute declaration.
3134 if (doc_state == XmlCommentState.Allowed)
3135 doc_state = XmlCommentState.NotAllowed;
3137 val = ltb.Create (current_source, ref_line, col);
3139 if (parsing_block == 0 || lambda_arguments_parsing)
3140 return Token.OPEN_BRACKET;
3142 int next = peek_char ();
3146 return Token.OPEN_BRACKET;
3154 next = peek_token ();
3155 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3156 return Token.OPEN_BRACKET;
3158 return Token.OPEN_BRACKET_EXPR;
3160 return Token.OPEN_BRACKET_EXPR;
3163 ltb.CreateOptional (current_source, ref_line, col, ref val);
3164 return Token.CLOSE_BRACKET;
3166 val = ltb.Create (current_source, ref_line, col);
3168 // An expression versions of parens can appear in block context only
3170 if (parsing_block != 0 && !lambda_arguments_parsing) {
3173 // Optmize most common case where we know that parens
3176 switch (current_token) {
3177 case Token.IDENTIFIER:
3186 case Token.DELEGATE:
3187 case Token.OP_GENERICS_GT:
3188 return Token.OPEN_PARENS;
3191 // Optimize using peek
3192 int xx = peek_char ();
3199 return Token.OPEN_PARENS;
3202 lambda_arguments_parsing = true;
3204 d = TokenizeOpenParens ();
3206 lambda_arguments_parsing = false;
3210 return Token.OPEN_PARENS;
3212 ltb.CreateOptional (current_source, ref_line, col, ref val);
3213 return Token.CLOSE_PARENS;
3215 ltb.CreateOptional (current_source, ref_line, col, ref val);
3218 ltb.CreateOptional (current_source, ref_line, col, ref val);
3219 return Token.SEMICOLON;
3221 val = ltb.Create (current_source, ref_line, col);
3224 val = ltb.Create (current_source, ref_line, col);
3225 return TokenizePossibleNullableType ();
3227 val = ltb.Create (current_source, ref_line, col);
3228 if (parsing_generic_less_than++ > 0)
3229 return Token.OP_GENERICS_LT;
3231 return TokenizeLessThan ();
3234 val = ltb.Create (current_source, ref_line, col);
3242 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3243 parsing_generic_less_than--;
3244 return Token.OP_GENERICS_GT;
3253 return Token.OP_SHIFT_RIGHT_ASSIGN;
3255 return Token.OP_SHIFT_RIGHT;
3261 val = ltb.Create (current_source, ref_line, col);
3265 } else if (d == '=') {
3266 d = Token.OP_ADD_ASSIGN;
3274 val = ltb.Create (current_source, ref_line, col);
3278 } else if (d == '=')
3279 d = Token.OP_SUB_ASSIGN;
3289 val = ltb.Create (current_source, ref_line, col);
3290 if (peek_char () == '='){
3297 val = ltb.Create (current_source, ref_line, col);
3308 return Token.ASSIGN;
3311 val = ltb.Create (current_source, ref_line, col);
3315 return Token.OP_AND;
3319 return Token.OP_AND_ASSIGN;
3321 return Token.BITWISE_AND;
3324 val = ltb.Create (current_source, ref_line, col);
3332 return Token.OP_OR_ASSIGN;
3334 return Token.BITWISE_OR;
3337 val = ltb.Create (current_source, ref_line, col);
3338 if (peek_char () == '='){
3340 return Token.OP_MULT_ASSIGN;
3347 val = ltb.Create (current_source, ref_line, col);
3349 return Token.OP_DIV_ASSIGN;
3352 // Handle double-slash comments.
3355 if (doc_processing) {
3356 if (peek_char () == '/') {
3358 // Don't allow ////.
3359 if ((d = peek_char ()) != '/') {
3360 if (doc_state == XmlCommentState.Allowed)
3361 handle_one_line_xml_comment ();
3362 else if (doc_state == XmlCommentState.NotAllowed)
3363 WarningMisplacedComment (Location - 3);
3366 if (xml_comment_buffer.Length > 0)
3367 doc_state = XmlCommentState.NotAllowed;
3371 while ((d = get_char ()) != -1 && d != '\n');
3373 any_token_seen |= tokens_seen;
3374 tokens_seen = false;
3375 comments_seen = false;
3377 } else if (d == '*'){
3379 bool docAppend = false;
3380 if (doc_processing && peek_char () == '*') {
3382 // But when it is /**/, just do nothing.
3383 if (peek_char () == '/') {
3387 if (doc_state == XmlCommentState.Allowed)
3389 else if (doc_state == XmlCommentState.NotAllowed) {
3390 WarningMisplacedComment (Location - 2);
3394 int current_comment_start = 0;
3396 current_comment_start = xml_comment_buffer.Length;
3397 xml_comment_buffer.Append (Environment.NewLine);
3400 while ((d = get_char ()) != -1){
3401 if (d == '*' && peek_char () == '/'){
3403 comments_seen = true;
3407 xml_comment_buffer.Append ((char) d);
3410 any_token_seen |= tokens_seen;
3411 tokens_seen = false;
3413 // Reset 'comments_seen' just to be consistent.
3414 // It doesn't matter either way, here.
3416 comments_seen = false;
3420 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3423 update_formatted_doc_comment (current_comment_start);
3426 val = ltb.Create (current_source, ref_line, col);
3430 val = ltb.Create (current_source, ref_line, col);
3431 if (peek_char () == '='){
3433 return Token.OP_MOD_ASSIGN;
3435 return Token.PERCENT;
3438 val = ltb.Create (current_source, ref_line, col);
3439 if (peek_char () == '='){
3441 return Token.OP_XOR_ASSIGN;
3443 return Token.CARRET;
3446 val = ltb.Create (current_source, ref_line, col);
3447 if (peek_char () == ':') {
3449 return Token.DOUBLE_COLON;
3453 case '0': case '1': case '2': case '3': case '4':
3454 case '5': case '6': case '7': case '8': case '9':
3456 return is_number (c, false);
3458 case '\n': // white space
3459 any_token_seen |= tokens_seen;
3460 tokens_seen = false;
3461 comments_seen = false;
3467 if (d >= '0' && d <= '9')
3468 return is_number (c, true);
3470 ltb.CreateOptional (current_source, ref_line, col, ref val);
3474 if (tokens_seen || comments_seen) {
3475 Eror_WrongPreprocessorLocation ();
3479 if (ParsePreprocessingDirective (true))
3482 bool directive_expected = false;
3483 while ((c = get_char ()) != -1) {
3485 directive_expected = true;
3486 } else if (!directive_expected) {
3487 // TODO: Implement comment support for disabled code and uncomment this code
3489 // Eror_WrongPreprocessorLocation ();
3490 // return Token.ERROR;
3495 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3499 if (ParsePreprocessingDirective (false))
3502 directive_expected = false;
3506 tokens_seen = false;
3513 return consume_string (false);
3516 return TokenizeBackslash ();
3522 return consume_string (true);
3525 if (is_identifier_start_character (c)){
3526 return consume_identifier (c, true);
3529 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3532 case EvalStatementParserCharacter:
3533 return Token.EVAL_STATEMENT_PARSER;
3534 case EvalCompilationUnitParserCharacter:
3535 return Token.EVAL_COMPILATION_UNIT_PARSER;
3536 case EvalUsingDeclarationsParserCharacter:
3537 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3538 case DocumentationXref:
3539 return Token.DOC_SEE;
3542 if (is_identifier_start_character (c)) {
3544 return consume_identifier (c);
3547 if (char.IsWhiteSpace ((char) c))
3550 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3555 return Token.COMPLETE_COMPLETION;
3558 return Token.GENERATE_COMPLETION;
3565 int TokenizeBackslash ()
3568 int read_start = reader.Position;
3570 Location start_location = Location;
3571 int c = get_char ();
3574 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3575 Report.Error (1011, start_location, "Empty character literal");
3576 return Token.LITERAL;
3580 Report.Error (1010, start_location, "Newline in constant");
3585 c = escape (c, out d);
3589 throw new NotImplementedException ();
3591 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3596 Report.Error (1012, start_location, "Too many characters in character literal");
3598 // Try to recover, read until newline or next "'"
3599 while ((c = get_char ()) != -1) {
3600 if (c == '\n' || c == '\'')
3606 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3609 return Token.LITERAL;
3612 int TokenizeLessThan ()
3615 if (handle_typeof) {
3617 if (parse_generic_dimension (out d)) {
3620 return Token.GENERIC_DIMENSION;
3625 // Save current position and parse next token.
3627 if (parse_less_than ()) {
3628 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3629 d = Token.OP_GENERICS_LT_DECL;
3631 d = Token.OP_GENERICS_LT;
3638 parsing_generic_less_than = 0;
3647 return Token.OP_SHIFT_LEFT_ASSIGN;
3649 return Token.OP_SHIFT_LEFT;
3660 // Handles one line xml comment
3662 private void handle_one_line_xml_comment ()
3665 while ((c = peek_char ()) == ' ')
3666 get_char (); // skip heading whitespaces.
3667 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3668 xml_comment_buffer.Append ((char) get_char ());
3670 if (c == '\r' || c == '\n')
3671 xml_comment_buffer.Append (Environment.NewLine);
3675 // Remove heading "*" in Javadoc-like xml documentation.
3677 private void update_formatted_doc_comment (int current_comment_start)
3679 int length = xml_comment_buffer.Length - current_comment_start;
3680 string [] lines = xml_comment_buffer.ToString (
3681 current_comment_start,
3682 length).Replace ("\r", "").Split ('\n');
3684 // The first line starts with /**, thus it is not target
3685 // for the format check.
3686 for (int i = 1; i < lines.Length; i++) {
3687 string s = lines [i];
3688 int idx = s.IndexOf ('*');
3691 if (i < lines.Length - 1)
3695 head = s.Substring (0, idx);
3696 foreach (char c in head)
3699 lines [i] = s.Substring (idx + 1);
3701 xml_comment_buffer.Remove (current_comment_start, length);
3702 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3706 // Checks if there was incorrect doc comments and raise
3709 public void check_incorrect_doc_comment ()
3711 if (xml_comment_buffer.Length > 0)
3712 WarningMisplacedComment (Location);
3716 // Consumes the saved xml comment lines (if any)
3717 // as for current target member or type.
3719 public string consume_doc_comment ()
3721 if (xml_comment_buffer.Length > 0) {
3722 string ret = xml_comment_buffer.ToString ();
3723 reset_doc_comment ();
3730 get { return context.Report; }
3733 void reset_doc_comment ()
3735 xml_comment_buffer.Length = 0;
3738 public void cleanup ()
3740 if (ifstack != null && ifstack.Count >= 1) {
3741 int state = ifstack.Pop ();
3742 if ((state & REGION) != 0)
3743 Report.Error (1038, Location, "#endregion directive expected");
3745 Report.Error (1027, Location, "Expected `#endif' directive");
3751 // Indicates whether it accepts XML documentation or not.
3753 public enum XmlCommentState {
3754 // comment is allowed in this state.
3756 // comment is not allowed in this state.
3758 // once comments appeared when it is NotAllowed, then the
3759 // state is changed to it, until the state is changed to