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
187 const int TAKING = 1;
188 const int ELSE_SEEN = 4;
189 const int PARENT_TAKING = 8;
190 const int REGION = 16;
193 // pre-processor if stack state:
197 static System.Text.StringBuilder string_builder;
199 const int max_id_size = 512;
200 static char [] id_builder = new char [max_id_size];
202 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
204 const int max_number_size = 512;
205 static char [] number_builder = new char [max_number_size];
206 static int number_pos;
209 // Details about the error encoutered by the tokenizer
211 string error_details;
213 public string error {
215 return error_details;
232 // This is used when the tokenizer needs to save
233 // the current position as it needs to do some parsing
234 // on its own to deamiguate a token in behalf of the
237 Stack position_stack = new Stack (2);
244 public int putback_char;
245 public int previous_col;
246 public Stack ifstack;
247 public int parsing_generic_less_than;
248 public int current_token;
250 public Position (Tokenizer t)
252 position = t.reader.Position;
254 ref_line = t.ref_line;
257 putback_char = t.putback_char;
258 previous_col = t.previous_col;
259 if (t.ifstack != null && t.ifstack.Count != 0)
260 ifstack = (Stack)t.ifstack.Clone ();
261 parsing_generic_less_than = t.parsing_generic_less_than;
262 current_token = t.current_token;
266 public void PushPosition ()
268 position_stack.Push (new Position (this));
271 public void PopPosition ()
273 Position p = (Position) position_stack.Pop ();
275 reader.Position = p.position;
276 ref_line = p.ref_line;
280 putback_char = p.putback_char;
281 previous_col = p.previous_col;
283 parsing_generic_less_than = p.parsing_generic_less_than;
284 current_token = p.current_token;
287 // Do not reset the position, ignore it.
288 public void DiscardPosition ()
290 position_stack.Pop ();
293 static void AddKeyword (string kw, int token)
295 keyword_strings.Add (kw, kw);
296 if (keywords [kw.Length] == null) {
297 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
299 keywords [kw.Length] [kw.ToCharArray ()] = token;
302 static void InitTokens ()
304 keyword_strings = new Hashtable ();
305 keywords = new CharArrayHashtable [64];
307 AddKeyword ("__arglist", Token.ARGLIST);
308 AddKeyword ("abstract", Token.ABSTRACT);
309 AddKeyword ("as", Token.AS);
310 AddKeyword ("add", Token.ADD);
311 AddKeyword ("assembly", Token.ASSEMBLY);
312 AddKeyword ("base", Token.BASE);
313 AddKeyword ("bool", Token.BOOL);
314 AddKeyword ("break", Token.BREAK);
315 AddKeyword ("byte", Token.BYTE);
316 AddKeyword ("case", Token.CASE);
317 AddKeyword ("catch", Token.CATCH);
318 AddKeyword ("char", Token.CHAR);
319 AddKeyword ("checked", Token.CHECKED);
320 AddKeyword ("class", Token.CLASS);
321 AddKeyword ("const", Token.CONST);
322 AddKeyword ("continue", Token.CONTINUE);
323 AddKeyword ("decimal", Token.DECIMAL);
324 AddKeyword ("default", Token.DEFAULT);
325 AddKeyword ("delegate", Token.DELEGATE);
326 AddKeyword ("do", Token.DO);
327 AddKeyword ("double", Token.DOUBLE);
328 AddKeyword ("else", Token.ELSE);
329 AddKeyword ("enum", Token.ENUM);
330 AddKeyword ("event", Token.EVENT);
331 AddKeyword ("explicit", Token.EXPLICIT);
332 AddKeyword ("extern", Token.EXTERN);
333 AddKeyword ("false", Token.FALSE);
334 AddKeyword ("finally", Token.FINALLY);
335 AddKeyword ("fixed", Token.FIXED);
336 AddKeyword ("float", Token.FLOAT);
337 AddKeyword ("for", Token.FOR);
338 AddKeyword ("foreach", Token.FOREACH);
339 AddKeyword ("goto", Token.GOTO);
340 AddKeyword ("get", Token.GET);
341 AddKeyword ("if", Token.IF);
342 AddKeyword ("implicit", Token.IMPLICIT);
343 AddKeyword ("in", Token.IN);
344 AddKeyword ("int", Token.INT);
345 AddKeyword ("interface", Token.INTERFACE);
346 AddKeyword ("internal", Token.INTERNAL);
347 AddKeyword ("is", Token.IS);
348 AddKeyword ("lock", Token.LOCK);
349 AddKeyword ("long", Token.LONG);
350 AddKeyword ("namespace", Token.NAMESPACE);
351 AddKeyword ("new", Token.NEW);
352 AddKeyword ("null", Token.NULL);
353 AddKeyword ("object", Token.OBJECT);
354 AddKeyword ("operator", Token.OPERATOR);
355 AddKeyword ("out", Token.OUT);
356 AddKeyword ("override", Token.OVERRIDE);
357 AddKeyword ("params", Token.PARAMS);
358 AddKeyword ("private", Token.PRIVATE);
359 AddKeyword ("protected", Token.PROTECTED);
360 AddKeyword ("public", Token.PUBLIC);
361 AddKeyword ("readonly", Token.READONLY);
362 AddKeyword ("ref", Token.REF);
363 AddKeyword ("remove", Token.REMOVE);
364 AddKeyword ("return", Token.RETURN);
365 AddKeyword ("sbyte", Token.SBYTE);
366 AddKeyword ("sealed", Token.SEALED);
367 AddKeyword ("set", Token.SET);
368 AddKeyword ("short", Token.SHORT);
369 AddKeyword ("sizeof", Token.SIZEOF);
370 AddKeyword ("stackalloc", Token.STACKALLOC);
371 AddKeyword ("static", Token.STATIC);
372 AddKeyword ("string", Token.STRING);
373 AddKeyword ("struct", Token.STRUCT);
374 AddKeyword ("switch", Token.SWITCH);
375 AddKeyword ("this", Token.THIS);
376 AddKeyword ("throw", Token.THROW);
377 AddKeyword ("true", Token.TRUE);
378 AddKeyword ("try", Token.TRY);
379 AddKeyword ("typeof", Token.TYPEOF);
380 AddKeyword ("uint", Token.UINT);
381 AddKeyword ("ulong", Token.ULONG);
382 AddKeyword ("unchecked", Token.UNCHECKED);
383 AddKeyword ("unsafe", Token.UNSAFE);
384 AddKeyword ("ushort", Token.USHORT);
385 AddKeyword ("using", Token.USING);
386 AddKeyword ("virtual", Token.VIRTUAL);
387 AddKeyword ("void", Token.VOID);
388 AddKeyword ("volatile", Token.VOLATILE);
389 AddKeyword ("while", Token.WHILE);
390 AddKeyword ("partial", Token.PARTIAL);
391 AddKeyword ("where", Token.WHERE);
394 AddKeyword ("from", Token.FROM);
395 AddKeyword ("join", Token.JOIN);
396 AddKeyword ("on", Token.ON);
397 AddKeyword ("equals", Token.EQUALS);
398 AddKeyword ("select", Token.SELECT);
399 AddKeyword ("group", Token.GROUP);
400 AddKeyword ("by", Token.BY);
401 AddKeyword ("let", Token.LET);
402 AddKeyword ("orderby", Token.ORDERBY);
403 AddKeyword ("ascending", Token.ASCENDING);
404 AddKeyword ("descending", Token.DESCENDING);
405 AddKeyword ("into", Token.INTO);
416 public static void Reset ()
419 csharp_format_info = NumberFormatInfo.InvariantInfo;
420 styles = NumberStyles.Float;
422 string_builder = new System.Text.StringBuilder ();
425 int GetKeyword (char[] id, int id_len)
428 * Keywords are stored in an array of hashtables grouped by their
432 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
434 object o = keywords [id_len] [id];
441 if (!handle_get_set && (res == Token.GET || res == Token.SET))
443 if (!handle_remove_add && (res == Token.REMOVE || res == Token.ADD))
445 if (!handle_assembly && res == Token.ASSEMBLY)
449 // A query expression is any expression that starts with `from identifier'
450 // followed by any token except ; , =
452 if (query_parsing == 0) {
453 if (res == Token.FROM && !lambda_arguments_parsing) {
455 // HACK: to disable generics micro-parser, because PushPosition does not
456 // store identifiers array
457 parsing_generic_less_than = 1;
459 case Token.IDENTIFIER:
471 int next_token = xtoken ();
472 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
476 if (RootContext.Version <= LanguageVersion.ISO_2)
477 Report.FeatureIsNotAvailable (Location, "query expressions");
480 Expression.Error_VoidInvalidInTheContext (Location);
484 // HACK: A token is not a keyword so we need to restore identifiers buffer
485 // which has been overwritten before we grabbed the identifier
486 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
493 if (res > Token.QUERY_FIRST_TOKEN && res < Token.QUERY_LAST_TOKEN)
497 if (res == Token.WHERE && !handle_where && query_parsing == 0)
503 public Location Location {
504 get { return current_location; }
507 public Tokenizer (SeekableStreamReader input, CompilationUnit file)
509 this.ref_name = file;
510 this.file_name = file;
515 xml_comment_buffer = new StringBuilder ();
518 // FIXME: This could be `Location.Push' but we have to
519 // find out why the MS compiler allows this
521 Mono.CSharp.Location.Push (file, file);
524 static bool is_identifier_start_character (char c)
526 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter (c);
529 static bool is_identifier_part_character (char c)
531 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') ||
532 Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
535 public static bool IsKeyword (string s)
537 return keyword_strings [s] != null;
541 // Tests whether '(' is beggining of lambda parameters
543 bool IsLambdaOpenParens ()
546 while ((ntoken = xtoken ()) != Token.EOF) {
548 case Token.CLOSE_PARENS:
549 return xtoken () == Token.ARROW;
552 case Token.SEMICOLON:
553 case Token.OPEN_BRACE:
554 case Token.OPEN_PARENS:
555 case Token.LITERAL_STRING:
556 case Token.LITERAL_INTEGER:
557 case Token.LITERAL_FLOAT:
558 case Token.LITERAL_DOUBLE:
559 case Token.LITERAL_DECIMAL:
560 case Token.LITERAL_CHARACTER:
566 case Token.OP_SHIFT_LEFT:
567 case Token.OP_SHIFT_RIGHT:
574 case Token.BITWISE_AND:
575 case Token.BITWISE_OR:
587 Error_TokenExpected (",' or `)");
591 public static bool IsValidIdentifier (string s)
593 if (s == null || s.Length == 0)
596 if (!is_identifier_start_character (s [0]))
599 for (int i = 1; i < s.Length; i ++)
600 if (! is_identifier_part_character (s [i]))
606 bool parse_less_than ()
609 int the_token = token ();
610 if (the_token == Token.OPEN_BRACKET) {
612 the_token = token ();
613 } while (the_token != Token.CLOSE_BRACKET);
614 the_token = token ();
617 case Token.IDENTIFIER:
636 case Token.OP_GENERICS_GT:
643 the_token = token ();
645 if (the_token == Token.OP_GENERICS_GT)
647 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
649 else if (the_token == Token.INTERR || the_token == Token.STAR)
651 else if (the_token == Token.OP_GENERICS_LT) {
652 if (!parse_less_than ())
655 } else if (the_token == Token.OPEN_BRACKET) {
657 the_token = token ();
658 if (the_token == Token.CLOSE_BRACKET)
660 else if (the_token == Token.COMMA)
661 goto rank_specifiers;
668 public void PutbackNullable ()
670 if (nullable_pos < 0)
671 throw new Exception ();
675 reader.Position = nullable_pos;
680 public void PutbackCloseParens ()
686 int nullable_pos = -1;
688 public void CheckNullable (bool is_nullable)
691 nullable_pos = reader.Position;
696 bool parse_generic_dimension (out int dimension)
701 int the_token = token ();
702 if (the_token == Token.OP_GENERICS_GT)
704 else if (the_token == Token.COMMA) {
712 public int peek_token ()
717 the_token = token ();
723 int parsing_generic_less_than = 0;
725 int is_punct (char c, ref bool doread)
735 return Token.OPEN_BRACE;
738 return Token.CLOSE_BRACE;
740 // To block doccomment inside attribute declaration.
741 if (doc_state == XmlCommentState.Allowed)
742 doc_state = XmlCommentState.NotAllowed;
743 return Token.OPEN_BRACKET;
745 return Token.CLOSE_BRACKET;
747 if (!lambda_arguments_parsing) {
748 lambda_arguments_parsing = true;
750 bool lambda_start = IsLambdaOpenParens ();
752 lambda_arguments_parsing = false;
754 if (RootContext.Version <= LanguageVersion.ISO_2)
755 Report.FeatureIsNotAvailable (Location, "lambda expressions");
757 return Token.OPEN_PARENS_LAMBDA;
760 return Token.OPEN_PARENS;
762 if (deambiguate_close_parens == 0)
763 return Token.CLOSE_PARENS;
765 --deambiguate_close_parens;
769 int new_token = xtoken ();
773 if (new_token == Token.OPEN_PARENS)
774 return Token.CLOSE_PARENS_OPEN_PARENS;
775 else if (new_token == Token.MINUS)
776 return Token.CLOSE_PARENS_MINUS;
777 else if (IsCastToken (new_token))
778 return Token.CLOSE_PARENS_CAST;
780 return Token.CLOSE_PARENS_NO_CAST;
787 return Token.SEMICOLON;
795 return Token.OP_COALESCING;
801 if (parsing_generic_less_than++ > 0)
802 return Token.OP_GENERICS_LT;
807 if (parse_generic_dimension (out dimension)) {
810 return Token.GENERIC_DIMENSION;
815 // Save current position and parse next token.
817 bool is_generic_lt = parse_less_than ();
821 return Token.OP_GENERICS_LT;
823 parsing_generic_less_than = 0;
832 return Token.OP_SHIFT_LEFT_ASSIGN;
834 return Token.OP_SHIFT_LEFT;
835 } else if (d == '='){
840 } else if (c == '>') {
848 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
849 parsing_generic_less_than--;
850 return Token.OP_GENERICS_GT;
859 return Token.OP_SHIFT_RIGHT_ASSIGN;
861 return Token.OP_SHIFT_RIGHT;
875 t = Token.OP_ADD_ASSIGN;
889 t = Token.OP_SUB_ASSIGN;
927 } else if (d == '='){
929 return Token.OP_AND_ASSIGN;
932 return Token.BITWISE_AND;
939 } else if (d == '='){
941 return Token.OP_OR_ASSIGN;
943 return Token.BITWISE_OR;
949 return Token.OP_MULT_ASSIGN;
958 return Token.OP_DIV_ASSIGN;
966 return Token.OP_MOD_ASSIGN;
968 return Token.PERCENT;
974 return Token.OP_XOR_ASSIGN;
982 return Token.DOUBLE_COLON;
991 int deambiguate_close_parens = 0;
993 public void Deambiguate_CloseParens (object expression)
997 // When any binary operation, a conditional is used we are sure it is not a cast
1000 if (expression is Binary || expression is Conditional)
1003 deambiguate_close_parens++;
1006 bool decimal_digits (int c)
1009 bool seen_digits = false;
1012 if (number_pos == max_number_size)
1013 Error_NumericConstantTooLong ();
1014 number_builder [number_pos++] = (char) c;
1018 // We use peek_char2, because decimal_digits needs to do a
1019 // 2-character look-ahead (5.ToString for example).
1021 while ((d = peek_char2 ()) != -1){
1022 if (d >= '0' && d <= '9'){
1023 if (number_pos == max_number_size)
1024 Error_NumericConstantTooLong ();
1025 number_builder [number_pos++] = (char) d;
1035 static bool is_hex (int e)
1037 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1040 static int real_type_suffix (int c)
1046 t = Token.LITERAL_FLOAT;
1049 t = Token.LITERAL_DOUBLE;
1052 t= Token.LITERAL_DECIMAL;
1060 int integer_type_suffix (ulong ul, int c)
1062 bool is_unsigned = false;
1063 bool is_long = false;
1066 bool scanning = true;
1079 // if we have not seen anything in between
1080 // report this error
1082 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1085 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1086 // work around that.
1110 if (is_long && is_unsigned){
1112 return Token.LITERAL_INTEGER;
1113 } else if (is_unsigned){
1114 // uint if possible, or ulong else.
1116 if ((ul & 0xffffffff00000000) == 0)
1120 } else if (is_long){
1121 // long if possible, ulong otherwise
1122 if ((ul & 0x8000000000000000) != 0)
1127 // int, uint, long or ulong in that order
1128 if ((ul & 0xffffffff00000000) == 0){
1129 uint ui = (uint) ul;
1131 if ((ui & 0x80000000) != 0)
1136 if ((ul & 0x8000000000000000) != 0)
1142 return Token.LITERAL_INTEGER;
1146 // given `c' as the next char in the input decide whether
1147 // we need to convert to a special type, and then choose
1148 // the best representation for the integer
1150 int adjust_int (int c)
1153 if (number_pos > 9){
1154 ulong ul = (uint) (number_builder [0] - '0');
1156 for (int i = 1; i < number_pos; i++){
1157 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1159 return integer_type_suffix (ul, c);
1161 uint ui = (uint) (number_builder [0] - '0');
1163 for (int i = 1; i < number_pos; i++){
1164 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1166 return integer_type_suffix (ui, c);
1168 } catch (OverflowException) {
1169 error_details = "Integral constant is too large";
1170 Report.Error (1021, Location, error_details);
1172 return Token.LITERAL_INTEGER;
1174 catch (FormatException) {
1175 Report.Error (1013, Location, "Invalid number");
1177 return Token.LITERAL_INTEGER;
1181 int adjust_real (int t)
1183 string s = new String (number_builder, 0, number_pos);
1184 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1187 case Token.LITERAL_DECIMAL:
1189 val = System.Decimal.Parse (s, styles, csharp_format_info);
1190 } catch (OverflowException) {
1192 Report.Error (594, Location, error_details, "decimal");
1195 case Token.LITERAL_FLOAT:
1197 val = float.Parse (s, styles, csharp_format_info);
1198 } catch (OverflowException) {
1200 Report.Error (594, Location, error_details, "float");
1204 case Token.LITERAL_DOUBLE:
1206 t = Token.LITERAL_DOUBLE;
1208 val = System.Double.Parse (s, styles, csharp_format_info);
1209 } catch (OverflowException) {
1211 Report.Error (594, Location, error_details, "double");
1224 while ((d = peek_char ()) != -1){
1226 number_builder [number_pos++] = (char) d;
1232 string s = new String (number_builder, 0, number_pos);
1234 if (number_pos <= 8)
1235 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1237 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1238 } catch (OverflowException){
1239 error_details = "Integral constant is too large";
1240 Report.Error (1021, Location, error_details);
1242 return Token.LITERAL_INTEGER;
1244 catch (FormatException) {
1245 Report.Error (1013, Location, "Invalid number");
1247 return Token.LITERAL_INTEGER;
1250 return integer_type_suffix (ul, peek_char ());
1254 // Invoked if we know we have .digits or digits
1256 int is_number (int c)
1258 bool is_real = false;
1263 if (c >= '0' && c <= '9'){
1265 int peek = peek_char ();
1267 if (peek == 'x' || peek == 'X')
1268 return handle_hex ();
1275 // We need to handle the case of
1276 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1279 if (decimal_digits ('.')){
1285 return adjust_int (-1);
1289 if (c == 'e' || c == 'E'){
1291 if (number_pos == max_number_size)
1292 Error_NumericConstantTooLong ();
1293 number_builder [number_pos++] = 'e';
1297 if (number_pos == max_number_size)
1298 Error_NumericConstantTooLong ();
1299 number_builder [number_pos++] = '+';
1301 } else if (c == '-') {
1302 if (number_pos == max_number_size)
1303 Error_NumericConstantTooLong ();
1304 number_builder [number_pos++] = '-';
1307 if (number_pos == max_number_size)
1308 Error_NumericConstantTooLong ();
1309 number_builder [number_pos++] = '+';
1316 type = real_type_suffix (c);
1317 if (type == Token.NONE && !is_real){
1319 return adjust_int (c);
1323 if (type == Token.NONE){
1328 return adjust_real (type);
1330 Console.WriteLine ("This should not be reached");
1331 throw new Exception ("Is Number should never reach this point");
1335 // Accepts exactly count (4 or 8) hex, no more no less
1337 int getHex (int count, out bool error)
1342 int top = count != -1 ? count : 4;
1346 for (i = 0; i < top; i++){
1349 if (c >= '0' && c <= '9')
1350 c = (int) c - (int) '0';
1351 else if (c >= 'A' && c <= 'F')
1352 c = (int) c - (int) 'A' + 10;
1353 else if (c >= 'a' && c <= 'f')
1354 c = (int) c - (int) 'a' + 10;
1360 total = (total * 16) + c;
1362 int p = peek_char ();
1365 if (!is_hex ((char)p))
1406 v = getHex (-1, out error);
1412 return EscapeUnicode (d);
1414 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1421 int EscapeUnicode (int ch)
1425 ch = getHex (8, out error);
1427 ch = getHex (4, out error);
1431 Report.Error (1009, Location, "Unrecognized escape sequence");
1439 if (putback_char != -1) {
1452 void advance_line ()
1462 if (putback_char != -1)
1463 return putback_char;
1464 putback_char = reader.Read ();
1465 return putback_char;
1470 if (putback_char != -1)
1471 return putback_char;
1472 return reader.Peek ();
1475 void putback (int c)
1477 if (putback_char != -1){
1478 Console.WriteLine ("Col: " + col);
1479 Console.WriteLine ("Row: " + line);
1480 Console.WriteLine ("Name: " + ref_name.Name);
1481 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1482 throw new Exception ("This should not happen putback on putback");
1484 if (c == '\n' || col == 0) {
1485 // It won't happen though.
1495 public bool advance ()
1497 return peek_char () != -1;
1500 public Object Value {
1506 public Object value ()
1511 static bool IsCastToken (int token)
1516 case Token.IDENTIFIER:
1517 case Token.LITERAL_INTEGER:
1518 case Token.LITERAL_FLOAT:
1519 case Token.LITERAL_DOUBLE:
1520 case Token.LITERAL_DECIMAL:
1521 case Token.LITERAL_CHARACTER:
1522 case Token.LITERAL_STRING:
1525 case Token.DELEGATE:
1535 case Token.UNCHECKED:
1540 // These can be part of a member access
1562 current_token = xtoken ();
1564 if (current_token != Token.DEFAULT)
1565 return current_token;
1570 current_token = Token.ERROR;
1571 else if (c == Token.OPEN_PARENS)
1572 current_token = Token.DEFAULT_OPEN_PARENS;
1573 else if (c == Token.COLON)
1574 current_token = Token.DEFAULT_COLON;
1578 return current_token;
1581 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1583 void get_cmd_arg (out string cmd, out string arg)
1587 tokens_seen = false;
1589 static_cmd_arg.Length = 0;
1591 // skip over white space
1592 while ((c = get_char ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1595 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1596 if (is_identifier_part_character ((char)c)){
1597 static_cmd_arg.Append ((char)c);
1603 int peek = peek_char ();
1604 if (peek == 'U' || peek == 'u') {
1605 c = EscapeUnicode (c);
1614 cmd = static_cmd_arg.ToString ();
1616 if (c == '\n' || c == '\r'){
1620 // skip over white space
1621 while ((c = get_char ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1626 } else if (c == '\r'){
1628 } else if (c == -1){
1633 static_cmd_arg.Length = 0;
1636 int peek = peek_char ();
1637 if (peek == 'U' || peek == 'u') {
1638 c = EscapeUnicode (c);
1642 static_cmd_arg.Append ((char) c);
1643 } while ((c = get_char ()) != -1 && (c != '\n') && (c != '\r'));
1645 arg = static_cmd_arg.ToString ();
1649 // Handles the #line directive
1651 bool PreProcessLine (string arg)
1653 if (arg.Length == 0)
1656 if (arg == "default"){
1658 ref_name = file_name;
1660 Location.Push (file_name, ref_name);
1662 } else if (arg == "hidden"){
1670 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1671 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1674 char [] quotes = { '\"' };
1676 string name = arg.Substring (pos). Trim (quotes);
1677 ref_name = Location.LookupFile (file_name, name);
1678 file_name.AddFile (ref_name);
1680 Location.Push (file_name, ref_name);
1682 ref_line = System.Int32.Parse (arg);
1693 // Handles #define and #undef
1695 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1697 if (ident.Length == 0 || ident == "true" || ident == "false"){
1698 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1702 if (ident.IndexOfAny (simple_whitespaces) != -1){
1703 Error_EndLineExpected ();
1707 if (!is_identifier_start_character (ident [0]))
1708 Report.Error (1001, Location, "Identifier expected: " + ident);
1710 foreach (char c in ident.Substring (1)){
1711 if (!is_identifier_part_character (c)){
1712 Report.Error (1001, Location, "Identifier expected: " + ident);
1717 if (!caller_is_taking)
1724 if (RootContext.IsConditionalDefined (ident))
1727 file_name.AddDefine (ident);
1732 file_name.AddUndefine (ident);
1736 static byte read_hex (string arg, int pos, out bool error)
1743 if ((c >= '0') && (c <= '9'))
1744 total = (int) c - (int) '0';
1745 else if ((c >= 'A') && (c <= 'F'))
1746 total = (int) c - (int) 'A' + 10;
1747 else if ((c >= 'a') && (c <= 'f'))
1748 total = (int) c - (int) 'a' + 10;
1757 if ((c >= '0') && (c <= '9'))
1758 total += (int) c - (int) '0';
1759 else if ((c >= 'A') && (c <= 'F'))
1760 total += (int) c - (int) 'A' + 10;
1761 else if ((c >= 'a') && (c <= 'f'))
1762 total += (int) c - (int) 'a' + 10;
1768 return (byte) total;
1772 /// Handles #pragma checksum
1774 bool PreProcessPragmaChecksum (string arg)
1776 if ((arg [0] != ' ') && (arg [0] != '\t'))
1779 arg = arg.Trim (simple_whitespaces);
1780 if ((arg.Length < 2) || (arg [0] != '"'))
1783 StringBuilder file_sb = new StringBuilder ();
1787 while ((ch = arg [pos++]) != '"') {
1788 if (pos >= arg.Length)
1792 if (pos+1 >= arg.Length)
1797 file_sb.Append (ch);
1800 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1803 arg = arg.Substring (pos).Trim (simple_whitespaces);
1804 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1805 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1806 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1810 byte[] guid_bytes = new byte [16];
1812 for (int i = 0; i < 4; i++) {
1813 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1817 for (int i = 0; i < 2; i++) {
1818 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1821 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1824 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1829 for (int i = 0; i < 6; i++) {
1830 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1835 arg = arg.Substring (40).Trim (simple_whitespaces);
1836 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1839 byte[] checksum_bytes = new byte [16];
1840 for (int i = 0; i < 16; i++) {
1841 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1846 arg = arg.Substring (34).Trim (simple_whitespaces);
1850 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1851 file.SetChecksum (guid_bytes, checksum_bytes);
1852 ref_name.AutoGenerated = true;
1857 /// Handles #pragma directive
1859 void PreProcessPragma (string arg)
1861 const string warning = "warning";
1862 const string w_disable = "warning disable";
1863 const string w_restore = "warning restore";
1864 const string checksum = "checksum";
1866 if (arg == w_disable) {
1867 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1871 if (arg == w_restore) {
1872 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1876 if (arg.StartsWith (w_disable)) {
1877 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1878 foreach (int code in codes) {
1880 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1885 if (arg.StartsWith (w_restore)) {
1886 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1887 Hashtable w_table = Report.warning_ignore_table;
1888 foreach (int code in codes) {
1889 if (w_table != null && w_table.Contains (code))
1890 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1891 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1896 if (arg.StartsWith (warning)) {
1897 Report.Warning (1634, 1, Location, "Expected disable or restore");
1901 if (arg.StartsWith (checksum)) {
1902 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1903 Warning_InvalidPragmaChecksum ();
1907 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1910 int[] ParseNumbers (string text)
1912 string[] string_array = text.Split (',');
1913 int[] values = new int [string_array.Length];
1915 foreach (string string_code in string_array) {
1917 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1919 catch (FormatException) {
1920 Report.Warning (1692, 1, Location, "Invalid number");
1926 bool eval_val (string s)
1933 return file_name.IsConditionalDefined (s);
1936 bool pp_primary (ref string s)
1945 s = s.Substring (1);
1946 bool val = pp_expr (ref s, false);
1947 if (s.Length > 0 && s [0] == ')'){
1948 s = s.Substring (1);
1951 Error_InvalidDirective ();
1955 if (is_identifier_start_character (c)){
1961 if (is_identifier_part_character (c)){
1965 bool v = eval_val (s.Substring (0, j));
1966 s = s.Substring (j);
1969 bool vv = eval_val (s);
1974 Error_InvalidDirective ();
1978 bool pp_unary (ref string s)
1985 if (len > 1 && s [1] == '='){
1986 Error_InvalidDirective ();
1989 s = s.Substring (1);
1990 return ! pp_primary (ref s);
1992 return pp_primary (ref s);
1994 Error_InvalidDirective ();
1999 bool pp_eq (ref string s)
2001 bool va = pp_unary (ref s);
2007 if (len > 2 && s [1] == '='){
2008 s = s.Substring (2);
2009 return va == pp_unary (ref s);
2011 Error_InvalidDirective ();
2014 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2015 s = s.Substring (2);
2017 return va != pp_unary (ref s);
2026 bool pp_and (ref string s)
2028 bool va = pp_eq (ref s);
2034 if (len > 2 && s [1] == '&'){
2035 s = s.Substring (2);
2036 return (va & pp_and (ref s));
2038 Error_InvalidDirective ();
2047 // Evaluates an expression for `#if' or `#elif'
2049 bool pp_expr (ref string s, bool isTerm)
2051 bool va = pp_and (ref s);
2058 if (len > 2 && s [1] == '|'){
2059 s = s.Substring (2);
2060 return va | pp_expr (ref s, isTerm);
2062 Error_InvalidDirective ();
2067 Error_EndLineExpected ();
2075 bool eval (string s)
2077 bool v = pp_expr (ref s, true);
2086 void Error_NumericConstantTooLong ()
2088 Report.Error (1021, Location, "Numeric constant too long");
2091 void Error_InvalidDirective ()
2093 Report.Error (1517, Location, "Invalid preprocessor directive");
2096 void Error_UnexpectedDirective (string extra)
2100 "Unexpected processor directive (" + extra + ")");
2103 void Error_TokenExpected (string token)
2105 Report.Error (1026, Location, "Expected `{0}'", token);
2108 void Error_TokensSeen ()
2110 Report.Error (1032, Location,
2111 "Cannot define or undefine preprocessor symbols after first token in file");
2114 void Eror_WrongPreprocessorLocation ()
2116 Report.Error (1040, Location,
2117 "Preprocessor directives must appear as the first non-whitespace character on a line");
2120 void Error_EndLineExpected ()
2122 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2125 void Warning_InvalidPragmaChecksum ()
2127 Report.Warning (1695, 1, Location,
2128 "Invalid #pragma checksum syntax; should be " +
2129 "#pragma checksum \"filename\" " +
2130 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2133 // if true, then the code continues processing the code
2134 // if false, the code stays in a loop until another directive is
2136 // When caller_is_taking is false we ignore all directives except the ones
2137 // which can help us to identify where the #if block ends
2138 bool handle_preprocessing_directive (bool caller_is_taking)
2141 bool region_directive = false;
2143 get_cmd_arg (out cmd, out arg);
2145 // Eat any trailing whitespaces and single-line comments
2146 if (arg.IndexOf ("//") != -1)
2147 arg = arg.Substring (0, arg.IndexOf ("//"));
2148 arg = arg.Trim (simple_whitespaces);
2151 // The first group of pre-processing instructions is always processed
2155 region_directive = true;
2160 if (ifstack == null || ifstack.Count == 0){
2161 Error_UnexpectedDirective ("no #region for this #endregion");
2164 int pop = (int) ifstack.Pop ();
2166 if ((pop & REGION) == 0)
2167 Report.Error (1027, Location, "Expected `#endif' directive");
2169 return caller_is_taking;
2172 if (ifstack == null)
2173 ifstack = new Stack (2);
2175 int flags = region_directive ? REGION : 0;
2176 if (ifstack.Count == 0){
2177 flags |= PARENT_TAKING;
2179 int state = (int) ifstack.Peek ();
2180 if ((state & TAKING) != 0) {
2181 flags |= PARENT_TAKING;
2185 if (caller_is_taking && eval (arg)) {
2186 ifstack.Push (flags | TAKING);
2189 ifstack.Push (flags);
2193 if (ifstack == null || ifstack.Count == 0){
2194 Error_UnexpectedDirective ("no #if for this #endif");
2197 pop = (int) ifstack.Pop ();
2199 if ((pop & REGION) != 0)
2200 Report.Error (1038, Location, "#endregion directive expected");
2202 if (arg.Length != 0) {
2203 Error_EndLineExpected ();
2206 if (ifstack.Count == 0)
2209 int state = (int) ifstack.Peek ();
2210 return (state & TAKING) != 0;
2214 if (ifstack == null || ifstack.Count == 0){
2215 Error_UnexpectedDirective ("no #if for this #elif");
2218 int state = (int) ifstack.Pop ();
2220 if ((state & REGION) != 0) {
2221 Report.Error (1038, Location, "#endregion directive expected");
2225 if ((state & ELSE_SEEN) != 0){
2226 Error_UnexpectedDirective ("#elif not valid after #else");
2230 if ((state & TAKING) != 0) {
2235 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2236 ifstack.Push (state | TAKING);
2240 ifstack.Push (state);
2245 if (ifstack == null || ifstack.Count == 0){
2246 Error_UnexpectedDirective ("no #if for this #else");
2249 int state = (int) ifstack.Peek ();
2251 if ((state & REGION) != 0) {
2252 Report.Error (1038, Location, "#endregion directive expected");
2256 if ((state & ELSE_SEEN) != 0){
2257 Error_UnexpectedDirective ("#else within #else");
2263 if (arg.Length != 0) {
2264 Error_EndLineExpected ();
2269 if ((state & PARENT_TAKING) != 0) {
2270 ret = (state & TAKING) == 0;
2278 ifstack.Push (state | ELSE_SEEN);
2283 if (any_token_seen){
2284 Error_TokensSeen ();
2285 return caller_is_taking;
2287 PreProcessDefinition (true, arg, caller_is_taking);
2288 return caller_is_taking;
2291 if (any_token_seen){
2292 Error_TokensSeen ();
2293 return caller_is_taking;
2295 PreProcessDefinition (false, arg, caller_is_taking);
2296 return caller_is_taking;
2300 // These are only processed if we are in a `taking' block
2302 if (!caller_is_taking)
2307 Report.Error (1029, Location, "#error: '" + arg + "'");
2311 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2315 if (RootContext.Version == LanguageVersion.ISO_1) {
2316 Report.FeatureIsNotAvailable (Location, "#pragma");
2320 PreProcessPragma (arg);
2324 if (!PreProcessLine (arg))
2327 "The line number specified for #line directive is missing or invalid");
2328 return caller_is_taking;
2331 Report.Error (1024, Location, "Wrong preprocessor directive");
2336 private int consume_string (bool quoted)
2339 string_builder.Length = 0;
2342 // No need to parse full string when parsing lambda arguments
2344 if (lambda_arguments_parsing)
2345 return Token.LITERAL_STRING;
2347 while ((c = get_char ()) != -1){
2349 if (quoted && peek_char () == '"'){
2350 string_builder.Append ((char) c);
2354 val = string_builder.ToString ();
2355 return Token.LITERAL_STRING;
2361 Report.Error (1010, Location, "Newline in constant");
2369 string_builder.Append ((char) c);
2372 Report.Error (1039, Location, "Unterminated string literal");
2376 private int consume_identifier (int s)
2378 int res = consume_identifier (s, false);
2380 if (doc_state == XmlCommentState.Allowed)
2381 doc_state = XmlCommentState.NotAllowed;
2384 case Token.NAMESPACE:
2385 check_incorrect_doc_comment ();
2389 if (res == Token.PARTIAL) {
2390 if (parsing_block > 0) {
2391 val = new LocatedToken (Location, "partial");
2392 return Token.IDENTIFIER;
2395 // Save current position and parse next token.
2398 int next_token = token ();
2399 bool ok = (next_token == Token.CLASS) ||
2400 (next_token == Token.STRUCT) ||
2401 (next_token == Token.INTERFACE) ||
2402 (next_token == Token.VOID);
2407 if (next_token == Token.VOID) {
2408 if (RootContext.Version <= LanguageVersion.ISO_2)
2409 Report.FeatureIsNotAvailable (Location, "partial methods");
2410 } else if (RootContext.Version == LanguageVersion.ISO_1)
2411 Report.FeatureIsNotAvailable (Location, "partial types");
2416 if (next_token < Token.LAST_KEYWORD)
2417 Report.Error (267, Location, "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
2419 val = new LocatedToken (Location, "partial");
2420 return Token.IDENTIFIER;
2426 private int consume_identifier (int s, bool quoted)
2431 id_builder [0] = (char) s;
2433 current_location = new Location (ref_line, hidden ? -1 : Col);
2435 while ((c = get_char ()) != -1) {
2437 if (is_identifier_part_character ((char) c)){
2438 if (pos == max_id_size){
2439 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2443 id_builder [pos++] = (char) c;
2444 // putback_char = -1;
2445 } else if (c == '\\') {
2449 // putback_char = c;
2456 // Optimization: avoids doing the keyword lookup
2457 // on uppercase letters and _
2459 if (!quoted && (s >= 'a' || s == '_')){
2460 int keyword = GetKeyword (id_builder, pos);
2461 if (keyword != -1) {
2468 // Keep identifiers in an array of hashtables to avoid needless
2472 if (identifiers [pos] != null) {
2473 val = identifiers [pos][id_builder];
2475 val = new LocatedToken (Location, (string) val);
2477 escaped_identifiers.Add (val);
2478 return Token.IDENTIFIER;
2482 identifiers [pos] = new CharArrayHashtable (pos);
2484 val = new String (id_builder, 0, pos);
2485 if (RootContext.Version == LanguageVersion.ISO_1) {
2486 for (int i = 1; i < id_builder.Length; i += 3) {
2487 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2488 Report.Error (1638, Location,
2489 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2495 char [] chars = new char [pos];
2496 Array.Copy (id_builder, chars, pos);
2498 identifiers [pos] [chars] = val;
2500 val = new LocatedToken (Location, (string) val);
2502 escaped_identifiers.Add (val);
2503 return Token.IDENTIFIER;
2506 public int xtoken ()
2509 bool doread = false;
2512 // Whether we have seen comments on the current line
2513 bool comments_seen = false;
2515 for (;(c = get_char ()) != -1;) {
2517 col = ((col + 8) / 8) * 8;
2521 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0 || c == 0)
2525 if (peek_char () != '\n')
2530 any_token_seen |= tokens_seen;
2531 tokens_seen = false;
2532 comments_seen = false;
2536 // Handle double-slash comments.
2538 int d = peek_char ();
2542 if (RootContext.Documentation != null && peek_char () == '/') {
2544 // Don't allow ////.
2545 if ((d = peek_char ()) != '/') {
2546 update_comment_location ();
2547 if (doc_state == XmlCommentState.Allowed)
2548 handle_one_line_xml_comment ();
2549 else if (doc_state == XmlCommentState.NotAllowed)
2550 warn_incorrect_doc_comment ();
2553 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2555 any_token_seen |= tokens_seen;
2556 tokens_seen = false;
2557 comments_seen = false;
2559 } else if (d == '*'){
2561 bool docAppend = false;
2562 if (RootContext.Documentation != null && peek_char () == '*') {
2564 update_comment_location ();
2565 // But when it is /**/, just do nothing.
2566 if (peek_char () == '/') {
2570 if (doc_state == XmlCommentState.Allowed)
2572 else if (doc_state == XmlCommentState.NotAllowed)
2573 warn_incorrect_doc_comment ();
2576 int current_comment_start = 0;
2578 current_comment_start = xml_comment_buffer.Length;
2579 xml_comment_buffer.Append (Environment.NewLine);
2582 Location start_location = Location;
2584 while ((d = get_char ()) != -1){
2585 if (d == '*' && peek_char () == '/'){
2587 comments_seen = true;
2591 xml_comment_buffer.Append ((char) d);
2594 any_token_seen |= tokens_seen;
2595 tokens_seen = false;
2597 // Reset 'comments_seen' just to be consistent.
2598 // It doesn't matter either way, here.
2600 comments_seen = false;
2604 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2607 update_formatted_doc_comment (current_comment_start);
2610 goto is_punct_label;
2614 if (c == '\\' || is_identifier_start_character ((char)c)){
2616 return consume_identifier (c);
2620 current_location = new Location (ref_line, hidden ? -1 : Col);
2621 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2631 any_token_seen |= tokens_seen;
2632 tokens_seen = false;
2633 comments_seen = false;
2637 if (c >= '0' && c <= '9'){
2639 return is_number (c);
2644 int peek = peek_char ();
2645 if (peek >= '0' && peek <= '9')
2646 return is_number (c);
2651 if (tokens_seen || comments_seen) {
2652 Eror_WrongPreprocessorLocation ();
2656 if (handle_preprocessing_directive (true))
2659 bool directive_expected = false;
2660 while ((c = get_char ()) != -1) {
2662 directive_expected = true;
2663 } else if (!directive_expected) {
2664 // TODO: Implement comment support for disabled code and uncomment this code
2666 // Eror_WrongPreprocessorLocation ();
2667 // return Token.ERROR;
2672 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2676 if (handle_preprocessing_directive (false))
2679 directive_expected = false;
2683 tokens_seen = false;
2691 return consume_string (false);
2697 error_details = "Empty character literal";
2698 Report.Error (1011, Location, error_details);
2701 if (c == '\r' || c == '\n') {
2702 Report.Error (1010, Location, "Newline in constant");
2708 val = new System.Char ();
2713 error_details = "Too many characters in character literal";
2714 Report.Error (1012, Location, error_details);
2716 // Try to recover, read until newline or next "'"
2717 while ((c = get_char ()) != -1){
2726 return Token.LITERAL_CHARACTER;
2733 return consume_string (true);
2734 } else if (is_identifier_start_character ((char) c)){
2735 return consume_identifier (c, true);
2737 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2741 error_details = ((char)c).ToString ();
2750 // Handles one line xml comment
2752 private void handle_one_line_xml_comment ()
2755 while ((c = peek_char ()) == ' ')
2756 get_char (); // skip heading whitespaces.
2757 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2758 xml_comment_buffer.Append ((char) get_char ());
2760 if (c == '\r' || c == '\n')
2761 xml_comment_buffer.Append (Environment.NewLine);
2765 // Remove heading "*" in Javadoc-like xml documentation.
2767 private void update_formatted_doc_comment (int current_comment_start)
2769 int length = xml_comment_buffer.Length - current_comment_start;
2770 string [] lines = xml_comment_buffer.ToString (
2771 current_comment_start,
2772 length).Replace ("\r", "").Split ('\n');
2774 // The first line starts with /**, thus it is not target
2775 // for the format check.
2776 for (int i = 1; i < lines.Length; i++) {
2777 string s = lines [i];
2778 int idx = s.IndexOf ('*');
2781 if (i < lines.Length - 1)
2785 head = s.Substring (0, idx);
2786 foreach (char c in head)
2789 lines [i] = s.Substring (idx + 1);
2791 xml_comment_buffer.Remove (current_comment_start, length);
2792 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2796 // Updates current comment location.
2798 private void update_comment_location ()
2800 if (current_comment_location.IsNull) {
2801 // "-2" is for heading "//" or "/*"
2802 current_comment_location =
2803 new Location (ref_line, hidden ? -1 : col - 2);
2808 // Checks if there was incorrect doc comments and raise
2811 public void check_incorrect_doc_comment ()
2813 if (xml_comment_buffer.Length > 0)
2814 warn_incorrect_doc_comment ();
2818 // Raises a warning when tokenizer found incorrect doccomment
2821 private void warn_incorrect_doc_comment ()
2823 if (doc_state != XmlCommentState.Error) {
2824 doc_state = XmlCommentState.Error;
2825 // in csc, it is 'XML comment is not placed on
2826 // a valid language element'. But that does not
2828 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2833 // Consumes the saved xml comment lines (if any)
2834 // as for current target member or type.
2836 public string consume_doc_comment ()
2838 if (xml_comment_buffer.Length > 0) {
2839 string ret = xml_comment_buffer.ToString ();
2840 reset_doc_comment ();
2846 void reset_doc_comment ()
2848 xml_comment_buffer.Length = 0;
2849 current_comment_location = Location.Null;
2852 public void cleanup ()
2854 if (ifstack != null && ifstack.Count >= 1) {
2855 current_location = new Location (ref_line, hidden ? -1 : Col);
2856 int state = (int) ifstack.Pop ();
2857 if ((state & REGION) != 0)
2858 Report.Error (1038, Location, "#endregion directive expected");
2860 Report.Error (1027, Location, "Expected `#endif' directive");
2866 // Indicates whether it accepts XML documentation or not.
2868 public enum XmlCommentState {
2869 // comment is allowed in this state.
2871 // comment is not allowed in this state.
2873 // once comments appeared when it is NotAllowed, then the
2874 // state is changed to it, until the state is changed to