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 == '>') {
829 if (parsing_generic_less_than > 0) {
830 parsing_generic_less_than--;
831 return Token.OP_GENERICS_GT;
841 return Token.OP_SHIFT_RIGHT_ASSIGN;
843 return Token.OP_SHIFT_RIGHT;
844 } else if (d == '='){
859 t = Token.OP_ADD_ASSIGN;
873 t = Token.OP_SUB_ASSIGN;
911 } else if (d == '='){
913 return Token.OP_AND_ASSIGN;
916 return Token.BITWISE_AND;
923 } else if (d == '='){
925 return Token.OP_OR_ASSIGN;
927 return Token.BITWISE_OR;
933 return Token.OP_MULT_ASSIGN;
942 return Token.OP_DIV_ASSIGN;
950 return Token.OP_MOD_ASSIGN;
952 return Token.PERCENT;
958 return Token.OP_XOR_ASSIGN;
966 return Token.DOUBLE_COLON;
975 int deambiguate_close_parens = 0;
977 public void Deambiguate_CloseParens (object expression)
981 // When any binary operation, a conditional is used we are sure it is not a cast
984 if (expression is Binary || expression is Conditional)
987 deambiguate_close_parens++;
990 bool decimal_digits (int c)
993 bool seen_digits = false;
996 if (number_pos == max_number_size)
997 Error_NumericConstantTooLong ();
998 number_builder [number_pos++] = (char) c;
1002 // We use peek_char2, because decimal_digits needs to do a
1003 // 2-character look-ahead (5.ToString for example).
1005 while ((d = peek_char2 ()) != -1){
1006 if (d >= '0' && d <= '9'){
1007 if (number_pos == max_number_size)
1008 Error_NumericConstantTooLong ();
1009 number_builder [number_pos++] = (char) d;
1019 static bool is_hex (int e)
1021 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1024 static int real_type_suffix (int c)
1030 t = Token.LITERAL_FLOAT;
1033 t = Token.LITERAL_DOUBLE;
1036 t= Token.LITERAL_DECIMAL;
1044 int integer_type_suffix (ulong ul, int c)
1046 bool is_unsigned = false;
1047 bool is_long = false;
1050 bool scanning = true;
1063 // if we have not seen anything in between
1064 // report this error
1066 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1069 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1070 // work around that.
1094 if (is_long && is_unsigned){
1096 return Token.LITERAL_INTEGER;
1097 } else if (is_unsigned){
1098 // uint if possible, or ulong else.
1100 if ((ul & 0xffffffff00000000) == 0)
1104 } else if (is_long){
1105 // long if possible, ulong otherwise
1106 if ((ul & 0x8000000000000000) != 0)
1111 // int, uint, long or ulong in that order
1112 if ((ul & 0xffffffff00000000) == 0){
1113 uint ui = (uint) ul;
1115 if ((ui & 0x80000000) != 0)
1120 if ((ul & 0x8000000000000000) != 0)
1126 return Token.LITERAL_INTEGER;
1130 // given `c' as the next char in the input decide whether
1131 // we need to convert to a special type, and then choose
1132 // the best representation for the integer
1134 int adjust_int (int c)
1137 if (number_pos > 9){
1138 ulong ul = (uint) (number_builder [0] - '0');
1140 for (int i = 1; i < number_pos; i++){
1141 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1143 return integer_type_suffix (ul, c);
1145 uint ui = (uint) (number_builder [0] - '0');
1147 for (int i = 1; i < number_pos; i++){
1148 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1150 return integer_type_suffix (ui, c);
1152 } catch (OverflowException) {
1153 error_details = "Integral constant is too large";
1154 Report.Error (1021, Location, error_details);
1156 return Token.LITERAL_INTEGER;
1158 catch (FormatException) {
1159 Report.Error (1013, Location, "Invalid number");
1161 return Token.LITERAL_INTEGER;
1165 int adjust_real (int t)
1167 string s = new String (number_builder, 0, number_pos);
1168 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1171 case Token.LITERAL_DECIMAL:
1173 val = System.Decimal.Parse (s, styles, csharp_format_info);
1174 } catch (OverflowException) {
1176 Report.Error (594, Location, error_details, "decimal");
1179 case Token.LITERAL_FLOAT:
1181 val = float.Parse (s, styles, csharp_format_info);
1182 } catch (OverflowException) {
1184 Report.Error (594, Location, error_details, "float");
1188 case Token.LITERAL_DOUBLE:
1190 t = Token.LITERAL_DOUBLE;
1192 val = System.Double.Parse (s, styles, csharp_format_info);
1193 } catch (OverflowException) {
1195 Report.Error (594, Location, error_details, "double");
1208 while ((d = peek_char ()) != -1){
1210 number_builder [number_pos++] = (char) d;
1216 string s = new String (number_builder, 0, number_pos);
1218 if (number_pos <= 8)
1219 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1221 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1222 } catch (OverflowException){
1223 error_details = "Integral constant is too large";
1224 Report.Error (1021, Location, error_details);
1226 return Token.LITERAL_INTEGER;
1228 catch (FormatException) {
1229 Report.Error (1013, Location, "Invalid number");
1231 return Token.LITERAL_INTEGER;
1234 return integer_type_suffix (ul, peek_char ());
1238 // Invoked if we know we have .digits or digits
1240 int is_number (int c)
1242 bool is_real = false;
1247 if (c >= '0' && c <= '9'){
1249 int peek = peek_char ();
1251 if (peek == 'x' || peek == 'X')
1252 return handle_hex ();
1259 // We need to handle the case of
1260 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1263 if (decimal_digits ('.')){
1269 return adjust_int (-1);
1273 if (c == 'e' || c == 'E'){
1275 if (number_pos == max_number_size)
1276 Error_NumericConstantTooLong ();
1277 number_builder [number_pos++] = 'e';
1281 if (number_pos == max_number_size)
1282 Error_NumericConstantTooLong ();
1283 number_builder [number_pos++] = '+';
1285 } else if (c == '-') {
1286 if (number_pos == max_number_size)
1287 Error_NumericConstantTooLong ();
1288 number_builder [number_pos++] = '-';
1291 if (number_pos == max_number_size)
1292 Error_NumericConstantTooLong ();
1293 number_builder [number_pos++] = '+';
1300 type = real_type_suffix (c);
1301 if (type == Token.NONE && !is_real){
1303 return adjust_int (c);
1307 if (type == Token.NONE){
1312 return adjust_real (type);
1314 Console.WriteLine ("This should not be reached");
1315 throw new Exception ("Is Number should never reach this point");
1319 // Accepts exactly count (4 or 8) hex, no more no less
1321 int getHex (int count, out bool error)
1326 int top = count != -1 ? count : 4;
1330 for (i = 0; i < top; i++){
1333 if (c >= '0' && c <= '9')
1334 c = (int) c - (int) '0';
1335 else if (c >= 'A' && c <= 'F')
1336 c = (int) c - (int) 'A' + 10;
1337 else if (c >= 'a' && c <= 'f')
1338 c = (int) c - (int) 'a' + 10;
1344 total = (total * 16) + c;
1346 int p = peek_char ();
1349 if (!is_hex ((char)p))
1390 v = getHex (-1, out error);
1395 v = getHex (4, out error);
1400 v = getHex (8, out error);
1405 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1415 if (putback_char != -1) {
1428 void advance_line ()
1438 if (putback_char != -1)
1439 return putback_char;
1440 putback_char = reader.Read ();
1441 return putback_char;
1446 if (putback_char != -1)
1447 return putback_char;
1448 return reader.Peek ();
1451 void putback (int c)
1453 if (putback_char != -1){
1454 Console.WriteLine ("Col: " + col);
1455 Console.WriteLine ("Row: " + line);
1456 Console.WriteLine ("Name: " + ref_name.Name);
1457 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1458 throw new Exception ("This should not happen putback on putback");
1460 if (c == '\n' || col == 0) {
1461 // It won't happen though.
1471 public bool advance ()
1473 return peek_char () != -1;
1476 public Object Value {
1482 public Object value ()
1487 static bool IsCastToken (int token)
1492 case Token.IDENTIFIER:
1493 case Token.LITERAL_INTEGER:
1494 case Token.LITERAL_FLOAT:
1495 case Token.LITERAL_DOUBLE:
1496 case Token.LITERAL_DECIMAL:
1497 case Token.LITERAL_CHARACTER:
1498 case Token.LITERAL_STRING:
1501 case Token.DELEGATE:
1511 case Token.UNCHECKED:
1516 // These can be part of a member access
1538 current_token = xtoken ();
1540 if (current_token != Token.DEFAULT)
1541 return current_token;
1546 current_token = Token.ERROR;
1547 else if (c == Token.OPEN_PARENS)
1548 current_token = Token.DEFAULT_OPEN_PARENS;
1549 else if (c == Token.COLON)
1550 current_token = Token.DEFAULT_COLON;
1554 return current_token;
1557 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1559 void get_cmd_arg (out string cmd, out string arg)
1563 tokens_seen = false;
1565 static_cmd_arg.Length = 0;
1567 // skip over white space
1568 while ((c = get_char ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1571 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1572 if (is_identifier_part_character ((char) c)){
1573 static_cmd_arg.Append ((char) c);
1581 cmd = static_cmd_arg.ToString ();
1583 if (c == '\n' || c == '\r'){
1587 // skip over white space
1588 while ((c = get_char ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1593 } else if (c == '\r'){
1595 } else if (c == -1){
1600 static_cmd_arg.Length = 0;
1601 static_cmd_arg.Append ((char) c);
1603 while ((c = get_char ()) != -1 && (c != '\n') && (c != '\r')){
1604 static_cmd_arg.Append ((char) c);
1607 arg = static_cmd_arg.ToString ();
1611 // Handles the #line directive
1613 bool PreProcessLine (string arg)
1615 if (arg.Length == 0)
1618 if (arg == "default"){
1620 ref_name = file_name;
1622 Location.Push (file_name, ref_name);
1624 } else if (arg == "hidden"){
1632 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1633 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1636 char [] quotes = { '\"' };
1638 string name = arg.Substring (pos). Trim (quotes);
1639 ref_name = Location.LookupFile (file_name, name);
1640 file_name.AddFile (ref_name);
1642 Location.Push (file_name, ref_name);
1644 ref_line = System.Int32.Parse (arg);
1655 // Handles #define and #undef
1657 void PreProcessDefinition (bool is_define, string arg, bool caller_is_taking)
1659 if (arg.Length == 0 || arg == "true" || arg == "false"){
1660 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1664 if (arg.IndexOfAny (simple_whitespaces) != -1){
1665 Error_EndLineExpected ();
1669 if (!is_identifier_start_character (arg [0]))
1670 Report.Error (1001, Location, "Identifier expected: " + arg);
1672 foreach (char c in arg.Substring (1)){
1673 if (!is_identifier_part_character (c)){
1674 Report.Error (1001, Location, "Identifier expected: " + arg);
1679 if (!caller_is_taking)
1683 if (defines == null)
1684 defines = new Hashtable ();
1687 if (defines == null)
1689 if (defines.Contains (arg))
1690 defines.Remove (arg);
1694 byte read_hex (string arg, int pos, out bool error)
1701 if ((c >= '0') && (c <= '9'))
1702 total = (int) c - (int) '0';
1703 else if ((c >= 'A') && (c <= 'F'))
1704 total = (int) c - (int) 'A' + 10;
1705 else if ((c >= 'a') && (c <= 'f'))
1706 total = (int) c - (int) 'a' + 10;
1715 if ((c >= '0') && (c <= '9'))
1716 total += (int) c - (int) '0';
1717 else if ((c >= 'A') && (c <= 'F'))
1718 total += (int) c - (int) 'A' + 10;
1719 else if ((c >= 'a') && (c <= 'f'))
1720 total += (int) c - (int) 'a' + 10;
1726 return (byte) total;
1730 /// Handles #pragma checksum
1732 bool PreProcessPragmaChecksum (string arg)
1734 if ((arg [0] != ' ') && (arg [0] != '\t'))
1737 arg = arg.Trim (simple_whitespaces);
1738 if ((arg.Length < 2) || (arg [0] != '"'))
1741 StringBuilder file_sb = new StringBuilder ();
1745 while ((ch = arg [pos++]) != '"') {
1746 if (pos >= arg.Length)
1750 if (pos+1 >= arg.Length)
1755 file_sb.Append (ch);
1758 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1761 arg = arg.Substring (pos).Trim (simple_whitespaces);
1762 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1763 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1764 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1768 byte[] guid_bytes = new byte [16];
1770 for (int i = 0; i < 4; i++) {
1771 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1775 for (int i = 0; i < 2; i++) {
1776 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1779 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1782 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1787 for (int i = 0; i < 6; i++) {
1788 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1793 arg = arg.Substring (40).Trim (simple_whitespaces);
1794 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1797 byte[] checksum_bytes = new byte [16];
1798 for (int i = 0; i < 16; i++) {
1799 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1804 arg = arg.Substring (34).Trim (simple_whitespaces);
1808 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1809 file.SetChecksum (guid_bytes, checksum_bytes);
1810 ref_name.AutoGenerated = true;
1815 /// Handles #pragma directive
1817 void PreProcessPragma (string arg)
1819 const string warning = "warning";
1820 const string w_disable = "warning disable";
1821 const string w_restore = "warning restore";
1822 const string checksum = "checksum";
1824 if (arg == w_disable) {
1825 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1829 if (arg == w_restore) {
1830 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1834 if (arg.StartsWith (w_disable)) {
1835 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1836 foreach (int code in codes) {
1838 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1843 if (arg.StartsWith (w_restore)) {
1844 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1845 Hashtable w_table = Report.warning_ignore_table;
1846 foreach (int code in codes) {
1847 if (w_table != null && w_table.Contains (code))
1848 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1849 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1854 if (arg.StartsWith (warning)) {
1855 Report.Warning (1634, 1, Location, "Expected disable or restore");
1859 if (arg.StartsWith (checksum)) {
1860 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1861 Warning_InvalidPragmaChecksum ();
1865 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1868 int[] ParseNumbers (string text)
1870 string[] string_array = text.Split (',');
1871 int[] values = new int [string_array.Length];
1873 foreach (string string_code in string_array) {
1875 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1877 catch (FormatException) {
1878 Report.Warning (1692, 1, Location, "Invalid number");
1884 bool eval_val (string s)
1891 if (defines == null)
1893 if (defines.Contains (s))
1899 bool pp_primary (ref string s)
1908 s = s.Substring (1);
1909 bool val = pp_expr (ref s, false);
1910 if (s.Length > 0 && s [0] == ')'){
1911 s = s.Substring (1);
1914 Error_InvalidDirective ();
1918 if (is_identifier_start_character (c)){
1924 if (is_identifier_part_character (c)){
1928 bool v = eval_val (s.Substring (0, j));
1929 s = s.Substring (j);
1932 bool vv = eval_val (s);
1937 Error_InvalidDirective ();
1941 bool pp_unary (ref string s)
1948 if (len > 1 && s [1] == '='){
1949 Error_InvalidDirective ();
1952 s = s.Substring (1);
1953 return ! pp_primary (ref s);
1955 return pp_primary (ref s);
1957 Error_InvalidDirective ();
1962 bool pp_eq (ref string s)
1964 bool va = pp_unary (ref s);
1970 if (len > 2 && s [1] == '='){
1971 s = s.Substring (2);
1972 return va == pp_unary (ref s);
1974 Error_InvalidDirective ();
1977 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1978 s = s.Substring (2);
1980 return va != pp_unary (ref s);
1989 bool pp_and (ref string s)
1991 bool va = pp_eq (ref s);
1997 if (len > 2 && s [1] == '&'){
1998 s = s.Substring (2);
1999 return (va & pp_and (ref s));
2001 Error_InvalidDirective ();
2010 // Evaluates an expression for `#if' or `#elif'
2012 bool pp_expr (ref string s, bool isTerm)
2014 bool va = pp_and (ref s);
2021 if (len > 2 && s [1] == '|'){
2022 s = s.Substring (2);
2023 return va | pp_expr (ref s, isTerm);
2025 Error_InvalidDirective ();
2030 Error_EndLineExpected ();
2038 bool eval (string s)
2040 bool v = pp_expr (ref s, true);
2049 void Error_NumericConstantTooLong ()
2051 Report.Error (1021, Location, "Numeric constant too long");
2054 void Error_InvalidDirective ()
2056 Report.Error (1517, Location, "Invalid preprocessor directive");
2059 void Error_UnexpectedDirective (string extra)
2063 "Unexpected processor directive (" + extra + ")");
2066 void Error_TokenExpected (string token)
2068 Report.Error (1026, Location, "Expected `{0}'", token);
2071 void Error_TokensSeen ()
2073 Report.Error (1032, Location,
2074 "Cannot define or undefine preprocessor symbols after first token in file");
2077 void Eror_WrongPreprocessorLocation ()
2079 Report.Error (1040, Location,
2080 "Preprocessor directives must appear as the first non-whitespace character on a line");
2083 void Error_EndLineExpected ()
2085 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2088 void Warning_InvalidPragmaChecksum ()
2090 Report.Warning (1695, 1, Location,
2091 "Invalid #pragma checksum syntax; should be " +
2092 "#pragma checksum \"filename\" " +
2093 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2096 // if true, then the code continues processing the code
2097 // if false, the code stays in a loop until another directive is
2099 // When caller_is_taking is false we ignore all directives except the ones
2100 // which can help us to identify where the #if block ends
2101 bool handle_preprocessing_directive (bool caller_is_taking)
2104 bool region_directive = false;
2106 get_cmd_arg (out cmd, out arg);
2108 // Eat any trailing whitespaces and single-line comments
2109 if (arg.IndexOf ("//") != -1)
2110 arg = arg.Substring (0, arg.IndexOf ("//"));
2111 arg = arg.Trim (simple_whitespaces);
2114 // The first group of pre-processing instructions is always processed
2118 region_directive = true;
2123 if (ifstack == null || ifstack.Count == 0){
2124 Error_UnexpectedDirective ("no #region for this #endregion");
2127 int pop = (int) ifstack.Pop ();
2129 if ((pop & REGION) == 0)
2130 Report.Error (1027, Location, "Expected `#endif' directive");
2132 return caller_is_taking;
2135 if (ifstack == null)
2136 ifstack = new Stack (2);
2138 int flags = region_directive ? REGION : 0;
2139 if (ifstack.Count == 0){
2140 flags |= PARENT_TAKING;
2142 int state = (int) ifstack.Peek ();
2143 if ((state & TAKING) != 0) {
2144 flags |= PARENT_TAKING;
2148 if (caller_is_taking && eval (arg)) {
2149 ifstack.Push (flags | TAKING);
2152 ifstack.Push (flags);
2156 if (ifstack == null || ifstack.Count == 0){
2157 Error_UnexpectedDirective ("no #if for this #endif");
2160 pop = (int) ifstack.Pop ();
2162 if ((pop & REGION) != 0)
2163 Report.Error (1038, Location, "#endregion directive expected");
2165 if (arg.Length != 0) {
2166 Error_EndLineExpected ();
2169 if (ifstack.Count == 0)
2172 int state = (int) ifstack.Peek ();
2173 return (state & TAKING) != 0;
2177 if (ifstack == null || ifstack.Count == 0){
2178 Error_UnexpectedDirective ("no #if for this #elif");
2181 int state = (int) ifstack.Pop ();
2183 if ((state & REGION) != 0) {
2184 Report.Error (1038, Location, "#endregion directive expected");
2188 if ((state & ELSE_SEEN) != 0){
2189 Error_UnexpectedDirective ("#elif not valid after #else");
2193 if ((state & TAKING) != 0) {
2198 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2199 ifstack.Push (state | TAKING);
2203 ifstack.Push (state);
2208 if (ifstack == null || ifstack.Count == 0){
2209 Error_UnexpectedDirective ("no #if for this #else");
2212 int state = (int) ifstack.Peek ();
2214 if ((state & REGION) != 0) {
2215 Report.Error (1038, Location, "#endregion directive expected");
2219 if ((state & ELSE_SEEN) != 0){
2220 Error_UnexpectedDirective ("#else within #else");
2226 if (arg.Length != 0) {
2227 Error_EndLineExpected ();
2232 if ((state & PARENT_TAKING) != 0) {
2233 ret = (state & TAKING) == 0;
2241 ifstack.Push (state | ELSE_SEEN);
2246 if (any_token_seen){
2247 Error_TokensSeen ();
2248 return caller_is_taking;
2250 PreProcessDefinition (true, arg, caller_is_taking);
2251 return caller_is_taking;
2254 if (any_token_seen){
2255 Error_TokensSeen ();
2256 return caller_is_taking;
2258 PreProcessDefinition (false, arg, caller_is_taking);
2259 return caller_is_taking;
2263 // These are only processed if we are in a `taking' block
2265 if (!caller_is_taking)
2270 Report.Error (1029, Location, "#error: '" + arg + "'");
2274 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2278 if (RootContext.Version == LanguageVersion.ISO_1) {
2279 Report.FeatureIsNotAvailable (Location, "#pragma");
2283 PreProcessPragma (arg);
2287 if (!PreProcessLine (arg))
2290 "The line number specified for #line directive is missing or invalid");
2291 return caller_is_taking;
2294 Report.Error (1024, Location, "Wrong preprocessor directive");
2299 private int consume_string (bool quoted)
2302 string_builder.Length = 0;
2305 // No need to parse full string when parsing lambda arguments
2307 if (lambda_arguments_parsing)
2308 return Token.LITERAL_STRING;
2310 while ((c = get_char ()) != -1){
2312 if (quoted && peek_char () == '"'){
2313 string_builder.Append ((char) c);
2317 val = string_builder.ToString ();
2318 return Token.LITERAL_STRING;
2324 Report.Error (1010, Location, "Newline in constant");
2332 string_builder.Append ((char) c);
2335 Report.Error (1039, Location, "Unterminated string literal");
2339 private int consume_identifier (int s)
2341 int res = consume_identifier (s, false);
2343 if (doc_state == XmlCommentState.Allowed)
2344 doc_state = XmlCommentState.NotAllowed;
2347 case Token.NAMESPACE:
2348 check_incorrect_doc_comment ();
2352 if (res == Token.PARTIAL) {
2353 if (parsing_block > 0) {
2354 val = new LocatedToken (Location, "partial");
2355 return Token.IDENTIFIER;
2358 // Save current position and parse next token.
2361 int next_token = token ();
2362 bool ok = (next_token == Token.CLASS) ||
2363 (next_token == Token.STRUCT) ||
2364 (next_token == Token.INTERFACE) ||
2365 (next_token == Token.VOID);
2370 if (next_token == Token.VOID) {
2371 if (RootContext.Version <= LanguageVersion.ISO_2)
2372 Report.FeatureIsNotAvailable (Location, "partial methods");
2373 } else if (RootContext.Version == LanguageVersion.ISO_1)
2374 Report.FeatureIsNotAvailable (Location, "partial types");
2379 if (next_token < Token.LAST_KEYWORD)
2380 Report.Error (267, Location, "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
2382 val = new LocatedToken (Location, "partial");
2383 return Token.IDENTIFIER;
2389 private int consume_identifier (int s, bool quoted)
2394 id_builder [0] = (char) s;
2396 current_location = new Location (ref_line, hidden ? -1 : Col);
2398 while ((c = get_char ()) != -1) {
2400 if (is_identifier_part_character ((char) c)){
2401 if (pos == max_id_size){
2402 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2406 id_builder [pos++] = (char) c;
2407 // putback_char = -1;
2408 } else if (c == '\\') {
2412 // putback_char = c;
2419 // Optimization: avoids doing the keyword lookup
2420 // on uppercase letters and _
2422 if (!quoted && (s >= 'a' || s == '_')){
2423 int keyword = GetKeyword (id_builder, pos);
2424 if (keyword != -1) {
2431 // Keep identifiers in an array of hashtables to avoid needless
2435 if (identifiers [pos] != null) {
2436 val = identifiers [pos][id_builder];
2438 val = new LocatedToken (Location, (string) val);
2440 escaped_identifiers.Add (val);
2441 return Token.IDENTIFIER;
2445 identifiers [pos] = new CharArrayHashtable (pos);
2447 val = new String (id_builder, 0, pos);
2448 if (RootContext.Version == LanguageVersion.ISO_1) {
2449 for (int i = 1; i < id_builder.Length; i += 3) {
2450 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2451 Report.Error (1638, Location,
2452 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2458 char [] chars = new char [pos];
2459 Array.Copy (id_builder, chars, pos);
2461 identifiers [pos] [chars] = val;
2463 val = new LocatedToken (Location, (string) val);
2465 escaped_identifiers.Add (val);
2466 return Token.IDENTIFIER;
2469 public int xtoken ()
2472 bool doread = false;
2475 // Whether we have seen comments on the current line
2476 bool comments_seen = false;
2478 for (;(c = get_char ()) != -1;) {
2480 col = ((col + 8) / 8) * 8;
2484 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0 || c == 0)
2488 if (peek_char () != '\n')
2493 any_token_seen |= tokens_seen;
2494 tokens_seen = false;
2495 comments_seen = false;
2499 // Handle double-slash comments.
2501 int d = peek_char ();
2505 if (RootContext.Documentation != null && peek_char () == '/') {
2507 // Don't allow ////.
2508 if ((d = peek_char ()) != '/') {
2509 update_comment_location ();
2510 if (doc_state == XmlCommentState.Allowed)
2511 handle_one_line_xml_comment ();
2512 else if (doc_state == XmlCommentState.NotAllowed)
2513 warn_incorrect_doc_comment ();
2516 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r')
2519 any_token_seen |= tokens_seen;
2520 tokens_seen = false;
2521 comments_seen = false;
2523 } else if (d == '*'){
2525 bool docAppend = false;
2526 if (RootContext.Documentation != null && peek_char () == '*') {
2528 update_comment_location ();
2529 // But when it is /**/, just do nothing.
2530 if (peek_char () == '/') {
2534 if (doc_state == XmlCommentState.Allowed)
2536 else if (doc_state == XmlCommentState.NotAllowed)
2537 warn_incorrect_doc_comment ();
2540 int current_comment_start = 0;
2542 current_comment_start = xml_comment_buffer.Length;
2543 xml_comment_buffer.Append (Environment.NewLine);
2546 Location start_location = Location;
2548 while ((d = get_char ()) != -1){
2549 if (d == '*' && peek_char () == '/'){
2551 comments_seen = true;
2555 xml_comment_buffer.Append ((char) d);
2558 any_token_seen |= tokens_seen;
2559 tokens_seen = false;
2561 // Reset 'comments_seen' just to be consistent.
2562 // It doesn't matter either way, here.
2564 comments_seen = false;
2568 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2571 update_formatted_doc_comment (current_comment_start);
2574 goto is_punct_label;
2578 if (c == '\\' || is_identifier_start_character ((char)c)){
2580 return consume_identifier (c);
2584 current_location = new Location (ref_line, hidden ? -1 : Col);
2585 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2595 any_token_seen |= tokens_seen;
2596 tokens_seen = false;
2597 comments_seen = false;
2601 if (c >= '0' && c <= '9'){
2603 return is_number (c);
2608 int peek = peek_char ();
2609 if (peek >= '0' && peek <= '9')
2610 return is_number (c);
2615 if (tokens_seen || comments_seen) {
2616 Eror_WrongPreprocessorLocation ();
2620 if (handle_preprocessing_directive (true))
2623 bool directive_expected = false;
2624 while ((c = get_char ()) != -1) {
2626 directive_expected = true;
2627 } else if (!directive_expected) {
2628 // TODO: Implement comment support for disabled code and uncomment this code
2630 // Eror_WrongPreprocessorLocation ();
2631 // return Token.ERROR;
2636 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2640 if (handle_preprocessing_directive (false))
2643 directive_expected = false;
2647 tokens_seen = false;
2655 return consume_string (false);
2661 error_details = "Empty character literal";
2662 Report.Error (1011, Location, error_details);
2665 if (c == '\r' || c == '\n') {
2666 Report.Error (1010, Location, "Newline in constant");
2672 val = new System.Char ();
2677 error_details = "Too many characters in character literal";
2678 Report.Error (1012, Location, error_details);
2680 // Try to recover, read until newline or next "'"
2681 while ((c = get_char ()) != -1){
2690 return Token.LITERAL_CHARACTER;
2697 return consume_string (true);
2698 } else if (is_identifier_start_character ((char) c)){
2699 return consume_identifier (c, true);
2701 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2705 error_details = ((char)c).ToString ();
2714 // Handles one line xml comment
2716 private void handle_one_line_xml_comment ()
2719 while ((c = peek_char ()) == ' ')
2720 get_char (); // skip heading whitespaces.
2721 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2722 xml_comment_buffer.Append ((char) get_char ());
2724 if (c == '\r' || c == '\n')
2725 xml_comment_buffer.Append (Environment.NewLine);
2729 // Remove heading "*" in Javadoc-like xml documentation.
2731 private void update_formatted_doc_comment (int current_comment_start)
2733 int length = xml_comment_buffer.Length - current_comment_start;
2734 string [] lines = xml_comment_buffer.ToString (
2735 current_comment_start,
2736 length).Replace ("\r", "").Split ('\n');
2738 // The first line starts with /**, thus it is not target
2739 // for the format check.
2740 for (int i = 1; i < lines.Length; i++) {
2741 string s = lines [i];
2742 int idx = s.IndexOf ('*');
2745 if (i < lines.Length - 1)
2749 head = s.Substring (0, idx);
2750 foreach (char c in head)
2753 lines [i] = s.Substring (idx + 1);
2755 xml_comment_buffer.Remove (current_comment_start, length);
2756 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2760 // Updates current comment location.
2762 private void update_comment_location ()
2764 if (current_comment_location.IsNull) {
2765 // "-2" is for heading "//" or "/*"
2766 current_comment_location =
2767 new Location (ref_line, hidden ? -1 : col - 2);
2772 // Checks if there was incorrect doc comments and raise
2775 public void check_incorrect_doc_comment ()
2777 if (xml_comment_buffer.Length > 0)
2778 warn_incorrect_doc_comment ();
2782 // Raises a warning when tokenizer found incorrect doccomment
2785 private void warn_incorrect_doc_comment ()
2787 if (doc_state != XmlCommentState.Error) {
2788 doc_state = XmlCommentState.Error;
2789 // in csc, it is 'XML comment is not placed on
2790 // a valid language element'. But that does not
2792 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2797 // Consumes the saved xml comment lines (if any)
2798 // as for current target member or type.
2800 public string consume_doc_comment ()
2802 if (xml_comment_buffer.Length > 0) {
2803 string ret = xml_comment_buffer.ToString ();
2804 reset_doc_comment ();
2810 void reset_doc_comment ()
2812 xml_comment_buffer.Length = 0;
2813 current_comment_location = Location.Null;
2816 public void cleanup ()
2818 if (ifstack != null && ifstack.Count >= 1) {
2819 current_location = new Location (ref_line, hidden ? -1 : Col);
2820 int state = (int) ifstack.Pop ();
2821 if ((state & REGION) != 0)
2822 Report.Error (1038, Location, "#endregion directive expected");
2824 Report.Error (1027, Location, "Expected `#endif' directive");
2830 // Indicates whether it accepts XML documentation or not.
2832 public enum XmlCommentState {
2833 // comment is allowed in this state.
2835 // comment is not allowed in this state.
2837 // once comments appeared when it is NotAllowed, then the
2838 // state is changed to it, until the state is changed to