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;
19 using System.Globalization;
20 using System.Reflection;
25 /// Tokenizer for C# source code.
28 public class Tokenizer : yyParser.yyInput
30 SeekableStreamReader reader;
32 CompilationUnit file_name;
39 bool handle_get_set = false;
40 bool handle_remove_add = false;
41 bool handle_where = false;
42 bool handle_typeof = false;
43 bool lambda_arguments_parsing;
44 Location current_location;
45 Location current_comment_location = Location.Null;
46 ArrayList escaped_identifiers = new ArrayList ();
49 // Used mainly for parser optimizations. Some expressions for instance
50 // can appear only in block (including initializer, base initializer)
53 public int parsing_block;
54 internal int query_parsing;
57 // Set when parsing generic declaration (type or method header)
59 public bool parsing_generic_declaration;
62 // The value indicates that we have not reach any declaration or
65 public int parsing_declaration;
68 // The special character to inject on streams to trigger the EXPRESSION_PARSE
69 // token to be returned. It just happens to be a Unicode character that
70 // would never be part of a program (can not be an identifier).
72 // This character is only tested just before the tokenizer is about to report
73 // an error; So on the regular operation mode, this addition will have no
74 // impact on the tokenizer's performance.
77 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
78 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
79 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
82 // XML documentation buffer. The save point is used to divide
83 // comments on types and comments on members.
85 StringBuilder xml_comment_buffer;
88 // See comment on XmlCommentState enumeration.
90 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
93 // Whether tokens have been seen on this line
95 bool tokens_seen = false;
98 // Whether a token has been seen on the file
99 // This is needed because `define' is not allowed to be used
100 // after a token has been seen.
102 bool any_token_seen = false;
104 static Hashtable token_values;
105 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
107 private static Hashtable TokenValueName
110 if (token_values == null)
111 token_values = GetTokenValueNameHash ();
117 private static Hashtable GetTokenValueNameHash ()
119 Type t = typeof (Token);
120 FieldInfo [] fields = t.GetFields ();
121 Hashtable hash = new Hashtable ();
122 foreach (FieldInfo field in fields) {
123 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
124 hash.Add (field.GetValue (null), field.Name);
130 // Returns a verbose representation of the current location
132 public string location {
136 if (current_token == Token.ERROR)
137 det = "detail: " + error_details;
141 // return "Line: "+line+" Col: "+col + "\n" +
142 // "VirtLine: "+ref_line +
143 // " Token: "+current_token + " " + det;
144 string current_token_name = TokenValueName [current_token] as string;
145 if (current_token_name == null)
146 current_token_name = current_token.ToString ();
148 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
156 public bool PropertyParsing {
157 get { return handle_get_set; }
158 set { handle_get_set = value; }
161 public bool EventParsing {
162 get { return handle_remove_add; }
163 set { handle_remove_add = value; }
166 public bool ConstraintsParsing {
167 get { return handle_where; }
168 set { handle_where = value; }
171 public bool TypeOfParsing {
172 get { return handle_typeof; }
173 set { handle_typeof = value; }
176 public XmlCommentState doc_state {
177 get { return xml_doc_state; }
179 if (value == XmlCommentState.Allowed) {
180 check_incorrect_doc_comment ();
181 reset_doc_comment ();
183 xml_doc_state = value;
187 public bool IsEscapedIdentifier (Location loc)
189 foreach (LocatedToken lt in escaped_identifiers)
190 if (lt.Location.Equals (loc))
198 static CharArrayHashtable[] keywords;
199 static Hashtable keyword_strings;
200 static NumberStyles styles;
201 static NumberFormatInfo csharp_format_info;
204 // Values for the associated token returned
206 internal int putback_char; // Used by repl only
212 const int TAKING = 1;
213 const int ELSE_SEEN = 4;
214 const int PARENT_TAKING = 8;
215 const int REGION = 16;
218 // pre-processor if stack state:
222 static System.Text.StringBuilder string_builder;
224 const int max_id_size = 512;
225 static char [] id_builder = new char [max_id_size];
227 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
229 const int max_number_size = 512;
230 static char [] number_builder = new char [max_number_size];
231 static int number_pos;
234 // Details about the error encoutered by the tokenizer
236 string error_details;
238 public string error {
240 return error_details;
257 // This is used when the tokenizer needs to save
258 // the current position as it needs to do some parsing
259 // on its own to deamiguate a token in behalf of the
262 Stack position_stack = new Stack (2);
269 public int putback_char;
270 public int previous_col;
271 public Stack ifstack;
272 public int parsing_generic_less_than;
273 public int current_token;
275 public Position (Tokenizer t)
277 position = t.reader.Position;
279 ref_line = t.ref_line;
282 putback_char = t.putback_char;
283 previous_col = t.previous_col;
284 if (t.ifstack != null && t.ifstack.Count != 0)
285 ifstack = (Stack)t.ifstack.Clone ();
286 parsing_generic_less_than = t.parsing_generic_less_than;
287 current_token = t.current_token;
291 public void PushPosition ()
293 position_stack.Push (new Position (this));
296 public void PopPosition ()
298 Position p = (Position) position_stack.Pop ();
300 reader.Position = p.position;
301 ref_line = p.ref_line;
305 putback_char = p.putback_char;
306 previous_col = p.previous_col;
308 parsing_generic_less_than = p.parsing_generic_less_than;
309 current_token = p.current_token;
312 // Do not reset the position, ignore it.
313 public void DiscardPosition ()
315 position_stack.Pop ();
318 static void AddKeyword (string kw, int token)
320 keyword_strings.Add (kw, kw);
321 if (keywords [kw.Length] == null) {
322 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
324 keywords [kw.Length] [kw.ToCharArray ()] = token;
327 static void InitTokens ()
329 keyword_strings = new Hashtable ();
330 keywords = new CharArrayHashtable [64];
332 AddKeyword ("__arglist", Token.ARGLIST);
333 AddKeyword ("abstract", Token.ABSTRACT);
334 AddKeyword ("as", Token.AS);
335 AddKeyword ("add", Token.ADD);
336 AddKeyword ("base", Token.BASE);
337 AddKeyword ("bool", Token.BOOL);
338 AddKeyword ("break", Token.BREAK);
339 AddKeyword ("byte", Token.BYTE);
340 AddKeyword ("case", Token.CASE);
341 AddKeyword ("catch", Token.CATCH);
342 AddKeyword ("char", Token.CHAR);
343 AddKeyword ("checked", Token.CHECKED);
344 AddKeyword ("class", Token.CLASS);
345 AddKeyword ("const", Token.CONST);
346 AddKeyword ("continue", Token.CONTINUE);
347 AddKeyword ("decimal", Token.DECIMAL);
348 AddKeyword ("default", Token.DEFAULT);
349 AddKeyword ("delegate", Token.DELEGATE);
350 AddKeyword ("do", Token.DO);
351 AddKeyword ("double", Token.DOUBLE);
352 AddKeyword ("else", Token.ELSE);
353 AddKeyword ("enum", Token.ENUM);
354 AddKeyword ("event", Token.EVENT);
355 AddKeyword ("explicit", Token.EXPLICIT);
356 AddKeyword ("extern", Token.EXTERN);
357 AddKeyword ("false", Token.FALSE);
358 AddKeyword ("finally", Token.FINALLY);
359 AddKeyword ("fixed", Token.FIXED);
360 AddKeyword ("float", Token.FLOAT);
361 AddKeyword ("for", Token.FOR);
362 AddKeyword ("foreach", Token.FOREACH);
363 AddKeyword ("goto", Token.GOTO);
364 AddKeyword ("get", Token.GET);
365 AddKeyword ("if", Token.IF);
366 AddKeyword ("implicit", Token.IMPLICIT);
367 AddKeyword ("in", Token.IN);
368 AddKeyword ("int", Token.INT);
369 AddKeyword ("interface", Token.INTERFACE);
370 AddKeyword ("internal", Token.INTERNAL);
371 AddKeyword ("is", Token.IS);
372 AddKeyword ("lock", Token.LOCK);
373 AddKeyword ("long", Token.LONG);
374 AddKeyword ("namespace", Token.NAMESPACE);
375 AddKeyword ("new", Token.NEW);
376 AddKeyword ("null", Token.NULL);
377 AddKeyword ("object", Token.OBJECT);
378 AddKeyword ("operator", Token.OPERATOR);
379 AddKeyword ("out", Token.OUT);
380 AddKeyword ("override", Token.OVERRIDE);
381 AddKeyword ("params", Token.PARAMS);
382 AddKeyword ("private", Token.PRIVATE);
383 AddKeyword ("protected", Token.PROTECTED);
384 AddKeyword ("public", Token.PUBLIC);
385 AddKeyword ("readonly", Token.READONLY);
386 AddKeyword ("ref", Token.REF);
387 AddKeyword ("remove", Token.REMOVE);
388 AddKeyword ("return", Token.RETURN);
389 AddKeyword ("sbyte", Token.SBYTE);
390 AddKeyword ("sealed", Token.SEALED);
391 AddKeyword ("set", Token.SET);
392 AddKeyword ("short", Token.SHORT);
393 AddKeyword ("sizeof", Token.SIZEOF);
394 AddKeyword ("stackalloc", Token.STACKALLOC);
395 AddKeyword ("static", Token.STATIC);
396 AddKeyword ("string", Token.STRING);
397 AddKeyword ("struct", Token.STRUCT);
398 AddKeyword ("switch", Token.SWITCH);
399 AddKeyword ("this", Token.THIS);
400 AddKeyword ("throw", Token.THROW);
401 AddKeyword ("true", Token.TRUE);
402 AddKeyword ("try", Token.TRY);
403 AddKeyword ("typeof", Token.TYPEOF);
404 AddKeyword ("uint", Token.UINT);
405 AddKeyword ("ulong", Token.ULONG);
406 AddKeyword ("unchecked", Token.UNCHECKED);
407 AddKeyword ("unsafe", Token.UNSAFE);
408 AddKeyword ("ushort", Token.USHORT);
409 AddKeyword ("using", Token.USING);
410 AddKeyword ("virtual", Token.VIRTUAL);
411 AddKeyword ("void", Token.VOID);
412 AddKeyword ("volatile", Token.VOLATILE);
413 AddKeyword ("while", Token.WHILE);
414 AddKeyword ("partial", Token.PARTIAL);
415 AddKeyword ("where", Token.WHERE);
418 AddKeyword ("from", Token.FROM);
419 AddKeyword ("join", Token.JOIN);
420 AddKeyword ("on", Token.ON);
421 AddKeyword ("equals", Token.EQUALS);
422 AddKeyword ("select", Token.SELECT);
423 AddKeyword ("group", Token.GROUP);
424 AddKeyword ("by", Token.BY);
425 AddKeyword ("let", Token.LET);
426 AddKeyword ("orderby", Token.ORDERBY);
427 AddKeyword ("ascending", Token.ASCENDING);
428 AddKeyword ("descending", Token.DESCENDING);
429 AddKeyword ("into", Token.INTO);
440 public static void Reset ()
443 csharp_format_info = NumberFormatInfo.InvariantInfo;
444 styles = NumberStyles.Float;
446 string_builder = new System.Text.StringBuilder ();
449 int GetKeyword (char[] id, int id_len)
452 * Keywords are stored in an array of hashtables grouped by their
456 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
458 object o = keywords [id_len] [id];
465 if (!handle_get_set && (res == Token.GET || res == Token.SET))
467 if (!handle_remove_add && (res == Token.REMOVE || res == Token.ADD))
469 if (parsing_declaration == 0 && res == Token.EXTERN)
470 return Token.EXTERN_ALIAS;
473 // A query expression is any expression that starts with `from identifier'
474 // followed by any token except ; , =
476 if (query_parsing == 0) {
477 if (res == Token.FROM && !lambda_arguments_parsing) {
479 // HACK: to disable generics micro-parser, because PushPosition does not
480 // store identifiers array
481 parsing_generic_less_than = 1;
483 case Token.IDENTIFIER:
495 int next_token = xtoken ();
496 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
500 if (RootContext.Version <= LanguageVersion.ISO_2)
501 Report.FeatureIsNotAvailable (Location, "query expressions");
504 Expression.Error_VoidInvalidInTheContext (Location);
508 // HACK: A token is not a keyword so we need to restore identifiers buffer
509 // which has been overwritten before we grabbed the identifier
510 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
517 if (res > Token.QUERY_FIRST_TOKEN && res < Token.QUERY_LAST_TOKEN)
521 if (res == Token.WHERE && !handle_where && query_parsing == 0)
527 public Location Location {
528 get { return current_location; }
531 public Tokenizer (SeekableStreamReader input, CompilationUnit file)
533 this.ref_name = file;
534 this.file_name = file;
539 xml_comment_buffer = new StringBuilder ();
542 // FIXME: This could be `Location.Push' but we have to
543 // find out why the MS compiler allows this
545 Mono.CSharp.Location.Push (file, file);
548 static bool is_identifier_start_character (char c)
550 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter (c);
553 static bool is_identifier_part_character (char c)
555 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') ||
556 Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
559 public static bool IsKeyword (string s)
561 return keyword_strings [s] != null;
565 // Open parens micro parser. Detects both lambda and cast ambiguity.
568 int TokenizeOpenParens ()
572 bool cast_posible = false;
573 bool cast_not = false;
574 bool has_star = false;
581 case Token.CLOSE_PARENS:
587 if (ntoken == Token.ARROW) {
588 if (RootContext.Version <= LanguageVersion.ISO_2)
589 Report.FeatureIsNotAvailable (Location, "lambda expressions");
591 return Token.OPEN_PARENS_LAMBDA;
595 // Token is possible cast, parser will decide later
597 if (cast_posible && !cast_not) {
600 // Indirection is a special
604 case Token.BITWISE_AND:
611 return Token.OPEN_PARENS_CAST;
613 case Token.OPEN_PARENS:
616 case Token.IDENTIFIER:
617 case Token.LITERAL_INTEGER:
618 case Token.LITERAL_FLOAT:
619 case Token.LITERAL_DOUBLE:
620 case Token.LITERAL_DECIMAL:
621 case Token.LITERAL_CHARACTER:
622 case Token.LITERAL_STRING:
635 case Token.UNCHECKED:
640 // These can be part of a member access
653 return Token.OPEN_PARENS_CAST;
656 return Token.OPEN_PARENS;
659 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
663 case Token.IDENTIFIER:
666 case Token.OP_GENERICS_LT:
668 case Token.DOUBLE_COLON:
697 case Token.OP_GENERICS_GT:
698 case Token.OP_GENERICS_LT:
699 case Token.INTERR_NULLABLE:
700 case Token.OPEN_BRACKET:
701 case Token.CLOSE_BRACKET:
703 case Token.DOUBLE_COLON:
713 return Token.OPEN_PARENS;
718 public static bool IsValidIdentifier (string s)
720 if (s == null || s.Length == 0)
723 if (!is_identifier_start_character (s [0]))
726 for (int i = 1; i < s.Length; i ++)
727 if (! is_identifier_part_character (s [i]))
733 bool parse_less_than ()
736 int the_token = token ();
737 if (the_token == Token.OPEN_BRACKET) {
739 the_token = token ();
740 } while (the_token != Token.CLOSE_BRACKET);
741 the_token = token ();
744 case Token.IDENTIFIER:
763 case Token.OP_GENERICS_GT:
770 the_token = token ();
772 if (the_token == Token.OP_GENERICS_GT)
774 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
776 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
778 else if (the_token == Token.OP_GENERICS_LT) {
779 if (!parse_less_than ())
782 } else if (the_token == Token.OPEN_BRACKET) {
784 the_token = token ();
785 if (the_token == Token.CLOSE_BRACKET)
787 else if (the_token == Token.COMMA)
788 goto rank_specifiers;
795 bool parse_generic_dimension (out int dimension)
800 int the_token = token ();
801 if (the_token == Token.OP_GENERICS_GT)
803 else if (the_token == Token.COMMA) {
811 public int peek_token ()
816 the_token = token ();
822 int parsing_generic_less_than = 0;
824 int is_punct (char c, ref bool doread)
834 return Token.OPEN_BRACE;
837 return Token.CLOSE_BRACE;
839 // To block doccomment inside attribute declaration.
840 if (doc_state == XmlCommentState.Allowed)
841 doc_state = XmlCommentState.NotAllowed;
842 return Token.OPEN_BRACKET;
844 return Token.CLOSE_BRACKET;
848 // An expression versions of parens can appear in block context only
850 if (parsing_block != 0 && !lambda_arguments_parsing) {
851 lambda_arguments_parsing = true;
853 t = TokenizeOpenParens ();
855 lambda_arguments_parsing = false;
859 return Token.OPEN_PARENS;
861 return Token.CLOSE_PARENS;
866 return Token.SEMICOLON;
871 return TokenizePossibleNullableType ();
875 if (parsing_generic_less_than++ > 0)
876 return Token.OP_GENERICS_LT;
881 if (parse_generic_dimension (out dimension)) {
884 return Token.GENERIC_DIMENSION;
889 // Save current position and parse next token.
891 bool is_generic_lt = parse_less_than ();
894 if (parsing_generic_declaration && token () != Token.DOT) {
895 rt = Token.OP_GENERICS_LT_DECL;
897 rt = Token.OP_GENERICS_LT;
904 parsing_generic_less_than = 0;
913 return Token.OP_SHIFT_LEFT_ASSIGN;
915 return Token.OP_SHIFT_LEFT;
916 } else if (d == '='){
921 } else if (c == '>') {
929 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
930 parsing_generic_less_than--;
931 return Token.OP_GENERICS_GT;
940 return Token.OP_SHIFT_RIGHT_ASSIGN;
942 return Token.OP_SHIFT_RIGHT;
956 t = Token.OP_ADD_ASSIGN;
970 t = Token.OP_SUB_ASSIGN;
1001 return Token.ASSIGN;
1007 return Token.OP_AND;
1008 } else if (d == '='){
1010 return Token.OP_AND_ASSIGN;
1013 return Token.BITWISE_AND;
1020 } else if (d == '='){
1022 return Token.OP_OR_ASSIGN;
1024 return Token.BITWISE_OR;
1030 return Token.OP_MULT_ASSIGN;
1039 return Token.OP_DIV_ASSIGN;
1047 return Token.OP_MOD_ASSIGN;
1049 return Token.PERCENT;
1055 return Token.OP_XOR_ASSIGN;
1057 return Token.CARRET;
1063 return Token.DOUBLE_COLON;
1073 // Tonizes `?' using custom disambiguous rules to return one
1074 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1076 // Tricky expression look like:
1078 // Foo ? a = x ? b : c;
1080 int TokenizePossibleNullableType ()
1082 if (parsing_block == 0)
1083 return Token.INTERR_NULLABLE;
1085 int d = peek_char ();
1088 return Token.OP_COALESCING;
1091 switch (current_token) {
1092 case Token.CLOSE_PARENS:
1096 case Token.LITERAL_INTEGER:
1097 case Token.LITERAL_STRING:
1098 return Token.INTERR;
1102 if (d == ',' || d == ';' || d == '>')
1103 return Token.INTERR_NULLABLE;
1104 if (d == '*' || (d >= '0' && d <= '9'))
1105 return Token.INTERR;
1110 switch (xtoken ()) {
1111 case Token.LITERAL_INTEGER:
1112 case Token.LITERAL_STRING:
1113 case Token.LITERAL_CHARACTER:
1114 case Token.LITERAL_DECIMAL:
1115 case Token.LITERAL_DOUBLE:
1116 case Token.LITERAL_FLOAT:
1121 next_token = Token.INTERR;
1124 case Token.SEMICOLON:
1126 case Token.CLOSE_PARENS:
1127 case Token.OPEN_BRACKET:
1128 case Token.OP_GENERICS_GT:
1129 next_token = Token.INTERR_NULLABLE;
1137 if (next_token == -1) {
1138 switch (xtoken ()) {
1140 case Token.SEMICOLON:
1141 case Token.OPEN_BRACE:
1142 case Token.CLOSE_PARENS:
1144 next_token = Token.INTERR_NULLABLE;
1148 next_token = Token.INTERR;
1156 // All shorcuts failed, do it hard way
1158 while ((ntoken = xtoken ()) != Token.EOF) {
1159 if (ntoken == Token.SEMICOLON)
1162 if (ntoken == Token.COLON) {
1163 if (++colons == interrs)
1168 if (ntoken == Token.INTERR) {
1174 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1183 bool decimal_digits (int c)
1186 bool seen_digits = false;
1189 if (number_pos == max_number_size)
1190 Error_NumericConstantTooLong ();
1191 number_builder [number_pos++] = (char) c;
1195 // We use peek_char2, because decimal_digits needs to do a
1196 // 2-character look-ahead (5.ToString for example).
1198 while ((d = peek_char2 ()) != -1){
1199 if (d >= '0' && d <= '9'){
1200 if (number_pos == max_number_size)
1201 Error_NumericConstantTooLong ();
1202 number_builder [number_pos++] = (char) d;
1212 static bool is_hex (int e)
1214 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1217 static int real_type_suffix (int c)
1223 t = Token.LITERAL_FLOAT;
1226 t = Token.LITERAL_DOUBLE;
1229 t= Token.LITERAL_DECIMAL;
1237 int integer_type_suffix (ulong ul, int c)
1239 bool is_unsigned = false;
1240 bool is_long = false;
1243 bool scanning = true;
1256 // if we have not seen anything in between
1257 // report this error
1259 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1262 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1263 // work around that.
1287 if (is_long && is_unsigned){
1289 return Token.LITERAL_INTEGER;
1290 } else if (is_unsigned){
1291 // uint if possible, or ulong else.
1293 if ((ul & 0xffffffff00000000) == 0)
1297 } else if (is_long){
1298 // long if possible, ulong otherwise
1299 if ((ul & 0x8000000000000000) != 0)
1304 // int, uint, long or ulong in that order
1305 if ((ul & 0xffffffff00000000) == 0){
1306 uint ui = (uint) ul;
1308 if ((ui & 0x80000000) != 0)
1313 if ((ul & 0x8000000000000000) != 0)
1319 return Token.LITERAL_INTEGER;
1323 // given `c' as the next char in the input decide whether
1324 // we need to convert to a special type, and then choose
1325 // the best representation for the integer
1327 int adjust_int (int c)
1330 if (number_pos > 9){
1331 ulong ul = (uint) (number_builder [0] - '0');
1333 for (int i = 1; i < number_pos; i++){
1334 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1336 return integer_type_suffix (ul, c);
1338 uint ui = (uint) (number_builder [0] - '0');
1340 for (int i = 1; i < number_pos; i++){
1341 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1343 return integer_type_suffix (ui, c);
1345 } catch (OverflowException) {
1346 error_details = "Integral constant is too large";
1347 Report.Error (1021, Location, error_details);
1349 return Token.LITERAL_INTEGER;
1351 catch (FormatException) {
1352 Report.Error (1013, Location, "Invalid number");
1354 return Token.LITERAL_INTEGER;
1358 int adjust_real (int t)
1360 string s = new String (number_builder, 0, number_pos);
1361 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1364 case Token.LITERAL_DECIMAL:
1366 val = System.Decimal.Parse (s, styles, csharp_format_info);
1367 } catch (OverflowException) {
1369 Report.Error (594, Location, error_details, "decimal");
1372 case Token.LITERAL_FLOAT:
1374 val = float.Parse (s, styles, csharp_format_info);
1375 } catch (OverflowException) {
1377 Report.Error (594, Location, error_details, "float");
1381 case Token.LITERAL_DOUBLE:
1383 t = Token.LITERAL_DOUBLE;
1385 val = System.Double.Parse (s, styles, csharp_format_info);
1386 } catch (OverflowException) {
1388 Report.Error (594, Location, error_details, "double");
1401 while ((d = peek_char ()) != -1){
1403 number_builder [number_pos++] = (char) d;
1409 string s = new String (number_builder, 0, number_pos);
1411 if (number_pos <= 8)
1412 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1414 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1415 } catch (OverflowException){
1416 error_details = "Integral constant is too large";
1417 Report.Error (1021, Location, error_details);
1419 return Token.LITERAL_INTEGER;
1421 catch (FormatException) {
1422 Report.Error (1013, Location, "Invalid number");
1424 return Token.LITERAL_INTEGER;
1427 return integer_type_suffix (ul, peek_char ());
1431 // Invoked if we know we have .digits or digits
1433 int is_number (int c)
1435 bool is_real = false;
1440 if (c >= '0' && c <= '9'){
1442 int peek = peek_char ();
1444 if (peek == 'x' || peek == 'X')
1445 return handle_hex ();
1452 // We need to handle the case of
1453 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1456 if (decimal_digits ('.')){
1462 return adjust_int (-1);
1466 if (c == 'e' || c == 'E'){
1468 if (number_pos == max_number_size)
1469 Error_NumericConstantTooLong ();
1470 number_builder [number_pos++] = 'e';
1474 if (number_pos == max_number_size)
1475 Error_NumericConstantTooLong ();
1476 number_builder [number_pos++] = '+';
1478 } else if (c == '-') {
1479 if (number_pos == max_number_size)
1480 Error_NumericConstantTooLong ();
1481 number_builder [number_pos++] = '-';
1484 if (number_pos == max_number_size)
1485 Error_NumericConstantTooLong ();
1486 number_builder [number_pos++] = '+';
1493 type = real_type_suffix (c);
1494 if (type == Token.NONE && !is_real){
1496 return adjust_int (c);
1500 if (type == Token.NONE){
1505 return adjust_real (type);
1507 Console.WriteLine ("This should not be reached");
1508 throw new Exception ("Is Number should never reach this point");
1512 // Accepts exactly count (4 or 8) hex, no more no less
1514 int getHex (int count, out int surrogate, out bool error)
1519 int top = count != -1 ? count : 4;
1524 for (i = 0; i < top; i++){
1527 if (c >= '0' && c <= '9')
1528 c = (int) c - (int) '0';
1529 else if (c >= 'A' && c <= 'F')
1530 c = (int) c - (int) 'A' + 10;
1531 else if (c >= 'a' && c <= 'f')
1532 c = (int) c - (int) 'a' + 10;
1538 total = (total * 16) + c;
1540 int p = peek_char ();
1543 if (!is_hex ((char)p))
1549 if (total > 0x0010FFFF) {
1554 if (total >= 0x00010000) {
1555 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1556 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1563 int escape (int c, out int surrogate)
1599 v = getHex (-1, out surrogate, out error);
1605 return EscapeUnicode (d, out surrogate);
1608 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1617 int EscapeUnicode (int ch, out int surrogate)
1621 ch = getHex (8, out surrogate, out error);
1623 ch = getHex (4, out surrogate, out error);
1627 Report.Error (1009, Location, "Unrecognized escape sequence");
1635 if (putback_char != -1) {
1648 void advance_line ()
1658 if (putback_char != -1)
1659 return putback_char;
1660 putback_char = reader.Read ();
1661 return putback_char;
1666 if (putback_char != -1)
1667 return putback_char;
1668 return reader.Peek ();
1671 void putback (int c)
1673 if (putback_char != -1){
1674 Console.WriteLine ("Col: " + col);
1675 Console.WriteLine ("Row: " + line);
1676 Console.WriteLine ("Name: " + ref_name.Name);
1677 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1678 throw new Exception ("This should not happen putback on putback");
1680 if (c == '\n' || col == 0) {
1681 // It won't happen though.
1691 public bool advance ()
1693 return peek_char () != -1;
1696 public Object Value {
1702 public Object value ()
1709 current_token = xtoken ();
1711 if (current_token != Token.DEFAULT)
1712 return current_token;
1717 current_token = Token.ERROR;
1718 else if (c == Token.COLON)
1719 current_token = Token.DEFAULT_COLON;
1723 return current_token;
1726 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1728 void get_cmd_arg (out string cmd, out string arg)
1732 tokens_seen = false;
1735 // skip over white space
1738 } while (c == '\r' || c == ' ' || c == '\t');
1740 static_cmd_arg.Length = 0;
1741 while (c != -1 && is_identifier_part_character ((char)c)) {
1742 static_cmd_arg.Append ((char)c);
1745 int peek = peek_char ();
1746 if (peek == 'U' || peek == 'u') {
1748 c = EscapeUnicode (c, out surrogate);
1749 if (surrogate != 0) {
1750 if (is_identifier_part_character ((char) c))
1751 static_cmd_arg.Append ((char) c);
1758 cmd = static_cmd_arg.ToString ();
1760 // skip over white space
1761 while (c == '\r' || c == ' ' || c == '\t')
1764 static_cmd_arg.Length = 0;
1765 while (c != -1 && c != '\n' && c != '\r') {
1767 int peek = peek_char ();
1768 if (peek == 'U' || peek == 'u') {
1770 c = EscapeUnicode (c, out surrogate);
1771 if (surrogate != 0) {
1772 if (is_identifier_part_character ((char) c))
1773 static_cmd_arg.Append ((char) c);
1778 static_cmd_arg.Append ((char) c);
1782 if (static_cmd_arg.Length != 0)
1783 arg = static_cmd_arg.ToString ();
1787 // Handles the #line directive
1789 bool PreProcessLine (string arg)
1791 if (arg.Length == 0)
1794 if (arg == "default"){
1796 ref_name = file_name;
1798 Location.Push (file_name, ref_name);
1800 } else if (arg == "hidden"){
1808 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1809 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1812 char [] quotes = { '\"' };
1814 string name = arg.Substring (pos). Trim (quotes);
1815 ref_name = Location.LookupFile (file_name, name);
1816 file_name.AddFile (ref_name);
1818 Location.Push (file_name, ref_name);
1820 ref_line = System.Int32.Parse (arg);
1831 // Handles #define and #undef
1833 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1835 if (ident.Length == 0 || ident == "true" || ident == "false"){
1836 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1840 if (ident.IndexOfAny (simple_whitespaces) != -1){
1841 Error_EndLineExpected ();
1845 if (!is_identifier_start_character (ident [0]))
1846 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1848 foreach (char c in ident.Substring (1)){
1849 if (!is_identifier_part_character (c)){
1850 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1855 if (!caller_is_taking)
1862 if (RootContext.IsConditionalDefined (ident))
1865 file_name.AddDefine (ident);
1870 file_name.AddUndefine (ident);
1874 static byte read_hex (string arg, int pos, out bool error)
1881 if ((c >= '0') && (c <= '9'))
1882 total = (int) c - (int) '0';
1883 else if ((c >= 'A') && (c <= 'F'))
1884 total = (int) c - (int) 'A' + 10;
1885 else if ((c >= 'a') && (c <= 'f'))
1886 total = (int) c - (int) 'a' + 10;
1895 if ((c >= '0') && (c <= '9'))
1896 total += (int) c - (int) '0';
1897 else if ((c >= 'A') && (c <= 'F'))
1898 total += (int) c - (int) 'A' + 10;
1899 else if ((c >= 'a') && (c <= 'f'))
1900 total += (int) c - (int) 'a' + 10;
1906 return (byte) total;
1910 /// Handles #pragma checksum
1912 bool PreProcessPragmaChecksum (string arg)
1914 if ((arg [0] != ' ') && (arg [0] != '\t'))
1917 arg = arg.Trim (simple_whitespaces);
1918 if ((arg.Length < 2) || (arg [0] != '"'))
1921 StringBuilder file_sb = new StringBuilder ();
1925 while ((ch = arg [pos++]) != '"') {
1926 if (pos >= arg.Length)
1930 if (pos+1 >= arg.Length)
1935 file_sb.Append (ch);
1938 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1941 arg = arg.Substring (pos).Trim (simple_whitespaces);
1942 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1943 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1944 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1948 byte[] guid_bytes = new byte [16];
1950 for (int i = 0; i < 4; i++) {
1951 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1955 for (int i = 0; i < 2; i++) {
1956 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1959 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1962 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1967 for (int i = 0; i < 6; i++) {
1968 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1973 arg = arg.Substring (40).Trim (simple_whitespaces);
1974 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1977 byte[] checksum_bytes = new byte [16];
1978 for (int i = 0; i < 16; i++) {
1979 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1984 arg = arg.Substring (34).Trim (simple_whitespaces);
1988 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1989 file.SetChecksum (guid_bytes, checksum_bytes);
1990 ref_name.AutoGenerated = true;
1995 /// Handles #pragma directive
1997 void PreProcessPragma (string arg)
1999 const string warning = "warning";
2000 const string w_disable = "warning disable";
2001 const string w_restore = "warning restore";
2002 const string checksum = "checksum";
2004 if (arg == w_disable) {
2005 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
2009 if (arg == w_restore) {
2010 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
2014 if (arg.StartsWith (w_disable)) {
2015 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
2016 foreach (int code in codes) {
2018 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
2023 if (arg.StartsWith (w_restore)) {
2024 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
2025 Hashtable w_table = Report.warning_ignore_table;
2026 foreach (int code in codes) {
2027 if (w_table != null && w_table.Contains (code))
2028 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
2029 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
2034 if (arg.StartsWith (warning)) {
2035 Report.Warning (1634, 1, Location, "Expected disable or restore");
2039 if (arg.StartsWith (checksum)) {
2040 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
2041 Warning_InvalidPragmaChecksum ();
2045 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2048 int[] ParseNumbers (string text)
2050 string[] string_array = text.Split (',');
2051 int[] values = new int [string_array.Length];
2053 foreach (string string_code in string_array) {
2055 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
2057 catch (FormatException) {
2058 Report.Warning (1692, 1, Location, "Invalid number");
2064 bool eval_val (string s)
2071 return file_name.IsConditionalDefined (s);
2074 bool pp_primary (ref string s)
2083 s = s.Substring (1);
2084 bool val = pp_expr (ref s, false);
2085 if (s.Length > 0 && s [0] == ')'){
2086 s = s.Substring (1);
2089 Error_InvalidDirective ();
2093 if (is_identifier_start_character (c)){
2099 if (is_identifier_part_character (c)){
2103 bool v = eval_val (s.Substring (0, j));
2104 s = s.Substring (j);
2107 bool vv = eval_val (s);
2112 Error_InvalidDirective ();
2116 bool pp_unary (ref string s)
2123 if (len > 1 && s [1] == '='){
2124 Error_InvalidDirective ();
2127 s = s.Substring (1);
2128 return ! pp_primary (ref s);
2130 return pp_primary (ref s);
2132 Error_InvalidDirective ();
2137 bool pp_eq (ref string s)
2139 bool va = pp_unary (ref s);
2145 if (len > 2 && s [1] == '='){
2146 s = s.Substring (2);
2147 return va == pp_unary (ref s);
2149 Error_InvalidDirective ();
2152 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2153 s = s.Substring (2);
2155 return va != pp_unary (ref s);
2164 bool pp_and (ref string s)
2166 bool va = pp_eq (ref s);
2172 if (len > 2 && s [1] == '&'){
2173 s = s.Substring (2);
2174 return (va & pp_and (ref s));
2176 Error_InvalidDirective ();
2185 // Evaluates an expression for `#if' or `#elif'
2187 bool pp_expr (ref string s, bool isTerm)
2189 bool va = pp_and (ref s);
2196 if (len > 2 && s [1] == '|'){
2197 s = s.Substring (2);
2198 return va | pp_expr (ref s, isTerm);
2200 Error_InvalidDirective ();
2205 Error_EndLineExpected ();
2213 bool eval (string s)
2215 bool v = pp_expr (ref s, true);
2224 void Error_NumericConstantTooLong ()
2226 Report.Error (1021, Location, "Numeric constant too long");
2229 void Error_InvalidDirective ()
2231 Report.Error (1517, Location, "Invalid preprocessor directive");
2234 void Error_UnexpectedDirective (string extra)
2238 "Unexpected processor directive ({0})", extra);
2241 void Error_TokensSeen ()
2243 Report.Error (1032, Location,
2244 "Cannot define or undefine preprocessor symbols after first token in file");
2247 void Eror_WrongPreprocessorLocation ()
2249 Report.Error (1040, Location,
2250 "Preprocessor directives must appear as the first non-whitespace character on a line");
2253 void Error_EndLineExpected ()
2255 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2258 void Warning_InvalidPragmaChecksum ()
2260 Report.Warning (1695, 1, Location,
2261 "Invalid #pragma checksum syntax; should be " +
2262 "#pragma checksum \"filename\" " +
2263 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2266 // if true, then the code continues processing the code
2267 // if false, the code stays in a loop until another directive is
2269 // When caller_is_taking is false we ignore all directives except the ones
2270 // which can help us to identify where the #if block ends
2271 bool handle_preprocessing_directive (bool caller_is_taking)
2274 bool region_directive = false;
2276 get_cmd_arg (out cmd, out arg);
2278 // Eat any trailing whitespaces and single-line comments
2279 if (arg.IndexOf ("//") != -1)
2280 arg = arg.Substring (0, arg.IndexOf ("//"));
2281 arg = arg.Trim (simple_whitespaces);
2284 // The first group of pre-processing instructions is always processed
2288 region_directive = true;
2293 if (ifstack == null || ifstack.Count == 0){
2294 Error_UnexpectedDirective ("no #region for this #endregion");
2297 int pop = (int) ifstack.Pop ();
2299 if ((pop & REGION) == 0)
2300 Report.Error (1027, Location, "Expected `#endif' directive");
2302 return caller_is_taking;
2305 if (ifstack == null)
2306 ifstack = new Stack (2);
2308 int flags = region_directive ? REGION : 0;
2309 if (ifstack.Count == 0){
2310 flags |= PARENT_TAKING;
2312 int state = (int) ifstack.Peek ();
2313 if ((state & TAKING) != 0) {
2314 flags |= PARENT_TAKING;
2318 if (caller_is_taking && eval (arg)) {
2319 ifstack.Push (flags | TAKING);
2322 ifstack.Push (flags);
2326 if (ifstack == null || ifstack.Count == 0){
2327 Error_UnexpectedDirective ("no #if for this #endif");
2330 pop = (int) ifstack.Pop ();
2332 if ((pop & REGION) != 0)
2333 Report.Error (1038, Location, "#endregion directive expected");
2335 if (arg.Length != 0) {
2336 Error_EndLineExpected ();
2339 if (ifstack.Count == 0)
2342 int state = (int) ifstack.Peek ();
2343 return (state & TAKING) != 0;
2347 if (ifstack == null || ifstack.Count == 0){
2348 Error_UnexpectedDirective ("no #if for this #elif");
2351 int state = (int) ifstack.Pop ();
2353 if ((state & REGION) != 0) {
2354 Report.Error (1038, Location, "#endregion directive expected");
2358 if ((state & ELSE_SEEN) != 0){
2359 Error_UnexpectedDirective ("#elif not valid after #else");
2363 if ((state & TAKING) != 0) {
2368 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2369 ifstack.Push (state | TAKING);
2373 ifstack.Push (state);
2378 if (ifstack == null || ifstack.Count == 0){
2379 Error_UnexpectedDirective ("no #if for this #else");
2382 int state = (int) ifstack.Peek ();
2384 if ((state & REGION) != 0) {
2385 Report.Error (1038, Location, "#endregion directive expected");
2389 if ((state & ELSE_SEEN) != 0){
2390 Error_UnexpectedDirective ("#else within #else");
2396 if (arg.Length != 0) {
2397 Error_EndLineExpected ();
2402 if ((state & PARENT_TAKING) != 0) {
2403 ret = (state & TAKING) == 0;
2411 ifstack.Push (state | ELSE_SEEN);
2416 if (any_token_seen){
2417 Error_TokensSeen ();
2418 return caller_is_taking;
2420 PreProcessDefinition (true, arg, caller_is_taking);
2421 return caller_is_taking;
2424 if (any_token_seen){
2425 Error_TokensSeen ();
2426 return caller_is_taking;
2428 PreProcessDefinition (false, arg, caller_is_taking);
2429 return caller_is_taking;
2433 // These are only processed if we are in a `taking' block
2435 if (!caller_is_taking)
2440 Report.Error (1029, Location, "#error: '{0}'", arg);
2444 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2448 if (RootContext.Version == LanguageVersion.ISO_1) {
2449 Report.FeatureIsNotAvailable (Location, "#pragma");
2453 PreProcessPragma (arg);
2457 if (!PreProcessLine (arg))
2460 "The line number specified for #line directive is missing or invalid");
2461 return caller_is_taking;
2464 Report.Error (1024, Location, "Wrong preprocessor directive");
2469 private int consume_string (bool quoted)
2472 string_builder.Length = 0;
2475 // No need to parse full string when parsing lambda arguments
2477 if (lambda_arguments_parsing)
2478 return Token.LITERAL_STRING;
2480 while ((c = get_char ()) != -1){
2482 if (quoted && peek_char () == '"'){
2483 string_builder.Append ((char) c);
2487 val = string_builder.ToString ();
2488 return Token.LITERAL_STRING;
2494 Report.Error (1010, Location, "Newline in constant");
2499 c = escape (c, out surrogate);
2502 if (surrogate != 0) {
2503 string_builder.Append ((char) c);
2507 string_builder.Append ((char) c);
2510 Report.Error (1039, Location, "Unterminated string literal");
2514 private int consume_identifier (int s)
2516 int res = consume_identifier (s, false);
2518 if (doc_state == XmlCommentState.Allowed)
2519 doc_state = XmlCommentState.NotAllowed;
2522 case Token.NAMESPACE:
2523 check_incorrect_doc_comment ();
2527 if (res == Token.PARTIAL) {
2528 if (parsing_block > 0) {
2529 val = new LocatedToken (Location, "partial");
2530 return Token.IDENTIFIER;
2533 // Save current position and parse next token.
2536 int next_token = token ();
2537 bool ok = (next_token == Token.CLASS) ||
2538 (next_token == Token.STRUCT) ||
2539 (next_token == Token.INTERFACE) ||
2540 (next_token == Token.VOID);
2545 if (next_token == Token.VOID) {
2546 if (RootContext.Version == LanguageVersion.ISO_1 ||
2547 RootContext.Version == LanguageVersion.ISO_2)
2548 Report.FeatureIsNotAvailable (Location, "partial methods");
2549 } else if (RootContext.Version == LanguageVersion.ISO_1)
2550 Report.FeatureIsNotAvailable (Location, "partial types");
2555 if (next_token < Token.LAST_KEYWORD) {
2556 Report.Error (267, Location,
2557 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
2561 val = new LocatedToken (Location, "partial");
2562 return Token.IDENTIFIER;
2568 private int consume_identifier (int c, bool quoted)
2574 c = escape (c, out surrogate);
2575 if (surrogate != 0) {
2576 id_builder [pos++] = (char) c;
2581 id_builder [pos++] = (char) c;
2582 current_location = new Location (ref_line, hidden ? -1 : Col);
2584 while ((c = get_char ()) != -1) {
2586 if (is_identifier_part_character ((char) c)){
2587 if (pos == max_id_size){
2588 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2592 id_builder [pos++] = (char) c;
2593 // putback_char = -1;
2594 } else if (c == '\\') {
2596 c = escape (c, out surrogate);
2597 if (surrogate != 0) {
2598 if (is_identifier_part_character ((char) c))
2599 id_builder [pos++] = (char) c;
2604 // putback_char = c;
2611 // Optimization: avoids doing the keyword lookup
2612 // on uppercase letters
2614 if (id_builder [0] >= '_' && !quoted) {
2615 int keyword = GetKeyword (id_builder, pos);
2616 if (keyword != -1) {
2623 // Keep identifiers in an array of hashtables to avoid needless
2627 if (identifiers [pos] != null) {
2628 val = identifiers [pos][id_builder];
2630 val = new LocatedToken (Location, (string) val);
2632 escaped_identifiers.Add (val);
2633 return Token.IDENTIFIER;
2637 identifiers [pos] = new CharArrayHashtable (pos);
2639 val = new String (id_builder, 0, pos);
2640 if (RootContext.Version == LanguageVersion.ISO_1) {
2641 for (int i = 1; i < id_builder.Length; i += 3) {
2642 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2643 Report.Error (1638, Location,
2644 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2650 char [] chars = new char [pos];
2651 Array.Copy (id_builder, chars, pos);
2653 identifiers [pos] [chars] = val;
2655 val = new LocatedToken (Location, (string) val);
2657 escaped_identifiers.Add (val);
2658 return Token.IDENTIFIER;
2661 public int xtoken ()
2664 bool doread = false;
2667 // Whether we have seen comments on the current line
2668 bool comments_seen = false;
2670 for (;(c = get_char ()) != -1;) {
2672 col = ((col + 8) / 8) * 8;
2676 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0 || c == 0)
2680 if (peek_char () != '\n')
2685 any_token_seen |= tokens_seen;
2686 tokens_seen = false;
2687 comments_seen = false;
2691 // Handle double-slash comments.
2693 int d = peek_char ();
2697 if (RootContext.Documentation != null && peek_char () == '/') {
2699 // Don't allow ////.
2700 if ((d = peek_char ()) != '/') {
2701 update_comment_location ();
2702 if (doc_state == XmlCommentState.Allowed)
2703 handle_one_line_xml_comment ();
2704 else if (doc_state == XmlCommentState.NotAllowed)
2705 warn_incorrect_doc_comment ();
2708 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2710 any_token_seen |= tokens_seen;
2711 tokens_seen = false;
2712 comments_seen = false;
2714 } else if (d == '*'){
2716 bool docAppend = false;
2717 if (RootContext.Documentation != null && peek_char () == '*') {
2719 update_comment_location ();
2720 // But when it is /**/, just do nothing.
2721 if (peek_char () == '/') {
2725 if (doc_state == XmlCommentState.Allowed)
2727 else if (doc_state == XmlCommentState.NotAllowed)
2728 warn_incorrect_doc_comment ();
2731 int current_comment_start = 0;
2733 current_comment_start = xml_comment_buffer.Length;
2734 xml_comment_buffer.Append (Environment.NewLine);
2737 Location start_location = Location;
2739 while ((d = get_char ()) != -1){
2740 if (d == '*' && peek_char () == '/'){
2742 comments_seen = true;
2746 xml_comment_buffer.Append ((char) d);
2749 any_token_seen |= tokens_seen;
2750 tokens_seen = false;
2752 // Reset 'comments_seen' just to be consistent.
2753 // It doesn't matter either way, here.
2755 comments_seen = false;
2759 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2762 update_formatted_doc_comment (current_comment_start);
2765 goto is_punct_label;
2769 if (c == '\\' || is_identifier_start_character ((char)c)){
2771 return consume_identifier (c);
2775 current_location = new Location (ref_line, hidden ? -1 : Col);
2776 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2786 any_token_seen |= tokens_seen;
2787 tokens_seen = false;
2788 comments_seen = false;
2792 if (c >= '0' && c <= '9'){
2794 return is_number (c);
2799 int peek = peek_char ();
2800 if (peek >= '0' && peek <= '9')
2801 return is_number (c);
2806 if (tokens_seen || comments_seen) {
2807 Eror_WrongPreprocessorLocation ();
2811 if (handle_preprocessing_directive (true))
2814 bool directive_expected = false;
2815 while ((c = get_char ()) != -1) {
2817 directive_expected = true;
2818 } else if (!directive_expected) {
2819 // TODO: Implement comment support for disabled code and uncomment this code
2821 // Eror_WrongPreprocessorLocation ();
2822 // return Token.ERROR;
2827 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2831 if (handle_preprocessing_directive (false))
2834 directive_expected = false;
2838 tokens_seen = false;
2846 return consume_string (false);
2852 error_details = "Empty character literal";
2853 Report.Error (1011, Location, error_details);
2856 if (c == '\r' || c == '\n') {
2857 Report.Error (1010, Location, "Newline in constant");
2862 c = escape (c, out surrogate);
2866 throw new NotImplementedException ();
2872 error_details = "Too many characters in character literal";
2873 Report.Error (1012, Location, error_details);
2875 // Try to recover, read until newline or next "'"
2876 while ((c = get_char ()) != -1){
2885 return Token.LITERAL_CHARACTER;
2892 return consume_string (true);
2893 } else if (is_identifier_start_character ((char) c)){
2894 return consume_identifier (c, true);
2896 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2900 if (c == EvalStatementParserCharacter)
2901 return Token.EVAL_STATEMENT_PARSER;
2902 if (c == EvalCompilationUnitParserCharacter)
2903 return Token.EVAL_COMPILATION_UNIT_PARSER;
2904 if (c == EvalUsingDeclarationsParserCharacter)
2905 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2907 error_details = ((char)c).ToString ();
2916 // Handles one line xml comment
2918 private void handle_one_line_xml_comment ()
2921 while ((c = peek_char ()) == ' ')
2922 get_char (); // skip heading whitespaces.
2923 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2924 xml_comment_buffer.Append ((char) get_char ());
2926 if (c == '\r' || c == '\n')
2927 xml_comment_buffer.Append (Environment.NewLine);
2931 // Remove heading "*" in Javadoc-like xml documentation.
2933 private void update_formatted_doc_comment (int current_comment_start)
2935 int length = xml_comment_buffer.Length - current_comment_start;
2936 string [] lines = xml_comment_buffer.ToString (
2937 current_comment_start,
2938 length).Replace ("\r", "").Split ('\n');
2940 // The first line starts with /**, thus it is not target
2941 // for the format check.
2942 for (int i = 1; i < lines.Length; i++) {
2943 string s = lines [i];
2944 int idx = s.IndexOf ('*');
2947 if (i < lines.Length - 1)
2951 head = s.Substring (0, idx);
2952 foreach (char c in head)
2955 lines [i] = s.Substring (idx + 1);
2957 xml_comment_buffer.Remove (current_comment_start, length);
2958 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2962 // Updates current comment location.
2964 private void update_comment_location ()
2966 if (current_comment_location.IsNull) {
2967 // "-2" is for heading "//" or "/*"
2968 current_comment_location =
2969 new Location (ref_line, hidden ? -1 : col - 2);
2974 // Checks if there was incorrect doc comments and raise
2977 public void check_incorrect_doc_comment ()
2979 if (xml_comment_buffer.Length > 0)
2980 warn_incorrect_doc_comment ();
2984 // Raises a warning when tokenizer found incorrect doccomment
2987 private void warn_incorrect_doc_comment ()
2989 if (doc_state != XmlCommentState.Error) {
2990 doc_state = XmlCommentState.Error;
2991 // in csc, it is 'XML comment is not placed on
2992 // a valid language element'. But that does not
2994 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2999 // Consumes the saved xml comment lines (if any)
3000 // as for current target member or type.
3002 public string consume_doc_comment ()
3004 if (xml_comment_buffer.Length > 0) {
3005 string ret = xml_comment_buffer.ToString ();
3006 reset_doc_comment ();
3012 void reset_doc_comment ()
3014 xml_comment_buffer.Length = 0;
3015 current_comment_location = Location.Null;
3018 public void cleanup ()
3020 if (ifstack != null && ifstack.Count >= 1) {
3021 current_location = new Location (ref_line, hidden ? -1 : Col);
3022 int state = (int) ifstack.Pop ();
3023 if ((state & REGION) != 0)
3024 Report.Error (1038, Location, "#endregion directive expected");
3026 Report.Error (1027, Location, "Expected `#endif' directive");
3032 // Indicates whether it accepts XML documentation or not.
3034 public enum XmlCommentState {
3035 // comment is allowed in this state.
3037 // comment is not allowed in this state.
3039 // once comments appeared when it is NotAllowed, then the
3040 // state is changed to it, until the state is changed to