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;
19 using System.Globalization;
20 using System.Reflection;
21 using System.Diagnostics;
26 /// Tokenizer for C# source code.
29 public class Tokenizer : yyParser.yyInput
33 public readonly int Token;
34 public KeywordEntry Next;
35 public readonly char[] Value;
37 public KeywordEntry (string value, int token)
39 this.Value = value.ToCharArray ();
44 sealed class IdentifiersComparer : IEqualityComparer<char[]>
48 public IdentifiersComparer (int length)
53 public bool Equals (char[] x, char[] y)
55 for (int i = 0; i < length; ++i)
62 public int GetHashCode (char[] obj)
65 for (int i = 0; i < length; ++i)
66 h = (h << 5) - h + obj [i];
73 // This class has to be used in the parser only, it reuses token
74 // details after each parse
76 public class LocatedToken
81 static LocatedToken[] buffer;
84 private LocatedToken ()
88 public static LocatedToken Create (int row, int column)
90 return Create (null, row, column);
93 public static LocatedToken Create (string value, int row, int column)
96 // TODO: I am not very happy about the logic but it's the best
97 // what I could come up with for now.
98 // Ideally we should be using just tiny buffer (256 elements) which
99 // is enough to hold all details for currect stack and recycle elements
100 // poped from the stack but there is a trick needed to recycle
104 if (pos >= buffer.Length) {
105 entry = new LocatedToken ();
107 entry = buffer [pos];
109 entry = new LocatedToken ();
110 buffer [pos] = entry;
117 entry.column = column;
122 // Used for token not required by expression evaluator
124 [Conditional ("FULL_AST")]
125 public static void CreateOptional (int row, int col, ref object token)
127 token = Create (row, col);
130 public static void Initialize ()
133 buffer = new LocatedToken [10000];
137 public Location Location {
138 get { return new Location (row, column); }
141 public string Value {
142 get { return value; }
146 SeekableStreamReader reader;
148 CompilationUnit file_name;
149 CompilerContext context;
157 bool handle_get_set = false;
158 bool handle_remove_add = false;
159 bool handle_where = false;
160 bool handle_typeof = false;
161 bool lambda_arguments_parsing;
162 Location current_comment_location = Location.Null;
163 List<Location> escaped_identifiers;
164 int parsing_generic_less_than;
167 // Used mainly for parser optimizations. Some expressions for instance
168 // can appear only in block (including initializer, base initializer)
171 public int parsing_block;
172 internal bool query_parsing;
175 // When parsing type only, useful for ambiguous nullable types
177 public int parsing_type;
180 // Set when parsing generic declaration (type or method header)
182 public bool parsing_generic_declaration;
185 // The value indicates that we have not reach any declaration or
188 public int parsing_declaration;
191 // The special character to inject on streams to trigger the EXPRESSION_PARSE
192 // token to be returned. It just happens to be a Unicode character that
193 // would never be part of a program (can not be an identifier).
195 // This character is only tested just before the tokenizer is about to report
196 // an error; So on the regular operation mode, this addition will have no
197 // impact on the tokenizer's performance.
200 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
201 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
202 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
205 // XML documentation buffer. The save point is used to divide
206 // comments on types and comments on members.
208 StringBuilder xml_comment_buffer;
211 // See comment on XmlCommentState enumeration.
213 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
216 // Whether tokens have been seen on this line
218 bool tokens_seen = false;
221 // Set to true once the GENERATE_COMPLETION token has bee
222 // returned. This helps produce one GENERATE_COMPLETION,
223 // as many COMPLETE_COMPLETION as necessary to complete the
224 // AST tree and one final EOF.
229 // Whether a token has been seen on the file
230 // This is needed because `define' is not allowed to be used
231 // after a token has been seen.
233 bool any_token_seen = false;
235 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
237 public bool PropertyParsing {
238 get { return handle_get_set; }
239 set { handle_get_set = value; }
242 public bool EventParsing {
243 get { return handle_remove_add; }
244 set { handle_remove_add = value; }
247 public bool ConstraintsParsing {
248 get { return handle_where; }
249 set { handle_where = value; }
252 public bool TypeOfParsing {
253 get { return handle_typeof; }
254 set { handle_typeof = value; }
258 get { return tab_size; }
259 set { tab_size = value; }
262 public XmlCommentState doc_state {
263 get { return xml_doc_state; }
265 if (value == XmlCommentState.Allowed) {
266 check_incorrect_doc_comment ();
267 reset_doc_comment ();
269 xml_doc_state = value;
274 // This is used to trigger completion generation on the parser
275 public bool CompleteOnEOF;
277 void AddEscapedIdentifier (Location loc)
279 if (escaped_identifiers == null)
280 escaped_identifiers = new List<Location> ();
282 escaped_identifiers.Add (loc);
285 public bool IsEscapedIdentifier (Location loc)
287 if (escaped_identifiers != null) {
288 foreach (Location lt in escaped_identifiers)
299 static KeywordEntry[][] keywords;
300 static Dictionary<string, object> keyword_strings; // TODO: HashSet
301 static NumberStyles styles;
302 static NumberFormatInfo csharp_format_info;
305 // Values for the associated token returned
307 internal int putback_char; // Used by repl only
313 const int TAKING = 1;
314 const int ELSE_SEEN = 4;
315 const int PARENT_TAKING = 8;
316 const int REGION = 16;
319 // pre-processor if stack state:
323 static System.Text.StringBuilder string_builder;
325 const int max_id_size = 512;
326 static char [] id_builder = new char [max_id_size];
328 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
330 const int max_number_size = 512;
331 static char [] number_builder = new char [max_number_size];
332 static int number_pos;
334 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
337 // Details about the error encoutered by the tokenizer
339 string error_details;
341 public string error {
343 return error_details;
354 // This is used when the tokenizer needs to save
355 // the current position as it needs to do some parsing
356 // on its own to deamiguate a token in behalf of the
359 Stack<Position> position_stack = new Stack<Position> (2);
367 public int putback_char;
368 public int previous_col;
369 public Stack<int> ifstack;
370 public int parsing_generic_less_than;
371 public int current_token;
374 public Position (Tokenizer t)
376 position = t.reader.Position;
378 ref_line = t.ref_line;
381 putback_char = t.putback_char;
382 previous_col = t.previous_col;
383 if (t.ifstack != null && t.ifstack.Count != 0) {
384 // There is no simple way to clone Stack<T> all
385 // methods reverse the order
386 var clone = t.ifstack.ToArray ();
387 Array.Reverse (clone);
388 ifstack = new Stack<int> (clone);
390 parsing_generic_less_than = t.parsing_generic_less_than;
391 current_token = t.current_token;
396 public void PushPosition ()
398 position_stack.Push (new Position (this));
401 public void PopPosition ()
403 Position p = position_stack.Pop ();
405 reader.Position = p.position;
406 ref_line = p.ref_line;
410 putback_char = p.putback_char;
411 previous_col = p.previous_col;
413 parsing_generic_less_than = p.parsing_generic_less_than;
414 current_token = p.current_token;
418 // Do not reset the position, ignore it.
419 public void DiscardPosition ()
421 position_stack.Pop ();
424 static void AddKeyword (string kw, int token)
426 keyword_strings.Add (kw, null);
428 int length = kw.Length;
429 if (keywords [length] == null) {
430 keywords [length] = new KeywordEntry ['z' - '_' + 1];
433 int char_index = kw [0] - '_';
434 KeywordEntry kwe = keywords [length] [char_index];
436 keywords [length] [char_index] = new KeywordEntry (kw, token);
440 while (kwe.Next != null) {
444 kwe.Next = new KeywordEntry (kw, token);
447 static void InitTokens ()
449 keyword_strings = new Dictionary<string, object> ();
451 // 11 is the length of the longest keyword for now
452 keywords = new KeywordEntry [11] [];
454 AddKeyword ("__arglist", Token.ARGLIST);
455 AddKeyword ("abstract", Token.ABSTRACT);
456 AddKeyword ("as", Token.AS);
457 AddKeyword ("add", Token.ADD);
458 AddKeyword ("base", Token.BASE);
459 AddKeyword ("bool", Token.BOOL);
460 AddKeyword ("break", Token.BREAK);
461 AddKeyword ("byte", Token.BYTE);
462 AddKeyword ("case", Token.CASE);
463 AddKeyword ("catch", Token.CATCH);
464 AddKeyword ("char", Token.CHAR);
465 AddKeyword ("checked", Token.CHECKED);
466 AddKeyword ("class", Token.CLASS);
467 AddKeyword ("const", Token.CONST);
468 AddKeyword ("continue", Token.CONTINUE);
469 AddKeyword ("decimal", Token.DECIMAL);
470 AddKeyword ("default", Token.DEFAULT);
471 AddKeyword ("delegate", Token.DELEGATE);
472 AddKeyword ("do", Token.DO);
473 AddKeyword ("double", Token.DOUBLE);
474 AddKeyword ("else", Token.ELSE);
475 AddKeyword ("enum", Token.ENUM);
476 AddKeyword ("event", Token.EVENT);
477 AddKeyword ("explicit", Token.EXPLICIT);
478 AddKeyword ("extern", Token.EXTERN);
479 AddKeyword ("false", Token.FALSE);
480 AddKeyword ("finally", Token.FINALLY);
481 AddKeyword ("fixed", Token.FIXED);
482 AddKeyword ("float", Token.FLOAT);
483 AddKeyword ("for", Token.FOR);
484 AddKeyword ("foreach", Token.FOREACH);
485 AddKeyword ("goto", Token.GOTO);
486 AddKeyword ("get", Token.GET);
487 AddKeyword ("if", Token.IF);
488 AddKeyword ("implicit", Token.IMPLICIT);
489 AddKeyword ("in", Token.IN);
490 AddKeyword ("int", Token.INT);
491 AddKeyword ("interface", Token.INTERFACE);
492 AddKeyword ("internal", Token.INTERNAL);
493 AddKeyword ("is", Token.IS);
494 AddKeyword ("lock", Token.LOCK);
495 AddKeyword ("long", Token.LONG);
496 AddKeyword ("namespace", Token.NAMESPACE);
497 AddKeyword ("new", Token.NEW);
498 AddKeyword ("null", Token.NULL);
499 AddKeyword ("object", Token.OBJECT);
500 AddKeyword ("operator", Token.OPERATOR);
501 AddKeyword ("out", Token.OUT);
502 AddKeyword ("override", Token.OVERRIDE);
503 AddKeyword ("params", Token.PARAMS);
504 AddKeyword ("private", Token.PRIVATE);
505 AddKeyword ("protected", Token.PROTECTED);
506 AddKeyword ("public", Token.PUBLIC);
507 AddKeyword ("readonly", Token.READONLY);
508 AddKeyword ("ref", Token.REF);
509 AddKeyword ("remove", Token.REMOVE);
510 AddKeyword ("return", Token.RETURN);
511 AddKeyword ("sbyte", Token.SBYTE);
512 AddKeyword ("sealed", Token.SEALED);
513 AddKeyword ("set", Token.SET);
514 AddKeyword ("short", Token.SHORT);
515 AddKeyword ("sizeof", Token.SIZEOF);
516 AddKeyword ("stackalloc", Token.STACKALLOC);
517 AddKeyword ("static", Token.STATIC);
518 AddKeyword ("string", Token.STRING);
519 AddKeyword ("struct", Token.STRUCT);
520 AddKeyword ("switch", Token.SWITCH);
521 AddKeyword ("this", Token.THIS);
522 AddKeyword ("throw", Token.THROW);
523 AddKeyword ("true", Token.TRUE);
524 AddKeyword ("try", Token.TRY);
525 AddKeyword ("typeof", Token.TYPEOF);
526 AddKeyword ("uint", Token.UINT);
527 AddKeyword ("ulong", Token.ULONG);
528 AddKeyword ("unchecked", Token.UNCHECKED);
529 AddKeyword ("unsafe", Token.UNSAFE);
530 AddKeyword ("ushort", Token.USHORT);
531 AddKeyword ("using", Token.USING);
532 AddKeyword ("virtual", Token.VIRTUAL);
533 AddKeyword ("void", Token.VOID);
534 AddKeyword ("volatile", Token.VOLATILE);
535 AddKeyword ("while", Token.WHILE);
536 AddKeyword ("partial", Token.PARTIAL);
537 AddKeyword ("where", Token.WHERE);
540 AddKeyword ("from", Token.FROM);
541 AddKeyword ("join", Token.JOIN);
542 AddKeyword ("on", Token.ON);
543 AddKeyword ("equals", Token.EQUALS);
544 AddKeyword ("select", Token.SELECT);
545 AddKeyword ("group", Token.GROUP);
546 AddKeyword ("by", Token.BY);
547 AddKeyword ("let", Token.LET);
548 AddKeyword ("orderby", Token.ORDERBY);
549 AddKeyword ("ascending", Token.ASCENDING);
550 AddKeyword ("descending", Token.DESCENDING);
551 AddKeyword ("into", Token.INTO);
560 csharp_format_info = NumberFormatInfo.InvariantInfo;
561 styles = NumberStyles.Float;
563 string_builder = new System.Text.StringBuilder ();
566 int GetKeyword (char[] id, int id_len)
569 // Keywords are stored in an array of arrays grouped by their
570 // length and then by the first character
572 if (id_len >= keywords.Length || keywords [id_len] == null)
575 int first_index = id [0] - '_';
576 if (first_index > 'z' - '_')
579 KeywordEntry kwe = keywords [id_len] [first_index];
586 for (int i = 1; i < id_len; ++i) {
587 if (id [i] != kwe.Value [i]) {
593 } while (res == 0 && kwe != null);
607 if (!handle_remove_add)
611 if (parsing_declaration == 0)
612 res = Token.EXTERN_ALIAS;
615 if (peek_token () == Token.COLON) {
617 res = Token.DEFAULT_COLON;
621 if (!handle_where && !query_parsing)
626 // A query expression is any expression that starts with `from identifier'
627 // followed by any token except ; , =
629 if (!query_parsing) {
630 if (lambda_arguments_parsing) {
636 // HACK: to disable generics micro-parser, because PushPosition does not
637 // store identifiers array
638 parsing_generic_less_than = 1;
640 case Token.IDENTIFIER:
652 next_token = xtoken ();
653 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
656 res = Token.FROM_FIRST;
657 query_parsing = true;
658 if (RootContext.Version <= LanguageVersion.ISO_2)
659 Report.FeatureIsNotAvailable (Location, "query expressions");
662 Expression.Error_VoidInvalidInTheContext (Location, Report);
666 // HACK: A token is not a keyword so we need to restore identifiers buffer
667 // which has been overwritten before we grabbed the identifier
668 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
682 case Token.ASCENDING:
683 case Token.DESCENDING:
690 case Token.NAMESPACE:
691 // TODO: some explanation needed
692 check_incorrect_doc_comment ();
696 if (parsing_block > 0) {
701 // Save current position and parse next token.
704 next_token = token ();
705 bool ok = (next_token == Token.CLASS) ||
706 (next_token == Token.STRUCT) ||
707 (next_token == Token.INTERFACE) ||
708 (next_token == Token.VOID);
713 if (next_token == Token.VOID) {
714 if (RootContext.Version == LanguageVersion.ISO_1 ||
715 RootContext.Version == LanguageVersion.ISO_2)
716 Report.FeatureIsNotAvailable (Location, "partial methods");
717 } else if (RootContext.Version == LanguageVersion.ISO_1)
718 Report.FeatureIsNotAvailable (Location, "partial types");
723 if (next_token < Token.LAST_KEYWORD) {
724 Report.Error (267, Location,
725 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
736 public Location Location {
738 return new Location (ref_line, hidden ? -1 : col);
742 public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
744 this.ref_name = file;
745 this.file_name = file;
751 xml_comment_buffer = new StringBuilder ();
753 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
759 // FIXME: This could be `Location.Push' but we have to
760 // find out why the MS compiler allows this
762 Mono.CSharp.Location.Push (file, file);
765 static bool is_identifier_start_character (int c)
767 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
770 static bool is_identifier_part_character (char c)
772 if (c >= 'a' && c <= 'z')
775 if (c >= 'A' && c <= 'Z')
778 if (c == '_' || (c >= '0' && c <= '9'))
784 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
787 public static bool IsKeyword (string s)
789 return keyword_strings.ContainsKey (s);
793 // Open parens micro parser. Detects both lambda and cast ambiguity.
795 int TokenizeOpenParens ()
800 int bracket_level = 0;
801 bool is_type = false;
802 bool can_be_type = false;
805 ptoken = current_token;
808 switch (current_token) {
809 case Token.CLOSE_PARENS:
813 // Expression inside parens is lambda, (int i) =>
815 if (current_token == Token.ARROW)
816 return Token.OPEN_PARENS_LAMBDA;
819 // Expression inside parens is single type, (int[])
822 return Token.OPEN_PARENS_CAST;
825 // Expression is possible cast, look at next token, (T)null
828 switch (current_token) {
829 case Token.OPEN_PARENS:
832 case Token.IDENTIFIER:
846 case Token.UNCHECKED:
851 // These can be part of a member access
865 return Token.OPEN_PARENS_CAST;
868 return Token.OPEN_PARENS;
871 case Token.DOUBLE_COLON:
872 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
877 case Token.IDENTIFIER:
880 case Token.OP_GENERICS_LT:
882 case Token.DOUBLE_COLON:
884 if (bracket_level == 0)
888 can_be_type = is_type = false;
908 if (bracket_level == 0)
913 if (bracket_level == 0) {
915 can_be_type = is_type = false;
919 case Token.OP_GENERICS_LT:
920 case Token.OPEN_BRACKET:
921 if (bracket_level++ == 0)
925 case Token.OP_GENERICS_GT:
926 case Token.CLOSE_BRACKET:
930 case Token.INTERR_NULLABLE:
932 if (bracket_level == 0)
938 can_be_type = is_type = false;
942 return Token.OPEN_PARENS;
947 public static bool IsValidIdentifier (string s)
949 if (s == null || s.Length == 0)
952 if (!is_identifier_start_character (s [0]))
955 for (int i = 1; i < s.Length; i ++)
956 if (! is_identifier_part_character (s [i]))
962 bool parse_less_than ()
965 int the_token = token ();
966 if (the_token == Token.OPEN_BRACKET) {
968 the_token = token ();
969 } while (the_token != Token.CLOSE_BRACKET);
970 the_token = token ();
971 } else if (the_token == Token.IN || the_token == Token.OUT) {
972 the_token = token ();
975 case Token.IDENTIFIER:
993 case Token.OP_GENERICS_GT:
1000 the_token = token ();
1002 if (the_token == Token.OP_GENERICS_GT)
1004 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1006 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1008 else if (the_token == Token.OP_GENERICS_LT) {
1009 if (!parse_less_than ())
1012 } else if (the_token == Token.OPEN_BRACKET) {
1014 the_token = token ();
1015 if (the_token == Token.CLOSE_BRACKET)
1017 else if (the_token == Token.COMMA)
1018 goto rank_specifiers;
1025 bool parse_generic_dimension (out int dimension)
1030 int the_token = token ();
1031 if (the_token == Token.OP_GENERICS_GT)
1033 else if (the_token == Token.COMMA) {
1041 public int peek_token ()
1046 the_token = token ();
1053 // Tonizes `?' using custom disambiguous rules to return one
1054 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1056 // Tricky expression look like:
1058 // Foo ? a = x ? b : c;
1060 int TokenizePossibleNullableType ()
1062 if (parsing_block == 0 || parsing_type > 0)
1063 return Token.INTERR_NULLABLE;
1065 int d = peek_char ();
1068 return Token.OP_COALESCING;
1071 switch (current_token) {
1072 case Token.CLOSE_PARENS:
1077 return Token.INTERR;
1081 if (d == ',' || d == ';' || d == '>')
1082 return Token.INTERR_NULLABLE;
1083 if (d == '*' || (d >= '0' && d <= '9'))
1084 return Token.INTERR;
1088 current_token = Token.NONE;
1090 switch (xtoken ()) {
1097 next_token = Token.INTERR;
1100 case Token.SEMICOLON:
1102 case Token.CLOSE_PARENS:
1103 case Token.OPEN_BRACKET:
1104 case Token.OP_GENERICS_GT:
1105 next_token = Token.INTERR_NULLABLE;
1113 if (next_token == -1) {
1114 switch (xtoken ()) {
1116 case Token.SEMICOLON:
1117 case Token.OPEN_BRACE:
1118 case Token.CLOSE_PARENS:
1120 next_token = Token.INTERR_NULLABLE;
1124 next_token = Token.INTERR;
1132 // All shorcuts failed, do it hard way
1134 while ((ntoken = xtoken ()) != Token.EOF) {
1135 if (ntoken == Token.SEMICOLON)
1138 if (ntoken == Token.COLON) {
1139 if (++colons == interrs)
1144 if (ntoken == Token.INTERR) {
1150 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1159 bool decimal_digits (int c)
1162 bool seen_digits = false;
1165 if (number_pos == max_number_size)
1166 Error_NumericConstantTooLong ();
1167 number_builder [number_pos++] = (char) c;
1171 // We use peek_char2, because decimal_digits needs to do a
1172 // 2-character look-ahead (5.ToString for example).
1174 while ((d = peek_char2 ()) != -1){
1175 if (d >= '0' && d <= '9'){
1176 if (number_pos == max_number_size)
1177 Error_NumericConstantTooLong ();
1178 number_builder [number_pos++] = (char) d;
1188 static bool is_hex (int e)
1190 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1193 static TypeCode real_type_suffix (int c)
1197 return TypeCode.Single;
1199 return TypeCode.Double;
1201 return TypeCode.Decimal;
1203 return TypeCode.Empty;
1207 int integer_type_suffix (ulong ul, int c)
1209 bool is_unsigned = false;
1210 bool is_long = false;
1213 bool scanning = true;
1226 // if we have not seen anything in between
1227 // report this error
1229 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1249 if (is_long && is_unsigned){
1250 val = new ULongLiteral (ul, Location);
1251 return Token.LITERAL;
1255 // uint if possible, or ulong else.
1257 if ((ul & 0xffffffff00000000) == 0)
1258 val = new UIntLiteral ((uint) ul, Location);
1260 val = new ULongLiteral (ul, Location);
1261 } else if (is_long){
1262 // long if possible, ulong otherwise
1263 if ((ul & 0x8000000000000000) != 0)
1264 val = new ULongLiteral (ul, Location);
1266 val = new LongLiteral ((long) ul, Location);
1268 // int, uint, long or ulong in that order
1269 if ((ul & 0xffffffff00000000) == 0){
1270 uint ui = (uint) ul;
1272 if ((ui & 0x80000000) != 0)
1273 val = new UIntLiteral (ui, Location);
1275 val = new IntLiteral ((int) ui, Location);
1277 if ((ul & 0x8000000000000000) != 0)
1278 val = new ULongLiteral (ul, Location);
1280 val = new LongLiteral ((long) ul, Location);
1283 return Token.LITERAL;
1287 // given `c' as the next char in the input decide whether
1288 // we need to convert to a special type, and then choose
1289 // the best representation for the integer
1291 int adjust_int (int c)
1294 if (number_pos > 9){
1295 ulong ul = (uint) (number_builder [0] - '0');
1297 for (int i = 1; i < number_pos; i++){
1298 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1300 return integer_type_suffix (ul, c);
1302 uint ui = (uint) (number_builder [0] - '0');
1304 for (int i = 1; i < number_pos; i++){
1305 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1307 return integer_type_suffix (ui, c);
1309 } catch (OverflowException) {
1310 error_details = "Integral constant is too large";
1311 Report.Error (1021, Location, error_details);
1312 val = new IntLiteral (0, Location);
1313 return Token.LITERAL;
1315 catch (FormatException) {
1316 Report.Error (1013, Location, "Invalid number");
1317 val = new IntLiteral (0, Location);
1318 return Token.LITERAL;
1322 int adjust_real (TypeCode t)
1324 string s = new String (number_builder, 0, number_pos);
1325 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1328 case TypeCode.Decimal:
1330 val = new DecimalLiteral (decimal.Parse (s, styles, csharp_format_info), Location);
1331 } catch (OverflowException) {
1332 val = new DecimalLiteral (0, Location);
1333 Report.Error (594, Location, error_details, "decimal");
1336 case TypeCode.Single:
1338 val = new FloatLiteral (float.Parse (s, styles, csharp_format_info), Location);
1339 } catch (OverflowException) {
1340 val = new FloatLiteral (0, Location);
1341 Report.Error (594, Location, error_details, "float");
1346 val = new DoubleLiteral (double.Parse (s, styles, csharp_format_info), Location);
1347 } catch (OverflowException) {
1348 val = new DoubleLiteral (0, Location);
1349 Report.Error (594, Location, error_details, "double");
1354 return Token.LITERAL;
1363 while ((d = peek_char ()) != -1){
1365 number_builder [number_pos++] = (char) d;
1371 string s = new String (number_builder, 0, number_pos);
1373 if (number_pos <= 8)
1374 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1376 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1377 } catch (OverflowException){
1378 error_details = "Integral constant is too large";
1379 Report.Error (1021, Location, error_details);
1380 val = new IntLiteral (0, Location);
1381 return Token.LITERAL;
1383 catch (FormatException) {
1384 Report.Error (1013, Location, "Invalid number");
1385 val = new IntLiteral (0, Location);
1386 return Token.LITERAL;
1389 return integer_type_suffix (ul, peek_char ());
1393 // Invoked if we know we have .digits or digits
1395 int is_number (int c)
1397 bool is_real = false;
1401 if (c >= '0' && c <= '9'){
1403 int peek = peek_char ();
1405 if (peek == 'x' || peek == 'X')
1406 return handle_hex ();
1413 // We need to handle the case of
1414 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1417 if (decimal_digits ('.')){
1423 return adjust_int (-1);
1427 if (c == 'e' || c == 'E'){
1429 if (number_pos == max_number_size)
1430 Error_NumericConstantTooLong ();
1431 number_builder [number_pos++] = 'e';
1435 if (number_pos == max_number_size)
1436 Error_NumericConstantTooLong ();
1437 number_builder [number_pos++] = '+';
1439 } else if (c == '-') {
1440 if (number_pos == max_number_size)
1441 Error_NumericConstantTooLong ();
1442 number_builder [number_pos++] = '-';
1445 if (number_pos == max_number_size)
1446 Error_NumericConstantTooLong ();
1447 number_builder [number_pos++] = '+';
1454 var type = real_type_suffix (c);
1455 if (type == TypeCode.Empty && !is_real){
1457 return adjust_int (c);
1462 if (type == TypeCode.Empty){
1467 return adjust_real (type);
1469 throw new Exception ("Is Number should never reach this point");
1473 // Accepts exactly count (4 or 8) hex, no more no less
1475 int getHex (int count, out int surrogate, out bool error)
1480 int top = count != -1 ? count : 4;
1485 for (i = 0; i < top; i++){
1488 if (c >= '0' && c <= '9')
1489 c = (int) c - (int) '0';
1490 else if (c >= 'A' && c <= 'F')
1491 c = (int) c - (int) 'A' + 10;
1492 else if (c >= 'a' && c <= 'f')
1493 c = (int) c - (int) 'a' + 10;
1499 total = (total * 16) + c;
1501 int p = peek_char ();
1504 if (!is_hex ((char)p))
1510 if (total > 0x0010FFFF) {
1515 if (total >= 0x00010000) {
1516 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1517 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1524 int escape (int c, out int surrogate)
1560 v = getHex (-1, out surrogate, out error);
1566 return EscapeUnicode (d, out surrogate);
1569 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1578 int EscapeUnicode (int ch, out int surrogate)
1582 ch = getHex (8, out surrogate, out error);
1584 ch = getHex (4, out surrogate, out error);
1588 Report.Error (1009, Location, "Unrecognized escape sequence");
1596 if (putback_char != -1) {
1609 void advance_line ()
1619 if (putback_char == -1)
1620 putback_char = reader.Read ();
1621 return putback_char;
1626 if (putback_char != -1)
1627 return putback_char;
1628 return reader.Peek ();
1631 void putback (int c)
1633 if (putback_char != -1){
1634 Console.WriteLine ("Col: " + col);
1635 Console.WriteLine ("Row: " + line);
1636 Console.WriteLine ("Name: " + ref_name.Name);
1637 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1638 throw new Exception ("This should not happen putback on putback");
1640 if (c == '\n' || col == 0) {
1641 // It won't happen though.
1651 public bool advance ()
1653 return peek_char () != -1 || CompleteOnEOF;
1656 public Object Value {
1662 public Object value ()
1669 current_token = xtoken ();
1670 return current_token;
1673 void get_cmd_arg (out string cmd, out string arg)
1677 tokens_seen = false;
1680 // skip over white space
1683 } while (c == '\r' || c == ' ' || c == '\t');
1685 static_cmd_arg.Length = 0;
1686 while (c != -1 && is_identifier_part_character ((char)c)) {
1687 static_cmd_arg.Append ((char)c);
1690 int peek = peek_char ();
1691 if (peek == 'U' || peek == 'u') {
1693 c = EscapeUnicode (c, out surrogate);
1694 if (surrogate != 0) {
1695 if (is_identifier_part_character ((char) c))
1696 static_cmd_arg.Append ((char) c);
1703 cmd = static_cmd_arg.ToString ();
1705 // skip over white space
1706 while (c == '\r' || c == ' ' || c == '\t')
1709 static_cmd_arg.Length = 0;
1710 int has_identifier_argument = 0;
1712 while (c != -1 && c != '\n' && c != '\r') {
1713 if (c == '\\' && has_identifier_argument >= 0) {
1714 if (has_identifier_argument != 0 || (cmd == "define" || cmd == "if" || cmd == "elif" || cmd == "undef")) {
1715 has_identifier_argument = 1;
1717 int peek = peek_char ();
1718 if (peek == 'U' || peek == 'u') {
1720 c = EscapeUnicode (c, out surrogate);
1721 if (surrogate != 0) {
1722 if (is_identifier_part_character ((char) c))
1723 static_cmd_arg.Append ((char) c);
1728 has_identifier_argument = -1;
1731 static_cmd_arg.Append ((char) c);
1735 if (static_cmd_arg.Length != 0)
1736 arg = static_cmd_arg.ToString ();
1740 // Handles the #line directive
1742 bool PreProcessLine (string arg)
1744 if (arg.Length == 0)
1747 if (arg == "default"){
1749 ref_name = file_name;
1751 Location.Push (file_name, ref_name);
1753 } else if (arg == "hidden"){
1761 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1762 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1765 char [] quotes = { '\"' };
1767 string name = arg.Substring (pos). Trim (quotes);
1768 ref_name = Location.LookupFile (file_name, name);
1769 file_name.AddFile (ref_name);
1771 Location.Push (file_name, ref_name);
1773 ref_line = System.Int32.Parse (arg);
1784 // Handles #define and #undef
1786 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1788 if (ident.Length == 0 || ident == "true" || ident == "false"){
1789 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1793 if (ident.IndexOfAny (simple_whitespaces) != -1){
1794 Error_EndLineExpected ();
1798 if (!is_identifier_start_character (ident [0]))
1799 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1801 foreach (char c in ident.Substring (1)){
1802 if (!is_identifier_part_character (c)){
1803 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1808 if (!caller_is_taking)
1815 if (RootContext.IsConditionalDefined (ident))
1818 file_name.AddDefine (ident);
1823 file_name.AddUndefine (ident);
1827 static byte read_hex (string arg, int pos, out bool error)
1834 if ((c >= '0') && (c <= '9'))
1835 total = (int) c - (int) '0';
1836 else if ((c >= 'A') && (c <= 'F'))
1837 total = (int) c - (int) 'A' + 10;
1838 else if ((c >= 'a') && (c <= 'f'))
1839 total = (int) c - (int) 'a' + 10;
1848 if ((c >= '0') && (c <= '9'))
1849 total += (int) c - (int) '0';
1850 else if ((c >= 'A') && (c <= 'F'))
1851 total += (int) c - (int) 'A' + 10;
1852 else if ((c >= 'a') && (c <= 'f'))
1853 total += (int) c - (int) 'a' + 10;
1859 return (byte) total;
1863 /// Handles #pragma checksum
1865 bool PreProcessPragmaChecksum (string arg)
1867 if ((arg [0] != ' ') && (arg [0] != '\t'))
1870 arg = arg.Trim (simple_whitespaces);
1871 if ((arg.Length < 2) || (arg [0] != '"'))
1874 StringBuilder file_sb = new StringBuilder ();
1878 while ((ch = arg [pos++]) != '"') {
1879 if (pos >= arg.Length)
1883 if (pos+1 >= arg.Length)
1888 file_sb.Append (ch);
1891 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1894 arg = arg.Substring (pos).Trim (simple_whitespaces);
1895 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1896 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1897 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1901 byte[] guid_bytes = new byte [16];
1903 for (int i = 0; i < 4; i++) {
1904 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1908 for (int i = 0; i < 2; i++) {
1909 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1912 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1915 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1920 for (int i = 0; i < 6; i++) {
1921 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1926 arg = arg.Substring (40).Trim (simple_whitespaces);
1927 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1930 byte[] checksum_bytes = new byte [16];
1931 for (int i = 0; i < 16; i++) {
1932 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1937 arg = arg.Substring (34).Trim (simple_whitespaces);
1941 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1942 file.SetChecksum (guid_bytes, checksum_bytes);
1943 ref_name.AutoGenerated = true;
1948 /// Handles #pragma directive
1950 void PreProcessPragma (string arg)
1952 const string warning = "warning";
1953 const string w_disable = "warning disable";
1954 const string w_restore = "warning restore";
1955 const string checksum = "checksum";
1957 if (arg == w_disable) {
1958 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1962 if (arg == w_restore) {
1963 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1967 if (arg.StartsWith (w_disable)) {
1968 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1969 foreach (int code in codes) {
1971 Report.RegisterWarningRegion (Location).WarningDisable (Location, code, Report);
1976 if (arg.StartsWith (w_restore)) {
1977 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1978 var w_table = Report.warning_ignore_table;
1979 foreach (int code in codes) {
1980 if (w_table != null && w_table.ContainsKey (code))
1981 Report.Warning (1635, 1, Location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1982 Report.RegisterWarningRegion (Location).WarningEnable (Location, code, Report);
1987 if (arg.StartsWith (warning)) {
1988 Report.Warning (1634, 1, Location, "Expected disable or restore");
1992 if (arg.StartsWith (checksum)) {
1993 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1994 Warning_InvalidPragmaChecksum ();
1998 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2001 int[] ParseNumbers (string text)
2003 string[] string_array = text.Split (',');
2004 int[] values = new int [string_array.Length];
2006 foreach (string string_code in string_array) {
2008 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
2010 catch (FormatException) {
2011 Report.Warning (1692, 1, Location, "Invalid number");
2017 bool eval_val (string s)
2024 return file_name.IsConditionalDefined (s);
2027 bool pp_primary (ref string s)
2036 s = s.Substring (1);
2037 bool val = pp_expr (ref s, false);
2038 if (s.Length > 0 && s [0] == ')'){
2039 s = s.Substring (1);
2042 Error_InvalidDirective ();
2046 if (is_identifier_start_character (c)){
2052 if (is_identifier_part_character (c)){
2056 bool v = eval_val (s.Substring (0, j));
2057 s = s.Substring (j);
2060 bool vv = eval_val (s);
2065 Error_InvalidDirective ();
2069 bool pp_unary (ref string s)
2076 if (len > 1 && s [1] == '='){
2077 Error_InvalidDirective ();
2080 s = s.Substring (1);
2081 return ! pp_primary (ref s);
2083 return pp_primary (ref s);
2085 Error_InvalidDirective ();
2090 bool pp_eq (ref string s)
2092 bool va = pp_unary (ref s);
2098 if (len > 2 && s [1] == '='){
2099 s = s.Substring (2);
2100 return va == pp_unary (ref s);
2102 Error_InvalidDirective ();
2105 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2106 s = s.Substring (2);
2108 return va != pp_unary (ref s);
2117 bool pp_and (ref string s)
2119 bool va = pp_eq (ref s);
2125 if (len > 2 && s [1] == '&'){
2126 s = s.Substring (2);
2127 return (va & pp_and (ref s));
2129 Error_InvalidDirective ();
2138 // Evaluates an expression for `#if' or `#elif'
2140 bool pp_expr (ref string s, bool isTerm)
2142 bool va = pp_and (ref s);
2149 if (len > 2 && s [1] == '|'){
2150 s = s.Substring (2);
2151 return va | pp_expr (ref s, isTerm);
2153 Error_InvalidDirective ();
2158 Error_EndLineExpected ();
2166 bool eval (string s)
2168 bool v = pp_expr (ref s, true);
2177 void Error_NumericConstantTooLong ()
2179 Report.Error (1021, Location, "Numeric constant too long");
2182 void Error_InvalidDirective ()
2184 Report.Error (1517, Location, "Invalid preprocessor directive");
2187 void Error_UnexpectedDirective (string extra)
2191 "Unexpected processor directive ({0})", extra);
2194 void Error_TokensSeen ()
2196 Report.Error (1032, Location,
2197 "Cannot define or undefine preprocessor symbols after first token in file");
2200 void Eror_WrongPreprocessorLocation ()
2202 Report.Error (1040, Location,
2203 "Preprocessor directives must appear as the first non-whitespace character on a line");
2206 void Error_EndLineExpected ()
2208 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2211 void Warning_InvalidPragmaChecksum ()
2213 Report.Warning (1695, 1, Location,
2214 "Invalid #pragma checksum syntax; should be " +
2215 "#pragma checksum \"filename\" " +
2216 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2219 // if true, then the code continues processing the code
2220 // if false, the code stays in a loop until another directive is
2222 // When caller_is_taking is false we ignore all directives except the ones
2223 // which can help us to identify where the #if block ends
2224 bool handle_preprocessing_directive (bool caller_is_taking)
2227 bool region_directive = false;
2229 get_cmd_arg (out cmd, out arg);
2231 // Eat any trailing whitespaces and single-line comments
2232 if (arg.IndexOf ("//") != -1)
2233 arg = arg.Substring (0, arg.IndexOf ("//"));
2234 arg = arg.Trim (simple_whitespaces);
2237 // The first group of pre-processing instructions is always processed
2241 region_directive = true;
2246 if (ifstack == null || ifstack.Count == 0){
2247 Error_UnexpectedDirective ("no #region for this #endregion");
2250 int pop = ifstack.Pop ();
2252 if ((pop & REGION) == 0)
2253 Report.Error (1027, Location, "Expected `#endif' directive");
2255 return caller_is_taking;
2258 if (ifstack == null)
2259 ifstack = new Stack<int> (2);
2261 int flags = region_directive ? REGION : 0;
2262 if (ifstack.Count == 0){
2263 flags |= PARENT_TAKING;
2265 int state = ifstack.Peek ();
2266 if ((state & TAKING) != 0) {
2267 flags |= PARENT_TAKING;
2271 if (caller_is_taking && eval (arg)) {
2272 ifstack.Push (flags | TAKING);
2275 ifstack.Push (flags);
2279 if (ifstack == null || ifstack.Count == 0){
2280 Error_UnexpectedDirective ("no #if for this #endif");
2283 pop = ifstack.Pop ();
2285 if ((pop & REGION) != 0)
2286 Report.Error (1038, Location, "#endregion directive expected");
2288 if (arg.Length != 0) {
2289 Error_EndLineExpected ();
2292 if (ifstack.Count == 0)
2295 int state = ifstack.Peek ();
2296 return (state & TAKING) != 0;
2300 if (ifstack == null || ifstack.Count == 0){
2301 Error_UnexpectedDirective ("no #if for this #elif");
2304 int state = ifstack.Pop ();
2306 if ((state & REGION) != 0) {
2307 Report.Error (1038, Location, "#endregion directive expected");
2311 if ((state & ELSE_SEEN) != 0){
2312 Error_UnexpectedDirective ("#elif not valid after #else");
2316 if ((state & TAKING) != 0) {
2321 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2322 ifstack.Push (state | TAKING);
2326 ifstack.Push (state);
2331 if (ifstack == null || ifstack.Count == 0){
2332 Error_UnexpectedDirective ("no #if for this #else");
2335 int state = ifstack.Peek ();
2337 if ((state & REGION) != 0) {
2338 Report.Error (1038, Location, "#endregion directive expected");
2342 if ((state & ELSE_SEEN) != 0){
2343 Error_UnexpectedDirective ("#else within #else");
2349 if (arg.Length != 0) {
2350 Error_EndLineExpected ();
2355 if ((state & PARENT_TAKING) != 0) {
2356 ret = (state & TAKING) == 0;
2364 ifstack.Push (state | ELSE_SEEN);
2369 if (any_token_seen){
2370 Error_TokensSeen ();
2371 return caller_is_taking;
2373 PreProcessDefinition (true, arg, caller_is_taking);
2374 return caller_is_taking;
2377 if (any_token_seen){
2378 Error_TokensSeen ();
2379 return caller_is_taking;
2381 PreProcessDefinition (false, arg, caller_is_taking);
2382 return caller_is_taking;
2386 // These are only processed if we are in a `taking' block
2388 if (!caller_is_taking)
2393 Report.Error (1029, Location, "#error: '{0}'", arg);
2397 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2401 if (RootContext.Version == LanguageVersion.ISO_1) {
2402 Report.FeatureIsNotAvailable (Location, "#pragma");
2406 PreProcessPragma (arg);
2410 if (!PreProcessLine (arg))
2413 "The line number specified for #line directive is missing or invalid");
2414 return caller_is_taking;
2417 Report.Error (1024, Location, "Wrong preprocessor directive");
2422 private int consume_string (bool quoted)
2425 string_builder.Length = 0;
2427 while ((c = get_char ()) != -1){
2429 if (quoted && peek_char () == '"'){
2430 string_builder.Append ((char) c);
2434 val = new StringLiteral (string_builder.ToString (), Location);
2435 return Token.LITERAL;
2441 Report.Error (1010, Location, "Newline in constant");
2446 c = escape (c, out surrogate);
2449 if (surrogate != 0) {
2450 string_builder.Append ((char) c);
2454 string_builder.Append ((char) c);
2457 Report.Error (1039, Location, "Unterminated string literal");
2461 private int consume_identifier (int s)
2463 int res = consume_identifier (s, false);
2465 if (doc_state == XmlCommentState.Allowed)
2466 doc_state = XmlCommentState.NotAllowed;
2471 int consume_identifier (int c, bool quoted)
2474 // This method is very performance sensitive. It accounts
2475 // for approximately 25% of all parser time
2483 c = escape (c, out surrogate);
2484 if (surrogate != 0) {
2485 id_builder [pos++] = (char) c;
2490 id_builder [pos++] = (char) c;
2496 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2497 id_builder [pos++] = (char) c;
2504 c = escape (c, out surrogate);
2505 if (surrogate != 0) {
2506 if (is_identifier_part_character ((char) c))
2507 id_builder[pos++] = (char) c;
2513 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2514 id_builder [pos++] = (char) c;
2521 } catch (IndexOutOfRangeException) {
2522 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2530 // Optimization: avoids doing the keyword lookup
2531 // on uppercase letters
2533 if (id_builder [0] >= '_' && !quoted) {
2534 int keyword = GetKeyword (id_builder, pos);
2535 if (keyword != -1) {
2536 val = LocatedToken.Create (null, ref_line, column);
2542 // Keep identifiers in an array of hashtables to avoid needless
2545 var identifiers_group = identifiers [pos];
2547 if (identifiers_group != null) {
2548 if (identifiers_group.TryGetValue (id_builder, out s)) {
2549 val = LocatedToken.Create (s, ref_line, column);
2551 AddEscapedIdentifier (((LocatedToken) val).Location);
2552 return Token.IDENTIFIER;
2555 // TODO: this should be number of files dependant
2556 // corlib compilation peaks at 1000 and System.Core at 150
2557 int capacity = pos > 20 ? 10 : 100;
2558 identifiers_group = new Dictionary<char[],string> (capacity, new IdentifiersComparer (pos));
2559 identifiers [pos] = identifiers_group;
2562 char [] chars = new char [pos];
2563 Array.Copy (id_builder, chars, pos);
2565 s = new string (id_builder, 0, pos);
2566 identifiers_group.Add (chars, s);
2568 val = LocatedToken.Create (s, ref_line, column);
2570 AddEscapedIdentifier (((LocatedToken) val).Location);
2572 return Token.IDENTIFIER;
2575 public int xtoken ()
2579 // Whether we have seen comments on the current line
2580 bool comments_seen = false;
2581 while ((c = get_char ()) != -1) {
2584 col = ((col - 1 + tab_size) / tab_size) * tab_size;
2592 case 0xFEFF: // Ignore BOM anywhere in the file
2595 /* This is required for compatibility with .NET
2597 if (peek_char () == 0xBB) {
2600 if (get_char () == 0xBF)
2607 if (peek_char () != '\n')
2612 any_token_seen |= tokens_seen;
2613 tokens_seen = false;
2614 comments_seen = false;
2619 return consume_identifier (c);
2622 val = LocatedToken.Create (ref_line, col);
2623 return Token.OPEN_BRACE;
2625 val = LocatedToken.Create (ref_line, col);
2626 return Token.CLOSE_BRACE;
2628 // To block doccomment inside attribute declaration.
2629 if (doc_state == XmlCommentState.Allowed)
2630 doc_state = XmlCommentState.NotAllowed;
2632 val = LocatedToken.Create (ref_line, col);
2634 if (parsing_block == 0 || lambda_arguments_parsing)
2635 return Token.OPEN_BRACKET;
2637 int next = peek_char ();
2641 return Token.OPEN_BRACKET;
2649 next = peek_token ();
2650 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2651 return Token.OPEN_BRACKET;
2653 return Token.OPEN_BRACKET_EXPR;
2655 return Token.OPEN_BRACKET_EXPR;
2658 LocatedToken.CreateOptional (ref_line, col, ref val);
2659 return Token.CLOSE_BRACKET;
2661 val = LocatedToken.Create (ref_line, col);
2663 // An expression versions of parens can appear in block context only
2665 if (parsing_block != 0 && !lambda_arguments_parsing) {
2668 // Optmize most common case where we know that parens
2671 switch (current_token) {
2672 case Token.IDENTIFIER:
2680 case Token.DELEGATE:
2681 case Token.OP_GENERICS_GT:
2682 return Token.OPEN_PARENS;
2685 // Optimize using peek
2686 int xx = peek_char ();
2693 return Token.OPEN_PARENS;
2696 lambda_arguments_parsing = true;
2698 d = TokenizeOpenParens ();
2700 lambda_arguments_parsing = false;
2704 return Token.OPEN_PARENS;
2706 LocatedToken.CreateOptional (ref_line, col, ref val);
2707 return Token.CLOSE_PARENS;
2709 LocatedToken.CreateOptional (ref_line, col, ref val);
2712 LocatedToken.CreateOptional (ref_line, col, ref val);
2713 return Token.SEMICOLON;
2715 val = LocatedToken.Create (ref_line, col);
2718 val = LocatedToken.Create (ref_line, col);
2719 return TokenizePossibleNullableType ();
2721 val = LocatedToken.Create (ref_line, col);
2722 if (parsing_generic_less_than++ > 0)
2723 return Token.OP_GENERICS_LT;
2725 return TokenizeLessThan ();
2728 val = LocatedToken.Create (ref_line, col);
2736 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2737 parsing_generic_less_than--;
2738 return Token.OP_GENERICS_GT;
2747 return Token.OP_SHIFT_RIGHT_ASSIGN;
2749 return Token.OP_SHIFT_RIGHT;
2755 val = LocatedToken.Create (ref_line, col);
2759 } else if (d == '=') {
2760 d = Token.OP_ADD_ASSIGN;
2768 val = LocatedToken.Create (ref_line, col);
2772 } else if (d == '=')
2773 d = Token.OP_SUB_ASSIGN;
2783 val = LocatedToken.Create (ref_line, col);
2784 if (peek_char () == '='){
2791 val = LocatedToken.Create (ref_line, col);
2802 return Token.ASSIGN;
2805 val = LocatedToken.Create (ref_line, col);
2809 return Token.OP_AND;
2813 return Token.OP_AND_ASSIGN;
2815 return Token.BITWISE_AND;
2818 val = LocatedToken.Create (ref_line, col);
2826 return Token.OP_OR_ASSIGN;
2828 return Token.BITWISE_OR;
2831 val = LocatedToken.Create (ref_line, col);
2832 if (peek_char () == '='){
2834 return Token.OP_MULT_ASSIGN;
2841 val = LocatedToken.Create (ref_line, col);
2843 return Token.OP_DIV_ASSIGN;
2846 // Handle double-slash comments.
2849 if (RootContext.Documentation != null && peek_char () == '/') {
2851 // Don't allow ////.
2852 if ((d = peek_char ()) != '/') {
2853 update_comment_location ();
2854 if (doc_state == XmlCommentState.Allowed)
2855 handle_one_line_xml_comment ();
2856 else if (doc_state == XmlCommentState.NotAllowed)
2857 warn_incorrect_doc_comment ();
2860 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2862 any_token_seen |= tokens_seen;
2863 tokens_seen = false;
2864 comments_seen = false;
2866 } else if (d == '*'){
2868 bool docAppend = false;
2869 if (RootContext.Documentation != null && peek_char () == '*') {
2871 update_comment_location ();
2872 // But when it is /**/, just do nothing.
2873 if (peek_char () == '/') {
2877 if (doc_state == XmlCommentState.Allowed)
2879 else if (doc_state == XmlCommentState.NotAllowed)
2880 warn_incorrect_doc_comment ();
2883 int current_comment_start = 0;
2885 current_comment_start = xml_comment_buffer.Length;
2886 xml_comment_buffer.Append (Environment.NewLine);
2889 while ((d = get_char ()) != -1){
2890 if (d == '*' && peek_char () == '/'){
2892 comments_seen = true;
2896 xml_comment_buffer.Append ((char) d);
2899 any_token_seen |= tokens_seen;
2900 tokens_seen = false;
2902 // Reset 'comments_seen' just to be consistent.
2903 // It doesn't matter either way, here.
2905 comments_seen = false;
2909 Report.Error (1035, Location, "End-of-file found, '*/' expected");
2912 update_formatted_doc_comment (current_comment_start);
2918 val = LocatedToken.Create (ref_line, col);
2919 if (peek_char () == '='){
2921 return Token.OP_MOD_ASSIGN;
2923 return Token.PERCENT;
2926 val = LocatedToken.Create (ref_line, col);
2927 if (peek_char () == '='){
2929 return Token.OP_XOR_ASSIGN;
2931 return Token.CARRET;
2934 val = LocatedToken.Create (ref_line, col);
2935 if (peek_char () == ':') {
2937 return Token.DOUBLE_COLON;
2941 case '0': case '1': case '2': case '3': case '4':
2942 case '5': case '6': case '7': case '8': case '9':
2944 return is_number (c);
2946 case '\n': // white space
2947 any_token_seen |= tokens_seen;
2948 tokens_seen = false;
2949 comments_seen = false;
2955 if (d >= '0' && d <= '9')
2956 return is_number (c);
2958 LocatedToken.CreateOptional (ref_line, col, ref val);
2962 if (tokens_seen || comments_seen) {
2963 Eror_WrongPreprocessorLocation ();
2967 if (handle_preprocessing_directive (true))
2970 bool directive_expected = false;
2971 while ((c = get_char ()) != -1) {
2973 directive_expected = true;
2974 } else if (!directive_expected) {
2975 // TODO: Implement comment support for disabled code and uncomment this code
2977 // Eror_WrongPreprocessorLocation ();
2978 // return Token.ERROR;
2983 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2987 if (handle_preprocessing_directive (false))
2990 directive_expected = false;
2994 tokens_seen = false;
3001 return consume_string (false);
3004 return TokenizeBackslash ();
3010 return consume_string (true);
3013 if (is_identifier_start_character (c)){
3014 return consume_identifier (c, true);
3017 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3020 case EvalStatementParserCharacter:
3021 return Token.EVAL_STATEMENT_PARSER;
3022 case EvalCompilationUnitParserCharacter:
3023 return Token.EVAL_COMPILATION_UNIT_PARSER;
3024 case EvalUsingDeclarationsParserCharacter:
3025 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3028 if (is_identifier_start_character (c)) {
3030 return consume_identifier (c);
3033 error_details = ((char)c).ToString ();
3039 return Token.COMPLETE_COMPLETION;
3042 return Token.GENERATE_COMPLETION;
3049 int TokenizeBackslash ()
3051 int c = get_char ();
3054 error_details = "Empty character literal";
3055 Report.Error (1011, Location, error_details);
3058 if (c == '\r' || c == '\n') {
3059 Report.Error (1010, Location, "Newline in constant");
3064 c = escape (c, out d);
3068 throw new NotImplementedException ();
3070 val = new CharLiteral ((char) c, Location);
3074 Report.Error (1012, Location, "Too many characters in character literal");
3076 // Try to recover, read until newline or next "'"
3077 while ((c = get_char ()) != -1) {
3078 if (c == '\n' || c == '\'')
3084 return Token.LITERAL;
3087 int TokenizeLessThan ()
3090 if (handle_typeof) {
3092 if (parse_generic_dimension (out d)) {
3095 return Token.GENERIC_DIMENSION;
3100 // Save current position and parse next token.
3102 if (parse_less_than ()) {
3103 if (parsing_generic_declaration && token () != Token.DOT) {
3104 d = Token.OP_GENERICS_LT_DECL;
3106 d = Token.OP_GENERICS_LT;
3113 parsing_generic_less_than = 0;
3122 return Token.OP_SHIFT_LEFT_ASSIGN;
3124 return Token.OP_SHIFT_LEFT;
3135 // Handles one line xml comment
3137 private void handle_one_line_xml_comment ()
3140 while ((c = peek_char ()) == ' ')
3141 get_char (); // skip heading whitespaces.
3142 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3143 xml_comment_buffer.Append ((char) get_char ());
3145 if (c == '\r' || c == '\n')
3146 xml_comment_buffer.Append (Environment.NewLine);
3150 // Remove heading "*" in Javadoc-like xml documentation.
3152 private void update_formatted_doc_comment (int current_comment_start)
3154 int length = xml_comment_buffer.Length - current_comment_start;
3155 string [] lines = xml_comment_buffer.ToString (
3156 current_comment_start,
3157 length).Replace ("\r", "").Split ('\n');
3159 // The first line starts with /**, thus it is not target
3160 // for the format check.
3161 for (int i = 1; i < lines.Length; i++) {
3162 string s = lines [i];
3163 int idx = s.IndexOf ('*');
3166 if (i < lines.Length - 1)
3170 head = s.Substring (0, idx);
3171 foreach (char c in head)
3174 lines [i] = s.Substring (idx + 1);
3176 xml_comment_buffer.Remove (current_comment_start, length);
3177 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3181 // Updates current comment location.
3183 private void update_comment_location ()
3185 if (current_comment_location.IsNull) {
3186 // "-2" is for heading "//" or "/*"
3187 current_comment_location =
3188 new Location (ref_line, hidden ? -1 : col - 2);
3193 // Checks if there was incorrect doc comments and raise
3196 public void check_incorrect_doc_comment ()
3198 if (xml_comment_buffer.Length > 0)
3199 warn_incorrect_doc_comment ();
3203 // Raises a warning when tokenizer found incorrect doccomment
3206 private void warn_incorrect_doc_comment ()
3208 if (doc_state != XmlCommentState.Error) {
3209 doc_state = XmlCommentState.Error;
3210 // in csc, it is 'XML comment is not placed on
3211 // a valid language element'. But that does not
3213 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3218 // Consumes the saved xml comment lines (if any)
3219 // as for current target member or type.
3221 public string consume_doc_comment ()
3223 if (xml_comment_buffer.Length > 0) {
3224 string ret = xml_comment_buffer.ToString ();
3225 reset_doc_comment ();
3232 get { return context.Report; }
3235 void reset_doc_comment ()
3237 xml_comment_buffer.Length = 0;
3238 current_comment_location = Location.Null;
3241 public void cleanup ()
3243 if (ifstack != null && ifstack.Count >= 1) {
3244 int state = ifstack.Pop ();
3245 if ((state & REGION) != 0)
3246 Report.Error (1038, Location, "#endregion directive expected");
3248 Report.Error (1027, Location, "Expected `#endif' directive");
3254 // Indicates whether it accepts XML documentation or not.
3256 public enum XmlCommentState {
3257 // comment is allowed in this state.
3259 // comment is not allowed in this state.
3261 // once comments appeared when it is NotAllowed, then the
3262 // state is changed to it, until the state is changed to