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 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
16 * Make sure we accept the proper Unicode ranges, per the spec.
22 using System.Collections;
24 using System.Globalization;
25 using System.Reflection;
30 /// Tokenizer for C# source code.
33 public class Tokenizer : yyParser.yyInput
35 SeekableStreamReader reader;
43 bool handle_get_set = false;
44 bool handle_remove_add = false;
45 bool handle_assembly = false;
46 bool handle_constraints = false;
47 bool handle_typeof = false;
48 Location current_location;
49 Location current_comment_location = Location.Null;
50 ArrayList escapedIdentifiers = new ArrayList ();
53 // XML documentation buffer. The save point is used to divide
54 // comments on types and comments on members.
56 StringBuilder xml_comment_buffer;
59 // See comment on XmlCommentState enumeration.
61 XmlCommentState xmlDocState = XmlCommentState.Allowed;
64 // Whether tokens have been seen on this line
66 bool tokens_seen = false;
69 // Whether a token has been seen on the file
70 // This is needed because `define' is not allowed to be used
71 // after a token has been seen.
73 bool any_token_seen = false;
75 static Hashtable tokenValues;
77 private static Hashtable TokenValueName
80 if (tokenValues == null)
81 tokenValues = 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 {
128 return handle_get_set;
132 handle_get_set = value;
136 public bool AssemblyTargetParsing {
138 return handle_assembly;
142 handle_assembly = value;
146 public bool EventParsing {
148 return handle_remove_add;
152 handle_remove_add = value;
156 public bool ConstraintsParsing {
158 return handle_constraints;
162 handle_constraints = value;
166 public bool TypeOfParsing {
168 return handle_typeof;
172 handle_typeof = value;
176 public XmlCommentState doc_state {
177 get { return xmlDocState; }
179 if (value == XmlCommentState.Allowed) {
180 check_incorrect_doc_comment ();
181 reset_doc_comment ();
187 public bool IsEscapedIdentifier (Location loc)
189 foreach (LocatedToken lt in escapedIdentifiers)
190 if (lt.Location.Equals (loc))
198 static CharArrayHashtable[] keywords;
199 static Hashtable keywordStrings = new Hashtable ();
200 static NumberStyles styles;
201 static NumberFormatInfo csharp_format_info;
204 // Values for the associated token returned
214 const int TAKING = 1;
215 const int ELSE_SEEN = 4;
216 const int PARENT_TAKING = 8;
217 const int REGION = 16;
220 // pre-processor if stack state:
224 static System.Text.StringBuilder string_builder;
226 const int max_id_size = 512;
227 static char [] id_builder = new char [max_id_size];
229 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
231 const int max_number_size = 512;
232 static char [] number_builder = new char [max_number_size];
233 static int number_pos;
236 // Details about the error encoutered by the tokenizer
238 string error_details;
240 public string error {
242 return error_details;
259 // This is used when the tokenizer needs to save
260 // the current position as it needs to do some parsing
261 // on its own to deamiguate a token in behalf of the
264 Stack position_stack = new Stack (2);
269 public int putback_char;
270 public int previous_col;
271 public Stack ifstack;
273 public int parsing_generic_less_than;
275 public Position (Tokenizer t)
277 position = t.reader.Position;
278 ref_line = t.ref_line;
280 putback_char = t.putback_char;
281 previous_col = t.previous_col;
282 if (t.ifstack != null && t.ifstack.Count != 0)
283 ifstack = (Stack)t.ifstack.Clone ();
285 parsing_generic_less_than = t.parsing_generic_less_than;
290 public void PushPosition ()
292 position_stack.Push (new Position (this));
295 public void PopPosition ()
297 Position p = (Position) position_stack.Pop ();
299 reader.Position = p.position;
300 ref_line = p.ref_line;
302 putback_char = p.putback_char;
303 previous_col = p.previous_col;
307 // Do not reset the position, ignore it.
308 public void DiscardPosition ()
310 position_stack.Pop ();
313 static void AddKeyword (string kw, int token) {
314 keywordStrings.Add (kw, kw);
315 if (keywords [kw.Length] == null) {
316 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
318 keywords [kw.Length] [kw.ToCharArray ()] = token;
321 static void InitTokens ()
323 keywords = new CharArrayHashtable [64];
325 AddKeyword ("__arglist", Token.ARGLIST);
326 AddKeyword ("abstract", Token.ABSTRACT);
327 AddKeyword ("as", Token.AS);
328 AddKeyword ("add", Token.ADD);
329 AddKeyword ("assembly", Token.ASSEMBLY);
330 AddKeyword ("base", Token.BASE);
331 AddKeyword ("bool", Token.BOOL);
332 AddKeyword ("break", Token.BREAK);
333 AddKeyword ("byte", Token.BYTE);
334 AddKeyword ("case", Token.CASE);
335 AddKeyword ("catch", Token.CATCH);
336 AddKeyword ("char", Token.CHAR);
337 AddKeyword ("checked", Token.CHECKED);
338 AddKeyword ("class", Token.CLASS);
339 AddKeyword ("const", Token.CONST);
340 AddKeyword ("continue", Token.CONTINUE);
341 AddKeyword ("decimal", Token.DECIMAL);
342 AddKeyword ("default", Token.DEFAULT);
343 AddKeyword ("delegate", Token.DELEGATE);
344 AddKeyword ("do", Token.DO);
345 AddKeyword ("double", Token.DOUBLE);
346 AddKeyword ("else", Token.ELSE);
347 AddKeyword ("enum", Token.ENUM);
348 AddKeyword ("event", Token.EVENT);
349 AddKeyword ("explicit", Token.EXPLICIT);
350 AddKeyword ("extern", Token.EXTERN);
351 AddKeyword ("false", Token.FALSE);
352 AddKeyword ("finally", Token.FINALLY);
353 AddKeyword ("fixed", Token.FIXED);
354 AddKeyword ("float", Token.FLOAT);
355 AddKeyword ("for", Token.FOR);
356 AddKeyword ("foreach", Token.FOREACH);
357 AddKeyword ("goto", Token.GOTO);
358 AddKeyword ("get", Token.GET);
359 AddKeyword ("if", Token.IF);
360 AddKeyword ("implicit", Token.IMPLICIT);
361 AddKeyword ("in", Token.IN);
362 AddKeyword ("int", Token.INT);
363 AddKeyword ("interface", Token.INTERFACE);
364 AddKeyword ("internal", Token.INTERNAL);
365 AddKeyword ("is", Token.IS);
366 AddKeyword ("lock", Token.LOCK);
367 AddKeyword ("long", Token.LONG);
368 AddKeyword ("namespace", Token.NAMESPACE);
369 AddKeyword ("new", Token.NEW);
370 AddKeyword ("null", Token.NULL);
371 AddKeyword ("object", Token.OBJECT);
372 AddKeyword ("operator", Token.OPERATOR);
373 AddKeyword ("out", Token.OUT);
374 AddKeyword ("override", Token.OVERRIDE);
375 AddKeyword ("params", Token.PARAMS);
376 AddKeyword ("private", Token.PRIVATE);
377 AddKeyword ("protected", Token.PROTECTED);
378 AddKeyword ("public", Token.PUBLIC);
379 AddKeyword ("readonly", Token.READONLY);
380 AddKeyword ("ref", Token.REF);
381 AddKeyword ("remove", Token.REMOVE);
382 AddKeyword ("return", Token.RETURN);
383 AddKeyword ("sbyte", Token.SBYTE);
384 AddKeyword ("sealed", Token.SEALED);
385 AddKeyword ("set", Token.SET);
386 AddKeyword ("short", Token.SHORT);
387 AddKeyword ("sizeof", Token.SIZEOF);
388 AddKeyword ("stackalloc", Token.STACKALLOC);
389 AddKeyword ("static", Token.STATIC);
390 AddKeyword ("string", Token.STRING);
391 AddKeyword ("struct", Token.STRUCT);
392 AddKeyword ("switch", Token.SWITCH);
393 AddKeyword ("this", Token.THIS);
394 AddKeyword ("throw", Token.THROW);
395 AddKeyword ("true", Token.TRUE);
396 AddKeyword ("try", Token.TRY);
397 AddKeyword ("typeof", Token.TYPEOF);
398 AddKeyword ("uint", Token.UINT);
399 AddKeyword ("ulong", Token.ULONG);
400 AddKeyword ("unchecked", Token.UNCHECKED);
401 AddKeyword ("unsafe", Token.UNSAFE);
402 AddKeyword ("ushort", Token.USHORT);
403 AddKeyword ("using", Token.USING);
404 AddKeyword ("virtual", Token.VIRTUAL);
405 AddKeyword ("void", Token.VOID);
406 AddKeyword ("volatile", Token.VOLATILE);
407 AddKeyword ("while", Token.WHILE);
408 AddKeyword ("partial", Token.PARTIAL);
410 AddKeyword ("where", Token.WHERE);
420 csharp_format_info = NumberFormatInfo.InvariantInfo;
421 styles = NumberStyles.Float;
423 string_builder = new System.Text.StringBuilder ();
426 int GetKeyword (char[] id, int id_len)
429 * Keywords are stored in an array of hashtables grouped by their
433 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
435 object o = keywords [id_len] [id];
442 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
444 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
446 if (handle_assembly == false && res == Token.ASSEMBLY)
449 if (handle_constraints == false && res == Token.WHERE)
456 public Location Location {
457 get { return current_location; }
460 void define (string def)
462 if (!RootContext.AllDefines.Contains (def)){
463 RootContext.AllDefines [def] = true;
465 if (defines.Contains (def))
467 defines [def] = true;
470 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
472 this.ref_name = file;
473 this.file_name = file;
479 defines = new Hashtable ();
480 foreach (string def in defs)
484 xml_comment_buffer = new StringBuilder ();
487 // FIXME: This could be `Location.Push' but we have to
488 // find out why the MS compiler allows this
490 Mono.CSharp.Location.Push (file);
493 static bool is_identifier_start_character (char c)
495 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter (c);
498 static bool is_identifier_part_character (char c)
500 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
503 public static bool IsKeyword (string s)
505 return keywordStrings [s] != null;
508 public static bool IsValidIdentifier (string s)
510 if (s == null || s.Length == 0)
513 if (!is_identifier_start_character (s [0]))
516 for (int i = 1; i < s.Length; i ++)
517 if (! is_identifier_part_character (s [i]))
524 bool parse_generic_dimension (out int dimension)
529 int the_token = token ();
530 if (the_token == Token.OP_GENERICS_GT)
532 else if (the_token == Token.COMMA) {
540 bool parse_less_than ()
543 int the_token = token ();
544 if (the_token == Token.OPEN_BRACKET) {
546 the_token = token ();
547 } while (the_token != Token.CLOSE_BRACKET);
548 the_token = token ();
551 case Token.IDENTIFIER:
574 the_token = token ();
576 if (the_token == Token.OP_GENERICS_GT)
578 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
580 else if (the_token == Token.INTERR || the_token == Token.STAR)
582 else if (the_token == Token.OP_GENERICS_LT) {
583 if (!parse_less_than ())
586 } else if (the_token == Token.OPEN_BRACKET) {
588 the_token = token ();
589 if (the_token == Token.CLOSE_BRACKET)
591 else if (the_token == Token.COMMA)
592 goto rank_specifiers;
599 int parsing_generic_less_than = 0;
601 public void PutbackNullable ()
603 if (nullable_pos < 0)
604 throw new Exception ();
608 reader.Position = nullable_pos;
613 public void PutbackCloseParens ()
619 int nullable_pos = -1;
621 public void CheckNullable (bool is_nullable)
624 nullable_pos = reader.Position;
629 int is_punct (char c, ref bool doread)
639 return Token.OPEN_BRACE;
642 return Token.CLOSE_BRACE;
644 // To block doccomment inside attribute declaration.
645 if (doc_state == XmlCommentState.Allowed)
646 doc_state = XmlCommentState.NotAllowed;
647 return Token.OPEN_BRACKET;
649 return Token.CLOSE_BRACKET;
651 return Token.OPEN_PARENS;
653 if (deambiguate_close_parens == 0)
654 return Token.CLOSE_PARENS;
656 --deambiguate_close_parens;
660 int new_token = xtoken ();
664 if (new_token == Token.OPEN_PARENS)
665 return Token.CLOSE_PARENS_OPEN_PARENS;
666 else if (new_token == Token.MINUS)
667 return Token.CLOSE_PARENS_MINUS;
668 else if (IsCastToken (new_token))
669 return Token.CLOSE_PARENS_CAST;
671 return Token.CLOSE_PARENS_NO_CAST;
678 return Token.SEMICOLON;
687 if (parsing_generic_less_than++ > 0)
688 return Token.OP_GENERICS_LT;
693 if (parse_generic_dimension (out dimension)) {
696 return Token.GENERIC_DIMENSION;
701 // Save current position and parse next token.
703 bool is_generic_lt = parse_less_than ();
707 parsing_generic_less_than++;
708 return Token.OP_GENERICS_LT;
710 parsing_generic_less_than = 0;
719 return Token.OP_SHIFT_LEFT_ASSIGN;
721 return Token.OP_SHIFT_LEFT;
722 } else if (d == '='){
727 } else if (c == '>') {
728 if (parsing_generic_less_than > 0) {
729 parsing_generic_less_than--;
730 return Token.OP_GENERICS_GT;
740 return Token.OP_SHIFT_RIGHT_ASSIGN;
742 return Token.OP_SHIFT_RIGHT;
743 } else if (d == '='){
758 t = Token.OP_ADD_ASSIGN;
772 t = Token.OP_SUB_ASSIGN;
804 } else if (d == '='){
806 return Token.OP_AND_ASSIGN;
809 return Token.BITWISE_AND;
816 } else if (d == '='){
818 return Token.OP_OR_ASSIGN;
820 return Token.BITWISE_OR;
826 return Token.OP_MULT_ASSIGN;
835 return Token.OP_DIV_ASSIGN;
843 return Token.OP_MOD_ASSIGN;
845 return Token.PERCENT;
851 return Token.OP_XOR_ASSIGN;
864 return Token.OP_SHIFT_LEFT_ASSIGN;
866 return Token.OP_SHIFT_LEFT;
867 } else if (d == '='){
881 return Token.OP_SHIFT_RIGHT_ASSIGN;
883 return Token.OP_SHIFT_RIGHT;
884 } else if (d == '='){
894 return Token.DOUBLE_COLON;
903 int deambiguate_close_parens = 0;
905 public void Deambiguate_CloseParens (object expression)
909 // When any binary operation is used we are sure it is not a cast
910 if (expression is Binary)
913 deambiguate_close_parens++;
916 bool decimal_digits (int c)
919 bool seen_digits = false;
922 if (number_pos == max_number_size)
923 Error_NumericConstantTooLong ();
924 number_builder [number_pos++] = (char) c;
928 // We use peekChar2, because decimal_digits needs to do a
929 // 2-character look-ahead (5.ToString for example).
931 while ((d = peekChar2 ()) != -1){
932 if (d >= '0' && d <= '9'){
933 if (number_pos == max_number_size)
934 Error_NumericConstantTooLong ();
935 number_builder [number_pos++] = (char) d;
945 static bool is_hex (int e)
947 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
950 static int real_type_suffix (int c)
956 t = Token.LITERAL_FLOAT;
959 t = Token.LITERAL_DOUBLE;
962 t= Token.LITERAL_DECIMAL;
970 int integer_type_suffix (ulong ul, int c)
972 bool is_unsigned = false;
973 bool is_long = false;
976 bool scanning = true;
987 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
989 // if we have not seen anything in between
992 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
995 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1020 if (is_long && is_unsigned){
1022 return Token.LITERAL_INTEGER;
1023 } else if (is_unsigned){
1024 // uint if possible, or ulong else.
1026 if ((ul & 0xffffffff00000000) == 0)
1030 } else if (is_long){
1031 // long if possible, ulong otherwise
1032 if ((ul & 0x8000000000000000) != 0)
1037 // int, uint, long or ulong in that order
1038 if ((ul & 0xffffffff00000000) == 0){
1039 uint ui = (uint) ul;
1041 if ((ui & 0x80000000) != 0)
1046 if ((ul & 0x8000000000000000) != 0)
1052 return Token.LITERAL_INTEGER;
1056 // given `c' as the next char in the input decide whether
1057 // we need to convert to a special type, and then choose
1058 // the best representation for the integer
1060 int adjust_int (int c)
1063 if (number_pos > 9){
1064 ulong ul = (uint) (number_builder [0] - '0');
1066 for (int i = 1; i < number_pos; i++){
1067 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1069 return integer_type_suffix (ul, c);
1071 uint ui = (uint) (number_builder [0] - '0');
1073 for (int i = 1; i < number_pos; i++){
1074 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1076 return integer_type_suffix (ui, c);
1078 } catch (OverflowException) {
1079 error_details = "Integral constant is too large";
1080 Report.Error (1021, Location, error_details);
1082 return Token.LITERAL_INTEGER;
1084 catch (FormatException) {
1085 Report.Error (1013, Location, "Invalid number");
1087 return Token.LITERAL_INTEGER;
1091 int adjust_real (int t)
1093 string s = new String (number_builder, 0, number_pos);
1094 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1097 case Token.LITERAL_DECIMAL:
1099 val = System.Decimal.Parse (s, styles, csharp_format_info);
1100 } catch (OverflowException) {
1102 Report.Error (594, Location, error_details, "decimal");
1105 case Token.LITERAL_FLOAT:
1107 val = float.Parse (s, styles, csharp_format_info);
1108 } catch (OverflowException) {
1110 Report.Error (594, Location, error_details, "float");
1114 case Token.LITERAL_DOUBLE:
1116 t = Token.LITERAL_DOUBLE;
1118 val = System.Double.Parse (s, styles, csharp_format_info);
1119 } catch (OverflowException) {
1121 Report.Error (594, Location, error_details, "double");
1134 while ((d = peekChar ()) != -1){
1136 number_builder [number_pos++] = (char) d;
1142 string s = new String (number_builder, 0, number_pos);
1144 if (number_pos <= 8)
1145 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1147 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1148 } catch (OverflowException){
1149 error_details = "Integral constant is too large";
1150 Report.Error (1021, Location, error_details);
1152 return Token.LITERAL_INTEGER;
1154 catch (FormatException) {
1155 Report.Error (1013, Location, "Invalid number");
1157 return Token.LITERAL_INTEGER;
1160 return integer_type_suffix (ul, peekChar ());
1164 // Invoked if we know we have .digits or digits
1166 int is_number (int c)
1168 bool is_real = false;
1173 if (c >= '0' && c <= '9'){
1175 int peek = peekChar ();
1177 if (peek == 'x' || peek == 'X')
1178 return handle_hex ();
1185 // We need to handle the case of
1186 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1189 if (decimal_digits ('.')){
1195 return adjust_int (-1);
1199 if (c == 'e' || c == 'E'){
1201 if (number_pos == max_number_size)
1202 Error_NumericConstantTooLong ();
1203 number_builder [number_pos++] = 'e';
1207 if (number_pos == max_number_size)
1208 Error_NumericConstantTooLong ();
1209 number_builder [number_pos++] = '+';
1211 } else if (c == '-') {
1212 if (number_pos == max_number_size)
1213 Error_NumericConstantTooLong ();
1214 number_builder [number_pos++] = '-';
1217 if (number_pos == max_number_size)
1218 Error_NumericConstantTooLong ();
1219 number_builder [number_pos++] = '+';
1226 type = real_type_suffix (c);
1227 if (type == Token.NONE && !is_real){
1229 return adjust_int (c);
1233 if (type == Token.NONE){
1238 return adjust_real (type);
1240 Console.WriteLine ("This should not be reached");
1241 throw new Exception ("Is Number should never reach this point");
1245 // Accepts exactly count (4 or 8) hex, no more no less
1247 int getHex (int count, out bool error)
1252 int top = count != -1 ? count : 4;
1256 for (i = 0; i < top; i++){
1259 if (c >= '0' && c <= '9')
1260 c = (int) c - (int) '0';
1261 else if (c >= 'A' && c <= 'F')
1262 c = (int) c - (int) 'A' + 10;
1263 else if (c >= 'a' && c <= 'f')
1264 c = (int) c - (int) 'a' + 10;
1270 total = (total * 16) + c;
1272 int p = peekChar ();
1275 if (!is_hex ((char)p))
1316 v = getHex (-1, out error);
1321 v = getHex (4, out error);
1326 v = getHex (8, out error);
1331 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1341 if (putback_char != -1) {
1359 if (putback_char != -1)
1360 return putback_char;
1361 putback_char = reader.Read ();
1362 return putback_char;
1367 if (putback_char != -1)
1368 return putback_char;
1369 return reader.Peek ();
1372 void putback (int c)
1374 if (putback_char != -1){
1375 Console.WriteLine ("Col: " + col);
1376 Console.WriteLine ("Row: " + line);
1377 Console.WriteLine ("Name: " + ref_name.Name);
1378 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1379 throw new Exception ("This should not happen putback on putback");
1381 if (c == '\n' || col == 0) {
1382 // It won't happen though.
1392 public bool advance ()
1394 return peekChar () != -1;
1397 public Object Value {
1403 public Object value ()
1408 static bool IsCastToken (int token)
1413 case Token.IDENTIFIER:
1414 case Token.LITERAL_INTEGER:
1415 case Token.LITERAL_FLOAT:
1416 case Token.LITERAL_DOUBLE:
1417 case Token.LITERAL_DECIMAL:
1418 case Token.LITERAL_CHARACTER:
1419 case Token.LITERAL_STRING:
1422 case Token.DELEGATE:
1432 case Token.UNCHECKED:
1439 // These can be part of a member access
1459 current_token = xtoken ();
1462 if (current_token != Token.DEFAULT)
1463 return current_token;
1468 current_token = Token.ERROR;
1469 else if (c == Token.OPEN_PARENS)
1470 current_token = Token.DEFAULT_OPEN_PARENS;
1471 else if (c == Token.COLON)
1472 current_token = Token.DEFAULT_COLON;
1476 return current_token;
1479 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1481 void get_cmd_arg (out string cmd, out string arg)
1485 tokens_seen = false;
1487 static_cmd_arg.Length = 0;
1489 // skip over white space
1490 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1493 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1494 if (is_identifier_part_character ((char) c)){
1495 static_cmd_arg.Append ((char) c);
1503 cmd = static_cmd_arg.ToString ();
1505 if (c == '\n' || c == '\r'){
1509 // skip over white space
1510 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1515 } else if (c == '\r'){
1517 } else if (c == -1){
1522 static_cmd_arg.Length = 0;
1523 static_cmd_arg.Append ((char) c);
1525 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1526 static_cmd_arg.Append ((char) c);
1529 arg = static_cmd_arg.ToString ();
1533 // Handles the #line directive
1535 bool PreProcessLine (string arg)
1537 if (arg.Length == 0)
1540 if (arg == "default"){
1542 ref_name = file_name;
1543 Location.Push (ref_name);
1545 } else if (arg == "hidden"){
1547 // We ignore #line hidden
1555 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1556 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1559 char [] quotes = { '\"' };
1561 string name = arg.Substring (pos). Trim (quotes);
1562 ref_name = Location.LookupFile (name);
1563 file_name.HasLineDirective = true;
1564 ref_name.HasLineDirective = true;
1565 Location.Push (ref_name);
1567 ref_line = System.Int32.Parse (arg);
1577 // Handles #define and #undef
1579 void PreProcessDefinition (bool is_define, string arg, bool caller_is_taking)
1581 if (arg.Length == 0 || arg == "true" || arg == "false"){
1582 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1586 char[] whitespace = { ' ', '\t' };
1587 if (arg.IndexOfAny (whitespace) != -1){
1588 Error_EndLineExpected ();
1592 if (!is_identifier_start_character (arg [0]))
1593 Report.Error (1001, Location, "Identifier expected: " + arg);
1595 foreach (char c in arg.Substring (1)){
1596 if (!is_identifier_part_character (c)){
1597 Report.Error (1001, Location, "Identifier expected: " + arg);
1602 if (!caller_is_taking)
1606 if (defines == null)
1607 defines = new Hashtable ();
1610 if (defines == null)
1612 if (defines.Contains (arg))
1613 defines.Remove (arg);
1618 /// Handles #pragma directive
1620 void PreProcessPragma (string arg)
1622 const string warning = "warning";
1623 const string w_disable = "warning disable";
1624 const string w_restore = "warning restore";
1626 if (arg == w_disable) {
1627 Report.RegisterWarningRegion (Location).WarningDisable (line);
1631 if (arg == w_restore) {
1632 Report.RegisterWarningRegion (Location).WarningEnable (line);
1636 if (arg.StartsWith (w_disable)) {
1637 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1638 foreach (int code in codes) {
1640 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1645 if (arg.StartsWith (w_restore)) {
1646 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1647 Hashtable w_table = Report.warning_ignore_table;
1648 foreach (int code in codes) {
1649 if (w_table != null && w_table.Contains (code))
1650 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1651 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1656 if (arg.StartsWith (warning)) {
1657 Report.Warning (1634, 1, Location, "Expected disable or restore");
1661 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1664 int[] ParseNumbers (string text)
1666 string[] string_array = text.Split (',');
1667 int[] values = new int [string_array.Length];
1669 foreach (string string_code in string_array) {
1671 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1673 catch (FormatException) {
1674 Report.Warning (1692, 1, Location, "Invalid number");
1680 bool eval_val (string s)
1687 if (defines == null)
1689 if (defines.Contains (s))
1695 bool pp_primary (ref string s)
1704 s = s.Substring (1);
1705 bool val = pp_expr (ref s, false);
1706 if (s.Length > 0 && s [0] == ')'){
1707 s = s.Substring (1);
1710 Error_InvalidDirective ();
1714 if (is_identifier_start_character (c)){
1720 if (is_identifier_part_character (c)){
1724 bool v = eval_val (s.Substring (0, j));
1725 s = s.Substring (j);
1728 bool vv = eval_val (s);
1733 Error_InvalidDirective ();
1737 bool pp_unary (ref string s)
1744 if (len > 1 && s [1] == '='){
1745 Error_InvalidDirective ();
1748 s = s.Substring (1);
1749 return ! pp_primary (ref s);
1751 return pp_primary (ref s);
1753 Error_InvalidDirective ();
1758 bool pp_eq (ref string s)
1760 bool va = pp_unary (ref s);
1766 if (len > 2 && s [1] == '='){
1767 s = s.Substring (2);
1768 return va == pp_unary (ref s);
1770 Error_InvalidDirective ();
1773 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1774 s = s.Substring (2);
1776 return va != pp_unary (ref s);
1785 bool pp_and (ref string s)
1787 bool va = pp_eq (ref s);
1793 if (len > 2 && s [1] == '&'){
1794 s = s.Substring (2);
1795 return (va & pp_and (ref s));
1797 Error_InvalidDirective ();
1806 // Evaluates an expression for `#if' or `#elif'
1808 bool pp_expr (ref string s, bool isTerm)
1810 bool va = pp_and (ref s);
1817 if (len > 2 && s [1] == '|'){
1818 s = s.Substring (2);
1819 return va | pp_expr (ref s, isTerm);
1821 Error_InvalidDirective ();
1826 Error_EndLineExpected ();
1834 bool eval (string s)
1836 bool v = pp_expr (ref s, true);
1845 void Error_NumericConstantTooLong ()
1847 Report.Error (1021, Location, "Numeric constant too long");
1850 void Error_InvalidDirective ()
1852 Report.Error (1517, Location, "Invalid preprocessor directive");
1855 void Error_UnexpectedDirective (string extra)
1859 "Unexpected processor directive (" + extra + ")");
1862 void Error_TokensSeen ()
1864 Report.Error (1032, Location,
1865 "Cannot define or undefine preprocessor symbols after first token in file");
1868 void Eror_WrongPreprocessorLocation ()
1870 Report.Error (1040, Location,
1871 "Preprocessor directives must appear as the first non-whitespace character on a line");
1874 void Error_EndLineExpected ()
1876 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1880 // if true, then the code continues processing the code
1881 // if false, the code stays in a loop until another directive is
1883 // When caller_is_taking is false we ignore all directives except the ones
1884 // which can help us to identify where the #if block ends
1885 bool handle_preprocessing_directive (bool caller_is_taking)
1888 bool region_directive = false;
1890 get_cmd_arg (out cmd, out arg);
1892 // Eat any trailing whitespaces and single-line comments
1893 if (arg.IndexOf ("//") != -1)
1894 arg = arg.Substring (0, arg.IndexOf ("//"));
1895 arg = arg.Trim (' ', '\t');
1898 // The first group of pre-processing instructions is always processed
1902 region_directive = true;
1907 if (ifstack == null || ifstack.Count == 0){
1908 Error_UnexpectedDirective ("no #region for this #endregion");
1911 int pop = (int) ifstack.Pop ();
1913 if ((pop & REGION) == 0)
1914 Report.Error (1027, Location, "Expected `#endif' directive");
1916 return caller_is_taking;
1919 if (ifstack == null)
1920 ifstack = new Stack (2);
1922 int flags = region_directive ? REGION : 0;
1923 if (ifstack.Count == 0){
1924 flags |= PARENT_TAKING;
1926 int state = (int) ifstack.Peek ();
1927 if ((state & TAKING) != 0) {
1928 flags |= PARENT_TAKING;
1932 if (caller_is_taking && eval (arg)) {
1933 ifstack.Push (flags | TAKING);
1936 ifstack.Push (flags);
1940 if (ifstack == null || ifstack.Count == 0){
1941 Error_UnexpectedDirective ("no #if for this #endif");
1944 pop = (int) ifstack.Pop ();
1946 if ((pop & REGION) != 0)
1947 Report.Error (1038, Location, "#endregion directive expected");
1949 if (arg.Length != 0) {
1950 Error_EndLineExpected ();
1953 if (ifstack.Count == 0)
1956 int state = (int) ifstack.Peek ();
1957 return (state & TAKING) != 0;
1961 if (ifstack == null || ifstack.Count == 0){
1962 Error_UnexpectedDirective ("no #if for this #elif");
1965 int state = (int) ifstack.Pop ();
1967 if ((state & REGION) != 0) {
1968 Report.Error (1038, Location, "#endregion directive expected");
1972 if ((state & ELSE_SEEN) != 0){
1973 Error_UnexpectedDirective ("#elif not valid after #else");
1977 if ((state & TAKING) != 0) {
1982 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1983 ifstack.Push (state | TAKING);
1987 ifstack.Push (state);
1992 if (ifstack == null || ifstack.Count == 0){
1993 Error_UnexpectedDirective ("no #if for this #else");
1996 int state = (int) ifstack.Peek ();
1998 if ((state & REGION) != 0) {
1999 Report.Error (1038, Location, "#endregion directive expected");
2003 if ((state & ELSE_SEEN) != 0){
2004 Error_UnexpectedDirective ("#else within #else");
2010 if (arg.Length != 0) {
2011 Error_EndLineExpected ();
2016 if ((state & PARENT_TAKING) != 0) {
2017 ret = (state & TAKING) == 0;
2025 ifstack.Push (state | ELSE_SEEN);
2030 if (any_token_seen){
2031 Error_TokensSeen ();
2032 return caller_is_taking;
2034 PreProcessDefinition (true, arg, caller_is_taking);
2035 return caller_is_taking;
2038 if (any_token_seen){
2039 Error_TokensSeen ();
2040 return caller_is_taking;
2042 PreProcessDefinition (false, arg, caller_is_taking);
2043 return caller_is_taking;
2047 // These are only processed if we are in a `taking' block
2049 if (!caller_is_taking)
2054 Report.Error (1029, Location, "#error: '" + arg + "'");
2058 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2062 if (RootContext.Version == LanguageVersion.ISO_1) {
2063 Report.FeatureIsNotStandardized (Location, "#pragma");
2067 PreProcessPragma (arg);
2071 if (!PreProcessLine (arg))
2074 "The line number specified for #line directive is missing or invalid");
2075 return caller_is_taking;
2078 Report.Error (1024, Location, "Wrong preprocessor directive");
2083 private int consume_string (bool quoted)
2086 string_builder.Length = 0;
2088 while ((c = getChar ()) != -1){
2090 if (quoted && peekChar () == '"'){
2091 string_builder.Append ((char) c);
2095 val = string_builder.ToString ();
2096 return Token.LITERAL_STRING;
2102 Report.Error (1010, Location, "Newline in constant");
2110 string_builder.Append ((char) c);
2113 Report.Error (1039, Location, "Unterminated string literal");
2117 private int consume_identifier (int s)
2119 int res = consume_identifier (s, false);
2121 if (doc_state == XmlCommentState.Allowed)
2122 doc_state = XmlCommentState.NotAllowed;
2125 case Token.NAMESPACE:
2126 check_incorrect_doc_comment ();
2130 if (res == Token.PARTIAL) {
2131 // Save current position and parse next token.
2134 int next_token = token ();
2135 bool ok = (next_token == Token.CLASS) ||
2136 (next_token == Token.STRUCT) ||
2137 (next_token == Token.INTERFACE);
2144 if (next_token < Token.LAST_KEYWORD)
2145 Report.Error (267, Location, "The `partial' modifier can be used only immediately before keyword `class', `struct', or `interface'");
2147 val = new LocatedToken (Location, "partial");
2148 return Token.IDENTIFIER;
2154 private int consume_identifier (int s, bool quoted)
2159 id_builder [0] = (char) s;
2161 current_location = new Location (ref_line, Col);
2163 while ((c = getChar ()) != -1) {
2165 if (is_identifier_part_character ((char) c)){
2166 if (pos == max_id_size){
2167 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2171 id_builder [pos++] = (char) c;
2172 // putback_char = -1;
2173 } else if (c == '\\') {
2177 // putback_char = c;
2184 // Optimization: avoids doing the keyword lookup
2185 // on uppercase letters and _
2187 if (!quoted && (s >= 'a' || s == '_')){
2188 int keyword = GetKeyword (id_builder, pos);
2189 if (keyword != -1) {
2196 // Keep identifiers in an array of hashtables to avoid needless
2200 if (identifiers [pos] != null) {
2201 val = identifiers [pos][id_builder];
2203 val = new LocatedToken (Location, (string) val);
2205 escapedIdentifiers.Add (val);
2206 return Token.IDENTIFIER;
2210 identifiers [pos] = new CharArrayHashtable (pos);
2212 val = new String (id_builder, 0, pos);
2213 if (RootContext.Version == LanguageVersion.ISO_1) {
2214 for (int i = 1; i < id_builder.Length; i += 3) {
2215 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2216 Report.Error (1638, Location,
2217 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2223 char [] chars = new char [pos];
2224 Array.Copy (id_builder, chars, pos);
2226 identifiers [pos] [chars] = val;
2228 val = new LocatedToken (Location, (string) val);
2230 escapedIdentifiers.Add (val);
2231 return Token.IDENTIFIER;
2234 public int xtoken ()
2237 bool doread = false;
2240 // Whether we have seen comments on the current line
2241 bool comments_seen = false;
2244 for (;(c = getChar ()) != -1;) {
2245 if (c == ' ' || c == '\t' || c == '\f' || c == '\v' || c == 0xa0)
2249 if (peekChar () == '\n')
2252 any_token_seen |= tokens_seen;
2253 tokens_seen = false;
2254 comments_seen = false;
2258 // Handle double-slash comments.
2260 int d = peekChar ();
2264 if (RootContext.Documentation != null && peekChar () == '/') {
2266 // Don't allow ////.
2267 if ((d = peekChar ()) != '/') {
2268 update_comment_location ();
2269 if (doc_state == XmlCommentState.Allowed)
2270 handle_one_line_xml_comment ();
2271 else if (doc_state == XmlCommentState.NotAllowed)
2272 warn_incorrect_doc_comment ();
2275 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2278 any_token_seen |= tokens_seen;
2279 tokens_seen = false;
2280 comments_seen = false;
2282 } else if (d == '*'){
2284 bool docAppend = false;
2285 if (RootContext.Documentation != null && peekChar () == '*') {
2287 update_comment_location ();
2288 // But when it is /**/, just do nothing.
2289 if (peekChar () == '/') {
2293 if (doc_state == XmlCommentState.Allowed)
2295 else if (doc_state == XmlCommentState.NotAllowed)
2296 warn_incorrect_doc_comment ();
2299 int current_comment_start = 0;
2301 current_comment_start = xml_comment_buffer.Length;
2302 xml_comment_buffer.Append (Environment.NewLine);
2305 Location start_location = Location;
2307 while ((d = getChar ()) != -1){
2308 if (d == '*' && peekChar () == '/'){
2310 comments_seen = true;
2314 xml_comment_buffer.Append ((char) d);
2317 any_token_seen |= tokens_seen;
2318 tokens_seen = false;
2320 // Reset 'comments_seen' just to be consistent.
2321 // It doesn't matter either way, here.
2323 comments_seen = false;
2327 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2330 update_formatted_doc_comment (current_comment_start);
2333 goto is_punct_label;
2337 if (c == '\\' || is_identifier_start_character ((char)c)){
2339 return consume_identifier (c);
2343 current_location = new Location (ref_line, Col);
2344 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2354 any_token_seen |= tokens_seen;
2355 tokens_seen = false;
2356 comments_seen = false;
2360 if (c >= '0' && c <= '9'){
2362 return is_number (c);
2367 int peek = peekChar ();
2368 if (peek >= '0' && peek <= '9')
2369 return is_number (c);
2374 if (tokens_seen || comments_seen) {
2375 Eror_WrongPreprocessorLocation ();
2379 if (handle_preprocessing_directive (true))
2382 bool directive_expected = false;
2383 while ((c = getChar ()) != -1) {
2385 directive_expected = true;
2386 } else if (!directive_expected) {
2387 // TODO: Implement comment support for disabled code and uncomment this code
2389 // Eror_WrongPreprocessorLocation ();
2390 // return Token.ERROR;
2395 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2399 if (handle_preprocessing_directive (false))
2402 directive_expected = false;
2406 tokens_seen = false;
2414 return consume_string (false);
2420 error_details = "Empty character literal";
2421 Report.Error (1011, Location, error_details);
2424 if (c == '\r' || c == '\n') {
2425 Report.Error (1010, Location, "Newline in constant");
2431 val = new System.Char ();
2436 error_details = "Too many characters in character literal";
2437 Report.Error (1012, Location, error_details);
2439 // Try to recover, read until newline or next "'"
2440 while ((c = getChar ()) != -1){
2449 return Token.LITERAL_CHARACTER;
2456 return consume_string (true);
2457 } else if (is_identifier_start_character ((char) c)){
2458 return consume_identifier (c, true);
2460 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2464 error_details = ((char)c).ToString ();
2473 // Handles one line xml comment
2475 private void handle_one_line_xml_comment ()
2478 while ((c = peekChar ()) == ' ')
2479 getChar (); // skip heading whitespaces.
2480 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2481 xml_comment_buffer.Append ((char) getChar ());
2483 if (c == '\r' || c == '\n')
2484 xml_comment_buffer.Append (Environment.NewLine);
2488 // Remove heading "*" in Javadoc-like xml documentation.
2490 private void update_formatted_doc_comment (int current_comment_start)
2492 int length = xml_comment_buffer.Length - current_comment_start;
2493 string [] lines = xml_comment_buffer.ToString (
2494 current_comment_start,
2495 length).Replace ("\r", "").Split ('\n');
2497 // The first line starts with /**, thus it is not target
2498 // for the format check.
2499 for (int i = 1; i < lines.Length; i++) {
2500 string s = lines [i];
2501 int idx = s.IndexOf ('*');
2504 if (i < lines.Length - 1)
2508 head = s.Substring (0, idx);
2509 foreach (char c in head)
2512 lines [i] = s.Substring (idx + 1);
2514 xml_comment_buffer.Remove (current_comment_start, length);
2515 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2519 // Updates current comment location.
2521 private void update_comment_location ()
2523 if (current_comment_location.IsNull) {
2524 // "-2" is for heading "//" or "/*"
2525 current_comment_location =
2526 new Location (ref_line, col - 2);
2531 // Checks if there was incorrect doc comments and raise
2534 public void check_incorrect_doc_comment ()
2536 if (xml_comment_buffer.Length > 0)
2537 warn_incorrect_doc_comment ();
2541 // Raises a warning when tokenizer found incorrect doccomment
2544 private void warn_incorrect_doc_comment ()
2546 if (doc_state != XmlCommentState.Error) {
2547 doc_state = XmlCommentState.Error;
2548 // in csc, it is 'XML comment is not placed on
2549 // a valid language element'. But that does not
2551 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2556 // Consumes the saved xml comment lines (if any)
2557 // as for current target member or type.
2559 public string consume_doc_comment ()
2561 if (xml_comment_buffer.Length > 0) {
2562 string ret = xml_comment_buffer.ToString ();
2563 reset_doc_comment ();
2569 void reset_doc_comment ()
2571 xml_comment_buffer.Length = 0;
2572 current_comment_location = Location.Null;
2575 public void cleanup ()
2577 if (ifstack != null && ifstack.Count >= 1) {
2578 current_location = new Location (ref_line, Col);
2579 int state = (int) ifstack.Pop ();
2580 if ((state & REGION) != 0)
2581 Report.Error (1038, Location, "#endregion directive expected");
2583 Report.Error (1027, Location, "Expected `#endif' directive");
2589 // Indicates whether it accepts XML documentation or not.
2591 public enum XmlCommentState {
2592 // comment is allowed in this state.
2594 // comment is not allowed in this state.
2596 // once comments appeared when it is NotAllowed, then the
2597 // state is changed to it, until the state is changed to