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;
18 using System.Collections.Generic;
20 using System.Globalization;
21 using System.Reflection;
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;
121 public static void Initialize ()
124 buffer = new LocatedToken [10000];
128 public Location Location {
129 get { return new Location (row, column); }
132 public string Value {
133 get { return value; }
137 SeekableStreamReader reader;
139 CompilationUnit file_name;
140 CompilerContext context;
147 bool handle_get_set = false;
148 bool handle_remove_add = false;
149 bool handle_where = false;
150 bool handle_typeof = false;
151 bool lambda_arguments_parsing;
152 Location current_comment_location = Location.Null;
153 ArrayList escaped_identifiers;
154 int parsing_generic_less_than;
157 // Used mainly for parser optimizations. Some expressions for instance
158 // can appear only in block (including initializer, base initializer)
161 public int parsing_block;
162 internal bool query_parsing;
165 // When parsing type only, useful for ambiguous nullable types
167 public int parsing_type;
170 // Set when parsing generic declaration (type or method header)
172 public bool parsing_generic_declaration;
175 // The value indicates that we have not reach any declaration or
178 public int parsing_declaration;
181 // The special character to inject on streams to trigger the EXPRESSION_PARSE
182 // token to be returned. It just happens to be a Unicode character that
183 // would never be part of a program (can not be an identifier).
185 // This character is only tested just before the tokenizer is about to report
186 // an error; So on the regular operation mode, this addition will have no
187 // impact on the tokenizer's performance.
190 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
191 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
192 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
195 // XML documentation buffer. The save point is used to divide
196 // comments on types and comments on members.
198 StringBuilder xml_comment_buffer;
201 // See comment on XmlCommentState enumeration.
203 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
206 // Whether tokens have been seen on this line
208 bool tokens_seen = false;
211 // Set to true once the GENERATE_COMPLETION token has bee
212 // returned. This helps produce one GENERATE_COMPLETION,
213 // as many COMPLETE_COMPLETION as necessary to complete the
214 // AST tree and one final EOF.
219 // Whether a token has been seen on the file
220 // This is needed because `define' is not allowed to be used
221 // after a token has been seen.
223 bool any_token_seen = false;
225 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
227 public bool PropertyParsing {
228 get { return handle_get_set; }
229 set { handle_get_set = value; }
232 public bool EventParsing {
233 get { return handle_remove_add; }
234 set { handle_remove_add = value; }
237 public bool ConstraintsParsing {
238 get { return handle_where; }
239 set { handle_where = value; }
242 public bool TypeOfParsing {
243 get { return handle_typeof; }
244 set { handle_typeof = value; }
247 public XmlCommentState doc_state {
248 get { return xml_doc_state; }
250 if (value == XmlCommentState.Allowed) {
251 check_incorrect_doc_comment ();
252 reset_doc_comment ();
254 xml_doc_state = value;
259 // This is used to trigger completion generation on the parser
260 public bool CompleteOnEOF;
262 void AddEscapedIdentifier (Location loc)
264 if (escaped_identifiers == null)
265 escaped_identifiers = new ArrayList ();
267 escaped_identifiers.Add (loc);
270 public bool IsEscapedIdentifier (Location loc)
272 if (escaped_identifiers != null) {
273 foreach (Location lt in escaped_identifiers)
284 static KeywordEntry[][] keywords;
285 static Dictionary<string, object> keyword_strings; // TODO: HashSet
286 static NumberStyles styles;
287 static NumberFormatInfo csharp_format_info;
290 // Values for the associated token returned
292 internal int putback_char; // Used by repl only
298 const int TAKING = 1;
299 const int ELSE_SEEN = 4;
300 const int PARENT_TAKING = 8;
301 const int REGION = 16;
304 // pre-processor if stack state:
308 static System.Text.StringBuilder string_builder;
310 const int max_id_size = 512;
311 static char [] id_builder = new char [max_id_size];
313 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
315 const int max_number_size = 512;
316 static char [] number_builder = new char [max_number_size];
317 static int number_pos;
319 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
322 // Details about the error encoutered by the tokenizer
324 string error_details;
326 public string error {
328 return error_details;
339 // This is used when the tokenizer needs to save
340 // the current position as it needs to do some parsing
341 // on its own to deamiguate a token in behalf of the
344 Stack position_stack = new Stack (2);
351 public int putback_char;
352 public int previous_col;
353 public Stack ifstack;
354 public int parsing_generic_less_than;
355 public int current_token;
357 public Position (Tokenizer t)
359 position = t.reader.Position;
361 ref_line = t.ref_line;
364 putback_char = t.putback_char;
365 previous_col = t.previous_col;
366 if (t.ifstack != null && t.ifstack.Count != 0)
367 ifstack = (Stack)t.ifstack.Clone ();
368 parsing_generic_less_than = t.parsing_generic_less_than;
369 current_token = t.current_token;
373 public void PushPosition ()
375 position_stack.Push (new Position (this));
378 public void PopPosition ()
380 Position p = (Position) position_stack.Pop ();
382 reader.Position = p.position;
383 ref_line = p.ref_line;
387 putback_char = p.putback_char;
388 previous_col = p.previous_col;
390 parsing_generic_less_than = p.parsing_generic_less_than;
391 current_token = p.current_token;
394 // Do not reset the position, ignore it.
395 public void DiscardPosition ()
397 position_stack.Pop ();
400 static void AddKeyword (string kw, int token)
402 keyword_strings.Add (kw, null);
404 int length = kw.Length;
405 if (keywords [length] == null) {
406 keywords [length] = new KeywordEntry ['z' - '_' + 1];
409 int char_index = kw [0] - '_';
410 KeywordEntry kwe = keywords [length] [char_index];
412 keywords [length] [char_index] = new KeywordEntry (kw, token);
416 while (kwe.Next != null) {
420 kwe.Next = new KeywordEntry (kw, token);
423 static void InitTokens ()
425 keyword_strings = new Dictionary<string, object> ();
427 // 11 is the length of the longest keyword for now
428 keywords = new KeywordEntry [11] [];
430 AddKeyword ("__arglist", Token.ARGLIST);
431 AddKeyword ("abstract", Token.ABSTRACT);
432 AddKeyword ("as", Token.AS);
433 AddKeyword ("add", Token.ADD);
434 AddKeyword ("base", Token.BASE);
435 AddKeyword ("bool", Token.BOOL);
436 AddKeyword ("break", Token.BREAK);
437 AddKeyword ("byte", Token.BYTE);
438 AddKeyword ("case", Token.CASE);
439 AddKeyword ("catch", Token.CATCH);
440 AddKeyword ("char", Token.CHAR);
441 AddKeyword ("checked", Token.CHECKED);
442 AddKeyword ("class", Token.CLASS);
443 AddKeyword ("const", Token.CONST);
444 AddKeyword ("continue", Token.CONTINUE);
445 AddKeyword ("decimal", Token.DECIMAL);
446 AddKeyword ("default", Token.DEFAULT);
447 AddKeyword ("delegate", Token.DELEGATE);
448 AddKeyword ("do", Token.DO);
449 AddKeyword ("double", Token.DOUBLE);
450 AddKeyword ("else", Token.ELSE);
451 AddKeyword ("enum", Token.ENUM);
452 AddKeyword ("event", Token.EVENT);
453 AddKeyword ("explicit", Token.EXPLICIT);
454 AddKeyword ("extern", Token.EXTERN);
455 AddKeyword ("false", Token.FALSE);
456 AddKeyword ("finally", Token.FINALLY);
457 AddKeyword ("fixed", Token.FIXED);
458 AddKeyword ("float", Token.FLOAT);
459 AddKeyword ("for", Token.FOR);
460 AddKeyword ("foreach", Token.FOREACH);
461 AddKeyword ("goto", Token.GOTO);
462 AddKeyword ("get", Token.GET);
463 AddKeyword ("if", Token.IF);
464 AddKeyword ("implicit", Token.IMPLICIT);
465 AddKeyword ("in", Token.IN);
466 AddKeyword ("int", Token.INT);
467 AddKeyword ("interface", Token.INTERFACE);
468 AddKeyword ("internal", Token.INTERNAL);
469 AddKeyword ("is", Token.IS);
470 AddKeyword ("lock", Token.LOCK);
471 AddKeyword ("long", Token.LONG);
472 AddKeyword ("namespace", Token.NAMESPACE);
473 AddKeyword ("new", Token.NEW);
474 AddKeyword ("null", Token.NULL);
475 AddKeyword ("object", Token.OBJECT);
476 AddKeyword ("operator", Token.OPERATOR);
477 AddKeyword ("out", Token.OUT);
478 AddKeyword ("override", Token.OVERRIDE);
479 AddKeyword ("params", Token.PARAMS);
480 AddKeyword ("private", Token.PRIVATE);
481 AddKeyword ("protected", Token.PROTECTED);
482 AddKeyword ("public", Token.PUBLIC);
483 AddKeyword ("readonly", Token.READONLY);
484 AddKeyword ("ref", Token.REF);
485 AddKeyword ("remove", Token.REMOVE);
486 AddKeyword ("return", Token.RETURN);
487 AddKeyword ("sbyte", Token.SBYTE);
488 AddKeyword ("sealed", Token.SEALED);
489 AddKeyword ("set", Token.SET);
490 AddKeyword ("short", Token.SHORT);
491 AddKeyword ("sizeof", Token.SIZEOF);
492 AddKeyword ("stackalloc", Token.STACKALLOC);
493 AddKeyword ("static", Token.STATIC);
494 AddKeyword ("string", Token.STRING);
495 AddKeyword ("struct", Token.STRUCT);
496 AddKeyword ("switch", Token.SWITCH);
497 AddKeyword ("this", Token.THIS);
498 AddKeyword ("throw", Token.THROW);
499 AddKeyword ("true", Token.TRUE);
500 AddKeyword ("try", Token.TRY);
501 AddKeyword ("typeof", Token.TYPEOF);
502 AddKeyword ("uint", Token.UINT);
503 AddKeyword ("ulong", Token.ULONG);
504 AddKeyword ("unchecked", Token.UNCHECKED);
505 AddKeyword ("unsafe", Token.UNSAFE);
506 AddKeyword ("ushort", Token.USHORT);
507 AddKeyword ("using", Token.USING);
508 AddKeyword ("virtual", Token.VIRTUAL);
509 AddKeyword ("void", Token.VOID);
510 AddKeyword ("volatile", Token.VOLATILE);
511 AddKeyword ("while", Token.WHILE);
512 AddKeyword ("partial", Token.PARTIAL);
513 AddKeyword ("where", Token.WHERE);
516 AddKeyword ("from", Token.FROM);
517 AddKeyword ("join", Token.JOIN);
518 AddKeyword ("on", Token.ON);
519 AddKeyword ("equals", Token.EQUALS);
520 AddKeyword ("select", Token.SELECT);
521 AddKeyword ("group", Token.GROUP);
522 AddKeyword ("by", Token.BY);
523 AddKeyword ("let", Token.LET);
524 AddKeyword ("orderby", Token.ORDERBY);
525 AddKeyword ("ascending", Token.ASCENDING);
526 AddKeyword ("descending", Token.DESCENDING);
527 AddKeyword ("into", Token.INTO);
536 csharp_format_info = NumberFormatInfo.InvariantInfo;
537 styles = NumberStyles.Float;
539 string_builder = new System.Text.StringBuilder ();
542 int GetKeyword (char[] id, int id_len)
545 // Keywords are stored in an array of arrays grouped by their
546 // length and then by the first character
548 if (id_len >= keywords.Length || keywords [id_len] == null)
551 int first_index = id [0] - '_';
552 if (first_index > 'z')
555 KeywordEntry kwe = keywords [id_len] [first_index];
562 for (int i = 1; i < id_len; ++i) {
563 if (id [i] != kwe.Value [i]) {
569 } while (res == 0 && kwe != null);
583 if (!handle_remove_add)
587 if (parsing_declaration == 0)
588 res = Token.EXTERN_ALIAS;
591 if (peek_token () == Token.COLON) {
593 res = Token.DEFAULT_COLON;
597 if (!handle_where && !query_parsing)
602 // A query expression is any expression that starts with `from identifier'
603 // followed by any token except ; , =
605 if (!query_parsing) {
606 if (lambda_arguments_parsing) {
612 // HACK: to disable generics micro-parser, because PushPosition does not
613 // store identifiers array
614 parsing_generic_less_than = 1;
616 case Token.IDENTIFIER:
628 next_token = xtoken ();
629 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
632 res = Token.FROM_FIRST;
633 query_parsing = true;
634 if (RootContext.Version <= LanguageVersion.ISO_2)
635 Report.FeatureIsNotAvailable (Location, "query expressions");
638 Expression.Error_VoidInvalidInTheContext (Location, Report);
642 // HACK: A token is not a keyword so we need to restore identifiers buffer
643 // which has been overwritten before we grabbed the identifier
644 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
658 case Token.ASCENDING:
659 case Token.DESCENDING:
666 case Token.NAMESPACE:
667 // TODO: some explanation needed
668 check_incorrect_doc_comment ();
672 if (parsing_block > 0) {
677 // Save current position and parse next token.
680 next_token = token ();
681 bool ok = (next_token == Token.CLASS) ||
682 (next_token == Token.STRUCT) ||
683 (next_token == Token.INTERFACE) ||
684 (next_token == Token.VOID);
689 if (next_token == Token.VOID) {
690 if (RootContext.Version == LanguageVersion.ISO_1 ||
691 RootContext.Version == LanguageVersion.ISO_2)
692 Report.FeatureIsNotAvailable (Location, "partial methods");
693 } else if (RootContext.Version == LanguageVersion.ISO_1)
694 Report.FeatureIsNotAvailable (Location, "partial types");
699 if (next_token < Token.LAST_KEYWORD) {
700 Report.Error (267, Location,
701 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
712 public Location Location {
714 return new Location (ref_line, hidden ? -1 : col);
718 public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
720 this.ref_name = file;
721 this.file_name = file;
727 xml_comment_buffer = new StringBuilder ();
730 // FIXME: This could be `Location.Push' but we have to
731 // find out why the MS compiler allows this
733 Mono.CSharp.Location.Push (file, file);
736 static bool is_identifier_start_character (int c)
738 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
741 static bool is_identifier_part_character (char c)
743 if (c >= 'a' && c <= 'z')
746 if (c >= 'A' && c <= 'Z')
749 if (c == '_' || (c >= '0' && c <= '9'))
755 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
758 public static bool IsKeyword (string s)
760 return keyword_strings.ContainsKey (s);
764 // Open parens micro parser. Detects both lambda and cast ambiguity.
767 int TokenizeOpenParens ()
772 int bracket_level = 0;
773 bool is_type = false;
774 bool can_be_type = false;
777 ptoken = current_token;
780 switch (current_token) {
781 case Token.CLOSE_PARENS:
785 // Expression inside parens is lambda, (int i) =>
787 if (current_token == Token.ARROW) {
788 if (RootContext.Version <= LanguageVersion.ISO_2)
789 Report.FeatureIsNotAvailable (Location, "lambda expressions");
791 return Token.OPEN_PARENS_LAMBDA;
795 // Expression inside parens is single type, (int[])
798 return Token.OPEN_PARENS_CAST;
801 // Expression is possible cast, look at next token, (T)null
804 switch (current_token) {
805 case Token.OPEN_PARENS:
808 case Token.IDENTIFIER:
822 case Token.UNCHECKED:
827 // These can be part of a member access
841 return Token.OPEN_PARENS_CAST;
844 return Token.OPEN_PARENS;
847 case Token.DOUBLE_COLON:
848 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
853 case Token.IDENTIFIER:
856 case Token.OP_GENERICS_LT:
858 case Token.DOUBLE_COLON:
860 if (bracket_level == 0)
864 can_be_type = is_type = false;
884 if (bracket_level == 0)
889 if (bracket_level == 0) {
891 can_be_type = is_type = false;
895 case Token.OP_GENERICS_LT:
896 case Token.OPEN_BRACKET:
897 if (bracket_level++ == 0)
901 case Token.OP_GENERICS_GT:
902 case Token.CLOSE_BRACKET:
906 case Token.INTERR_NULLABLE:
908 if (bracket_level == 0)
914 can_be_type = is_type = false;
918 return Token.OPEN_PARENS;
923 public static bool IsValidIdentifier (string s)
925 if (s == null || s.Length == 0)
928 if (!is_identifier_start_character (s [0]))
931 for (int i = 1; i < s.Length; i ++)
932 if (! is_identifier_part_character (s [i]))
938 bool parse_less_than ()
941 int the_token = token ();
942 if (the_token == Token.OPEN_BRACKET) {
944 the_token = token ();
945 } while (the_token != Token.CLOSE_BRACKET);
946 the_token = token ();
947 } else if (the_token == Token.IN || the_token == Token.OUT) {
948 the_token = token ();
951 case Token.IDENTIFIER:
969 case Token.OP_GENERICS_GT:
976 the_token = token ();
978 if (the_token == Token.OP_GENERICS_GT)
980 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
982 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
984 else if (the_token == Token.OP_GENERICS_LT) {
985 if (!parse_less_than ())
988 } else if (the_token == Token.OPEN_BRACKET) {
990 the_token = token ();
991 if (the_token == Token.CLOSE_BRACKET)
993 else if (the_token == Token.COMMA)
994 goto rank_specifiers;
1001 bool parse_generic_dimension (out int dimension)
1006 int the_token = token ();
1007 if (the_token == Token.OP_GENERICS_GT)
1009 else if (the_token == Token.COMMA) {
1017 public int peek_token ()
1022 the_token = token ();
1029 // Tonizes `?' using custom disambiguous rules to return one
1030 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1032 // Tricky expression look like:
1034 // Foo ? a = x ? b : c;
1036 int TokenizePossibleNullableType ()
1038 if (parsing_block == 0 || parsing_type > 0)
1039 return Token.INTERR_NULLABLE;
1041 int d = peek_char ();
1044 return Token.OP_COALESCING;
1047 switch (current_token) {
1048 case Token.CLOSE_PARENS:
1053 return Token.INTERR;
1057 if (d == ',' || d == ';' || d == '>')
1058 return Token.INTERR_NULLABLE;
1059 if (d == '*' || (d >= '0' && d <= '9'))
1060 return Token.INTERR;
1064 current_token = Token.NONE;
1066 switch (xtoken ()) {
1073 next_token = Token.INTERR;
1076 case Token.SEMICOLON:
1078 case Token.CLOSE_PARENS:
1079 case Token.OPEN_BRACKET:
1080 case Token.OP_GENERICS_GT:
1081 next_token = Token.INTERR_NULLABLE;
1089 if (next_token == -1) {
1090 switch (xtoken ()) {
1092 case Token.SEMICOLON:
1093 case Token.OPEN_BRACE:
1094 case Token.CLOSE_PARENS:
1096 next_token = Token.INTERR_NULLABLE;
1100 next_token = Token.INTERR;
1108 // All shorcuts failed, do it hard way
1110 while ((ntoken = xtoken ()) != Token.EOF) {
1111 if (ntoken == Token.SEMICOLON)
1114 if (ntoken == Token.COLON) {
1115 if (++colons == interrs)
1120 if (ntoken == Token.INTERR) {
1126 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1135 bool decimal_digits (int c)
1138 bool seen_digits = false;
1141 if (number_pos == max_number_size)
1142 Error_NumericConstantTooLong ();
1143 number_builder [number_pos++] = (char) c;
1147 // We use peek_char2, because decimal_digits needs to do a
1148 // 2-character look-ahead (5.ToString for example).
1150 while ((d = peek_char2 ()) != -1){
1151 if (d >= '0' && d <= '9'){
1152 if (number_pos == max_number_size)
1153 Error_NumericConstantTooLong ();
1154 number_builder [number_pos++] = (char) d;
1164 static bool is_hex (int e)
1166 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1169 static TypeCode real_type_suffix (int c)
1173 return TypeCode.Single;
1175 return TypeCode.Double;
1177 return TypeCode.Decimal;
1179 return TypeCode.Empty;
1183 int integer_type_suffix (ulong ul, int c)
1185 bool is_unsigned = false;
1186 bool is_long = false;
1189 bool scanning = true;
1202 // if we have not seen anything in between
1203 // report this error
1205 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1225 if (is_long && is_unsigned){
1226 val = new ULongLiteral (ul, Location);
1227 return Token.LITERAL;
1231 // uint if possible, or ulong else.
1233 if ((ul & 0xffffffff00000000) == 0)
1234 val = new UIntLiteral ((uint) ul, Location);
1236 val = new ULongLiteral (ul, Location);
1237 } else if (is_long){
1238 // long if possible, ulong otherwise
1239 if ((ul & 0x8000000000000000) != 0)
1240 val = new ULongLiteral (ul, Location);
1242 val = new LongLiteral ((long) ul, Location);
1244 // int, uint, long or ulong in that order
1245 if ((ul & 0xffffffff00000000) == 0){
1246 uint ui = (uint) ul;
1248 if ((ui & 0x80000000) != 0)
1249 val = new UIntLiteral (ui, Location);
1251 val = new IntLiteral ((int) ui, Location);
1253 if ((ul & 0x8000000000000000) != 0)
1254 val = new ULongLiteral (ul, Location);
1256 val = new LongLiteral ((long) ul, Location);
1259 return Token.LITERAL;
1263 // given `c' as the next char in the input decide whether
1264 // we need to convert to a special type, and then choose
1265 // the best representation for the integer
1267 int adjust_int (int c)
1270 if (number_pos > 9){
1271 ulong ul = (uint) (number_builder [0] - '0');
1273 for (int i = 1; i < number_pos; i++){
1274 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1276 return integer_type_suffix (ul, c);
1278 uint ui = (uint) (number_builder [0] - '0');
1280 for (int i = 1; i < number_pos; i++){
1281 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1283 return integer_type_suffix (ui, c);
1285 } catch (OverflowException) {
1286 error_details = "Integral constant is too large";
1287 Report.Error (1021, Location, error_details);
1288 val = new IntLiteral (0, Location);
1289 return Token.LITERAL;
1291 catch (FormatException) {
1292 Report.Error (1013, Location, "Invalid number");
1293 val = new IntLiteral (0, Location);
1294 return Token.LITERAL;
1298 int adjust_real (TypeCode t)
1300 string s = new String (number_builder, 0, number_pos);
1301 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1304 case TypeCode.Decimal:
1306 val = new DecimalLiteral (decimal.Parse (s, styles, csharp_format_info), Location);
1307 } catch (OverflowException) {
1308 val = new DecimalLiteral (0, Location);
1309 Report.Error (594, Location, error_details, "decimal");
1312 case TypeCode.Single:
1314 val = new FloatLiteral (float.Parse (s, styles, csharp_format_info), Location);
1315 } catch (OverflowException) {
1316 val = new FloatLiteral (0, Location);
1317 Report.Error (594, Location, error_details, "float");
1322 val = new DoubleLiteral (double.Parse (s, styles, csharp_format_info), Location);
1323 } catch (OverflowException) {
1324 val = new DoubleLiteral (0, Location);
1325 Report.Error (594, Location, error_details, "double");
1330 return Token.LITERAL;
1339 while ((d = peek_char ()) != -1){
1341 number_builder [number_pos++] = (char) d;
1347 string s = new String (number_builder, 0, number_pos);
1349 if (number_pos <= 8)
1350 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1352 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1353 } catch (OverflowException){
1354 error_details = "Integral constant is too large";
1355 Report.Error (1021, Location, error_details);
1356 val = new IntLiteral (0, Location);
1357 return Token.LITERAL;
1359 catch (FormatException) {
1360 Report.Error (1013, Location, "Invalid number");
1361 val = new IntLiteral (0, Location);
1362 return Token.LITERAL;
1365 return integer_type_suffix (ul, peek_char ());
1369 // Invoked if we know we have .digits or digits
1371 int is_number (int c)
1373 bool is_real = false;
1377 if (c >= '0' && c <= '9'){
1379 int peek = peek_char ();
1381 if (peek == 'x' || peek == 'X')
1382 return handle_hex ();
1389 // We need to handle the case of
1390 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1393 if (decimal_digits ('.')){
1399 return adjust_int (-1);
1403 if (c == 'e' || c == 'E'){
1405 if (number_pos == max_number_size)
1406 Error_NumericConstantTooLong ();
1407 number_builder [number_pos++] = 'e';
1411 if (number_pos == max_number_size)
1412 Error_NumericConstantTooLong ();
1413 number_builder [number_pos++] = '+';
1415 } else if (c == '-') {
1416 if (number_pos == max_number_size)
1417 Error_NumericConstantTooLong ();
1418 number_builder [number_pos++] = '-';
1421 if (number_pos == max_number_size)
1422 Error_NumericConstantTooLong ();
1423 number_builder [number_pos++] = '+';
1430 var type = real_type_suffix (c);
1431 if (type == TypeCode.Empty && !is_real){
1433 return adjust_int (c);
1438 if (type == TypeCode.Empty){
1443 return adjust_real (type);
1445 throw new Exception ("Is Number should never reach this point");
1449 // Accepts exactly count (4 or 8) hex, no more no less
1451 int getHex (int count, out int surrogate, out bool error)
1456 int top = count != -1 ? count : 4;
1461 for (i = 0; i < top; i++){
1464 if (c >= '0' && c <= '9')
1465 c = (int) c - (int) '0';
1466 else if (c >= 'A' && c <= 'F')
1467 c = (int) c - (int) 'A' + 10;
1468 else if (c >= 'a' && c <= 'f')
1469 c = (int) c - (int) 'a' + 10;
1475 total = (total * 16) + c;
1477 int p = peek_char ();
1480 if (!is_hex ((char)p))
1486 if (total > 0x0010FFFF) {
1491 if (total >= 0x00010000) {
1492 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1493 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1500 int escape (int c, out int surrogate)
1536 v = getHex (-1, out surrogate, out error);
1542 return EscapeUnicode (d, out surrogate);
1545 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1554 int EscapeUnicode (int ch, out int surrogate)
1558 ch = getHex (8, out surrogate, out error);
1560 ch = getHex (4, out surrogate, out error);
1564 Report.Error (1009, Location, "Unrecognized escape sequence");
1572 if (putback_char != -1) {
1585 void advance_line ()
1595 if (putback_char == -1)
1596 putback_char = reader.Read ();
1597 return putback_char;
1602 if (putback_char != -1)
1603 return putback_char;
1604 return reader.Peek ();
1607 void putback (int c)
1609 if (putback_char != -1){
1610 Console.WriteLine ("Col: " + col);
1611 Console.WriteLine ("Row: " + line);
1612 Console.WriteLine ("Name: " + ref_name.Name);
1613 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1614 throw new Exception ("This should not happen putback on putback");
1616 if (c == '\n' || col == 0) {
1617 // It won't happen though.
1627 public bool advance ()
1629 return peek_char () != -1 || CompleteOnEOF;
1632 public Object Value {
1638 public Object value ()
1645 current_token = xtoken ();
1646 return current_token;
1649 void get_cmd_arg (out string cmd, out string arg)
1653 tokens_seen = false;
1656 // skip over white space
1659 } while (c == '\r' || c == ' ' || c == '\t');
1661 static_cmd_arg.Length = 0;
1662 while (c != -1 && is_identifier_part_character ((char)c)) {
1663 static_cmd_arg.Append ((char)c);
1666 int peek = peek_char ();
1667 if (peek == 'U' || peek == 'u') {
1669 c = EscapeUnicode (c, out surrogate);
1670 if (surrogate != 0) {
1671 if (is_identifier_part_character ((char) c))
1672 static_cmd_arg.Append ((char) c);
1679 cmd = static_cmd_arg.ToString ();
1681 // skip over white space
1682 while (c == '\r' || c == ' ' || c == '\t')
1685 static_cmd_arg.Length = 0;
1686 int has_identifier_argument = 0;
1688 while (c != -1 && c != '\n' && c != '\r') {
1689 if (c == '\\' && has_identifier_argument >= 0) {
1690 if (has_identifier_argument != 0 || (cmd == "define" || cmd == "if" || cmd == "elif" || cmd == "undef")) {
1691 has_identifier_argument = 1;
1693 int peek = peek_char ();
1694 if (peek == 'U' || peek == 'u') {
1696 c = EscapeUnicode (c, out surrogate);
1697 if (surrogate != 0) {
1698 if (is_identifier_part_character ((char) c))
1699 static_cmd_arg.Append ((char) c);
1704 has_identifier_argument = -1;
1707 static_cmd_arg.Append ((char) c);
1711 if (static_cmd_arg.Length != 0)
1712 arg = static_cmd_arg.ToString ();
1716 // Handles the #line directive
1718 bool PreProcessLine (string arg)
1720 if (arg.Length == 0)
1723 if (arg == "default"){
1725 ref_name = file_name;
1727 Location.Push (file_name, ref_name);
1729 } else if (arg == "hidden"){
1737 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1738 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1741 char [] quotes = { '\"' };
1743 string name = arg.Substring (pos). Trim (quotes);
1744 ref_name = Location.LookupFile (file_name, name);
1745 file_name.AddFile (ref_name);
1747 Location.Push (file_name, ref_name);
1749 ref_line = System.Int32.Parse (arg);
1760 // Handles #define and #undef
1762 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1764 if (ident.Length == 0 || ident == "true" || ident == "false"){
1765 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1769 if (ident.IndexOfAny (simple_whitespaces) != -1){
1770 Error_EndLineExpected ();
1774 if (!is_identifier_start_character (ident [0]))
1775 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1777 foreach (char c in ident.Substring (1)){
1778 if (!is_identifier_part_character (c)){
1779 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1784 if (!caller_is_taking)
1791 if (RootContext.IsConditionalDefined (ident))
1794 file_name.AddDefine (ident);
1799 file_name.AddUndefine (ident);
1803 static byte read_hex (string arg, int pos, out bool error)
1810 if ((c >= '0') && (c <= '9'))
1811 total = (int) c - (int) '0';
1812 else if ((c >= 'A') && (c <= 'F'))
1813 total = (int) c - (int) 'A' + 10;
1814 else if ((c >= 'a') && (c <= 'f'))
1815 total = (int) c - (int) 'a' + 10;
1824 if ((c >= '0') && (c <= '9'))
1825 total += (int) c - (int) '0';
1826 else if ((c >= 'A') && (c <= 'F'))
1827 total += (int) c - (int) 'A' + 10;
1828 else if ((c >= 'a') && (c <= 'f'))
1829 total += (int) c - (int) 'a' + 10;
1835 return (byte) total;
1839 /// Handles #pragma checksum
1841 bool PreProcessPragmaChecksum (string arg)
1843 if ((arg [0] != ' ') && (arg [0] != '\t'))
1846 arg = arg.Trim (simple_whitespaces);
1847 if ((arg.Length < 2) || (arg [0] != '"'))
1850 StringBuilder file_sb = new StringBuilder ();
1854 while ((ch = arg [pos++]) != '"') {
1855 if (pos >= arg.Length)
1859 if (pos+1 >= arg.Length)
1864 file_sb.Append (ch);
1867 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1870 arg = arg.Substring (pos).Trim (simple_whitespaces);
1871 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1872 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1873 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1877 byte[] guid_bytes = new byte [16];
1879 for (int i = 0; i < 4; i++) {
1880 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1884 for (int i = 0; i < 2; i++) {
1885 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1888 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1891 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1896 for (int i = 0; i < 6; i++) {
1897 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1902 arg = arg.Substring (40).Trim (simple_whitespaces);
1903 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1906 byte[] checksum_bytes = new byte [16];
1907 for (int i = 0; i < 16; i++) {
1908 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1913 arg = arg.Substring (34).Trim (simple_whitespaces);
1917 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1918 file.SetChecksum (guid_bytes, checksum_bytes);
1919 ref_name.AutoGenerated = true;
1924 /// Handles #pragma directive
1926 void PreProcessPragma (string arg)
1928 const string warning = "warning";
1929 const string w_disable = "warning disable";
1930 const string w_restore = "warning restore";
1931 const string checksum = "checksum";
1933 if (arg == w_disable) {
1934 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1938 if (arg == w_restore) {
1939 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1943 if (arg.StartsWith (w_disable)) {
1944 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1945 foreach (int code in codes) {
1947 Report.RegisterWarningRegion (Location).WarningDisable (Location, code, Report);
1952 if (arg.StartsWith (w_restore)) {
1953 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1954 Hashtable w_table = Report.warning_ignore_table;
1955 foreach (int code in codes) {
1956 if (w_table != null && w_table.Contains (code))
1957 Report.Warning (1635, 1, Location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1958 Report.RegisterWarningRegion (Location).WarningEnable (Location, code, Report);
1963 if (arg.StartsWith (warning)) {
1964 Report.Warning (1634, 1, Location, "Expected disable or restore");
1968 if (arg.StartsWith (checksum)) {
1969 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1970 Warning_InvalidPragmaChecksum ();
1974 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1977 int[] ParseNumbers (string text)
1979 string[] string_array = text.Split (',');
1980 int[] values = new int [string_array.Length];
1982 foreach (string string_code in string_array) {
1984 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1986 catch (FormatException) {
1987 Report.Warning (1692, 1, Location, "Invalid number");
1993 bool eval_val (string s)
2000 return file_name.IsConditionalDefined (s);
2003 bool pp_primary (ref string s)
2012 s = s.Substring (1);
2013 bool val = pp_expr (ref s, false);
2014 if (s.Length > 0 && s [0] == ')'){
2015 s = s.Substring (1);
2018 Error_InvalidDirective ();
2022 if (is_identifier_start_character (c)){
2028 if (is_identifier_part_character (c)){
2032 bool v = eval_val (s.Substring (0, j));
2033 s = s.Substring (j);
2036 bool vv = eval_val (s);
2041 Error_InvalidDirective ();
2045 bool pp_unary (ref string s)
2052 if (len > 1 && s [1] == '='){
2053 Error_InvalidDirective ();
2056 s = s.Substring (1);
2057 return ! pp_primary (ref s);
2059 return pp_primary (ref s);
2061 Error_InvalidDirective ();
2066 bool pp_eq (ref string s)
2068 bool va = pp_unary (ref s);
2074 if (len > 2 && s [1] == '='){
2075 s = s.Substring (2);
2076 return va == pp_unary (ref s);
2078 Error_InvalidDirective ();
2081 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2082 s = s.Substring (2);
2084 return va != pp_unary (ref s);
2093 bool pp_and (ref string s)
2095 bool va = pp_eq (ref s);
2101 if (len > 2 && s [1] == '&'){
2102 s = s.Substring (2);
2103 return (va & pp_and (ref s));
2105 Error_InvalidDirective ();
2114 // Evaluates an expression for `#if' or `#elif'
2116 bool pp_expr (ref string s, bool isTerm)
2118 bool va = pp_and (ref s);
2125 if (len > 2 && s [1] == '|'){
2126 s = s.Substring (2);
2127 return va | pp_expr (ref s, isTerm);
2129 Error_InvalidDirective ();
2134 Error_EndLineExpected ();
2142 bool eval (string s)
2144 bool v = pp_expr (ref s, true);
2153 void Error_NumericConstantTooLong ()
2155 Report.Error (1021, Location, "Numeric constant too long");
2158 void Error_InvalidDirective ()
2160 Report.Error (1517, Location, "Invalid preprocessor directive");
2163 void Error_UnexpectedDirective (string extra)
2167 "Unexpected processor directive ({0})", extra);
2170 void Error_TokensSeen ()
2172 Report.Error (1032, Location,
2173 "Cannot define or undefine preprocessor symbols after first token in file");
2176 void Eror_WrongPreprocessorLocation ()
2178 Report.Error (1040, Location,
2179 "Preprocessor directives must appear as the first non-whitespace character on a line");
2182 void Error_EndLineExpected ()
2184 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2187 void Warning_InvalidPragmaChecksum ()
2189 Report.Warning (1695, 1, Location,
2190 "Invalid #pragma checksum syntax; should be " +
2191 "#pragma checksum \"filename\" " +
2192 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2195 // if true, then the code continues processing the code
2196 // if false, the code stays in a loop until another directive is
2198 // When caller_is_taking is false we ignore all directives except the ones
2199 // which can help us to identify where the #if block ends
2200 bool handle_preprocessing_directive (bool caller_is_taking)
2203 bool region_directive = false;
2205 get_cmd_arg (out cmd, out arg);
2207 // Eat any trailing whitespaces and single-line comments
2208 if (arg.IndexOf ("//") != -1)
2209 arg = arg.Substring (0, arg.IndexOf ("//"));
2210 arg = arg.Trim (simple_whitespaces);
2213 // The first group of pre-processing instructions is always processed
2217 region_directive = true;
2222 if (ifstack == null || ifstack.Count == 0){
2223 Error_UnexpectedDirective ("no #region for this #endregion");
2226 int pop = (int) ifstack.Pop ();
2228 if ((pop & REGION) == 0)
2229 Report.Error (1027, Location, "Expected `#endif' directive");
2231 return caller_is_taking;
2234 if (ifstack == null)
2235 ifstack = new Stack (2);
2237 int flags = region_directive ? REGION : 0;
2238 if (ifstack.Count == 0){
2239 flags |= PARENT_TAKING;
2241 int state = (int) ifstack.Peek ();
2242 if ((state & TAKING) != 0) {
2243 flags |= PARENT_TAKING;
2247 if (caller_is_taking && eval (arg)) {
2248 ifstack.Push (flags | TAKING);
2251 ifstack.Push (flags);
2255 if (ifstack == null || ifstack.Count == 0){
2256 Error_UnexpectedDirective ("no #if for this #endif");
2259 pop = (int) ifstack.Pop ();
2261 if ((pop & REGION) != 0)
2262 Report.Error (1038, Location, "#endregion directive expected");
2264 if (arg.Length != 0) {
2265 Error_EndLineExpected ();
2268 if (ifstack.Count == 0)
2271 int state = (int) ifstack.Peek ();
2272 return (state & TAKING) != 0;
2276 if (ifstack == null || ifstack.Count == 0){
2277 Error_UnexpectedDirective ("no #if for this #elif");
2280 int state = (int) ifstack.Pop ();
2282 if ((state & REGION) != 0) {
2283 Report.Error (1038, Location, "#endregion directive expected");
2287 if ((state & ELSE_SEEN) != 0){
2288 Error_UnexpectedDirective ("#elif not valid after #else");
2292 if ((state & TAKING) != 0) {
2297 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2298 ifstack.Push (state | TAKING);
2302 ifstack.Push (state);
2307 if (ifstack == null || ifstack.Count == 0){
2308 Error_UnexpectedDirective ("no #if for this #else");
2311 int state = (int) ifstack.Peek ();
2313 if ((state & REGION) != 0) {
2314 Report.Error (1038, Location, "#endregion directive expected");
2318 if ((state & ELSE_SEEN) != 0){
2319 Error_UnexpectedDirective ("#else within #else");
2325 if (arg.Length != 0) {
2326 Error_EndLineExpected ();
2331 if ((state & PARENT_TAKING) != 0) {
2332 ret = (state & TAKING) == 0;
2340 ifstack.Push (state | ELSE_SEEN);
2345 if (any_token_seen){
2346 Error_TokensSeen ();
2347 return caller_is_taking;
2349 PreProcessDefinition (true, arg, caller_is_taking);
2350 return caller_is_taking;
2353 if (any_token_seen){
2354 Error_TokensSeen ();
2355 return caller_is_taking;
2357 PreProcessDefinition (false, arg, caller_is_taking);
2358 return caller_is_taking;
2362 // These are only processed if we are in a `taking' block
2364 if (!caller_is_taking)
2369 Report.Error (1029, Location, "#error: '{0}'", arg);
2373 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2377 if (RootContext.Version == LanguageVersion.ISO_1) {
2378 Report.FeatureIsNotAvailable (Location, "#pragma");
2382 PreProcessPragma (arg);
2386 if (!PreProcessLine (arg))
2389 "The line number specified for #line directive is missing or invalid");
2390 return caller_is_taking;
2393 Report.Error (1024, Location, "Wrong preprocessor directive");
2398 private int consume_string (bool quoted)
2401 string_builder.Length = 0;
2403 while ((c = get_char ()) != -1){
2405 if (quoted && peek_char () == '"'){
2406 string_builder.Append ((char) c);
2410 val = new StringLiteral (string_builder.ToString (), Location);
2411 return Token.LITERAL;
2417 Report.Error (1010, Location, "Newline in constant");
2422 c = escape (c, out surrogate);
2425 if (surrogate != 0) {
2426 string_builder.Append ((char) c);
2430 string_builder.Append ((char) c);
2433 Report.Error (1039, Location, "Unterminated string literal");
2437 private int consume_identifier (int s)
2439 int res = consume_identifier (s, false);
2441 if (doc_state == XmlCommentState.Allowed)
2442 doc_state = XmlCommentState.NotAllowed;
2447 int consume_identifier (int c, bool quoted)
2450 // This method is very performance sensitive. It accounts
2451 // for approximately 25% of all parser time
2459 c = escape (c, out surrogate);
2460 if (surrogate != 0) {
2461 id_builder [pos++] = (char) c;
2466 id_builder [pos++] = (char) c;
2472 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2473 id_builder [pos++] = (char) c;
2480 c = escape (c, out surrogate);
2481 if (surrogate != 0) {
2482 if (is_identifier_part_character ((char) c))
2483 id_builder[pos++] = (char) c;
2489 } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2490 id_builder [pos++] = (char) c;
2497 } catch (IndexOutOfRangeException) {
2498 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2506 // Optimization: avoids doing the keyword lookup
2507 // on uppercase letters
2509 if (id_builder [0] >= '_' && !quoted) {
2510 int keyword = GetKeyword (id_builder, pos);
2511 if (keyword != -1) {
2512 val = LocatedToken.Create (null, ref_line, column);
2518 // Keep identifiers in an array of hashtables to avoid needless
2521 var identifiers_group = identifiers [pos];
2523 if (identifiers_group != null) {
2524 if (identifiers_group.TryGetValue (id_builder, out s)) {
2525 val = LocatedToken.Create (s, ref_line, column);
2527 AddEscapedIdentifier (((LocatedToken) val).Location);
2528 return Token.IDENTIFIER;
2531 // TODO: this should be number of files dependant
2532 // corlib compilation peaks at 1000 and System.Core at 150
2533 int capacity = pos > 20 ? 10 : 100;
2534 identifiers_group = new Dictionary<char[],string> (capacity, new IdentifiersComparer (pos));
2535 identifiers [pos] = identifiers_group;
2538 char [] chars = new char [pos];
2539 Array.Copy (id_builder, chars, pos);
2541 s = new string (id_builder, 0, pos);
2542 identifiers_group.Add (chars, s);
2544 val = LocatedToken.Create (s, ref_line, column);
2546 AddEscapedIdentifier (((LocatedToken) val).Location);
2548 return Token.IDENTIFIER;
2551 public int xtoken ()
2555 // Whether we have seen comments on the current line
2556 bool comments_seen = false;
2557 while ((c = get_char ()) != -1) {
2560 col = ((col + 8) / 8) * 8;
2568 case 0xFEFF: // Ignore BOM anywhere in the file
2571 /* This is required for compatibility with .NET
2573 if (peek_char () == 0xBB) {
2576 if (get_char () == 0xBF)
2583 if (peek_char () != '\n')
2588 any_token_seen |= tokens_seen;
2589 tokens_seen = false;
2590 comments_seen = false;
2595 return consume_identifier (c);
2598 val = LocatedToken.Create (ref_line, col);
2599 return Token.OPEN_BRACE;
2601 val = LocatedToken.Create (ref_line, col);
2602 return Token.CLOSE_BRACE;
2604 // To block doccomment inside attribute declaration.
2605 if (doc_state == XmlCommentState.Allowed)
2606 doc_state = XmlCommentState.NotAllowed;
2607 return Token.OPEN_BRACKET;
2609 return Token.CLOSE_BRACKET;
2611 val = LocatedToken.Create (ref_line, col);
2613 // An expression versions of parens can appear in block context only
2615 if (parsing_block != 0 && !lambda_arguments_parsing) {
2618 // Optmize most common case where we know that parens
2621 switch (current_token) {
2622 case Token.IDENTIFIER:
2630 case Token.DELEGATE:
2631 case Token.OP_GENERICS_GT:
2632 return Token.OPEN_PARENS;
2635 // Optimize using peek
2636 int xx = peek_char ();
2643 return Token.OPEN_PARENS;
2646 lambda_arguments_parsing = true;
2648 d = TokenizeOpenParens ();
2650 lambda_arguments_parsing = false;
2654 return Token.OPEN_PARENS;
2656 return Token.CLOSE_PARENS;
2660 return Token.SEMICOLON;
2664 return TokenizePossibleNullableType ();
2666 if (parsing_generic_less_than++ > 0)
2667 return Token.OP_GENERICS_LT;
2669 return TokenizeLessThan ();
2679 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2680 parsing_generic_less_than--;
2681 return Token.OP_GENERICS_GT;
2690 return Token.OP_SHIFT_RIGHT_ASSIGN;
2692 return Token.OP_SHIFT_RIGHT;
2701 } else if (d == '=') {
2702 d = Token.OP_ADD_ASSIGN;
2713 } else if (d == '=')
2714 d = Token.OP_SUB_ASSIGN;
2724 if (peek_char () == '='){
2741 return Token.ASSIGN;
2747 return Token.OP_AND;
2751 return Token.OP_AND_ASSIGN;
2753 return Token.BITWISE_AND;
2763 return Token.OP_OR_ASSIGN;
2765 return Token.BITWISE_OR;
2768 if (peek_char () == '='){
2770 return Token.OP_MULT_ASSIGN;
2772 val = LocatedToken.Create (ref_line, col);
2779 return Token.OP_DIV_ASSIGN;
2782 // Handle double-slash comments.
2785 if (RootContext.Documentation != null && peek_char () == '/') {
2787 // Don't allow ////.
2788 if ((d = peek_char ()) != '/') {
2789 update_comment_location ();
2790 if (doc_state == XmlCommentState.Allowed)
2791 handle_one_line_xml_comment ();
2792 else if (doc_state == XmlCommentState.NotAllowed)
2793 warn_incorrect_doc_comment ();
2796 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2798 any_token_seen |= tokens_seen;
2799 tokens_seen = false;
2800 comments_seen = false;
2802 } else if (d == '*'){
2804 bool docAppend = false;
2805 if (RootContext.Documentation != null && peek_char () == '*') {
2807 update_comment_location ();
2808 // But when it is /**/, just do nothing.
2809 if (peek_char () == '/') {
2813 if (doc_state == XmlCommentState.Allowed)
2815 else if (doc_state == XmlCommentState.NotAllowed)
2816 warn_incorrect_doc_comment ();
2819 int current_comment_start = 0;
2821 current_comment_start = xml_comment_buffer.Length;
2822 xml_comment_buffer.Append (Environment.NewLine);
2825 while ((d = get_char ()) != -1){
2826 if (d == '*' && peek_char () == '/'){
2828 comments_seen = true;
2832 xml_comment_buffer.Append ((char) d);
2835 any_token_seen |= tokens_seen;
2836 tokens_seen = false;
2838 // Reset 'comments_seen' just to be consistent.
2839 // It doesn't matter either way, here.
2841 comments_seen = false;
2845 Report.Error (1035, Location, "End-of-file found, '*/' expected");
2848 update_formatted_doc_comment (current_comment_start);
2854 if (peek_char () == '='){
2856 return Token.OP_MOD_ASSIGN;
2858 return Token.PERCENT;
2861 if (peek_char () == '='){
2863 return Token.OP_XOR_ASSIGN;
2865 return Token.CARRET;
2868 if (peek_char () == ':') {
2870 return Token.DOUBLE_COLON;
2874 case '0': case '1': case '2': case '3': case '4':
2875 case '5': case '6': case '7': case '8': case '9':
2877 return is_number (c);
2879 case '\n': // white space
2880 any_token_seen |= tokens_seen;
2881 tokens_seen = false;
2882 comments_seen = false;
2888 if (d >= '0' && d <= '9')
2889 return is_number (c);
2893 if (tokens_seen || comments_seen) {
2894 Eror_WrongPreprocessorLocation ();
2898 if (handle_preprocessing_directive (true))
2901 bool directive_expected = false;
2902 while ((c = get_char ()) != -1) {
2904 directive_expected = true;
2905 } else if (!directive_expected) {
2906 // TODO: Implement comment support for disabled code and uncomment this code
2908 // Eror_WrongPreprocessorLocation ();
2909 // return Token.ERROR;
2914 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2918 if (handle_preprocessing_directive (false))
2921 directive_expected = false;
2925 tokens_seen = false;
2932 return consume_string (false);
2935 return TokenizeBackslash ();
2941 return consume_string (true);
2944 if (is_identifier_start_character (c)){
2945 return consume_identifier (c, true);
2948 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2951 case EvalStatementParserCharacter:
2952 return Token.EVAL_STATEMENT_PARSER;
2953 case EvalCompilationUnitParserCharacter:
2954 return Token.EVAL_COMPILATION_UNIT_PARSER;
2955 case EvalUsingDeclarationsParserCharacter:
2956 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2959 if (is_identifier_start_character (c)) {
2961 return consume_identifier (c);
2964 error_details = ((char)c).ToString ();
2970 return Token.COMPLETE_COMPLETION;
2973 return Token.GENERATE_COMPLETION;
2980 int TokenizeBackslash ()
2982 int c = get_char ();
2985 error_details = "Empty character literal";
2986 Report.Error (1011, Location, error_details);
2989 if (c == '\r' || c == '\n') {
2990 Report.Error (1010, Location, "Newline in constant");
2995 c = escape (c, out d);
2999 throw new NotImplementedException ();
3001 val = new CharLiteral ((char) c, Location);
3005 Report.Error (1012, Location, "Too many characters in character literal");
3007 // Try to recover, read until newline or next "'"
3008 while ((c = get_char ()) != -1) {
3009 if (c == '\n' || c == '\'')
3015 return Token.LITERAL;
3018 int TokenizeLessThan ()
3021 if (handle_typeof) {
3023 if (parse_generic_dimension (out d)) {
3026 return Token.GENERIC_DIMENSION;
3031 // Save current position and parse next token.
3033 if (parse_less_than ()) {
3034 if (parsing_generic_declaration && token () != Token.DOT) {
3035 d = Token.OP_GENERICS_LT_DECL;
3037 d = Token.OP_GENERICS_LT;
3044 parsing_generic_less_than = 0;
3053 return Token.OP_SHIFT_LEFT_ASSIGN;
3055 return Token.OP_SHIFT_LEFT;
3066 // Handles one line xml comment
3068 private void handle_one_line_xml_comment ()
3071 while ((c = peek_char ()) == ' ')
3072 get_char (); // skip heading whitespaces.
3073 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3074 xml_comment_buffer.Append ((char) get_char ());
3076 if (c == '\r' || c == '\n')
3077 xml_comment_buffer.Append (Environment.NewLine);
3081 // Remove heading "*" in Javadoc-like xml documentation.
3083 private void update_formatted_doc_comment (int current_comment_start)
3085 int length = xml_comment_buffer.Length - current_comment_start;
3086 string [] lines = xml_comment_buffer.ToString (
3087 current_comment_start,
3088 length).Replace ("\r", "").Split ('\n');
3090 // The first line starts with /**, thus it is not target
3091 // for the format check.
3092 for (int i = 1; i < lines.Length; i++) {
3093 string s = lines [i];
3094 int idx = s.IndexOf ('*');
3097 if (i < lines.Length - 1)
3101 head = s.Substring (0, idx);
3102 foreach (char c in head)
3105 lines [i] = s.Substring (idx + 1);
3107 xml_comment_buffer.Remove (current_comment_start, length);
3108 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3112 // Updates current comment location.
3114 private void update_comment_location ()
3116 if (current_comment_location.IsNull) {
3117 // "-2" is for heading "//" or "/*"
3118 current_comment_location =
3119 new Location (ref_line, hidden ? -1 : col - 2);
3124 // Checks if there was incorrect doc comments and raise
3127 public void check_incorrect_doc_comment ()
3129 if (xml_comment_buffer.Length > 0)
3130 warn_incorrect_doc_comment ();
3134 // Raises a warning when tokenizer found incorrect doccomment
3137 private void warn_incorrect_doc_comment ()
3139 if (doc_state != XmlCommentState.Error) {
3140 doc_state = XmlCommentState.Error;
3141 // in csc, it is 'XML comment is not placed on
3142 // a valid language element'. But that does not
3144 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3149 // Consumes the saved xml comment lines (if any)
3150 // as for current target member or type.
3152 public string consume_doc_comment ()
3154 if (xml_comment_buffer.Length > 0) {
3155 string ret = xml_comment_buffer.ToString ();
3156 reset_doc_comment ();
3163 get { return context.Report; }
3166 void reset_doc_comment ()
3168 xml_comment_buffer.Length = 0;
3169 current_comment_location = Location.Null;
3172 public void cleanup ()
3174 if (ifstack != null && ifstack.Count >= 1) {
3175 int state = (int) ifstack.Pop ();
3176 if ((state & REGION) != 0)
3177 Report.Error (1038, Location, "#endregion directive expected");
3179 Report.Error (1027, Location, "Expected `#endif' directive");
3185 // Indicates whether it accepts XML documentation or not.
3187 public enum XmlCommentState {
3188 // comment is allowed in this state.
3190 // comment is not allowed in this state.
3192 // once comments appeared when it is NotAllowed, then the
3193 // state is changed to it, until the state is changed to