2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 // This also implements the preprocessor
5 // Author: Miguel de Icaza (miguel@gnu.org)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
15 * Make sure we accept the proper Unicode ranges, per the spec.
21 using System.Collections;
23 using System.Globalization;
24 using System.Reflection;
29 /// Tokenizer for C# source code.
32 public class Tokenizer : yyParser.yyInput
34 SeekableStreamReader reader;
42 bool handle_get_set = false;
43 bool handle_remove_add = false;
44 bool handle_assembly = false;
45 bool handle_constraints = false;
46 bool handle_typeof = false;
47 Location current_location;
48 Location current_comment_location = Location.Null;
49 ArrayList escapedIdentifiers = new ArrayList ();
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 xmlDocState = 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 tokenValues;
76 private static Hashtable TokenValueName
79 if (tokenValues == null)
80 tokenValues = GetTokenValueNameHash ();
86 private static Hashtable GetTokenValueNameHash ()
88 Type t = typeof (Token);
89 FieldInfo [] fields = t.GetFields ();
90 Hashtable hash = new Hashtable ();
91 foreach (FieldInfo field in fields) {
92 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
93 hash.Add (field.GetValue (null), field.Name);
99 // Returns a verbose representation of the current location
101 public string location {
105 if (current_token == Token.ERROR)
106 det = "detail: " + error_details;
110 // return "Line: "+line+" Col: "+col + "\n" +
111 // "VirtLine: "+ref_line +
112 // " Token: "+current_token + " " + det;
113 string current_token_name = TokenValueName [current_token] as string;
114 if (current_token_name == null)
115 current_token_name = current_token.ToString ();
117 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
125 public bool PropertyParsing {
127 return handle_get_set;
131 handle_get_set = value;
135 public bool AssemblyTargetParsing {
137 return handle_assembly;
141 handle_assembly = value;
145 public bool EventParsing {
147 return handle_remove_add;
151 handle_remove_add = value;
155 public bool ConstraintsParsing {
157 return handle_constraints;
161 handle_constraints = value;
165 public bool TypeOfParsing {
167 return handle_typeof;
171 handle_typeof = value;
175 public XmlCommentState doc_state {
176 get { return xmlDocState; }
178 if (value == XmlCommentState.Allowed) {
179 check_incorrect_doc_comment ();
180 reset_doc_comment ();
186 public bool IsEscapedIdentifier (Location loc)
188 foreach (LocatedToken lt in escapedIdentifiers)
189 if (lt.Location.Equals (loc))
197 static CharArrayHashtable[] keywords;
198 static Hashtable keywordStrings = new Hashtable ();
199 static NumberStyles styles;
200 static NumberFormatInfo csharp_format_info;
203 // Values for the associated token returned
213 const int TAKING = 1;
214 const int TAKEN_BEFORE = 2;
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 ();
269 public int putback_char;
270 public int previous_col;
271 public int parsing_generic_less_than;
273 public Position (Tokenizer t)
275 position = t.reader.Position;
276 ref_line = t.ref_line;
278 putback_char = t.putback_char;
279 previous_col = t.previous_col;
280 parsing_generic_less_than = t.parsing_generic_less_than;
284 public void PushPosition ()
286 position_stack.Push (new Position (this));
289 public void PopPosition ()
291 Position p = (Position) position_stack.Pop ();
293 reader.Position = p.position;
294 ref_line = p.ref_line;
296 putback_char = p.putback_char;
297 previous_col = p.previous_col;
301 // Do not reset the position, ignore it.
302 public void DiscardPosition ()
304 position_stack.Pop ();
307 static void AddKeyword (string kw, int token) {
308 keywordStrings.Add (kw, kw);
309 if (keywords [kw.Length] == null) {
310 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
312 keywords [kw.Length] [kw.ToCharArray ()] = token;
315 static void InitTokens ()
317 keywords = new CharArrayHashtable [64];
319 AddKeyword ("__arglist", Token.ARGLIST);
320 AddKeyword ("abstract", Token.ABSTRACT);
321 AddKeyword ("as", Token.AS);
322 AddKeyword ("add", Token.ADD);
323 AddKeyword ("assembly", Token.ASSEMBLY);
324 AddKeyword ("base", Token.BASE);
325 AddKeyword ("bool", Token.BOOL);
326 AddKeyword ("break", Token.BREAK);
327 AddKeyword ("byte", Token.BYTE);
328 AddKeyword ("case", Token.CASE);
329 AddKeyword ("catch", Token.CATCH);
330 AddKeyword ("char", Token.CHAR);
331 AddKeyword ("checked", Token.CHECKED);
332 AddKeyword ("class", Token.CLASS);
333 AddKeyword ("const", Token.CONST);
334 AddKeyword ("continue", Token.CONTINUE);
335 AddKeyword ("decimal", Token.DECIMAL);
336 AddKeyword ("default", Token.DEFAULT);
337 AddKeyword ("delegate", Token.DELEGATE);
338 AddKeyword ("do", Token.DO);
339 AddKeyword ("double", Token.DOUBLE);
340 AddKeyword ("else", Token.ELSE);
341 AddKeyword ("enum", Token.ENUM);
342 AddKeyword ("event", Token.EVENT);
343 AddKeyword ("explicit", Token.EXPLICIT);
344 AddKeyword ("extern", Token.EXTERN);
345 AddKeyword ("false", Token.FALSE);
346 AddKeyword ("finally", Token.FINALLY);
347 AddKeyword ("fixed", Token.FIXED);
348 AddKeyword ("float", Token.FLOAT);
349 AddKeyword ("for", Token.FOR);
350 AddKeyword ("foreach", Token.FOREACH);
351 AddKeyword ("goto", Token.GOTO);
352 AddKeyword ("get", Token.GET);
353 AddKeyword ("if", Token.IF);
354 AddKeyword ("implicit", Token.IMPLICIT);
355 AddKeyword ("in", Token.IN);
356 AddKeyword ("int", Token.INT);
357 AddKeyword ("interface", Token.INTERFACE);
358 AddKeyword ("internal", Token.INTERNAL);
359 AddKeyword ("is", Token.IS);
360 AddKeyword ("lock", Token.LOCK);
361 AddKeyword ("long", Token.LONG);
362 AddKeyword ("namespace", Token.NAMESPACE);
363 AddKeyword ("new", Token.NEW);
364 AddKeyword ("null", Token.NULL);
365 AddKeyword ("object", Token.OBJECT);
366 AddKeyword ("operator", Token.OPERATOR);
367 AddKeyword ("out", Token.OUT);
368 AddKeyword ("override", Token.OVERRIDE);
369 AddKeyword ("params", Token.PARAMS);
370 AddKeyword ("private", Token.PRIVATE);
371 AddKeyword ("protected", Token.PROTECTED);
372 AddKeyword ("public", Token.PUBLIC);
373 AddKeyword ("readonly", Token.READONLY);
374 AddKeyword ("ref", Token.REF);
375 AddKeyword ("remove", Token.REMOVE);
376 AddKeyword ("return", Token.RETURN);
377 AddKeyword ("sbyte", Token.SBYTE);
378 AddKeyword ("sealed", Token.SEALED);
379 AddKeyword ("set", Token.SET);
380 AddKeyword ("short", Token.SHORT);
381 AddKeyword ("sizeof", Token.SIZEOF);
382 AddKeyword ("stackalloc", Token.STACKALLOC);
383 AddKeyword ("static", Token.STATIC);
384 AddKeyword ("string", Token.STRING);
385 AddKeyword ("struct", Token.STRUCT);
386 AddKeyword ("switch", Token.SWITCH);
387 AddKeyword ("this", Token.THIS);
388 AddKeyword ("throw", Token.THROW);
389 AddKeyword ("true", Token.TRUE);
390 AddKeyword ("try", Token.TRY);
391 AddKeyword ("typeof", Token.TYPEOF);
392 AddKeyword ("uint", Token.UINT);
393 AddKeyword ("ulong", Token.ULONG);
394 AddKeyword ("unchecked", Token.UNCHECKED);
395 AddKeyword ("unsafe", Token.UNSAFE);
396 AddKeyword ("ushort", Token.USHORT);
397 AddKeyword ("using", Token.USING);
398 AddKeyword ("virtual", Token.VIRTUAL);
399 AddKeyword ("void", Token.VOID);
400 AddKeyword ("volatile", Token.VOLATILE);
401 AddKeyword ("where", Token.WHERE);
402 AddKeyword ("while", Token.WHILE);
403 AddKeyword ("partial", Token.PARTIAL);
412 csharp_format_info = NumberFormatInfo.InvariantInfo;
413 styles = NumberStyles.Float;
415 string_builder = new System.Text.StringBuilder ();
418 int GetKeyword (char[] id, int id_len)
421 * Keywords are stored in an array of hashtables grouped by their
425 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
427 object o = keywords [id_len] [id];
434 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
436 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
438 if (handle_assembly == false && res == Token.ASSEMBLY)
440 if (handle_constraints == false && res == Token.WHERE)
447 public Location Location {
448 get { return current_location; }
451 void define (string def)
453 if (!RootContext.AllDefines.Contains (def)){
454 RootContext.AllDefines [def] = true;
456 if (defines.Contains (def))
458 defines [def] = true;
461 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
463 this.ref_name = file;
464 this.file_name = file;
470 defines = new Hashtable ();
471 foreach (string def in defs)
475 xml_comment_buffer = new StringBuilder ();
478 // FIXME: This could be `Location.Push' but we have to
479 // find out why the MS compiler allows this
481 Mono.CSharp.Location.Push (file, 0);
484 static bool is_identifier_start_character (char c)
486 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
489 static bool is_identifier_part_character (char c)
491 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
494 public static bool IsKeyword (string s)
496 return keywordStrings [s] != null;
499 public static bool IsValidIdentifier (string s)
501 if (s == null || s.Length == 0)
504 if (!is_identifier_start_character (s [0]))
507 for (int i = 1; i < s.Length; i ++)
508 if (! is_identifier_part_character (s [i]))
514 bool parse_generic_dimension (out int dimension)
519 int the_token = token ();
520 if (the_token == Token.OP_GENERICS_GT)
522 else if (the_token == Token.COMMA) {
530 bool parse_less_than ()
533 int the_token = token ();
534 if (the_token == Token.OPEN_BRACKET) {
536 the_token = token ();
537 } while (the_token != Token.CLOSE_BRACKET);
538 the_token = token ();
541 case Token.IDENTIFIER:
564 the_token = token ();
566 if (the_token == Token.OP_GENERICS_GT)
568 else if ((the_token == Token.COMMA) || (the_token == Token.DOT))
570 else if (the_token == Token.INTERR)
572 else if (the_token == Token.OP_GENERICS_LT) {
573 if (!parse_less_than ())
576 } else if (the_token == Token.OPEN_BRACKET) {
578 the_token = token ();
579 if (the_token == Token.CLOSE_BRACKET)
581 else if (the_token == Token.COMMA)
582 goto rank_specifiers;
589 int parsing_generic_less_than = 0;
591 int is_punct (char c, ref bool doread)
601 return Token.OPEN_BRACE;
604 return Token.CLOSE_BRACE;
606 // To block doccomment inside attribute declaration.
607 if (doc_state == XmlCommentState.Allowed)
608 doc_state = XmlCommentState.NotAllowed;
609 return Token.OPEN_BRACKET;
611 return Token.CLOSE_BRACKET;
613 return Token.OPEN_PARENS;
615 if (deambiguate_close_parens == 0)
616 return Token.CLOSE_PARENS;
618 --deambiguate_close_parens;
621 int new_token = token ();
624 if (new_token == Token.OPEN_PARENS)
625 return Token.CLOSE_PARENS_OPEN_PARENS;
626 else if (new_token == Token.MINUS)
627 return Token.CLOSE_PARENS_MINUS;
628 else if (IsCastToken (new_token))
629 return Token.CLOSE_PARENS_CAST;
631 return Token.CLOSE_PARENS_NO_CAST;
638 return Token.SEMICOLON;
647 if (parsing_generic_less_than++ > 0)
648 return Token.OP_GENERICS_LT;
653 if (parse_generic_dimension (out dimension)) {
656 return Token.GENERIC_DIMENSION;
661 // Save current position and parse next token.
663 bool is_generic_lt = parse_less_than ();
667 parsing_generic_less_than++;
668 return Token.OP_GENERICS_LT;
670 parsing_generic_less_than = 0;
679 return Token.OP_SHIFT_LEFT_ASSIGN;
681 return Token.OP_SHIFT_LEFT;
682 } else if (d == '='){
687 } else if (c == '>') {
688 if (parsing_generic_less_than > 0) {
689 parsing_generic_less_than--;
690 return Token.OP_GENERICS_GT;
700 return Token.OP_SHIFT_RIGHT_ASSIGN;
702 return Token.OP_SHIFT_RIGHT;
703 } else if (d == '='){
718 t = Token.OP_ADD_ASSIGN;
732 t = Token.OP_SUB_ASSIGN;
764 } else if (d == '='){
766 return Token.OP_AND_ASSIGN;
769 return Token.BITWISE_AND;
776 } else if (d == '='){
778 return Token.OP_OR_ASSIGN;
780 return Token.BITWISE_OR;
786 return Token.OP_MULT_ASSIGN;
795 return Token.OP_DIV_ASSIGN;
803 return Token.OP_MOD_ASSIGN;
805 return Token.PERCENT;
811 return Token.OP_XOR_ASSIGN;
819 return Token.DOUBLE_COLON;
828 int deambiguate_close_parens = 0;
830 public void Deambiguate_CloseParens ()
833 deambiguate_close_parens++;
836 public void PutbackNullable ()
838 if (nullable_pos < 0)
839 throw new Exception ();
843 reader.Position = nullable_pos;
848 public void PutbackCloseParens ()
853 void Error_NumericConstantTooLong ()
855 Report.Error (1021, Location, "Numeric constant too long");
858 int nullable_pos = -1;
860 public void CheckNullable (bool is_nullable)
863 nullable_pos = reader.Position;
868 bool decimal_digits (int c)
871 bool seen_digits = false;
874 if (number_pos == max_number_size)
875 Error_NumericConstantTooLong ();
876 number_builder [number_pos++] = (char) c;
880 // We use peekChar2, because decimal_digits needs to do a
881 // 2-character look-ahead (5.ToString for example).
883 while ((d = peekChar2 ()) != -1){
884 if (d >= '0' && d <= '9'){
885 if (number_pos == max_number_size)
886 Error_NumericConstantTooLong ();
887 number_builder [number_pos++] = (char) d;
899 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
902 int real_type_suffix (int c)
908 t = Token.LITERAL_FLOAT;
911 t = Token.LITERAL_DOUBLE;
914 t= Token.LITERAL_DECIMAL;
922 int integer_type_suffix (ulong ul, int c)
924 bool is_unsigned = false;
925 bool is_long = false;
928 bool scanning = true;
939 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
941 // if we have not seen anything in between
944 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
947 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
972 if (is_long && is_unsigned){
974 return Token.LITERAL_INTEGER;
975 } else if (is_unsigned){
976 // uint if possible, or ulong else.
978 if ((ul & 0xffffffff00000000) == 0)
983 // long if possible, ulong otherwise
984 if ((ul & 0x8000000000000000) != 0)
989 // int, uint, long or ulong in that order
990 if ((ul & 0xffffffff00000000) == 0){
993 if ((ui & 0x80000000) != 0)
998 if ((ul & 0x8000000000000000) != 0)
1004 return Token.LITERAL_INTEGER;
1008 // given `c' as the next char in the input decide whether
1009 // we need to convert to a special type, and then choose
1010 // the best representation for the integer
1012 int adjust_int (int c)
1015 if (number_pos > 9){
1016 ulong ul = (uint) (number_builder [0] - '0');
1018 for (int i = 1; i < number_pos; i++){
1019 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1021 return integer_type_suffix (ul, c);
1023 uint ui = (uint) (number_builder [0] - '0');
1025 for (int i = 1; i < number_pos; i++){
1026 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1028 return integer_type_suffix (ui, c);
1030 } catch (OverflowException) {
1031 error_details = "Integral constant is too large";
1032 Report.Error (1021, Location, error_details);
1034 return Token.LITERAL_INTEGER;
1036 catch (FormatException) {
1037 Report.Error (1013, Location, "Invalid number");
1039 return Token.LITERAL_INTEGER;
1043 int adjust_real (int t)
1045 string s = new String (number_builder, 0, number_pos);
1046 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1049 case Token.LITERAL_DECIMAL:
1051 val = System.Decimal.Parse (s, styles, csharp_format_info);
1052 } catch (OverflowException) {
1054 Report.Error (594, Location, error_details, "decimal");
1057 case Token.LITERAL_FLOAT:
1059 val = (float) System.Double.Parse (s, styles, csharp_format_info);
1060 } catch (OverflowException) {
1062 Report.Error (594, Location, error_details, "float");
1066 case Token.LITERAL_DOUBLE:
1068 t = Token.LITERAL_DOUBLE;
1070 val = System.Double.Parse (s, styles, csharp_format_info);
1071 } catch (OverflowException) {
1073 Report.Error (594, Location, error_details, "double");
1086 while ((d = peekChar ()) != -1){
1088 number_builder [number_pos++] = (char) d;
1094 string s = new String (number_builder, 0, number_pos);
1096 if (number_pos <= 8)
1097 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1099 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1100 } catch (OverflowException){
1101 error_details = "Integral constant is too large";
1102 Report.Error (1021, Location, error_details);
1104 return Token.LITERAL_INTEGER;
1106 catch (FormatException) {
1107 Report.Error (1013, Location, "Invalid number");
1109 return Token.LITERAL_INTEGER;
1112 return integer_type_suffix (ul, peekChar ());
1116 // Invoked if we know we have .digits or digits
1118 int is_number (int c)
1120 bool is_real = false;
1125 if (c >= '0' && c <= '9'){
1127 int peek = peekChar ();
1129 if (peek == 'x' || peek == 'X')
1130 return handle_hex ();
1137 // We need to handle the case of
1138 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1141 if (decimal_digits ('.')){
1147 return adjust_int (-1);
1151 if (c == 'e' || c == 'E'){
1153 if (number_pos == max_number_size)
1154 Error_NumericConstantTooLong ();
1155 number_builder [number_pos++] = 'e';
1159 if (number_pos == max_number_size)
1160 Error_NumericConstantTooLong ();
1161 number_builder [number_pos++] = '+';
1163 } else if (c == '-') {
1164 if (number_pos == max_number_size)
1165 Error_NumericConstantTooLong ();
1166 number_builder [number_pos++] = '-';
1169 if (number_pos == max_number_size)
1170 Error_NumericConstantTooLong ();
1171 number_builder [number_pos++] = '+';
1178 type = real_type_suffix (c);
1179 if (type == Token.NONE && !is_real){
1181 return adjust_int (c);
1185 if (type == Token.NONE){
1190 return adjust_real (type);
1192 Console.WriteLine ("This should not be reached");
1193 throw new Exception ("Is Number should never reach this point");
1197 // Accepts exactly count (4 or 8) hex, no more no less
1199 int getHex (int count, out bool error)
1204 int top = count != -1 ? count : 4;
1208 for (i = 0; i < top; i++){
1211 if (c >= '0' && c <= '9')
1212 c = (int) c - (int) '0';
1213 else if (c >= 'A' && c <= 'F')
1214 c = (int) c - (int) 'A' + 10;
1215 else if (c >= 'a' && c <= 'f')
1216 c = (int) c - (int) 'a' + 10;
1222 total = (total * 16) + c;
1224 int p = peekChar ();
1227 if (!is_hex ((char)p))
1268 v = getHex (-1, out error);
1273 v = getHex (4, out error);
1278 v = getHex (8, out error);
1283 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1293 if (putback_char != -1) {
1311 if (putback_char != -1)
1312 return putback_char;
1313 putback_char = reader.Read ();
1314 return putback_char;
1319 if (putback_char != -1)
1320 return putback_char;
1321 return reader.Peek ();
1324 void putback (int c)
1326 if (putback_char != -1){
1327 Console.WriteLine ("Col: " + col);
1328 Console.WriteLine ("Row: " + line);
1329 Console.WriteLine ("Name: " + ref_name.Name);
1330 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1331 throw new Exception ("This should not happen putback on putback");
1333 if (c == '\n' || col == 0) {
1334 // It won't happen though.
1344 public bool advance ()
1346 return peekChar () != -1;
1349 public Object Value {
1355 public Object value ()
1360 bool IsCastToken (int token)
1365 case Token.IDENTIFIER:
1366 case Token.LITERAL_INTEGER:
1367 case Token.LITERAL_FLOAT:
1368 case Token.LITERAL_DOUBLE:
1369 case Token.LITERAL_DECIMAL:
1370 case Token.LITERAL_CHARACTER:
1371 case Token.LITERAL_STRING:
1383 case Token.UNCHECKED:
1387 // These can be part of a member access
1407 current_token = xtoken ();
1409 if (current_token != Token.DEFAULT)
1410 return current_token;
1412 int c = consume_whitespace ();
1414 current_token = Token.ERROR;
1416 current_token = Token.DEFAULT_OPEN_PARENS;
1420 return current_token;
1423 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1425 void get_cmd_arg (out string cmd, out string arg)
1429 tokens_seen = false;
1431 static_cmd_arg.Length = 0;
1433 // skip over white space
1434 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1437 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1438 if (is_identifier_part_character ((char) c)){
1439 static_cmd_arg.Append ((char) c);
1447 cmd = static_cmd_arg.ToString ();
1453 // skip over white space
1454 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1459 } else if (c == '\r'){
1461 } else if (c == -1){
1466 static_cmd_arg.Length = 0;
1467 static_cmd_arg.Append ((char) c);
1469 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1470 static_cmd_arg.Append ((char) c);
1473 arg = static_cmd_arg.ToString ().Trim ();
1477 // Handles the #line directive
1479 bool PreProcessLine (string arg)
1484 if (arg == "default"){
1486 ref_name = file_name;
1487 Location.Push (ref_name, line);
1489 } else if (arg == "hidden"){
1491 // We ignore #line hidden
1499 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1500 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1503 char [] quotes = { '\"' };
1505 string name = arg.Substring (pos). Trim (quotes);
1506 ref_name = Location.LookupFile (name);
1507 file_name.HasLineDirective = true;
1508 ref_name.HasLineDirective = true;
1509 Location.Push (ref_name, ref_line);
1511 ref_line = System.Int32.Parse (arg);
1521 // Handles #define and #undef
1523 void PreProcessDefinition (bool is_define, string arg)
1525 if (arg == "" || arg == "true" || arg == "false"){
1526 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1530 char[] whitespace = { ' ', '\t' };
1531 if (arg.IndexOfAny (whitespace) != -1){
1532 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1536 if (!is_identifier_start_character (arg [0]))
1537 Report.Error (1001, Location, "Identifier expected: " + arg);
1539 foreach (char c in arg.Substring (1)){
1540 if (!is_identifier_part_character (c)){
1541 Report.Error (1001, Location, "Identifier expected: " + arg);
1547 if (defines == null)
1548 defines = new Hashtable ();
1551 if (defines == null)
1553 if (defines.Contains (arg))
1554 defines.Remove (arg);
1559 /// Handles #pragma directive
1561 void PreProcessPragma (string arg)
1563 const string warning = "warning";
1564 const string w_disable = "warning disable";
1565 const string w_restore = "warning restore";
1567 if (arg == w_disable) {
1568 Report.RegisterWarningRegion (Location).WarningDisable (line);
1572 if (arg == w_restore) {
1573 Report.RegisterWarningRegion (Location).WarningEnable (line);
1577 if (arg.StartsWith (w_disable)) {
1578 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1579 foreach (int code in codes) {
1581 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1586 if (arg.StartsWith (w_restore)) {
1587 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1588 Hashtable w_table = Report.warning_ignore_table;
1589 foreach (int code in codes) {
1590 if (w_table != null && w_table.Contains (code))
1591 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1592 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1597 if (arg.StartsWith (warning)) {
1598 Report.Warning (1634, 1, Location, "Expected disable or restore");
1602 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1605 int[] ParseNumbers (string text)
1607 string[] string_array = text.Split (',');
1608 int[] values = new int [string_array.Length];
1610 foreach (string string_code in string_array) {
1612 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1614 catch (FormatException) {
1615 Report.Warning (1692, 1, Location, "Invalid number");
1621 bool eval_val (string s)
1628 if (defines == null)
1630 if (defines.Contains (s))
1636 bool pp_primary (ref string s)
1645 s = s.Substring (1);
1646 bool val = pp_expr (ref s);
1647 if (s.Length > 0 && s [0] == ')'){
1648 s = s.Substring (1);
1651 Error_InvalidDirective ();
1655 if (is_identifier_start_character (c)){
1661 if (is_identifier_part_character (c)){
1665 bool v = eval_val (s.Substring (0, j));
1666 s = s.Substring (j);
1669 bool vv = eval_val (s);
1674 Error_InvalidDirective ();
1678 bool pp_unary (ref string s)
1685 if (len > 1 && s [1] == '='){
1686 Error_InvalidDirective ();
1689 s = s.Substring (1);
1690 return ! pp_primary (ref s);
1692 return pp_primary (ref s);
1694 Error_InvalidDirective ();
1699 bool pp_eq (ref string s)
1701 bool va = pp_unary (ref s);
1707 if (len > 2 && s [1] == '='){
1708 s = s.Substring (2);
1709 return va == pp_unary (ref s);
1711 Error_InvalidDirective ();
1714 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1715 s = s.Substring (2);
1717 return va != pp_unary (ref s);
1726 bool pp_and (ref string s)
1728 bool va = pp_eq (ref s);
1734 if (len > 2 && s [1] == '&'){
1735 s = s.Substring (2);
1736 return (va & pp_and (ref s));
1738 Error_InvalidDirective ();
1747 // Evaluates an expression for `#if' or `#elif'
1749 bool pp_expr (ref string s)
1751 bool va = pp_and (ref s);
1758 if (len > 2 && s [1] == '|'){
1759 s = s.Substring (2);
1760 return va | pp_expr (ref s);
1762 Error_InvalidDirective ();
1771 bool eval (string s)
1773 bool v = pp_expr (ref s);
1776 Error_InvalidDirective ();
1783 void Error_InvalidDirective ()
1785 Report.Error (1517, Location, "Invalid preprocessor directive");
1788 void Error_UnexpectedDirective (string extra)
1792 "Unexpected processor directive (" + extra + ")");
1795 void Error_TokensSeen ()
1797 Report.Error (1032, Location,
1798 "Cannot define or undefine preprocessor symbols after first token in file");
1802 // if true, then the code continues processing the code
1803 // if false, the code stays in a loop until another directive is
1806 bool handle_preprocessing_directive (bool caller_is_taking)
1809 bool region_directive = false;
1811 current_location = new Location (ref_line, Col);
1813 get_cmd_arg (out cmd, out arg);
1815 // Eat any trailing whitespaces and single-line comments
1816 if (arg.IndexOf ("//") != -1)
1817 arg = arg.Substring (0, arg.IndexOf ("//"));
1818 arg = arg.TrimEnd (' ', '\t');
1821 // The first group of pre-processing instructions is always processed
1825 if (RootContext.Version == LanguageVersion.ISO_1) {
1826 Report.FeatureIsNotStandardized (Location, "#pragma");
1827 return caller_is_taking;
1830 PreProcessPragma (arg);
1831 return caller_is_taking;
1834 if (!PreProcessLine (arg))
1837 "The line number specified for #line directive is missing or invalid");
1838 return caller_is_taking;
1841 region_directive = true;
1846 region_directive = true;
1851 Error_InvalidDirective ();
1854 bool taking = false;
1855 if (ifstack == null)
1856 ifstack = new Stack ();
1858 if (ifstack.Count == 0){
1861 int state = (int) ifstack.Peek ();
1862 if ((state & TAKING) != 0)
1866 if (eval (arg) && taking){
1867 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1868 if (region_directive)
1870 ifstack.Push (push);
1873 int push = (taking ? PARENT_TAKING : 0);
1874 if (region_directive)
1876 ifstack.Push (push);
1881 if (ifstack == null || ifstack.Count == 0){
1882 Error_UnexpectedDirective ("no #if for this #endif");
1885 int pop = (int) ifstack.Pop ();
1887 if (region_directive && ((pop & REGION) == 0))
1888 Report.Error (1027, Location, "Expected `#endif' directive");
1889 else if (!region_directive && ((pop & REGION) != 0))
1890 Report.Error (1038, Location, "#endregion directive expected");
1892 if (!region_directive && arg.Length != 0) {
1893 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1896 if (ifstack.Count == 0)
1899 int state = (int) ifstack.Peek ();
1901 if ((state & TAKING) != 0)
1909 if (ifstack == null || ifstack.Count == 0){
1910 Error_UnexpectedDirective ("no #if for this #elif");
1913 int state = (int) ifstack.Peek ();
1915 if ((state & REGION) != 0) {
1916 Report.Error (1038, Location, "#endregion directive expected");
1920 if ((state & ELSE_SEEN) != 0){
1921 Error_UnexpectedDirective ("#elif not valid after #else");
1925 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1928 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1929 state = (int) ifstack.Pop ();
1930 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1937 if (ifstack == null || ifstack.Count == 0){
1938 Error_UnexpectedDirective ("no #if for this #else");
1941 int state = (int) ifstack.Peek ();
1943 if ((state & REGION) != 0) {
1944 Report.Error (1038, Location, "#endregion directive expected");
1948 if ((state & ELSE_SEEN) != 0){
1949 Error_UnexpectedDirective ("#else within #else");
1956 if ((state & TAKEN_BEFORE) == 0){
1957 ret = ((state & PARENT_TAKING) != 0);
1966 ifstack.Push (state | ELSE_SEEN);
1973 // These are only processed if we are in a `taking' block
1975 if (!caller_is_taking)
1980 if (any_token_seen){
1981 Error_TokensSeen ();
1984 PreProcessDefinition (true, arg);
1988 if (any_token_seen){
1989 Error_TokensSeen ();
1992 PreProcessDefinition (false, arg);
1996 Report.Error (1029, Location, "#error: '" + arg + "'");
2000 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2004 Report.Error (1024, Location, "Wrong preprocessor directive");
2009 private int consume_string (bool quoted)
2012 string_builder.Length = 0;
2014 while ((c = getChar ()) != -1){
2016 if (quoted && peekChar () == '"'){
2017 string_builder.Append ((char) c);
2021 val = string_builder.ToString ();
2022 return Token.LITERAL_STRING;
2028 Report.Error (1010, Location, "Newline in constant");
2036 string_builder.Append ((char) c);
2039 Report.Error (1039, Location, "Unterminated string literal");
2043 private int consume_identifier (int s)
2045 int res = consume_identifier (s, false);
2047 if (doc_state == XmlCommentState.Allowed)
2048 doc_state = XmlCommentState.NotAllowed;
2051 case Token.NAMESPACE:
2052 check_incorrect_doc_comment ();
2056 if (res == Token.PARTIAL) {
2057 // Save current position and parse next token.
2060 int next_token = token ();
2061 bool ok = (next_token == Token.CLASS) ||
2062 (next_token == Token.STRUCT) ||
2063 (next_token == Token.INTERFACE) ||
2064 (next_token == Token.ENUM); // "partial" is a keyword in 'partial enum', even though it's not valid
2071 val = new LocatedToken (Location, "partial");
2072 return Token.IDENTIFIER;
2079 private int consume_identifier (int s, bool quoted)
2084 id_builder [0] = (char) s;
2086 current_location = new Location (ref_line, Col);
2088 while ((c = getChar ()) != -1) {
2089 if (is_identifier_part_character ((char) c)){
2090 if (pos == max_id_size){
2091 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2095 id_builder [pos++] = (char) c;
2096 // putback_char = -1;
2098 // putback_char = c;
2105 // Optimization: avoids doing the keyword lookup
2106 // on uppercase letters and _
2108 if (!quoted && (s >= 'a' || s == '_')){
2109 int keyword = GetKeyword (id_builder, pos);
2110 if (keyword != -1) {
2117 // Keep identifiers in an array of hashtables to avoid needless
2121 if (identifiers [pos] != null) {
2122 val = identifiers [pos][id_builder];
2124 val = new LocatedToken (Location, (string) val);
2126 escapedIdentifiers.Add (val);
2127 return Token.IDENTIFIER;
2131 identifiers [pos] = new CharArrayHashtable (pos);
2133 val = new String (id_builder, 0, pos);
2134 if (RootContext.Version == LanguageVersion.ISO_1) {
2135 for (int i = 1; i < id_builder.Length; i += 3) {
2136 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2137 Report.Error (1638, Location,
2138 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2144 char [] chars = new char [pos];
2145 Array.Copy (id_builder, chars, pos);
2147 identifiers [pos] [chars] = val;
2149 val = new LocatedToken (Location, (string) val);
2151 escapedIdentifiers.Add (val);
2152 return Token.IDENTIFIER;
2155 int consume_whitespace ()
2159 // Whether we have seen comments on the current line
2160 bool comments_seen = false;
2163 // optimization: eliminate col and implement #directive semantic correctly.
2164 for (;(c = getChar ()) != -1;) {
2172 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
2176 if (peekChar () == '\n')
2179 any_token_seen |= tokens_seen;
2180 tokens_seen = false;
2181 comments_seen = false;
2185 // Handle double-slash comments.
2187 int d = peekChar ();
2191 if (RootContext.Documentation != null && peekChar () == '/') {
2193 // Don't allow ////.
2194 if ((d = peekChar ()) != '/') {
2195 update_comment_location ();
2196 if (doc_state == XmlCommentState.Allowed)
2197 handle_one_line_xml_comment ();
2198 else if (doc_state == XmlCommentState.NotAllowed)
2199 warn_incorrect_doc_comment ();
2202 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2205 any_token_seen |= tokens_seen;
2206 tokens_seen = false;
2207 comments_seen = false;
2209 } else if (d == '*'){
2211 bool docAppend = false;
2212 if (RootContext.Documentation != null && peekChar () == '*') {
2214 update_comment_location ();
2215 // But when it is /**/, just do nothing.
2216 if (peekChar () == '/') {
2220 if (doc_state == XmlCommentState.Allowed)
2222 else if (doc_state == XmlCommentState.NotAllowed)
2223 warn_incorrect_doc_comment ();
2226 int current_comment_start = 0;
2228 current_comment_start = xml_comment_buffer.Length;
2229 xml_comment_buffer.Append (Environment.NewLine);
2232 Location start_location = Location;
2234 while ((d = getChar ()) != -1){
2235 if (d == '*' && peekChar () == '/'){
2237 comments_seen = true;
2241 xml_comment_buffer.Append ((char) d);
2244 any_token_seen |= tokens_seen;
2245 tokens_seen = false;
2247 // Reset 'comments_seen' just to be consistent.
2248 // It doesn't matter either way, here.
2250 comments_seen = false;
2254 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2257 update_formatted_doc_comment (current_comment_start);
2260 goto is_punct_label;
2266 any_token_seen |= tokens_seen;
2267 tokens_seen = false;
2268 comments_seen = false;
2272 /* For now, ignore pre-processor commands */
2273 // FIXME: In C# the '#' is not limited to appear
2274 // on the first column.
2278 if (tokens_seen || comments_seen) {
2279 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2280 "character on a line.";
2282 Report.Error (1040, Location, error_details);
2289 cont = handle_preprocessing_directive (cont);
2295 bool skipping = false;
2296 for (;(c = getChar ()) != -1;){
2299 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2303 if (c == '#' && !skipping)
2306 any_token_seen |= tokens_seen;
2307 tokens_seen = false;
2309 Report.Error (1027, Location, "Expected `#endif' directive");
2319 public int xtoken ()
2322 bool doread = false;
2326 // optimization: eliminate col and implement #directive semantic correctly.
2328 c = consume_whitespace ();
2332 if (is_identifier_start_character ((char)c)){
2334 return consume_identifier (c);
2337 current_location = new Location (ref_line, Col);
2338 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2347 if (c >= '0' && c <= '9'){
2349 return is_number (c);
2354 int peek = peekChar ();
2355 if (peek >= '0' && peek <= '9')
2356 return is_number (c);
2361 return consume_string (false);
2367 error_details = "Empty character literal";
2368 Report.Error (1011, Location, error_details);
2371 if (c == '\r' || c == '\n') {
2372 Report.Error (1010, Location, "Newline in constant");
2378 val = new System.Char ();
2383 error_details = "Too many characters in character literal";
2384 Report.Error (1012, Location, error_details);
2386 // Try to recover, read until newline or next "'"
2387 while ((c = getChar ()) != -1){
2396 return Token.LITERAL_CHARACTER;
2403 return consume_string (true);
2404 } else if (is_identifier_start_character ((char) c)){
2405 return consume_identifier (c, true);
2407 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2412 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2413 "character on a line.";
2415 Report.Error (1040, Location, error_details);
2420 error_details = ((char)c).ToString ();
2426 // Handles one line xml comment
2428 private void handle_one_line_xml_comment ()
2431 while ((c = peekChar ()) == ' ')
2432 getChar (); // skip heading whitespaces.
2433 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2434 xml_comment_buffer.Append ((char) getChar ());
2436 if (c == '\r' || c == '\n')
2437 xml_comment_buffer.Append (Environment.NewLine);
2441 // Remove heading "*" in Javadoc-like xml documentation.
2443 private void update_formatted_doc_comment (int current_comment_start)
2445 int length = xml_comment_buffer.Length - current_comment_start;
2446 string [] lines = xml_comment_buffer.ToString (
2447 current_comment_start,
2448 length).Replace ("\r", "").Split ('\n');
2450 // The first line starts with /**, thus it is not target
2451 // for the format check.
2452 for (int i = 1; i < lines.Length; i++) {
2453 string s = lines [i];
2454 int idx = s.IndexOf ('*');
2457 if (i < lines.Length - 1)
2461 head = s.Substring (0, idx);
2462 foreach (char c in head)
2465 lines [i] = s.Substring (idx + 1);
2467 xml_comment_buffer.Remove (current_comment_start, length);
2468 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2472 // Updates current comment location.
2474 private void update_comment_location ()
2476 if (current_comment_location.IsNull) {
2477 // "-2" is for heading "//" or "/*"
2478 current_comment_location =
2479 new Location (ref_line, col - 2);
2484 // Checks if there was incorrect doc comments and raise
2487 public void check_incorrect_doc_comment ()
2489 if (xml_comment_buffer.Length > 0)
2490 warn_incorrect_doc_comment ();
2494 // Raises a warning when tokenizer found incorrect doccomment
2497 private void warn_incorrect_doc_comment ()
2499 if (doc_state != XmlCommentState.Error) {
2500 doc_state = XmlCommentState.Error;
2501 // in csc, it is 'XML comment is not placed on
2502 // a valid language element'. But that does not
2504 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2509 // Consumes the saved xml comment lines (if any)
2510 // as for current target member or type.
2512 public string consume_doc_comment ()
2514 if (xml_comment_buffer.Length > 0) {
2515 string ret = xml_comment_buffer.ToString ();
2516 reset_doc_comment ();
2522 void reset_doc_comment ()
2524 xml_comment_buffer.Length = 0;
2525 current_comment_location = Location.Null;
2528 public void cleanup ()
2530 if (ifstack != null && ifstack.Count >= 1) {
2531 int state = (int) ifstack.Pop ();
2532 if ((state & REGION) != 0)
2533 Report.Error (1038, Location, "#endregion directive expected");
2535 Report.Error (1027, Location, "Expected `#endif' directive");
2542 // Indicates whether it accepts XML documentation or not.
2544 public enum XmlCommentState {
2545 // comment is allowed in this state.
2547 // comment is not allowed in this state.
2549 // once comments appeared when it is NotAllowed, then the
2550 // state is changed to it, until the state is changed to