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_assembly = false;
42 bool handle_where = false;
43 bool handle_typeof = false;
44 bool lambda_arguments_parsing;
45 Location current_location;
46 Location current_comment_location = Location.Null;
47 ArrayList escaped_identifiers = new ArrayList ();
50 // Used mainly for parser optimizations. Some expressions for instance
51 // can appear only in block (including initializer, base initializer)
54 public int parsing_block;
55 internal int query_parsing;
58 // Set when parsing generic declaration (type or method header)
60 public bool parsing_generic_declaration;
63 // The special character to inject on streams to trigger the EXPRESSION_PARSE
64 // token to be returned. It just happens to be a Unicode character that
65 // would never be part of a program (can not be an identifier).
67 // This character is only tested just before the tokenizer is about to report
68 // an error; So on the regular operation mode, this addition will have no
69 // impact on the tokenizer's performance.
72 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
73 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
74 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
77 // XML documentation buffer. The save point is used to divide
78 // comments on types and comments on members.
80 StringBuilder xml_comment_buffer;
83 // See comment on XmlCommentState enumeration.
85 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
88 // Whether tokens have been seen on this line
90 bool tokens_seen = false;
93 // Whether a token has been seen on the file
94 // This is needed because `define' is not allowed to be used
95 // after a token has been seen.
97 bool any_token_seen = false;
99 static Hashtable token_values;
100 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
102 private static Hashtable TokenValueName
105 if (token_values == null)
106 token_values = GetTokenValueNameHash ();
112 private static Hashtable GetTokenValueNameHash ()
114 Type t = typeof (Token);
115 FieldInfo [] fields = t.GetFields ();
116 Hashtable hash = new Hashtable ();
117 foreach (FieldInfo field in fields) {
118 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
119 hash.Add (field.GetValue (null), field.Name);
125 // Returns a verbose representation of the current location
127 public string location {
131 if (current_token == Token.ERROR)
132 det = "detail: " + error_details;
136 // return "Line: "+line+" Col: "+col + "\n" +
137 // "VirtLine: "+ref_line +
138 // " Token: "+current_token + " " + det;
139 string current_token_name = TokenValueName [current_token] as string;
140 if (current_token_name == null)
141 current_token_name = current_token.ToString ();
143 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
151 public bool PropertyParsing {
152 get { return handle_get_set; }
153 set { handle_get_set = value; }
156 public bool AssemblyTargetParsing {
157 get { return handle_assembly; }
158 set { handle_assembly = 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 ("assembly", Token.ASSEMBLY);
337 AddKeyword ("base", Token.BASE);
338 AddKeyword ("bool", Token.BOOL);
339 AddKeyword ("break", Token.BREAK);
340 AddKeyword ("byte", Token.BYTE);
341 AddKeyword ("case", Token.CASE);
342 AddKeyword ("catch", Token.CATCH);
343 AddKeyword ("char", Token.CHAR);
344 AddKeyword ("checked", Token.CHECKED);
345 AddKeyword ("class", Token.CLASS);
346 AddKeyword ("const", Token.CONST);
347 AddKeyword ("continue", Token.CONTINUE);
348 AddKeyword ("decimal", Token.DECIMAL);
349 AddKeyword ("default", Token.DEFAULT);
350 AddKeyword ("delegate", Token.DELEGATE);
351 AddKeyword ("do", Token.DO);
352 AddKeyword ("double", Token.DOUBLE);
353 AddKeyword ("else", Token.ELSE);
354 AddKeyword ("enum", Token.ENUM);
355 AddKeyword ("event", Token.EVENT);
356 AddKeyword ("explicit", Token.EXPLICIT);
357 AddKeyword ("extern", Token.EXTERN);
358 AddKeyword ("false", Token.FALSE);
359 AddKeyword ("finally", Token.FINALLY);
360 AddKeyword ("fixed", Token.FIXED);
361 AddKeyword ("float", Token.FLOAT);
362 AddKeyword ("for", Token.FOR);
363 AddKeyword ("foreach", Token.FOREACH);
364 AddKeyword ("goto", Token.GOTO);
365 AddKeyword ("get", Token.GET);
366 AddKeyword ("if", Token.IF);
367 AddKeyword ("implicit", Token.IMPLICIT);
368 AddKeyword ("in", Token.IN);
369 AddKeyword ("int", Token.INT);
370 AddKeyword ("interface", Token.INTERFACE);
371 AddKeyword ("internal", Token.INTERNAL);
372 AddKeyword ("is", Token.IS);
373 AddKeyword ("lock", Token.LOCK);
374 AddKeyword ("long", Token.LONG);
375 AddKeyword ("namespace", Token.NAMESPACE);
376 AddKeyword ("new", Token.NEW);
377 AddKeyword ("null", Token.NULL);
378 AddKeyword ("object", Token.OBJECT);
379 AddKeyword ("operator", Token.OPERATOR);
380 AddKeyword ("out", Token.OUT);
381 AddKeyword ("override", Token.OVERRIDE);
382 AddKeyword ("params", Token.PARAMS);
383 AddKeyword ("private", Token.PRIVATE);
384 AddKeyword ("protected", Token.PROTECTED);
385 AddKeyword ("public", Token.PUBLIC);
386 AddKeyword ("readonly", Token.READONLY);
387 AddKeyword ("ref", Token.REF);
388 AddKeyword ("remove", Token.REMOVE);
389 AddKeyword ("return", Token.RETURN);
390 AddKeyword ("sbyte", Token.SBYTE);
391 AddKeyword ("sealed", Token.SEALED);
392 AddKeyword ("set", Token.SET);
393 AddKeyword ("short", Token.SHORT);
394 AddKeyword ("sizeof", Token.SIZEOF);
395 AddKeyword ("stackalloc", Token.STACKALLOC);
396 AddKeyword ("static", Token.STATIC);
397 AddKeyword ("string", Token.STRING);
398 AddKeyword ("struct", Token.STRUCT);
399 AddKeyword ("switch", Token.SWITCH);
400 AddKeyword ("this", Token.THIS);
401 AddKeyword ("throw", Token.THROW);
402 AddKeyword ("true", Token.TRUE);
403 AddKeyword ("try", Token.TRY);
404 AddKeyword ("typeof", Token.TYPEOF);
405 AddKeyword ("uint", Token.UINT);
406 AddKeyword ("ulong", Token.ULONG);
407 AddKeyword ("unchecked", Token.UNCHECKED);
408 AddKeyword ("unsafe", Token.UNSAFE);
409 AddKeyword ("ushort", Token.USHORT);
410 AddKeyword ("using", Token.USING);
411 AddKeyword ("virtual", Token.VIRTUAL);
412 AddKeyword ("void", Token.VOID);
413 AddKeyword ("volatile", Token.VOLATILE);
414 AddKeyword ("while", Token.WHILE);
415 AddKeyword ("partial", Token.PARTIAL);
416 AddKeyword ("where", Token.WHERE);
419 AddKeyword ("from", Token.FROM);
420 AddKeyword ("join", Token.JOIN);
421 AddKeyword ("on", Token.ON);
422 AddKeyword ("equals", Token.EQUALS);
423 AddKeyword ("select", Token.SELECT);
424 AddKeyword ("group", Token.GROUP);
425 AddKeyword ("by", Token.BY);
426 AddKeyword ("let", Token.LET);
427 AddKeyword ("orderby", Token.ORDERBY);
428 AddKeyword ("ascending", Token.ASCENDING);
429 AddKeyword ("descending", Token.DESCENDING);
430 AddKeyword ("into", Token.INTO);
441 public static void Reset ()
444 csharp_format_info = NumberFormatInfo.InvariantInfo;
445 styles = NumberStyles.Float;
447 string_builder = new System.Text.StringBuilder ();
450 int GetKeyword (char[] id, int id_len)
453 * Keywords are stored in an array of hashtables grouped by their
457 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
459 object o = keywords [id_len] [id];
466 if (!handle_get_set && (res == Token.GET || res == Token.SET))
468 if (!handle_remove_add && (res == Token.REMOVE || res == Token.ADD))
470 if (!handle_assembly && res == Token.ASSEMBLY)
474 // A query expression is any expression that starts with `from identifier'
475 // followed by any token except ; , =
477 if (query_parsing == 0) {
478 if (res == Token.FROM && !lambda_arguments_parsing) {
480 // HACK: to disable generics micro-parser, because PushPosition does not
481 // store identifiers array
482 parsing_generic_less_than = 1;
484 case Token.IDENTIFIER:
496 int next_token = xtoken ();
497 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
501 if (RootContext.Version <= LanguageVersion.ISO_2)
502 Report.FeatureIsNotAvailable (Location, "query expressions");
505 Expression.Error_VoidInvalidInTheContext (Location);
509 // HACK: A token is not a keyword so we need to restore identifiers buffer
510 // which has been overwritten before we grabbed the identifier
511 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
518 if (res > Token.QUERY_FIRST_TOKEN && res < Token.QUERY_LAST_TOKEN)
522 if (res == Token.WHERE && !handle_where && query_parsing == 0)
528 public Location Location {
529 get { return current_location; }
532 public Tokenizer (SeekableStreamReader input, CompilationUnit file)
534 this.ref_name = file;
535 this.file_name = file;
540 xml_comment_buffer = new StringBuilder ();
543 // FIXME: This could be `Location.Push' but we have to
544 // find out why the MS compiler allows this
546 Mono.CSharp.Location.Push (file, file);
549 static bool is_identifier_start_character (char c)
551 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter (c);
554 static bool is_identifier_part_character (char c)
556 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') ||
557 Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
560 public static bool IsKeyword (string s)
562 return keyword_strings [s] != null;
566 // Tests whether '(' is beggining of lambda parameters
568 bool IsLambdaOpenParens ()
571 while ((ntoken = xtoken ()) != Token.EOF) {
573 case Token.CLOSE_PARENS:
574 return xtoken () == Token.ARROW;
577 case Token.SEMICOLON:
578 case Token.OPEN_BRACE:
579 case Token.OPEN_PARENS:
580 case Token.LITERAL_STRING:
581 case Token.LITERAL_INTEGER:
582 case Token.LITERAL_FLOAT:
583 case Token.LITERAL_DOUBLE:
584 case Token.LITERAL_DECIMAL:
585 case Token.LITERAL_CHARACTER:
591 case Token.OP_SHIFT_LEFT:
592 case Token.OP_SHIFT_RIGHT:
599 case Token.BITWISE_AND:
600 case Token.BITWISE_OR:
612 Error_TokenExpected (",' or `)");
616 public static bool IsValidIdentifier (string s)
618 if (s == null || s.Length == 0)
621 if (!is_identifier_start_character (s [0]))
624 for (int i = 1; i < s.Length; i ++)
625 if (! is_identifier_part_character (s [i]))
631 bool parse_less_than ()
634 int the_token = token ();
635 if (the_token == Token.OPEN_BRACKET) {
637 the_token = token ();
638 } while (the_token != Token.CLOSE_BRACKET);
639 the_token = token ();
642 case Token.IDENTIFIER:
661 case Token.OP_GENERICS_GT:
668 the_token = token ();
670 if (the_token == Token.OP_GENERICS_GT)
672 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
674 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
676 else if (the_token == Token.OP_GENERICS_LT) {
677 if (!parse_less_than ())
680 } else if (the_token == Token.OPEN_BRACKET) {
682 the_token = token ();
683 if (the_token == Token.CLOSE_BRACKET)
685 else if (the_token == Token.COMMA)
686 goto rank_specifiers;
693 bool parse_generic_dimension (out int dimension)
698 int the_token = token ();
699 if (the_token == Token.OP_GENERICS_GT)
701 else if (the_token == Token.COMMA) {
709 public int peek_token ()
714 the_token = token ();
720 int parsing_generic_less_than = 0;
722 int is_punct (char c, ref bool doread)
732 return Token.OPEN_BRACE;
735 return Token.CLOSE_BRACE;
737 // To block doccomment inside attribute declaration.
738 if (doc_state == XmlCommentState.Allowed)
739 doc_state = XmlCommentState.NotAllowed;
740 return Token.OPEN_BRACKET;
742 return Token.CLOSE_BRACKET;
745 // A lambda expression can appear in block context only
747 if (parsing_block != 0 && !lambda_arguments_parsing) {
748 lambda_arguments_parsing = true;
750 bool lambda_start = IsLambdaOpenParens ();
752 lambda_arguments_parsing = false;
754 if (RootContext.Version <= LanguageVersion.ISO_2)
755 Report.FeatureIsNotAvailable (Location, "lambda expressions");
757 return Token.OPEN_PARENS_LAMBDA;
760 return Token.OPEN_PARENS;
762 if (deambiguate_close_parens == 0)
763 return Token.CLOSE_PARENS;
765 --deambiguate_close_parens;
769 int new_token = xtoken ();
773 if (new_token == Token.OPEN_PARENS)
774 return Token.CLOSE_PARENS_OPEN_PARENS;
775 else if (new_token == Token.MINUS)
776 return Token.CLOSE_PARENS_MINUS;
777 else if (IsCastToken (new_token))
778 return Token.CLOSE_PARENS_CAST;
780 return Token.CLOSE_PARENS_NO_CAST;
787 return Token.SEMICOLON;
792 return TokenizePossibleNullableType ();
796 if (parsing_generic_less_than++ > 0)
797 return Token.OP_GENERICS_LT;
802 if (parse_generic_dimension (out dimension)) {
805 return Token.GENERIC_DIMENSION;
810 // Save current position and parse next token.
812 bool is_generic_lt = parse_less_than ();
815 if (parsing_generic_declaration && token () != Token.DOT) {
816 rt = Token.OP_GENERICS_LT_DECL;
818 rt = Token.OP_GENERICS_LT;
825 parsing_generic_less_than = 0;
834 return Token.OP_SHIFT_LEFT_ASSIGN;
836 return Token.OP_SHIFT_LEFT;
837 } else if (d == '='){
842 } else if (c == '>') {
850 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
851 parsing_generic_less_than--;
852 return Token.OP_GENERICS_GT;
861 return Token.OP_SHIFT_RIGHT_ASSIGN;
863 return Token.OP_SHIFT_RIGHT;
877 t = Token.OP_ADD_ASSIGN;
891 t = Token.OP_SUB_ASSIGN;
929 } else if (d == '='){
931 return Token.OP_AND_ASSIGN;
934 return Token.BITWISE_AND;
941 } else if (d == '='){
943 return Token.OP_OR_ASSIGN;
945 return Token.BITWISE_OR;
951 return Token.OP_MULT_ASSIGN;
960 return Token.OP_DIV_ASSIGN;
968 return Token.OP_MOD_ASSIGN;
970 return Token.PERCENT;
976 return Token.OP_XOR_ASSIGN;
984 return Token.DOUBLE_COLON;
994 // Tonizes `?' using custom disambiguous rules to return one
995 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
997 // Tricky expression look like:
999 // Foo ? a = x ? b : c;
1001 int TokenizePossibleNullableType ()
1003 if (parsing_block == 0)
1004 return Token.INTERR_NULLABLE;
1006 int d = peek_char ();
1009 return Token.OP_COALESCING;
1012 switch (current_token) {
1013 case Token.CLOSE_PARENS:
1017 case Token.LITERAL_INTEGER:
1018 case Token.LITERAL_STRING:
1019 return Token.INTERR;
1023 if (d == ',' || d == ';' || d == '>')
1024 return Token.INTERR_NULLABLE;
1025 if (d == '*' || (d >= '0' && d <= '9'))
1026 return Token.INTERR;
1031 switch (xtoken ()) {
1032 case Token.LITERAL_INTEGER:
1033 case Token.LITERAL_STRING:
1034 case Token.LITERAL_CHARACTER:
1035 case Token.LITERAL_DECIMAL:
1036 case Token.LITERAL_DOUBLE:
1037 case Token.LITERAL_FLOAT:
1042 next_token = Token.INTERR;
1045 case Token.SEMICOLON:
1047 case Token.CLOSE_PARENS:
1048 case Token.OPEN_BRACKET:
1049 case Token.OP_GENERICS_GT:
1050 next_token = Token.INTERR_NULLABLE;
1058 if (next_token == -1) {
1059 switch (xtoken ()) {
1061 case Token.SEMICOLON:
1062 case Token.OPEN_BRACE:
1063 case Token.CLOSE_PARENS:
1065 next_token = Token.INTERR_NULLABLE;
1069 next_token = Token.INTERR;
1077 // All shorcuts failed, do it hard way
1079 while ((ntoken = xtoken ()) != Token.EOF) {
1080 if (ntoken == Token.SEMICOLON)
1083 if (ntoken == Token.COLON) {
1084 if (++colons == interrs)
1089 if (ntoken == Token.INTERR) {
1095 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1104 int deambiguate_close_parens = 0;
1106 public void Deambiguate_CloseParens (object expression)
1110 // When any binary operation, a conditional is used we are sure it is not a cast
1113 if (expression is Binary || expression is Conditional)
1116 deambiguate_close_parens++;
1119 bool decimal_digits (int c)
1122 bool seen_digits = false;
1125 if (number_pos == max_number_size)
1126 Error_NumericConstantTooLong ();
1127 number_builder [number_pos++] = (char) c;
1131 // We use peek_char2, because decimal_digits needs to do a
1132 // 2-character look-ahead (5.ToString for example).
1134 while ((d = peek_char2 ()) != -1){
1135 if (d >= '0' && d <= '9'){
1136 if (number_pos == max_number_size)
1137 Error_NumericConstantTooLong ();
1138 number_builder [number_pos++] = (char) d;
1148 static bool is_hex (int e)
1150 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1153 static int real_type_suffix (int c)
1159 t = Token.LITERAL_FLOAT;
1162 t = Token.LITERAL_DOUBLE;
1165 t= Token.LITERAL_DECIMAL;
1173 int integer_type_suffix (ulong ul, int c)
1175 bool is_unsigned = false;
1176 bool is_long = false;
1179 bool scanning = true;
1192 // if we have not seen anything in between
1193 // report this error
1195 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1198 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1199 // work around that.
1223 if (is_long && is_unsigned){
1225 return Token.LITERAL_INTEGER;
1226 } else if (is_unsigned){
1227 // uint if possible, or ulong else.
1229 if ((ul & 0xffffffff00000000) == 0)
1233 } else if (is_long){
1234 // long if possible, ulong otherwise
1235 if ((ul & 0x8000000000000000) != 0)
1240 // int, uint, long or ulong in that order
1241 if ((ul & 0xffffffff00000000) == 0){
1242 uint ui = (uint) ul;
1244 if ((ui & 0x80000000) != 0)
1249 if ((ul & 0x8000000000000000) != 0)
1255 return Token.LITERAL_INTEGER;
1259 // given `c' as the next char in the input decide whether
1260 // we need to convert to a special type, and then choose
1261 // the best representation for the integer
1263 int adjust_int (int c)
1266 if (number_pos > 9){
1267 ulong ul = (uint) (number_builder [0] - '0');
1269 for (int i = 1; i < number_pos; i++){
1270 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1272 return integer_type_suffix (ul, c);
1274 uint ui = (uint) (number_builder [0] - '0');
1276 for (int i = 1; i < number_pos; i++){
1277 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1279 return integer_type_suffix (ui, c);
1281 } catch (OverflowException) {
1282 error_details = "Integral constant is too large";
1283 Report.Error (1021, Location, error_details);
1285 return Token.LITERAL_INTEGER;
1287 catch (FormatException) {
1288 Report.Error (1013, Location, "Invalid number");
1290 return Token.LITERAL_INTEGER;
1294 int adjust_real (int t)
1296 string s = new String (number_builder, 0, number_pos);
1297 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1300 case Token.LITERAL_DECIMAL:
1302 val = System.Decimal.Parse (s, styles, csharp_format_info);
1303 } catch (OverflowException) {
1305 Report.Error (594, Location, error_details, "decimal");
1308 case Token.LITERAL_FLOAT:
1310 val = float.Parse (s, styles, csharp_format_info);
1311 } catch (OverflowException) {
1313 Report.Error (594, Location, error_details, "float");
1317 case Token.LITERAL_DOUBLE:
1319 t = Token.LITERAL_DOUBLE;
1321 val = System.Double.Parse (s, styles, csharp_format_info);
1322 } catch (OverflowException) {
1324 Report.Error (594, Location, error_details, "double");
1337 while ((d = peek_char ()) != -1){
1339 number_builder [number_pos++] = (char) d;
1345 string s = new String (number_builder, 0, number_pos);
1347 if (number_pos <= 8)
1348 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1350 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1351 } catch (OverflowException){
1352 error_details = "Integral constant is too large";
1353 Report.Error (1021, Location, error_details);
1355 return Token.LITERAL_INTEGER;
1357 catch (FormatException) {
1358 Report.Error (1013, Location, "Invalid number");
1360 return Token.LITERAL_INTEGER;
1363 return integer_type_suffix (ul, peek_char ());
1367 // Invoked if we know we have .digits or digits
1369 int is_number (int c)
1371 bool is_real = false;
1376 if (c >= '0' && c <= '9'){
1378 int peek = peek_char ();
1380 if (peek == 'x' || peek == 'X')
1381 return handle_hex ();
1388 // We need to handle the case of
1389 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1392 if (decimal_digits ('.')){
1398 return adjust_int (-1);
1402 if (c == 'e' || c == 'E'){
1404 if (number_pos == max_number_size)
1405 Error_NumericConstantTooLong ();
1406 number_builder [number_pos++] = 'e';
1410 if (number_pos == max_number_size)
1411 Error_NumericConstantTooLong ();
1412 number_builder [number_pos++] = '+';
1414 } else if (c == '-') {
1415 if (number_pos == max_number_size)
1416 Error_NumericConstantTooLong ();
1417 number_builder [number_pos++] = '-';
1420 if (number_pos == max_number_size)
1421 Error_NumericConstantTooLong ();
1422 number_builder [number_pos++] = '+';
1429 type = real_type_suffix (c);
1430 if (type == Token.NONE && !is_real){
1432 return adjust_int (c);
1436 if (type == Token.NONE){
1441 return adjust_real (type);
1443 Console.WriteLine ("This should not be reached");
1444 throw new Exception ("Is Number should never reach this point");
1448 // Accepts exactly count (4 or 8) hex, no more no less
1450 int getHex (int count, out int surrogate, out bool error)
1455 int top = count != -1 ? count : 4;
1460 for (i = 0; i < top; i++){
1463 if (c >= '0' && c <= '9')
1464 c = (int) c - (int) '0';
1465 else if (c >= 'A' && c <= 'F')
1466 c = (int) c - (int) 'A' + 10;
1467 else if (c >= 'a' && c <= 'f')
1468 c = (int) c - (int) 'a' + 10;
1474 total = (total * 16) + c;
1476 int p = peek_char ();
1479 if (!is_hex ((char)p))
1485 if (total > 0x0010FFFF) {
1490 if (total >= 0x00010000) {
1491 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1492 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1499 int escape (int c, out int surrogate)
1535 v = getHex (-1, out surrogate, out error);
1541 return EscapeUnicode (d, out surrogate);
1544 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1553 int EscapeUnicode (int ch, out int surrogate)
1557 ch = getHex (8, out surrogate, out error);
1559 ch = getHex (4, out surrogate, out error);
1563 Report.Error (1009, Location, "Unrecognized escape sequence");
1571 if (putback_char != -1) {
1584 void advance_line ()
1594 if (putback_char != -1)
1595 return putback_char;
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;
1632 public Object Value {
1638 public Object value ()
1643 static bool IsCastToken (int token)
1648 case Token.IDENTIFIER:
1649 case Token.LITERAL_INTEGER:
1650 case Token.LITERAL_FLOAT:
1651 case Token.LITERAL_DOUBLE:
1652 case Token.LITERAL_DECIMAL:
1653 case Token.LITERAL_CHARACTER:
1654 case Token.LITERAL_STRING:
1657 case Token.DELEGATE:
1667 case Token.UNCHECKED:
1672 // These can be part of a member access
1694 current_token = xtoken ();
1696 if (current_token != Token.DEFAULT)
1697 return current_token;
1702 current_token = Token.ERROR;
1703 else if (c == Token.OPEN_PARENS)
1704 current_token = Token.DEFAULT_OPEN_PARENS;
1705 else if (c == Token.COLON)
1706 current_token = Token.DEFAULT_COLON;
1710 return current_token;
1713 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1715 void get_cmd_arg (out string cmd, out string arg)
1719 tokens_seen = false;
1722 // skip over white space
1725 } while (c == '\r' || c == ' ' || c == '\t');
1727 static_cmd_arg.Length = 0;
1728 while (c != -1 && is_identifier_part_character ((char)c)) {
1729 static_cmd_arg.Append ((char)c);
1732 int peek = peek_char ();
1733 if (peek == 'U' || peek == 'u') {
1735 c = EscapeUnicode (c, out surrogate);
1736 if (surrogate != 0) {
1737 if (is_identifier_part_character ((char) c))
1738 static_cmd_arg.Append ((char) c);
1745 cmd = static_cmd_arg.ToString ();
1747 // skip over white space
1748 while (c == '\r' || c == ' ' || c == '\t')
1751 static_cmd_arg.Length = 0;
1752 while (c != -1 && c != '\n' && c != '\r') {
1754 int peek = peek_char ();
1755 if (peek == 'U' || peek == 'u') {
1757 c = EscapeUnicode (c, out surrogate);
1758 if (surrogate != 0) {
1759 if (is_identifier_part_character ((char) c))
1760 static_cmd_arg.Append ((char) c);
1765 static_cmd_arg.Append ((char) c);
1769 if (static_cmd_arg.Length != 0)
1770 arg = static_cmd_arg.ToString ();
1774 // Handles the #line directive
1776 bool PreProcessLine (string arg)
1778 if (arg.Length == 0)
1781 if (arg == "default"){
1783 ref_name = file_name;
1785 Location.Push (file_name, ref_name);
1787 } else if (arg == "hidden"){
1795 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1796 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1799 char [] quotes = { '\"' };
1801 string name = arg.Substring (pos). Trim (quotes);
1802 ref_name = Location.LookupFile (file_name, name);
1803 file_name.AddFile (ref_name);
1805 Location.Push (file_name, ref_name);
1807 ref_line = System.Int32.Parse (arg);
1818 // Handles #define and #undef
1820 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1822 if (ident.Length == 0 || ident == "true" || ident == "false"){
1823 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1827 if (ident.IndexOfAny (simple_whitespaces) != -1){
1828 Error_EndLineExpected ();
1832 if (!is_identifier_start_character (ident [0]))
1833 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1835 foreach (char c in ident.Substring (1)){
1836 if (!is_identifier_part_character (c)){
1837 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1842 if (!caller_is_taking)
1849 if (RootContext.IsConditionalDefined (ident))
1852 file_name.AddDefine (ident);
1857 file_name.AddUndefine (ident);
1861 static byte read_hex (string arg, int pos, out bool error)
1868 if ((c >= '0') && (c <= '9'))
1869 total = (int) c - (int) '0';
1870 else if ((c >= 'A') && (c <= 'F'))
1871 total = (int) c - (int) 'A' + 10;
1872 else if ((c >= 'a') && (c <= 'f'))
1873 total = (int) c - (int) 'a' + 10;
1882 if ((c >= '0') && (c <= '9'))
1883 total += (int) c - (int) '0';
1884 else if ((c >= 'A') && (c <= 'F'))
1885 total += (int) c - (int) 'A' + 10;
1886 else if ((c >= 'a') && (c <= 'f'))
1887 total += (int) c - (int) 'a' + 10;
1893 return (byte) total;
1897 /// Handles #pragma checksum
1899 bool PreProcessPragmaChecksum (string arg)
1901 if ((arg [0] != ' ') && (arg [0] != '\t'))
1904 arg = arg.Trim (simple_whitespaces);
1905 if ((arg.Length < 2) || (arg [0] != '"'))
1908 StringBuilder file_sb = new StringBuilder ();
1912 while ((ch = arg [pos++]) != '"') {
1913 if (pos >= arg.Length)
1917 if (pos+1 >= arg.Length)
1922 file_sb.Append (ch);
1925 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1928 arg = arg.Substring (pos).Trim (simple_whitespaces);
1929 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1930 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1931 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1935 byte[] guid_bytes = new byte [16];
1937 for (int i = 0; i < 4; i++) {
1938 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1942 for (int i = 0; i < 2; i++) {
1943 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1946 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1949 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1954 for (int i = 0; i < 6; i++) {
1955 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1960 arg = arg.Substring (40).Trim (simple_whitespaces);
1961 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1964 byte[] checksum_bytes = new byte [16];
1965 for (int i = 0; i < 16; i++) {
1966 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1971 arg = arg.Substring (34).Trim (simple_whitespaces);
1975 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1976 file.SetChecksum (guid_bytes, checksum_bytes);
1977 ref_name.AutoGenerated = true;
1982 /// Handles #pragma directive
1984 void PreProcessPragma (string arg)
1986 const string warning = "warning";
1987 const string w_disable = "warning disable";
1988 const string w_restore = "warning restore";
1989 const string checksum = "checksum";
1991 if (arg == w_disable) {
1992 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1996 if (arg == w_restore) {
1997 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
2001 if (arg.StartsWith (w_disable)) {
2002 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
2003 foreach (int code in codes) {
2005 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
2010 if (arg.StartsWith (w_restore)) {
2011 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
2012 Hashtable w_table = Report.warning_ignore_table;
2013 foreach (int code in codes) {
2014 if (w_table != null && w_table.Contains (code))
2015 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
2016 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
2021 if (arg.StartsWith (warning)) {
2022 Report.Warning (1634, 1, Location, "Expected disable or restore");
2026 if (arg.StartsWith (checksum)) {
2027 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
2028 Warning_InvalidPragmaChecksum ();
2032 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2035 int[] ParseNumbers (string text)
2037 string[] string_array = text.Split (',');
2038 int[] values = new int [string_array.Length];
2040 foreach (string string_code in string_array) {
2042 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
2044 catch (FormatException) {
2045 Report.Warning (1692, 1, Location, "Invalid number");
2051 bool eval_val (string s)
2058 return file_name.IsConditionalDefined (s);
2061 bool pp_primary (ref string s)
2070 s = s.Substring (1);
2071 bool val = pp_expr (ref s, false);
2072 if (s.Length > 0 && s [0] == ')'){
2073 s = s.Substring (1);
2076 Error_InvalidDirective ();
2080 if (is_identifier_start_character (c)){
2086 if (is_identifier_part_character (c)){
2090 bool v = eval_val (s.Substring (0, j));
2091 s = s.Substring (j);
2094 bool vv = eval_val (s);
2099 Error_InvalidDirective ();
2103 bool pp_unary (ref string s)
2110 if (len > 1 && s [1] == '='){
2111 Error_InvalidDirective ();
2114 s = s.Substring (1);
2115 return ! pp_primary (ref s);
2117 return pp_primary (ref s);
2119 Error_InvalidDirective ();
2124 bool pp_eq (ref string s)
2126 bool va = pp_unary (ref s);
2132 if (len > 2 && s [1] == '='){
2133 s = s.Substring (2);
2134 return va == pp_unary (ref s);
2136 Error_InvalidDirective ();
2139 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2140 s = s.Substring (2);
2142 return va != pp_unary (ref s);
2151 bool pp_and (ref string s)
2153 bool va = pp_eq (ref s);
2159 if (len > 2 && s [1] == '&'){
2160 s = s.Substring (2);
2161 return (va & pp_and (ref s));
2163 Error_InvalidDirective ();
2172 // Evaluates an expression for `#if' or `#elif'
2174 bool pp_expr (ref string s, bool isTerm)
2176 bool va = pp_and (ref s);
2183 if (len > 2 && s [1] == '|'){
2184 s = s.Substring (2);
2185 return va | pp_expr (ref s, isTerm);
2187 Error_InvalidDirective ();
2192 Error_EndLineExpected ();
2200 bool eval (string s)
2202 bool v = pp_expr (ref s, true);
2211 void Error_NumericConstantTooLong ()
2213 Report.Error (1021, Location, "Numeric constant too long");
2216 void Error_InvalidDirective ()
2218 Report.Error (1517, Location, "Invalid preprocessor directive");
2221 void Error_UnexpectedDirective (string extra)
2225 "Unexpected processor directive ({0})", extra);
2228 void Error_TokenExpected (string token)
2230 Report.Error (1026, Location, "Expected `{0}'", token);
2233 void Error_TokensSeen ()
2235 Report.Error (1032, Location,
2236 "Cannot define or undefine preprocessor symbols after first token in file");
2239 void Eror_WrongPreprocessorLocation ()
2241 Report.Error (1040, Location,
2242 "Preprocessor directives must appear as the first non-whitespace character on a line");
2245 void Error_EndLineExpected ()
2247 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2250 void Warning_InvalidPragmaChecksum ()
2252 Report.Warning (1695, 1, Location,
2253 "Invalid #pragma checksum syntax; should be " +
2254 "#pragma checksum \"filename\" " +
2255 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2258 // if true, then the code continues processing the code
2259 // if false, the code stays in a loop until another directive is
2261 // When caller_is_taking is false we ignore all directives except the ones
2262 // which can help us to identify where the #if block ends
2263 bool handle_preprocessing_directive (bool caller_is_taking)
2266 bool region_directive = false;
2268 get_cmd_arg (out cmd, out arg);
2270 // Eat any trailing whitespaces and single-line comments
2271 if (arg.IndexOf ("//") != -1)
2272 arg = arg.Substring (0, arg.IndexOf ("//"));
2273 arg = arg.Trim (simple_whitespaces);
2276 // The first group of pre-processing instructions is always processed
2280 region_directive = true;
2285 if (ifstack == null || ifstack.Count == 0){
2286 Error_UnexpectedDirective ("no #region for this #endregion");
2289 int pop = (int) ifstack.Pop ();
2291 if ((pop & REGION) == 0)
2292 Report.Error (1027, Location, "Expected `#endif' directive");
2294 return caller_is_taking;
2297 if (ifstack == null)
2298 ifstack = new Stack (2);
2300 int flags = region_directive ? REGION : 0;
2301 if (ifstack.Count == 0){
2302 flags |= PARENT_TAKING;
2304 int state = (int) ifstack.Peek ();
2305 if ((state & TAKING) != 0) {
2306 flags |= PARENT_TAKING;
2310 if (caller_is_taking && eval (arg)) {
2311 ifstack.Push (flags | TAKING);
2314 ifstack.Push (flags);
2318 if (ifstack == null || ifstack.Count == 0){
2319 Error_UnexpectedDirective ("no #if for this #endif");
2322 pop = (int) ifstack.Pop ();
2324 if ((pop & REGION) != 0)
2325 Report.Error (1038, Location, "#endregion directive expected");
2327 if (arg.Length != 0) {
2328 Error_EndLineExpected ();
2331 if (ifstack.Count == 0)
2334 int state = (int) ifstack.Peek ();
2335 return (state & TAKING) != 0;
2339 if (ifstack == null || ifstack.Count == 0){
2340 Error_UnexpectedDirective ("no #if for this #elif");
2343 int state = (int) ifstack.Pop ();
2345 if ((state & REGION) != 0) {
2346 Report.Error (1038, Location, "#endregion directive expected");
2350 if ((state & ELSE_SEEN) != 0){
2351 Error_UnexpectedDirective ("#elif not valid after #else");
2355 if ((state & TAKING) != 0) {
2360 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2361 ifstack.Push (state | TAKING);
2365 ifstack.Push (state);
2370 if (ifstack == null || ifstack.Count == 0){
2371 Error_UnexpectedDirective ("no #if for this #else");
2374 int state = (int) ifstack.Peek ();
2376 if ((state & REGION) != 0) {
2377 Report.Error (1038, Location, "#endregion directive expected");
2381 if ((state & ELSE_SEEN) != 0){
2382 Error_UnexpectedDirective ("#else within #else");
2388 if (arg.Length != 0) {
2389 Error_EndLineExpected ();
2394 if ((state & PARENT_TAKING) != 0) {
2395 ret = (state & TAKING) == 0;
2403 ifstack.Push (state | ELSE_SEEN);
2408 if (any_token_seen){
2409 Error_TokensSeen ();
2410 return caller_is_taking;
2412 PreProcessDefinition (true, arg, caller_is_taking);
2413 return caller_is_taking;
2416 if (any_token_seen){
2417 Error_TokensSeen ();
2418 return caller_is_taking;
2420 PreProcessDefinition (false, arg, caller_is_taking);
2421 return caller_is_taking;
2425 // These are only processed if we are in a `taking' block
2427 if (!caller_is_taking)
2432 Report.Error (1029, Location, "#error: '{0}'", arg);
2436 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2440 if (RootContext.Version == LanguageVersion.ISO_1) {
2441 Report.FeatureIsNotAvailable (Location, "#pragma");
2445 PreProcessPragma (arg);
2449 if (!PreProcessLine (arg))
2452 "The line number specified for #line directive is missing or invalid");
2453 return caller_is_taking;
2456 Report.Error (1024, Location, "Wrong preprocessor directive");
2461 private int consume_string (bool quoted)
2464 string_builder.Length = 0;
2467 // No need to parse full string when parsing lambda arguments
2469 if (lambda_arguments_parsing)
2470 return Token.LITERAL_STRING;
2472 while ((c = get_char ()) != -1){
2474 if (quoted && peek_char () == '"'){
2475 string_builder.Append ((char) c);
2479 val = string_builder.ToString ();
2480 return Token.LITERAL_STRING;
2486 Report.Error (1010, Location, "Newline in constant");
2491 c = escape (c, out surrogate);
2494 if (surrogate != 0) {
2495 string_builder.Append ((char) c);
2499 string_builder.Append ((char) c);
2502 Report.Error (1039, Location, "Unterminated string literal");
2506 private int consume_identifier (int s)
2508 int res = consume_identifier (s, false);
2510 if (doc_state == XmlCommentState.Allowed)
2511 doc_state = XmlCommentState.NotAllowed;
2514 case Token.NAMESPACE:
2515 check_incorrect_doc_comment ();
2519 if (res == Token.PARTIAL) {
2520 if (parsing_block > 0) {
2521 val = new LocatedToken (Location, "partial");
2522 return Token.IDENTIFIER;
2525 // Save current position and parse next token.
2528 int next_token = token ();
2529 bool ok = (next_token == Token.CLASS) ||
2530 (next_token == Token.STRUCT) ||
2531 (next_token == Token.INTERFACE) ||
2532 (next_token == Token.VOID);
2537 if (next_token == Token.VOID) {
2538 if (RootContext.Version == LanguageVersion.ISO_1 ||
2539 RootContext.Version == LanguageVersion.ISO_2)
2540 Report.FeatureIsNotAvailable (Location, "partial methods");
2541 } else if (RootContext.Version == LanguageVersion.ISO_1)
2542 Report.FeatureIsNotAvailable (Location, "partial types");
2547 if (next_token < Token.LAST_KEYWORD) {
2548 Report.Error (267, Location,
2549 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
2553 val = new LocatedToken (Location, "partial");
2554 return Token.IDENTIFIER;
2560 private int consume_identifier (int c, bool quoted)
2566 c = escape (c, out surrogate);
2567 if (surrogate != 0) {
2568 id_builder [pos++] = (char) c;
2573 id_builder [pos++] = (char) c;
2574 current_location = new Location (ref_line, hidden ? -1 : Col);
2576 while ((c = get_char ()) != -1) {
2578 if (is_identifier_part_character ((char) c)){
2579 if (pos == max_id_size){
2580 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2584 id_builder [pos++] = (char) c;
2585 // putback_char = -1;
2586 } else if (c == '\\') {
2588 c = escape (c, out surrogate);
2589 if (surrogate != 0) {
2590 if (is_identifier_part_character ((char) c))
2591 id_builder [pos++] = (char) c;
2596 // putback_char = c;
2603 // Optimization: avoids doing the keyword lookup
2604 // on uppercase letters
2606 if (id_builder [0] >= '_' && !quoted) {
2607 int keyword = GetKeyword (id_builder, pos);
2608 if (keyword != -1) {
2615 // Keep identifiers in an array of hashtables to avoid needless
2619 if (identifiers [pos] != null) {
2620 val = identifiers [pos][id_builder];
2622 val = new LocatedToken (Location, (string) val);
2624 escaped_identifiers.Add (val);
2625 return Token.IDENTIFIER;
2629 identifiers [pos] = new CharArrayHashtable (pos);
2631 val = new String (id_builder, 0, pos);
2632 if (RootContext.Version == LanguageVersion.ISO_1) {
2633 for (int i = 1; i < id_builder.Length; i += 3) {
2634 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2635 Report.Error (1638, Location,
2636 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2642 char [] chars = new char [pos];
2643 Array.Copy (id_builder, chars, pos);
2645 identifiers [pos] [chars] = val;
2647 val = new LocatedToken (Location, (string) val);
2649 escaped_identifiers.Add (val);
2650 return Token.IDENTIFIER;
2653 public int xtoken ()
2656 bool doread = false;
2659 // Whether we have seen comments on the current line
2660 bool comments_seen = false;
2662 for (;(c = get_char ()) != -1;) {
2664 col = ((col + 8) / 8) * 8;
2668 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0 || c == 0)
2672 if (peek_char () != '\n')
2677 any_token_seen |= tokens_seen;
2678 tokens_seen = false;
2679 comments_seen = false;
2683 // Handle double-slash comments.
2685 int d = peek_char ();
2689 if (RootContext.Documentation != null && peek_char () == '/') {
2691 // Don't allow ////.
2692 if ((d = peek_char ()) != '/') {
2693 update_comment_location ();
2694 if (doc_state == XmlCommentState.Allowed)
2695 handle_one_line_xml_comment ();
2696 else if (doc_state == XmlCommentState.NotAllowed)
2697 warn_incorrect_doc_comment ();
2700 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2702 any_token_seen |= tokens_seen;
2703 tokens_seen = false;
2704 comments_seen = false;
2706 } else if (d == '*'){
2708 bool docAppend = false;
2709 if (RootContext.Documentation != null && peek_char () == '*') {
2711 update_comment_location ();
2712 // But when it is /**/, just do nothing.
2713 if (peek_char () == '/') {
2717 if (doc_state == XmlCommentState.Allowed)
2719 else if (doc_state == XmlCommentState.NotAllowed)
2720 warn_incorrect_doc_comment ();
2723 int current_comment_start = 0;
2725 current_comment_start = xml_comment_buffer.Length;
2726 xml_comment_buffer.Append (Environment.NewLine);
2729 Location start_location = Location;
2731 while ((d = get_char ()) != -1){
2732 if (d == '*' && peek_char () == '/'){
2734 comments_seen = true;
2738 xml_comment_buffer.Append ((char) d);
2741 any_token_seen |= tokens_seen;
2742 tokens_seen = false;
2744 // Reset 'comments_seen' just to be consistent.
2745 // It doesn't matter either way, here.
2747 comments_seen = false;
2751 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2754 update_formatted_doc_comment (current_comment_start);
2757 goto is_punct_label;
2761 if (c == '\\' || is_identifier_start_character ((char)c)){
2763 return consume_identifier (c);
2767 current_location = new Location (ref_line, hidden ? -1 : Col);
2768 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2778 any_token_seen |= tokens_seen;
2779 tokens_seen = false;
2780 comments_seen = false;
2784 if (c >= '0' && c <= '9'){
2786 return is_number (c);
2791 int peek = peek_char ();
2792 if (peek >= '0' && peek <= '9')
2793 return is_number (c);
2798 if (tokens_seen || comments_seen) {
2799 Eror_WrongPreprocessorLocation ();
2803 if (handle_preprocessing_directive (true))
2806 bool directive_expected = false;
2807 while ((c = get_char ()) != -1) {
2809 directive_expected = true;
2810 } else if (!directive_expected) {
2811 // TODO: Implement comment support for disabled code and uncomment this code
2813 // Eror_WrongPreprocessorLocation ();
2814 // return Token.ERROR;
2819 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2823 if (handle_preprocessing_directive (false))
2826 directive_expected = false;
2830 tokens_seen = false;
2838 return consume_string (false);
2844 error_details = "Empty character literal";
2845 Report.Error (1011, Location, error_details);
2848 if (c == '\r' || c == '\n') {
2849 Report.Error (1010, Location, "Newline in constant");
2854 c = escape (c, out surrogate);
2858 throw new NotImplementedException ();
2864 error_details = "Too many characters in character literal";
2865 Report.Error (1012, Location, error_details);
2867 // Try to recover, read until newline or next "'"
2868 while ((c = get_char ()) != -1){
2877 return Token.LITERAL_CHARACTER;
2884 return consume_string (true);
2885 } else if (is_identifier_start_character ((char) c)){
2886 return consume_identifier (c, true);
2888 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2892 if (c == EvalStatementParserCharacter)
2893 return Token.EVAL_STATEMENT_PARSER;
2894 if (c == EvalCompilationUnitParserCharacter)
2895 return Token.EVAL_COMPILATION_UNIT_PARSER;
2896 if (c == EvalUsingDeclarationsParserCharacter)
2897 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2899 error_details = ((char)c).ToString ();
2908 // Handles one line xml comment
2910 private void handle_one_line_xml_comment ()
2913 while ((c = peek_char ()) == ' ')
2914 get_char (); // skip heading whitespaces.
2915 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2916 xml_comment_buffer.Append ((char) get_char ());
2918 if (c == '\r' || c == '\n')
2919 xml_comment_buffer.Append (Environment.NewLine);
2923 // Remove heading "*" in Javadoc-like xml documentation.
2925 private void update_formatted_doc_comment (int current_comment_start)
2927 int length = xml_comment_buffer.Length - current_comment_start;
2928 string [] lines = xml_comment_buffer.ToString (
2929 current_comment_start,
2930 length).Replace ("\r", "").Split ('\n');
2932 // The first line starts with /**, thus it is not target
2933 // for the format check.
2934 for (int i = 1; i < lines.Length; i++) {
2935 string s = lines [i];
2936 int idx = s.IndexOf ('*');
2939 if (i < lines.Length - 1)
2943 head = s.Substring (0, idx);
2944 foreach (char c in head)
2947 lines [i] = s.Substring (idx + 1);
2949 xml_comment_buffer.Remove (current_comment_start, length);
2950 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2954 // Updates current comment location.
2956 private void update_comment_location ()
2958 if (current_comment_location.IsNull) {
2959 // "-2" is for heading "//" or "/*"
2960 current_comment_location =
2961 new Location (ref_line, hidden ? -1 : col - 2);
2966 // Checks if there was incorrect doc comments and raise
2969 public void check_incorrect_doc_comment ()
2971 if (xml_comment_buffer.Length > 0)
2972 warn_incorrect_doc_comment ();
2976 // Raises a warning when tokenizer found incorrect doccomment
2979 private void warn_incorrect_doc_comment ()
2981 if (doc_state != XmlCommentState.Error) {
2982 doc_state = XmlCommentState.Error;
2983 // in csc, it is 'XML comment is not placed on
2984 // a valid language element'. But that does not
2986 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2991 // Consumes the saved xml comment lines (if any)
2992 // as for current target member or type.
2994 public string consume_doc_comment ()
2996 if (xml_comment_buffer.Length > 0) {
2997 string ret = xml_comment_buffer.ToString ();
2998 reset_doc_comment ();
3004 void reset_doc_comment ()
3006 xml_comment_buffer.Length = 0;
3007 current_comment_location = Location.Null;
3010 public void cleanup ()
3012 if (ifstack != null && ifstack.Count >= 1) {
3013 current_location = new Location (ref_line, hidden ? -1 : Col);
3014 int state = (int) ifstack.Pop ();
3015 if ((state & REGION) != 0)
3016 Report.Error (1038, Location, "#endregion directive expected");
3018 Report.Error (1027, Location, "Expected `#endif' directive");
3024 // Indicates whether it accepts XML documentation or not.
3026 public enum XmlCommentState {
3027 // comment is allowed in this state.
3029 // comment is not allowed in this state.
3031 // once comments appeared when it is NotAllowed, then the
3032 // state is changed to it, until the state is changed to