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 ();
48 public int parsing_block;
49 internal int query_parsing;
52 // XML documentation buffer. The save point is used to divide
53 // comments on types and comments on members.
55 StringBuilder xml_comment_buffer;
58 // See comment on XmlCommentState enumeration.
60 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
63 // Whether tokens have been seen on this line
65 bool tokens_seen = false;
68 // Whether a token has been seen on the file
69 // This is needed because `define' is not allowed to be used
70 // after a token has been seen.
72 bool any_token_seen = false;
74 static Hashtable token_values;
75 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
77 private static Hashtable TokenValueName
80 if (token_values == null)
81 token_values = GetTokenValueNameHash ();
87 private static Hashtable GetTokenValueNameHash ()
89 Type t = typeof (Token);
90 FieldInfo [] fields = t.GetFields ();
91 Hashtable hash = new Hashtable ();
92 foreach (FieldInfo field in fields) {
93 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
94 hash.Add (field.GetValue (null), field.Name);
100 // Returns a verbose representation of the current location
102 public string location {
106 if (current_token == Token.ERROR)
107 det = "detail: " + error_details;
111 // return "Line: "+line+" Col: "+col + "\n" +
112 // "VirtLine: "+ref_line +
113 // " Token: "+current_token + " " + det;
114 string current_token_name = TokenValueName [current_token] as string;
115 if (current_token_name == null)
116 current_token_name = current_token.ToString ();
118 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
126 public bool PropertyParsing {
127 get { return handle_get_set; }
128 set { handle_get_set = value; }
131 public bool AssemblyTargetParsing {
132 get { return handle_assembly; }
133 set { handle_assembly = value; }
136 public bool EventParsing {
137 get { return handle_remove_add; }
138 set { handle_remove_add = value; }
141 public bool ConstraintsParsing {
142 get { return handle_where; }
143 set { handle_where = value; }
146 public bool TypeOfParsing {
147 get { return handle_typeof; }
148 set { handle_typeof = value; }
151 public XmlCommentState doc_state {
152 get { return xml_doc_state; }
154 if (value == XmlCommentState.Allowed) {
155 check_incorrect_doc_comment ();
156 reset_doc_comment ();
158 xml_doc_state = value;
162 public bool IsEscapedIdentifier (Location loc)
164 foreach (LocatedToken lt in escaped_identifiers)
165 if (lt.Location.Equals (loc))
173 static CharArrayHashtable[] keywords;
174 static Hashtable keyword_strings;
175 static NumberStyles styles;
176 static NumberFormatInfo csharp_format_info;
179 // Values for the associated token returned
189 const int TAKING = 1;
190 const int ELSE_SEEN = 4;
191 const int PARENT_TAKING = 8;
192 const int REGION = 16;
195 // pre-processor if stack state:
199 static System.Text.StringBuilder string_builder;
201 const int max_id_size = 512;
202 static char [] id_builder = new char [max_id_size];
204 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
206 const int max_number_size = 512;
207 static char [] number_builder = new char [max_number_size];
208 static int number_pos;
211 // Details about the error encoutered by the tokenizer
213 string error_details;
215 public string error {
217 return error_details;
234 // This is used when the tokenizer needs to save
235 // the current position as it needs to do some parsing
236 // on its own to deamiguate a token in behalf of the
239 Stack position_stack = new Stack (2);
246 public int putback_char;
247 public int previous_col;
248 public Stack ifstack;
249 public int parsing_generic_less_than;
250 public int current_token;
252 public Position (Tokenizer t)
254 position = t.reader.Position;
256 ref_line = t.ref_line;
259 putback_char = t.putback_char;
260 previous_col = t.previous_col;
261 if (t.ifstack != null && t.ifstack.Count != 0)
262 ifstack = (Stack)t.ifstack.Clone ();
263 parsing_generic_less_than = t.parsing_generic_less_than;
264 current_token = t.current_token;
268 public void PushPosition ()
270 position_stack.Push (new Position (this));
273 public void PopPosition ()
275 Position p = (Position) position_stack.Pop ();
277 reader.Position = p.position;
278 ref_line = p.ref_line;
282 putback_char = p.putback_char;
283 previous_col = p.previous_col;
285 parsing_generic_less_than = p.parsing_generic_less_than;
286 current_token = p.current_token;
289 // Do not reset the position, ignore it.
290 public void DiscardPosition ()
292 position_stack.Pop ();
295 static void AddKeyword (string kw, int token)
297 keyword_strings.Add (kw, kw);
298 if (keywords [kw.Length] == null) {
299 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
301 keywords [kw.Length] [kw.ToCharArray ()] = token;
304 static void InitTokens ()
306 keyword_strings = new Hashtable ();
307 keywords = new CharArrayHashtable [64];
309 AddKeyword ("__arglist", Token.ARGLIST);
310 AddKeyword ("abstract", Token.ABSTRACT);
311 AddKeyword ("as", Token.AS);
312 AddKeyword ("add", Token.ADD);
313 AddKeyword ("assembly", Token.ASSEMBLY);
314 AddKeyword ("base", Token.BASE);
315 AddKeyword ("bool", Token.BOOL);
316 AddKeyword ("break", Token.BREAK);
317 AddKeyword ("byte", Token.BYTE);
318 AddKeyword ("case", Token.CASE);
319 AddKeyword ("catch", Token.CATCH);
320 AddKeyword ("char", Token.CHAR);
321 AddKeyword ("checked", Token.CHECKED);
322 AddKeyword ("class", Token.CLASS);
323 AddKeyword ("const", Token.CONST);
324 AddKeyword ("continue", Token.CONTINUE);
325 AddKeyword ("decimal", Token.DECIMAL);
326 AddKeyword ("default", Token.DEFAULT);
327 AddKeyword ("delegate", Token.DELEGATE);
328 AddKeyword ("do", Token.DO);
329 AddKeyword ("double", Token.DOUBLE);
330 AddKeyword ("else", Token.ELSE);
331 AddKeyword ("enum", Token.ENUM);
332 AddKeyword ("event", Token.EVENT);
333 AddKeyword ("explicit", Token.EXPLICIT);
334 AddKeyword ("extern", Token.EXTERN);
335 AddKeyword ("false", Token.FALSE);
336 AddKeyword ("finally", Token.FINALLY);
337 AddKeyword ("fixed", Token.FIXED);
338 AddKeyword ("float", Token.FLOAT);
339 AddKeyword ("for", Token.FOR);
340 AddKeyword ("foreach", Token.FOREACH);
341 AddKeyword ("goto", Token.GOTO);
342 AddKeyword ("get", Token.GET);
343 AddKeyword ("if", Token.IF);
344 AddKeyword ("implicit", Token.IMPLICIT);
345 AddKeyword ("in", Token.IN);
346 AddKeyword ("int", Token.INT);
347 AddKeyword ("interface", Token.INTERFACE);
348 AddKeyword ("internal", Token.INTERNAL);
349 AddKeyword ("is", Token.IS);
350 AddKeyword ("lock", Token.LOCK);
351 AddKeyword ("long", Token.LONG);
352 AddKeyword ("namespace", Token.NAMESPACE);
353 AddKeyword ("new", Token.NEW);
354 AddKeyword ("null", Token.NULL);
355 AddKeyword ("object", Token.OBJECT);
356 AddKeyword ("operator", Token.OPERATOR);
357 AddKeyword ("out", Token.OUT);
358 AddKeyword ("override", Token.OVERRIDE);
359 AddKeyword ("params", Token.PARAMS);
360 AddKeyword ("private", Token.PRIVATE);
361 AddKeyword ("protected", Token.PROTECTED);
362 AddKeyword ("public", Token.PUBLIC);
363 AddKeyword ("readonly", Token.READONLY);
364 AddKeyword ("ref", Token.REF);
365 AddKeyword ("remove", Token.REMOVE);
366 AddKeyword ("return", Token.RETURN);
367 AddKeyword ("sbyte", Token.SBYTE);
368 AddKeyword ("sealed", Token.SEALED);
369 AddKeyword ("set", Token.SET);
370 AddKeyword ("short", Token.SHORT);
371 AddKeyword ("sizeof", Token.SIZEOF);
372 AddKeyword ("stackalloc", Token.STACKALLOC);
373 AddKeyword ("static", Token.STATIC);
374 AddKeyword ("string", Token.STRING);
375 AddKeyword ("struct", Token.STRUCT);
376 AddKeyword ("switch", Token.SWITCH);
377 AddKeyword ("this", Token.THIS);
378 AddKeyword ("throw", Token.THROW);
379 AddKeyword ("true", Token.TRUE);
380 AddKeyword ("try", Token.TRY);
381 AddKeyword ("typeof", Token.TYPEOF);
382 AddKeyword ("uint", Token.UINT);
383 AddKeyword ("ulong", Token.ULONG);
384 AddKeyword ("unchecked", Token.UNCHECKED);
385 AddKeyword ("unsafe", Token.UNSAFE);
386 AddKeyword ("ushort", Token.USHORT);
387 AddKeyword ("using", Token.USING);
388 AddKeyword ("virtual", Token.VIRTUAL);
389 AddKeyword ("void", Token.VOID);
390 AddKeyword ("volatile", Token.VOLATILE);
391 AddKeyword ("while", Token.WHILE);
392 AddKeyword ("partial", Token.PARTIAL);
393 AddKeyword ("where", Token.WHERE);
396 AddKeyword ("from", Token.FROM);
397 AddKeyword ("join", Token.JOIN);
398 AddKeyword ("on", Token.ON);
399 AddKeyword ("equals", Token.EQUALS);
400 AddKeyword ("select", Token.SELECT);
401 AddKeyword ("group", Token.GROUP);
402 AddKeyword ("by", Token.BY);
403 AddKeyword ("let", Token.LET);
404 AddKeyword ("orderby", Token.ORDERBY);
405 AddKeyword ("ascending", Token.ASCENDING);
406 AddKeyword ("descending", Token.DESCENDING);
407 AddKeyword ("into", Token.INTO);
418 public static void Reset ()
421 csharp_format_info = NumberFormatInfo.InvariantInfo;
422 styles = NumberStyles.Float;
424 string_builder = new System.Text.StringBuilder ();
427 int GetKeyword (char[] id, int id_len)
430 * Keywords are stored in an array of hashtables grouped by their
434 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
436 object o = keywords [id_len] [id];
443 if (!handle_get_set && (res == Token.GET || res == Token.SET))
445 if (!handle_remove_add && (res == Token.REMOVE || res == Token.ADD))
447 if (!handle_assembly && res == Token.ASSEMBLY)
451 // A query expression is any expression that starts with `from identifier'
452 // followed by any token except ; , =
454 if (query_parsing == 0) {
455 if (res == Token.FROM && !lambda_arguments_parsing) {
457 // HACK: to disable generics micro-parser, because PushPosition does not
458 // store identifiers array
459 parsing_generic_less_than = 1;
461 case Token.IDENTIFIER:
473 int next_token = xtoken ();
474 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
478 if (RootContext.Version <= LanguageVersion.ISO_2)
479 Report.FeatureIsNotAvailable (Location, "query expressions");
482 Expression.Error_VoidInvalidInTheContext (Location);
486 // HACK: A token is not a keyword so we need to restore identifiers buffer
487 // which has been overwritten before we grabbed the identifier
488 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
495 if (res > Token.QUERY_FIRST_TOKEN && res < Token.QUERY_LAST_TOKEN)
499 if (res == Token.WHERE && !handle_where && query_parsing == 0)
505 public Location Location {
506 get { return current_location; }
509 void define (string def)
511 if (!RootContext.AllDefines.Contains (def)){
512 RootContext.AllDefines [def] = true;
514 if (defines.Contains (def))
516 defines [def] = true;
519 public Tokenizer (SeekableStreamReader input, CompilationUnit file, ArrayList defs)
521 this.ref_name = file;
522 this.file_name = file;
528 defines = new Hashtable ();
529 foreach (string def in defs)
533 xml_comment_buffer = new StringBuilder ();
536 // FIXME: This could be `Location.Push' but we have to
537 // find out why the MS compiler allows this
539 Mono.CSharp.Location.Push (file, file);
542 static bool is_identifier_start_character (char c)
544 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter (c);
547 static bool is_identifier_part_character (char c)
549 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') ||
550 Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
553 public static bool IsKeyword (string s)
555 return keyword_strings [s] != null;
559 // Tests whether '(' is beggining of lambda parameters
561 bool IsLambdaOpenParens ()
564 while ((ntoken = xtoken ()) != Token.EOF) {
566 case Token.CLOSE_PARENS:
567 return xtoken () == Token.ARROW;
570 case Token.SEMICOLON:
571 case Token.OPEN_BRACE:
572 case Token.OPEN_PARENS:
573 case Token.LITERAL_STRING:
578 Error_TokenExpected (",' or `)");
582 public static bool IsValidIdentifier (string s)
584 if (s == null || s.Length == 0)
587 if (!is_identifier_start_character (s [0]))
590 for (int i = 1; i < s.Length; i ++)
591 if (! is_identifier_part_character (s [i]))
597 bool parse_less_than ()
600 int the_token = token ();
601 if (the_token == Token.OPEN_BRACKET) {
603 the_token = token ();
604 } while (the_token != Token.CLOSE_BRACKET);
605 the_token = token ();
608 case Token.IDENTIFIER:
631 the_token = token ();
633 if (the_token == Token.OP_GENERICS_GT)
635 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
637 else if (the_token == Token.INTERR || the_token == Token.STAR)
639 else if (the_token == Token.OP_GENERICS_LT) {
640 if (!parse_less_than ())
643 } else if (the_token == Token.OPEN_BRACKET) {
645 the_token = token ();
646 if (the_token == Token.CLOSE_BRACKET)
648 else if (the_token == Token.COMMA)
649 goto rank_specifiers;
656 public void PutbackNullable ()
658 if (nullable_pos < 0)
659 throw new Exception ();
663 reader.Position = nullable_pos;
668 public void PutbackCloseParens ()
674 int nullable_pos = -1;
676 public void CheckNullable (bool is_nullable)
679 nullable_pos = reader.Position;
684 bool parse_generic_dimension (out int dimension)
689 int the_token = token ();
690 if (the_token == Token.OP_GENERICS_GT)
692 else if (the_token == Token.COMMA) {
700 public int peek_token ()
705 the_token = token ();
711 int parsing_generic_less_than = 0;
713 int is_punct (char c, ref bool doread)
723 return Token.OPEN_BRACE;
726 return Token.CLOSE_BRACE;
728 // To block doccomment inside attribute declaration.
729 if (doc_state == XmlCommentState.Allowed)
730 doc_state = XmlCommentState.NotAllowed;
731 return Token.OPEN_BRACKET;
733 return Token.CLOSE_BRACKET;
735 if (!lambda_arguments_parsing) {
736 lambda_arguments_parsing = true;
738 bool lambda_start = IsLambdaOpenParens ();
740 lambda_arguments_parsing = false;
742 if (RootContext.Version <= LanguageVersion.ISO_2)
743 Report.FeatureIsNotAvailable (Location, "lambda expressions");
745 return Token.OPEN_PARENS_LAMBDA;
748 return Token.OPEN_PARENS;
750 if (deambiguate_close_parens == 0)
751 return Token.CLOSE_PARENS;
753 --deambiguate_close_parens;
757 int new_token = xtoken ();
761 if (new_token == Token.OPEN_PARENS)
762 return Token.CLOSE_PARENS_OPEN_PARENS;
763 else if (new_token == Token.MINUS)
764 return Token.CLOSE_PARENS_MINUS;
765 else if (IsCastToken (new_token))
766 return Token.CLOSE_PARENS_CAST;
768 return Token.CLOSE_PARENS_NO_CAST;
775 return Token.SEMICOLON;
783 return Token.OP_COALESCING;
789 if (parsing_generic_less_than++ > 0)
790 return Token.OP_GENERICS_LT;
795 if (parse_generic_dimension (out dimension)) {
798 return Token.GENERIC_DIMENSION;
803 // Save current position and parse next token.
805 bool is_generic_lt = parse_less_than ();
809 return Token.OP_GENERICS_LT;
811 parsing_generic_less_than = 0;
820 return Token.OP_SHIFT_LEFT_ASSIGN;
822 return Token.OP_SHIFT_LEFT;
823 } else if (d == '='){
828 } else if (c == '>') {
836 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
837 parsing_generic_less_than--;
838 return Token.OP_GENERICS_GT;
847 return Token.OP_SHIFT_RIGHT_ASSIGN;
849 return Token.OP_SHIFT_RIGHT;
863 t = Token.OP_ADD_ASSIGN;
877 t = Token.OP_SUB_ASSIGN;
915 } else if (d == '='){
917 return Token.OP_AND_ASSIGN;
920 return Token.BITWISE_AND;
927 } else if (d == '='){
929 return Token.OP_OR_ASSIGN;
931 return Token.BITWISE_OR;
937 return Token.OP_MULT_ASSIGN;
946 return Token.OP_DIV_ASSIGN;
954 return Token.OP_MOD_ASSIGN;
956 return Token.PERCENT;
962 return Token.OP_XOR_ASSIGN;
970 return Token.DOUBLE_COLON;
979 int deambiguate_close_parens = 0;
981 public void Deambiguate_CloseParens (object expression)
985 // When any binary operation, a conditional is used we are sure it is not a cast
988 if (expression is Binary || expression is Conditional)
991 deambiguate_close_parens++;
994 bool decimal_digits (int c)
997 bool seen_digits = false;
1000 if (number_pos == max_number_size)
1001 Error_NumericConstantTooLong ();
1002 number_builder [number_pos++] = (char) c;
1006 // We use peek_char2, because decimal_digits needs to do a
1007 // 2-character look-ahead (5.ToString for example).
1009 while ((d = peek_char2 ()) != -1){
1010 if (d >= '0' && d <= '9'){
1011 if (number_pos == max_number_size)
1012 Error_NumericConstantTooLong ();
1013 number_builder [number_pos++] = (char) d;
1023 static bool is_hex (int e)
1025 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1028 static int real_type_suffix (int c)
1034 t = Token.LITERAL_FLOAT;
1037 t = Token.LITERAL_DOUBLE;
1040 t= Token.LITERAL_DECIMAL;
1048 int integer_type_suffix (ulong ul, int c)
1050 bool is_unsigned = false;
1051 bool is_long = false;
1054 bool scanning = true;
1067 // if we have not seen anything in between
1068 // report this error
1070 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1073 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1074 // work around that.
1098 if (is_long && is_unsigned){
1100 return Token.LITERAL_INTEGER;
1101 } else if (is_unsigned){
1102 // uint if possible, or ulong else.
1104 if ((ul & 0xffffffff00000000) == 0)
1108 } else if (is_long){
1109 // long if possible, ulong otherwise
1110 if ((ul & 0x8000000000000000) != 0)
1115 // int, uint, long or ulong in that order
1116 if ((ul & 0xffffffff00000000) == 0){
1117 uint ui = (uint) ul;
1119 if ((ui & 0x80000000) != 0)
1124 if ((ul & 0x8000000000000000) != 0)
1130 return Token.LITERAL_INTEGER;
1134 // given `c' as the next char in the input decide whether
1135 // we need to convert to a special type, and then choose
1136 // the best representation for the integer
1138 int adjust_int (int c)
1141 if (number_pos > 9){
1142 ulong ul = (uint) (number_builder [0] - '0');
1144 for (int i = 1; i < number_pos; i++){
1145 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1147 return integer_type_suffix (ul, c);
1149 uint ui = (uint) (number_builder [0] - '0');
1151 for (int i = 1; i < number_pos; i++){
1152 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1154 return integer_type_suffix (ui, c);
1156 } catch (OverflowException) {
1157 error_details = "Integral constant is too large";
1158 Report.Error (1021, Location, error_details);
1160 return Token.LITERAL_INTEGER;
1162 catch (FormatException) {
1163 Report.Error (1013, Location, "Invalid number");
1165 return Token.LITERAL_INTEGER;
1169 int adjust_real (int t)
1171 string s = new String (number_builder, 0, number_pos);
1172 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1175 case Token.LITERAL_DECIMAL:
1177 val = System.Decimal.Parse (s, styles, csharp_format_info);
1178 } catch (OverflowException) {
1180 Report.Error (594, Location, error_details, "decimal");
1183 case Token.LITERAL_FLOAT:
1185 val = float.Parse (s, styles, csharp_format_info);
1186 } catch (OverflowException) {
1188 Report.Error (594, Location, error_details, "float");
1192 case Token.LITERAL_DOUBLE:
1194 t = Token.LITERAL_DOUBLE;
1196 val = System.Double.Parse (s, styles, csharp_format_info);
1197 } catch (OverflowException) {
1199 Report.Error (594, Location, error_details, "double");
1212 while ((d = peek_char ()) != -1){
1214 number_builder [number_pos++] = (char) d;
1220 string s = new String (number_builder, 0, number_pos);
1222 if (number_pos <= 8)
1223 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1225 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1226 } catch (OverflowException){
1227 error_details = "Integral constant is too large";
1228 Report.Error (1021, Location, error_details);
1230 return Token.LITERAL_INTEGER;
1232 catch (FormatException) {
1233 Report.Error (1013, Location, "Invalid number");
1235 return Token.LITERAL_INTEGER;
1238 return integer_type_suffix (ul, peek_char ());
1242 // Invoked if we know we have .digits or digits
1244 int is_number (int c)
1246 bool is_real = false;
1251 if (c >= '0' && c <= '9'){
1253 int peek = peek_char ();
1255 if (peek == 'x' || peek == 'X')
1256 return handle_hex ();
1263 // We need to handle the case of
1264 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1267 if (decimal_digits ('.')){
1273 return adjust_int (-1);
1277 if (c == 'e' || c == 'E'){
1279 if (number_pos == max_number_size)
1280 Error_NumericConstantTooLong ();
1281 number_builder [number_pos++] = 'e';
1285 if (number_pos == max_number_size)
1286 Error_NumericConstantTooLong ();
1287 number_builder [number_pos++] = '+';
1289 } else if (c == '-') {
1290 if (number_pos == max_number_size)
1291 Error_NumericConstantTooLong ();
1292 number_builder [number_pos++] = '-';
1295 if (number_pos == max_number_size)
1296 Error_NumericConstantTooLong ();
1297 number_builder [number_pos++] = '+';
1304 type = real_type_suffix (c);
1305 if (type == Token.NONE && !is_real){
1307 return adjust_int (c);
1311 if (type == Token.NONE){
1316 return adjust_real (type);
1318 Console.WriteLine ("This should not be reached");
1319 throw new Exception ("Is Number should never reach this point");
1323 // Accepts exactly count (4 or 8) hex, no more no less
1325 int getHex (int count, out bool error)
1330 int top = count != -1 ? count : 4;
1334 for (i = 0; i < top; i++){
1337 if (c >= '0' && c <= '9')
1338 c = (int) c - (int) '0';
1339 else if (c >= 'A' && c <= 'F')
1340 c = (int) c - (int) 'A' + 10;
1341 else if (c >= 'a' && c <= 'f')
1342 c = (int) c - (int) 'a' + 10;
1348 total = (total * 16) + c;
1350 int p = peek_char ();
1353 if (!is_hex ((char)p))
1394 v = getHex (-1, out error);
1399 v = getHex (4, out error);
1404 v = getHex (8, out error);
1409 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1419 if (putback_char != -1) {
1432 void advance_line ()
1442 if (putback_char != -1)
1443 return putback_char;
1444 putback_char = reader.Read ();
1445 return putback_char;
1450 if (putback_char != -1)
1451 return putback_char;
1452 return reader.Peek ();
1455 void putback (int c)
1457 if (putback_char != -1){
1458 Console.WriteLine ("Col: " + col);
1459 Console.WriteLine ("Row: " + line);
1460 Console.WriteLine ("Name: " + ref_name.Name);
1461 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1462 throw new Exception ("This should not happen putback on putback");
1464 if (c == '\n' || col == 0) {
1465 // It won't happen though.
1475 public bool advance ()
1477 return peek_char () != -1;
1480 public Object Value {
1486 public Object value ()
1491 static bool IsCastToken (int token)
1496 case Token.IDENTIFIER:
1497 case Token.LITERAL_INTEGER:
1498 case Token.LITERAL_FLOAT:
1499 case Token.LITERAL_DOUBLE:
1500 case Token.LITERAL_DECIMAL:
1501 case Token.LITERAL_CHARACTER:
1502 case Token.LITERAL_STRING:
1505 case Token.DELEGATE:
1515 case Token.UNCHECKED:
1520 // These can be part of a member access
1542 current_token = xtoken ();
1544 if (current_token != Token.DEFAULT)
1545 return current_token;
1550 current_token = Token.ERROR;
1551 else if (c == Token.OPEN_PARENS)
1552 current_token = Token.DEFAULT_OPEN_PARENS;
1553 else if (c == Token.COLON)
1554 current_token = Token.DEFAULT_COLON;
1558 return current_token;
1561 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1563 void get_cmd_arg (out string cmd, out string arg)
1567 tokens_seen = false;
1569 static_cmd_arg.Length = 0;
1571 // skip over white space
1572 while ((c = get_char ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1575 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1576 if (is_identifier_part_character ((char) c)){
1577 static_cmd_arg.Append ((char) c);
1585 cmd = static_cmd_arg.ToString ();
1587 if (c == '\n' || c == '\r'){
1591 // skip over white space
1592 while ((c = get_char ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1597 } else if (c == '\r'){
1599 } else if (c == -1){
1604 static_cmd_arg.Length = 0;
1605 static_cmd_arg.Append ((char) c);
1607 while ((c = get_char ()) != -1 && (c != '\n') && (c != '\r')){
1608 static_cmd_arg.Append ((char) c);
1611 arg = static_cmd_arg.ToString ();
1615 // Handles the #line directive
1617 bool PreProcessLine (string arg)
1619 if (arg.Length == 0)
1622 if (arg == "default"){
1624 ref_name = file_name;
1626 Location.Push (file_name, ref_name);
1628 } else if (arg == "hidden"){
1636 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1637 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1640 char [] quotes = { '\"' };
1642 string name = arg.Substring (pos). Trim (quotes);
1643 ref_name = Location.LookupFile (file_name, name);
1644 file_name.AddFile (ref_name);
1646 Location.Push (file_name, ref_name);
1648 ref_line = System.Int32.Parse (arg);
1659 // Handles #define and #undef
1661 void PreProcessDefinition (bool is_define, string arg, bool caller_is_taking)
1663 if (arg.Length == 0 || arg == "true" || arg == "false"){
1664 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1668 if (arg.IndexOfAny (simple_whitespaces) != -1){
1669 Error_EndLineExpected ();
1673 if (!is_identifier_start_character (arg [0]))
1674 Report.Error (1001, Location, "Identifier expected: " + arg);
1676 foreach (char c in arg.Substring (1)){
1677 if (!is_identifier_part_character (c)){
1678 Report.Error (1001, Location, "Identifier expected: " + arg);
1683 if (!caller_is_taking)
1687 if (defines == null)
1688 defines = new Hashtable ();
1691 if (defines == null)
1693 if (defines.Contains (arg))
1694 defines.Remove (arg);
1698 byte read_hex (string arg, int pos, out bool error)
1705 if ((c >= '0') && (c <= '9'))
1706 total = (int) c - (int) '0';
1707 else if ((c >= 'A') && (c <= 'F'))
1708 total = (int) c - (int) 'A' + 10;
1709 else if ((c >= 'a') && (c <= 'f'))
1710 total = (int) c - (int) 'a' + 10;
1719 if ((c >= '0') && (c <= '9'))
1720 total += (int) c - (int) '0';
1721 else if ((c >= 'A') && (c <= 'F'))
1722 total += (int) c - (int) 'A' + 10;
1723 else if ((c >= 'a') && (c <= 'f'))
1724 total += (int) c - (int) 'a' + 10;
1730 return (byte) total;
1734 /// Handles #pragma checksum
1736 bool PreProcessPragmaChecksum (string arg)
1738 if ((arg [0] != ' ') && (arg [0] != '\t'))
1741 arg = arg.Trim (simple_whitespaces);
1742 if ((arg.Length < 2) || (arg [0] != '"'))
1745 StringBuilder file_sb = new StringBuilder ();
1749 while ((ch = arg [pos++]) != '"') {
1750 if (pos >= arg.Length)
1754 if (pos+1 >= arg.Length)
1759 file_sb.Append (ch);
1762 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1765 arg = arg.Substring (pos).Trim (simple_whitespaces);
1766 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1767 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1768 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1772 byte[] guid_bytes = new byte [16];
1774 for (int i = 0; i < 4; i++) {
1775 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1779 for (int i = 0; i < 2; i++) {
1780 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1783 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1786 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1791 for (int i = 0; i < 6; i++) {
1792 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1797 arg = arg.Substring (40).Trim (simple_whitespaces);
1798 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1801 byte[] checksum_bytes = new byte [16];
1802 for (int i = 0; i < 16; i++) {
1803 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1808 arg = arg.Substring (34).Trim (simple_whitespaces);
1812 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1813 file.SetChecksum (guid_bytes, checksum_bytes);
1814 ref_name.AutoGenerated = true;
1819 /// Handles #pragma directive
1821 void PreProcessPragma (string arg)
1823 const string warning = "warning";
1824 const string w_disable = "warning disable";
1825 const string w_restore = "warning restore";
1826 const string checksum = "checksum";
1828 if (arg == w_disable) {
1829 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1833 if (arg == w_restore) {
1834 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1838 if (arg.StartsWith (w_disable)) {
1839 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1840 foreach (int code in codes) {
1842 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1847 if (arg.StartsWith (w_restore)) {
1848 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1849 Hashtable w_table = Report.warning_ignore_table;
1850 foreach (int code in codes) {
1851 if (w_table != null && w_table.Contains (code))
1852 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1853 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1858 if (arg.StartsWith (warning)) {
1859 Report.Warning (1634, 1, Location, "Expected disable or restore");
1863 if (arg.StartsWith (checksum)) {
1864 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1865 Warning_InvalidPragmaChecksum ();
1869 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1872 int[] ParseNumbers (string text)
1874 string[] string_array = text.Split (',');
1875 int[] values = new int [string_array.Length];
1877 foreach (string string_code in string_array) {
1879 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1881 catch (FormatException) {
1882 Report.Warning (1692, 1, Location, "Invalid number");
1888 bool eval_val (string s)
1895 if (defines == null)
1897 if (defines.Contains (s))
1903 bool pp_primary (ref string s)
1912 s = s.Substring (1);
1913 bool val = pp_expr (ref s, false);
1914 if (s.Length > 0 && s [0] == ')'){
1915 s = s.Substring (1);
1918 Error_InvalidDirective ();
1922 if (is_identifier_start_character (c)){
1928 if (is_identifier_part_character (c)){
1932 bool v = eval_val (s.Substring (0, j));
1933 s = s.Substring (j);
1936 bool vv = eval_val (s);
1941 Error_InvalidDirective ();
1945 bool pp_unary (ref string s)
1952 if (len > 1 && s [1] == '='){
1953 Error_InvalidDirective ();
1956 s = s.Substring (1);
1957 return ! pp_primary (ref s);
1959 return pp_primary (ref s);
1961 Error_InvalidDirective ();
1966 bool pp_eq (ref string s)
1968 bool va = pp_unary (ref s);
1974 if (len > 2 && s [1] == '='){
1975 s = s.Substring (2);
1976 return va == pp_unary (ref s);
1978 Error_InvalidDirective ();
1981 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1982 s = s.Substring (2);
1984 return va != pp_unary (ref s);
1993 bool pp_and (ref string s)
1995 bool va = pp_eq (ref s);
2001 if (len > 2 && s [1] == '&'){
2002 s = s.Substring (2);
2003 return (va & pp_and (ref s));
2005 Error_InvalidDirective ();
2014 // Evaluates an expression for `#if' or `#elif'
2016 bool pp_expr (ref string s, bool isTerm)
2018 bool va = pp_and (ref s);
2025 if (len > 2 && s [1] == '|'){
2026 s = s.Substring (2);
2027 return va | pp_expr (ref s, isTerm);
2029 Error_InvalidDirective ();
2034 Error_EndLineExpected ();
2042 bool eval (string s)
2044 bool v = pp_expr (ref s, true);
2053 void Error_NumericConstantTooLong ()
2055 Report.Error (1021, Location, "Numeric constant too long");
2058 void Error_InvalidDirective ()
2060 Report.Error (1517, Location, "Invalid preprocessor directive");
2063 void Error_UnexpectedDirective (string extra)
2067 "Unexpected processor directive (" + extra + ")");
2070 void Error_TokenExpected (string token)
2072 Report.Error (1026, Location, "Expected `{0}'", token);
2075 void Error_TokensSeen ()
2077 Report.Error (1032, Location,
2078 "Cannot define or undefine preprocessor symbols after first token in file");
2081 void Eror_WrongPreprocessorLocation ()
2083 Report.Error (1040, Location,
2084 "Preprocessor directives must appear as the first non-whitespace character on a line");
2087 void Error_EndLineExpected ()
2089 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2092 void Warning_InvalidPragmaChecksum ()
2094 Report.Warning (1695, 1, Location,
2095 "Invalid #pragma checksum syntax; should be " +
2096 "#pragma checksum \"filename\" " +
2097 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2100 // if true, then the code continues processing the code
2101 // if false, the code stays in a loop until another directive is
2103 // When caller_is_taking is false we ignore all directives except the ones
2104 // which can help us to identify where the #if block ends
2105 bool handle_preprocessing_directive (bool caller_is_taking)
2108 bool region_directive = false;
2110 get_cmd_arg (out cmd, out arg);
2112 // Eat any trailing whitespaces and single-line comments
2113 if (arg.IndexOf ("//") != -1)
2114 arg = arg.Substring (0, arg.IndexOf ("//"));
2115 arg = arg.Trim (simple_whitespaces);
2118 // The first group of pre-processing instructions is always processed
2122 region_directive = true;
2127 if (ifstack == null || ifstack.Count == 0){
2128 Error_UnexpectedDirective ("no #region for this #endregion");
2131 int pop = (int) ifstack.Pop ();
2133 if ((pop & REGION) == 0)
2134 Report.Error (1027, Location, "Expected `#endif' directive");
2136 return caller_is_taking;
2139 if (ifstack == null)
2140 ifstack = new Stack (2);
2142 int flags = region_directive ? REGION : 0;
2143 if (ifstack.Count == 0){
2144 flags |= PARENT_TAKING;
2146 int state = (int) ifstack.Peek ();
2147 if ((state & TAKING) != 0) {
2148 flags |= PARENT_TAKING;
2152 if (caller_is_taking && eval (arg)) {
2153 ifstack.Push (flags | TAKING);
2156 ifstack.Push (flags);
2160 if (ifstack == null || ifstack.Count == 0){
2161 Error_UnexpectedDirective ("no #if for this #endif");
2164 pop = (int) ifstack.Pop ();
2166 if ((pop & REGION) != 0)
2167 Report.Error (1038, Location, "#endregion directive expected");
2169 if (arg.Length != 0) {
2170 Error_EndLineExpected ();
2173 if (ifstack.Count == 0)
2176 int state = (int) ifstack.Peek ();
2177 return (state & TAKING) != 0;
2181 if (ifstack == null || ifstack.Count == 0){
2182 Error_UnexpectedDirective ("no #if for this #elif");
2185 int state = (int) ifstack.Pop ();
2187 if ((state & REGION) != 0) {
2188 Report.Error (1038, Location, "#endregion directive expected");
2192 if ((state & ELSE_SEEN) != 0){
2193 Error_UnexpectedDirective ("#elif not valid after #else");
2197 if ((state & TAKING) != 0) {
2202 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2203 ifstack.Push (state | TAKING);
2207 ifstack.Push (state);
2212 if (ifstack == null || ifstack.Count == 0){
2213 Error_UnexpectedDirective ("no #if for this #else");
2216 int state = (int) ifstack.Peek ();
2218 if ((state & REGION) != 0) {
2219 Report.Error (1038, Location, "#endregion directive expected");
2223 if ((state & ELSE_SEEN) != 0){
2224 Error_UnexpectedDirective ("#else within #else");
2230 if (arg.Length != 0) {
2231 Error_EndLineExpected ();
2236 if ((state & PARENT_TAKING) != 0) {
2237 ret = (state & TAKING) == 0;
2245 ifstack.Push (state | ELSE_SEEN);
2250 if (any_token_seen){
2251 Error_TokensSeen ();
2252 return caller_is_taking;
2254 PreProcessDefinition (true, arg, caller_is_taking);
2255 return caller_is_taking;
2258 if (any_token_seen){
2259 Error_TokensSeen ();
2260 return caller_is_taking;
2262 PreProcessDefinition (false, arg, caller_is_taking);
2263 return caller_is_taking;
2267 // These are only processed if we are in a `taking' block
2269 if (!caller_is_taking)
2274 Report.Error (1029, Location, "#error: '" + arg + "'");
2278 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2282 if (RootContext.Version == LanguageVersion.ISO_1) {
2283 Report.FeatureIsNotAvailable (Location, "#pragma");
2287 PreProcessPragma (arg);
2291 if (!PreProcessLine (arg))
2294 "The line number specified for #line directive is missing or invalid");
2295 return caller_is_taking;
2298 Report.Error (1024, Location, "Wrong preprocessor directive");
2303 private int consume_string (bool quoted)
2306 string_builder.Length = 0;
2309 // No need to parse full string when parsing lambda arguments
2311 if (lambda_arguments_parsing)
2312 return Token.LITERAL_STRING;
2314 while ((c = get_char ()) != -1){
2316 if (quoted && peek_char () == '"'){
2317 string_builder.Append ((char) c);
2321 val = string_builder.ToString ();
2322 return Token.LITERAL_STRING;
2328 Report.Error (1010, Location, "Newline in constant");
2336 string_builder.Append ((char) c);
2339 Report.Error (1039, Location, "Unterminated string literal");
2343 private int consume_identifier (int s)
2345 int res = consume_identifier (s, false);
2347 if (doc_state == XmlCommentState.Allowed)
2348 doc_state = XmlCommentState.NotAllowed;
2351 case Token.NAMESPACE:
2352 check_incorrect_doc_comment ();
2356 if (res == Token.PARTIAL) {
2357 if (parsing_block > 0) {
2358 val = new LocatedToken (Location, "partial");
2359 return Token.IDENTIFIER;
2362 // Save current position and parse next token.
2365 int next_token = token ();
2366 bool ok = (next_token == Token.CLASS) ||
2367 (next_token == Token.STRUCT) ||
2368 (next_token == Token.INTERFACE) ||
2369 (next_token == Token.VOID);
2374 if (next_token == Token.VOID) {
2375 if (RootContext.Version <= LanguageVersion.ISO_2)
2376 Report.FeatureIsNotAvailable (Location, "partial methods");
2377 } else if (RootContext.Version == LanguageVersion.ISO_1)
2378 Report.FeatureIsNotAvailable (Location, "partial types");
2383 if (next_token < Token.LAST_KEYWORD)
2384 Report.Error (267, Location, "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
2386 val = new LocatedToken (Location, "partial");
2387 return Token.IDENTIFIER;
2393 private int consume_identifier (int s, bool quoted)
2398 id_builder [0] = (char) s;
2400 current_location = new Location (ref_line, hidden ? -1 : Col);
2402 while ((c = get_char ()) != -1) {
2404 if (is_identifier_part_character ((char) c)){
2405 if (pos == max_id_size){
2406 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2410 id_builder [pos++] = (char) c;
2411 // putback_char = -1;
2412 } else if (c == '\\') {
2416 // putback_char = c;
2423 // Optimization: avoids doing the keyword lookup
2424 // on uppercase letters and _
2426 if (!quoted && (s >= 'a' || s == '_')){
2427 int keyword = GetKeyword (id_builder, pos);
2428 if (keyword != -1) {
2435 // Keep identifiers in an array of hashtables to avoid needless
2439 if (identifiers [pos] != null) {
2440 val = identifiers [pos][id_builder];
2442 val = new LocatedToken (Location, (string) val);
2444 escaped_identifiers.Add (val);
2445 return Token.IDENTIFIER;
2449 identifiers [pos] = new CharArrayHashtable (pos);
2451 val = new String (id_builder, 0, pos);
2452 if (RootContext.Version == LanguageVersion.ISO_1) {
2453 for (int i = 1; i < id_builder.Length; i += 3) {
2454 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2455 Report.Error (1638, Location,
2456 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2462 char [] chars = new char [pos];
2463 Array.Copy (id_builder, chars, pos);
2465 identifiers [pos] [chars] = val;
2467 val = new LocatedToken (Location, (string) val);
2469 escaped_identifiers.Add (val);
2470 return Token.IDENTIFIER;
2473 public int xtoken ()
2476 bool doread = false;
2479 // Whether we have seen comments on the current line
2480 bool comments_seen = false;
2482 for (;(c = get_char ()) != -1;) {
2484 col = ((col + 8) / 8) * 8;
2488 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0 || c == 0)
2492 if (peek_char () != '\n')
2497 any_token_seen |= tokens_seen;
2498 tokens_seen = false;
2499 comments_seen = false;
2503 // Handle double-slash comments.
2505 int d = peek_char ();
2509 if (RootContext.Documentation != null && peek_char () == '/') {
2511 // Don't allow ////.
2512 if ((d = peek_char ()) != '/') {
2513 update_comment_location ();
2514 if (doc_state == XmlCommentState.Allowed)
2515 handle_one_line_xml_comment ();
2516 else if (doc_state == XmlCommentState.NotAllowed)
2517 warn_incorrect_doc_comment ();
2520 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r')
2523 any_token_seen |= tokens_seen;
2524 tokens_seen = false;
2525 comments_seen = false;
2527 } else if (d == '*'){
2529 bool docAppend = false;
2530 if (RootContext.Documentation != null && peek_char () == '*') {
2532 update_comment_location ();
2533 // But when it is /**/, just do nothing.
2534 if (peek_char () == '/') {
2538 if (doc_state == XmlCommentState.Allowed)
2540 else if (doc_state == XmlCommentState.NotAllowed)
2541 warn_incorrect_doc_comment ();
2544 int current_comment_start = 0;
2546 current_comment_start = xml_comment_buffer.Length;
2547 xml_comment_buffer.Append (Environment.NewLine);
2550 Location start_location = Location;
2552 while ((d = get_char ()) != -1){
2553 if (d == '*' && peek_char () == '/'){
2555 comments_seen = true;
2559 xml_comment_buffer.Append ((char) d);
2562 any_token_seen |= tokens_seen;
2563 tokens_seen = false;
2565 // Reset 'comments_seen' just to be consistent.
2566 // It doesn't matter either way, here.
2568 comments_seen = false;
2572 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2575 update_formatted_doc_comment (current_comment_start);
2578 goto is_punct_label;
2582 if (c == '\\' || is_identifier_start_character ((char)c)){
2584 return consume_identifier (c);
2588 current_location = new Location (ref_line, hidden ? -1 : Col);
2589 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2599 any_token_seen |= tokens_seen;
2600 tokens_seen = false;
2601 comments_seen = false;
2605 if (c >= '0' && c <= '9'){
2607 return is_number (c);
2612 int peek = peek_char ();
2613 if (peek >= '0' && peek <= '9')
2614 return is_number (c);
2619 if (tokens_seen || comments_seen) {
2620 Eror_WrongPreprocessorLocation ();
2624 if (handle_preprocessing_directive (true))
2627 bool directive_expected = false;
2628 while ((c = get_char ()) != -1) {
2630 directive_expected = true;
2631 } else if (!directive_expected) {
2632 // TODO: Implement comment support for disabled code and uncomment this code
2634 // Eror_WrongPreprocessorLocation ();
2635 // return Token.ERROR;
2640 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2644 if (handle_preprocessing_directive (false))
2647 directive_expected = false;
2651 tokens_seen = false;
2659 return consume_string (false);
2665 error_details = "Empty character literal";
2666 Report.Error (1011, Location, error_details);
2669 if (c == '\r' || c == '\n') {
2670 Report.Error (1010, Location, "Newline in constant");
2676 val = new System.Char ();
2681 error_details = "Too many characters in character literal";
2682 Report.Error (1012, Location, error_details);
2684 // Try to recover, read until newline or next "'"
2685 while ((c = get_char ()) != -1){
2694 return Token.LITERAL_CHARACTER;
2701 return consume_string (true);
2702 } else if (is_identifier_start_character ((char) c)){
2703 return consume_identifier (c, true);
2705 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2709 error_details = ((char)c).ToString ();
2718 // Handles one line xml comment
2720 private void handle_one_line_xml_comment ()
2723 while ((c = peek_char ()) == ' ')
2724 get_char (); // skip heading whitespaces.
2725 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2726 xml_comment_buffer.Append ((char) get_char ());
2728 if (c == '\r' || c == '\n')
2729 xml_comment_buffer.Append (Environment.NewLine);
2733 // Remove heading "*" in Javadoc-like xml documentation.
2735 private void update_formatted_doc_comment (int current_comment_start)
2737 int length = xml_comment_buffer.Length - current_comment_start;
2738 string [] lines = xml_comment_buffer.ToString (
2739 current_comment_start,
2740 length).Replace ("\r", "").Split ('\n');
2742 // The first line starts with /**, thus it is not target
2743 // for the format check.
2744 for (int i = 1; i < lines.Length; i++) {
2745 string s = lines [i];
2746 int idx = s.IndexOf ('*');
2749 if (i < lines.Length - 1)
2753 head = s.Substring (0, idx);
2754 foreach (char c in head)
2757 lines [i] = s.Substring (idx + 1);
2759 xml_comment_buffer.Remove (current_comment_start, length);
2760 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2764 // Updates current comment location.
2766 private void update_comment_location ()
2768 if (current_comment_location.IsNull) {
2769 // "-2" is for heading "//" or "/*"
2770 current_comment_location =
2771 new Location (ref_line, hidden ? -1 : col - 2);
2776 // Checks if there was incorrect doc comments and raise
2779 public void check_incorrect_doc_comment ()
2781 if (xml_comment_buffer.Length > 0)
2782 warn_incorrect_doc_comment ();
2786 // Raises a warning when tokenizer found incorrect doccomment
2789 private void warn_incorrect_doc_comment ()
2791 if (doc_state != XmlCommentState.Error) {
2792 doc_state = XmlCommentState.Error;
2793 // in csc, it is 'XML comment is not placed on
2794 // a valid language element'. But that does not
2796 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2801 // Consumes the saved xml comment lines (if any)
2802 // as for current target member or type.
2804 public string consume_doc_comment ()
2806 if (xml_comment_buffer.Length > 0) {
2807 string ret = xml_comment_buffer.ToString ();
2808 reset_doc_comment ();
2814 void reset_doc_comment ()
2816 xml_comment_buffer.Length = 0;
2817 current_comment_location = Location.Null;
2820 public void cleanup ()
2822 if (ifstack != null && ifstack.Count >= 1) {
2823 current_location = new Location (ref_line, hidden ? -1 : Col);
2824 int state = (int) ifstack.Pop ();
2825 if ((state & REGION) != 0)
2826 Report.Error (1038, Location, "#endregion directive expected");
2828 Report.Error (1027, Location, "Expected `#endif' directive");
2834 // Indicates whether it accepts XML documentation or not.
2836 public enum XmlCommentState {
2837 // comment is allowed in this state.
2839 // comment is not allowed in this state.
2841 // once comments appeared when it is NotAllowed, then the
2842 // state is changed to it, until the state is changed to