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 TAKEN_BEFORE = 2;
216 const int ELSE_SEEN = 4;
217 const int PARENT_TAKING = 8;
218 const int REGION = 16;
221 // pre-processor if stack state:
225 static System.Text.StringBuilder string_builder;
227 const int max_id_size = 512;
228 static char [] id_builder = new char [max_id_size];
230 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
232 const int max_number_size = 512;
233 static char [] number_builder = new char [max_number_size];
234 static int number_pos;
237 // Details about the error encoutered by the tokenizer
239 string error_details;
241 public string error {
243 return error_details;
260 // This is used when the tokenizer needs to save
261 // the current position as it needs to do some parsing
262 // on its own to deamiguate a token in behalf of the
265 Stack position_stack = new Stack (2);
270 public int putback_char;
271 public int previous_col;
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;
283 parsing_generic_less_than = t.parsing_generic_less_than;
288 public void PushPosition ()
290 position_stack.Push (new Position (this));
293 public void PopPosition ()
295 Position p = (Position) position_stack.Pop ();
297 reader.Position = p.position;
298 ref_line = p.ref_line;
300 putback_char = p.putback_char;
301 previous_col = p.previous_col;
305 // Do not reset the position, ignore it.
306 public void DiscardPosition ()
308 position_stack.Pop ();
311 static void AddKeyword (string kw, int token) {
312 keywordStrings.Add (kw, kw);
313 if (keywords [kw.Length] == null) {
314 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
316 keywords [kw.Length] [kw.ToCharArray ()] = token;
319 static void InitTokens ()
321 keywords = new CharArrayHashtable [64];
323 AddKeyword ("__arglist", Token.ARGLIST);
324 AddKeyword ("abstract", Token.ABSTRACT);
325 AddKeyword ("as", Token.AS);
326 AddKeyword ("add", Token.ADD);
327 AddKeyword ("assembly", Token.ASSEMBLY);
328 AddKeyword ("base", Token.BASE);
329 AddKeyword ("bool", Token.BOOL);
330 AddKeyword ("break", Token.BREAK);
331 AddKeyword ("byte", Token.BYTE);
332 AddKeyword ("case", Token.CASE);
333 AddKeyword ("catch", Token.CATCH);
334 AddKeyword ("char", Token.CHAR);
335 AddKeyword ("checked", Token.CHECKED);
336 AddKeyword ("class", Token.CLASS);
337 AddKeyword ("const", Token.CONST);
338 AddKeyword ("continue", Token.CONTINUE);
339 AddKeyword ("decimal", Token.DECIMAL);
340 AddKeyword ("default", Token.DEFAULT);
341 AddKeyword ("delegate", Token.DELEGATE);
342 AddKeyword ("do", Token.DO);
343 AddKeyword ("double", Token.DOUBLE);
344 AddKeyword ("else", Token.ELSE);
345 AddKeyword ("enum", Token.ENUM);
346 AddKeyword ("event", Token.EVENT);
347 AddKeyword ("explicit", Token.EXPLICIT);
348 AddKeyword ("extern", Token.EXTERN);
349 AddKeyword ("false", Token.FALSE);
350 AddKeyword ("finally", Token.FINALLY);
351 AddKeyword ("fixed", Token.FIXED);
352 AddKeyword ("float", Token.FLOAT);
353 AddKeyword ("for", Token.FOR);
354 AddKeyword ("foreach", Token.FOREACH);
355 AddKeyword ("goto", Token.GOTO);
356 AddKeyword ("get", Token.GET);
357 AddKeyword ("if", Token.IF);
358 AddKeyword ("implicit", Token.IMPLICIT);
359 AddKeyword ("in", Token.IN);
360 AddKeyword ("int", Token.INT);
361 AddKeyword ("interface", Token.INTERFACE);
362 AddKeyword ("internal", Token.INTERNAL);
363 AddKeyword ("is", Token.IS);
364 AddKeyword ("lock", Token.LOCK);
365 AddKeyword ("long", Token.LONG);
366 AddKeyword ("namespace", Token.NAMESPACE);
367 AddKeyword ("new", Token.NEW);
368 AddKeyword ("null", Token.NULL);
369 AddKeyword ("object", Token.OBJECT);
370 AddKeyword ("operator", Token.OPERATOR);
371 AddKeyword ("out", Token.OUT);
372 AddKeyword ("override", Token.OVERRIDE);
373 AddKeyword ("params", Token.PARAMS);
374 AddKeyword ("private", Token.PRIVATE);
375 AddKeyword ("protected", Token.PROTECTED);
376 AddKeyword ("public", Token.PUBLIC);
377 AddKeyword ("readonly", Token.READONLY);
378 AddKeyword ("ref", Token.REF);
379 AddKeyword ("remove", Token.REMOVE);
380 AddKeyword ("return", Token.RETURN);
381 AddKeyword ("sbyte", Token.SBYTE);
382 AddKeyword ("sealed", Token.SEALED);
383 AddKeyword ("set", Token.SET);
384 AddKeyword ("short", Token.SHORT);
385 AddKeyword ("sizeof", Token.SIZEOF);
386 AddKeyword ("stackalloc", Token.STACKALLOC);
387 AddKeyword ("static", Token.STATIC);
388 AddKeyword ("string", Token.STRING);
389 AddKeyword ("struct", Token.STRUCT);
390 AddKeyword ("switch", Token.SWITCH);
391 AddKeyword ("this", Token.THIS);
392 AddKeyword ("throw", Token.THROW);
393 AddKeyword ("true", Token.TRUE);
394 AddKeyword ("try", Token.TRY);
395 AddKeyword ("typeof", Token.TYPEOF);
396 AddKeyword ("uint", Token.UINT);
397 AddKeyword ("ulong", Token.ULONG);
398 AddKeyword ("unchecked", Token.UNCHECKED);
399 AddKeyword ("unsafe", Token.UNSAFE);
400 AddKeyword ("ushort", Token.USHORT);
401 AddKeyword ("using", Token.USING);
402 AddKeyword ("virtual", Token.VIRTUAL);
403 AddKeyword ("void", Token.VOID);
404 AddKeyword ("volatile", Token.VOLATILE);
405 AddKeyword ("while", Token.WHILE);
406 AddKeyword ("partial", Token.PARTIAL);
408 AddKeyword ("where", Token.WHERE);
418 csharp_format_info = NumberFormatInfo.InvariantInfo;
419 styles = NumberStyles.Float;
421 string_builder = new System.Text.StringBuilder ();
424 int GetKeyword (char[] id, int id_len)
427 * Keywords are stored in an array of hashtables grouped by their
431 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
433 object o = keywords [id_len] [id];
440 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
442 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
444 if (handle_assembly == false && res == Token.ASSEMBLY)
447 if (handle_constraints == false && res == Token.WHERE)
454 public Location Location {
455 get { return current_location; }
458 void define (string def)
460 if (!RootContext.AllDefines.Contains (def)){
461 RootContext.AllDefines [def] = true;
463 if (defines.Contains (def))
465 defines [def] = true;
468 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
470 this.ref_name = file;
471 this.file_name = file;
477 defines = new Hashtable ();
478 foreach (string def in defs)
482 xml_comment_buffer = new StringBuilder ();
485 // FIXME: This could be `Location.Push' but we have to
486 // find out why the MS compiler allows this
488 Mono.CSharp.Location.Push (file);
491 static bool is_identifier_start_character (char c)
493 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter (c);
496 static bool is_identifier_part_character (char c)
498 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
501 public static bool IsKeyword (string s)
503 return keywordStrings [s] != null;
506 public static bool IsValidIdentifier (string s)
508 if (s == null || s.Length == 0)
511 if (!is_identifier_start_character (s [0]))
514 for (int i = 1; i < s.Length; i ++)
515 if (! is_identifier_part_character (s [i]))
522 bool parse_generic_dimension (out int dimension)
527 int the_token = token ();
528 if (the_token == Token.OP_GENERICS_GT)
530 else if (the_token == Token.COMMA) {
538 bool parse_less_than ()
541 int the_token = token ();
542 if (the_token == Token.OPEN_BRACKET) {
544 the_token = token ();
545 } while (the_token != Token.CLOSE_BRACKET);
546 the_token = token ();
549 case Token.IDENTIFIER:
572 the_token = token ();
574 if (the_token == Token.OP_GENERICS_GT)
576 else if ((the_token == Token.COMMA) || (the_token == Token.DOT))
578 else if (the_token == Token.INTERR || the_token == Token.STAR)
580 else if (the_token == Token.OP_GENERICS_LT) {
581 if (!parse_less_than ())
584 } else if (the_token == Token.OPEN_BRACKET) {
586 the_token = token ();
587 if (the_token == Token.CLOSE_BRACKET)
589 else if (the_token == Token.COMMA)
590 goto rank_specifiers;
597 int parsing_generic_less_than = 0;
599 public void PutbackNullable ()
601 if (nullable_pos < 0)
602 throw new Exception ();
606 reader.Position = nullable_pos;
611 public void PutbackCloseParens ()
617 int nullable_pos = -1;
619 public void CheckNullable (bool is_nullable)
622 nullable_pos = reader.Position;
627 int is_punct (char c, ref bool doread)
637 return Token.OPEN_BRACE;
640 return Token.CLOSE_BRACE;
642 // To block doccomment inside attribute declaration.
643 if (doc_state == XmlCommentState.Allowed)
644 doc_state = XmlCommentState.NotAllowed;
645 return Token.OPEN_BRACKET;
647 return Token.CLOSE_BRACKET;
649 return Token.OPEN_PARENS;
651 if (deambiguate_close_parens == 0)
652 return Token.CLOSE_PARENS;
654 --deambiguate_close_parens;
658 // disable preprocessing directives when peeking
659 process_directives = false;
660 int new_token = xtoken ();
661 process_directives = true;
665 if (new_token == Token.OPEN_PARENS)
666 return Token.CLOSE_PARENS_OPEN_PARENS;
667 else if (new_token == Token.MINUS)
668 return Token.CLOSE_PARENS_MINUS;
669 else if (IsCastToken (new_token))
670 return Token.CLOSE_PARENS_CAST;
672 return Token.CLOSE_PARENS_NO_CAST;
679 return Token.SEMICOLON;
688 if (parsing_generic_less_than++ > 0)
689 return Token.OP_GENERICS_LT;
694 if (parse_generic_dimension (out dimension)) {
697 return Token.GENERIC_DIMENSION;
702 // Save current position and parse next token.
704 bool is_generic_lt = parse_less_than ();
708 parsing_generic_less_than++;
709 return Token.OP_GENERICS_LT;
711 parsing_generic_less_than = 0;
720 return Token.OP_SHIFT_LEFT_ASSIGN;
722 return Token.OP_SHIFT_LEFT;
723 } else if (d == '='){
728 } else if (c == '>') {
729 if (parsing_generic_less_than > 0) {
730 parsing_generic_less_than--;
731 return Token.OP_GENERICS_GT;
741 return Token.OP_SHIFT_RIGHT_ASSIGN;
743 return Token.OP_SHIFT_RIGHT;
744 } else if (d == '='){
759 t = Token.OP_ADD_ASSIGN;
773 t = Token.OP_SUB_ASSIGN;
805 } else if (d == '='){
807 return Token.OP_AND_ASSIGN;
810 return Token.BITWISE_AND;
817 } else if (d == '='){
819 return Token.OP_OR_ASSIGN;
821 return Token.BITWISE_OR;
827 return Token.OP_MULT_ASSIGN;
836 return Token.OP_DIV_ASSIGN;
844 return Token.OP_MOD_ASSIGN;
846 return Token.PERCENT;
852 return Token.OP_XOR_ASSIGN;
865 return Token.OP_SHIFT_LEFT_ASSIGN;
867 return Token.OP_SHIFT_LEFT;
868 } else if (d == '='){
882 return Token.OP_SHIFT_RIGHT_ASSIGN;
884 return Token.OP_SHIFT_RIGHT;
885 } else if (d == '='){
895 return Token.DOUBLE_COLON;
904 int deambiguate_close_parens = 0;
906 public void Deambiguate_CloseParens (object expression)
910 // When any binary operation is used we are sure it is not a cast
911 if (expression is Binary)
914 deambiguate_close_parens++;
917 bool decimal_digits (int c)
920 bool seen_digits = false;
923 if (number_pos == max_number_size)
924 Error_NumericConstantTooLong ();
925 number_builder [number_pos++] = (char) c;
929 // We use peekChar2, because decimal_digits needs to do a
930 // 2-character look-ahead (5.ToString for example).
932 while ((d = peekChar2 ()) != -1){
933 if (d >= '0' && d <= '9'){
934 if (number_pos == max_number_size)
935 Error_NumericConstantTooLong ();
936 number_builder [number_pos++] = (char) d;
946 static bool is_hex (int e)
948 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
951 static int real_type_suffix (int c)
957 t = Token.LITERAL_FLOAT;
960 t = Token.LITERAL_DOUBLE;
963 t= Token.LITERAL_DECIMAL;
971 int integer_type_suffix (ulong ul, int c)
973 bool is_unsigned = false;
974 bool is_long = false;
977 bool scanning = true;
988 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
990 // if we have not seen anything in between
993 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
996 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1021 if (is_long && is_unsigned){
1023 return Token.LITERAL_INTEGER;
1024 } else if (is_unsigned){
1025 // uint if possible, or ulong else.
1027 if ((ul & 0xffffffff00000000) == 0)
1031 } else if (is_long){
1032 // long if possible, ulong otherwise
1033 if ((ul & 0x8000000000000000) != 0)
1038 // int, uint, long or ulong in that order
1039 if ((ul & 0xffffffff00000000) == 0){
1040 uint ui = (uint) ul;
1042 if ((ui & 0x80000000) != 0)
1047 if ((ul & 0x8000000000000000) != 0)
1053 return Token.LITERAL_INTEGER;
1057 // given `c' as the next char in the input decide whether
1058 // we need to convert to a special type, and then choose
1059 // the best representation for the integer
1061 int adjust_int (int c)
1064 if (number_pos > 9){
1065 ulong ul = (uint) (number_builder [0] - '0');
1067 for (int i = 1; i < number_pos; i++){
1068 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1070 return integer_type_suffix (ul, c);
1072 uint ui = (uint) (number_builder [0] - '0');
1074 for (int i = 1; i < number_pos; i++){
1075 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1077 return integer_type_suffix (ui, c);
1079 } catch (OverflowException) {
1080 error_details = "Integral constant is too large";
1081 Report.Error (1021, Location, error_details);
1083 return Token.LITERAL_INTEGER;
1085 catch (FormatException) {
1086 Report.Error (1013, Location, "Invalid number");
1088 return Token.LITERAL_INTEGER;
1092 int adjust_real (int t)
1094 string s = new String (number_builder, 0, number_pos);
1095 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1098 case Token.LITERAL_DECIMAL:
1100 val = System.Decimal.Parse (s, styles, csharp_format_info);
1101 } catch (OverflowException) {
1103 Report.Error (594, Location, error_details, "decimal");
1106 case Token.LITERAL_FLOAT:
1108 val = float.Parse (s, styles, csharp_format_info);
1109 } catch (OverflowException) {
1111 Report.Error (594, Location, error_details, "float");
1115 case Token.LITERAL_DOUBLE:
1117 t = Token.LITERAL_DOUBLE;
1119 val = System.Double.Parse (s, styles, csharp_format_info);
1120 } catch (OverflowException) {
1122 Report.Error (594, Location, error_details, "double");
1135 while ((d = peekChar ()) != -1){
1137 number_builder [number_pos++] = (char) d;
1143 string s = new String (number_builder, 0, number_pos);
1145 if (number_pos <= 8)
1146 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1148 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1149 } catch (OverflowException){
1150 error_details = "Integral constant is too large";
1151 Report.Error (1021, Location, error_details);
1153 return Token.LITERAL_INTEGER;
1155 catch (FormatException) {
1156 Report.Error (1013, Location, "Invalid number");
1158 return Token.LITERAL_INTEGER;
1161 return integer_type_suffix (ul, peekChar ());
1165 // Invoked if we know we have .digits or digits
1167 int is_number (int c)
1169 bool is_real = false;
1174 if (c >= '0' && c <= '9'){
1176 int peek = peekChar ();
1178 if (peek == 'x' || peek == 'X')
1179 return handle_hex ();
1186 // We need to handle the case of
1187 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1190 if (decimal_digits ('.')){
1196 return adjust_int (-1);
1200 if (c == 'e' || c == 'E'){
1202 if (number_pos == max_number_size)
1203 Error_NumericConstantTooLong ();
1204 number_builder [number_pos++] = 'e';
1208 if (number_pos == max_number_size)
1209 Error_NumericConstantTooLong ();
1210 number_builder [number_pos++] = '+';
1212 } else if (c == '-') {
1213 if (number_pos == max_number_size)
1214 Error_NumericConstantTooLong ();
1215 number_builder [number_pos++] = '-';
1218 if (number_pos == max_number_size)
1219 Error_NumericConstantTooLong ();
1220 number_builder [number_pos++] = '+';
1227 type = real_type_suffix (c);
1228 if (type == Token.NONE && !is_real){
1230 return adjust_int (c);
1234 if (type == Token.NONE){
1239 return adjust_real (type);
1241 Console.WriteLine ("This should not be reached");
1242 throw new Exception ("Is Number should never reach this point");
1246 // Accepts exactly count (4 or 8) hex, no more no less
1248 int getHex (int count, out bool error)
1253 int top = count != -1 ? count : 4;
1257 for (i = 0; i < top; i++){
1260 if (c >= '0' && c <= '9')
1261 c = (int) c - (int) '0';
1262 else if (c >= 'A' && c <= 'F')
1263 c = (int) c - (int) 'A' + 10;
1264 else if (c >= 'a' && c <= 'f')
1265 c = (int) c - (int) 'a' + 10;
1271 total = (total * 16) + c;
1273 int p = peekChar ();
1276 if (!is_hex ((char)p))
1317 v = getHex (-1, out error);
1322 v = getHex (4, out error);
1327 v = getHex (8, out error);
1332 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1342 if (putback_char != -1) {
1360 if (putback_char != -1)
1361 return putback_char;
1362 putback_char = reader.Read ();
1363 return putback_char;
1368 if (putback_char != -1)
1369 return putback_char;
1370 return reader.Peek ();
1373 void putback (int c)
1375 if (putback_char != -1){
1376 Console.WriteLine ("Col: " + col);
1377 Console.WriteLine ("Row: " + line);
1378 Console.WriteLine ("Name: " + ref_name.Name);
1379 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1380 throw new Exception ("This should not happen putback on putback");
1382 if (c == '\n' || col == 0) {
1383 // It won't happen though.
1393 public bool advance ()
1395 return peekChar () != -1;
1398 public Object Value {
1404 public Object value ()
1409 static bool IsCastToken (int token)
1414 case Token.IDENTIFIER:
1415 case Token.LITERAL_INTEGER:
1416 case Token.LITERAL_FLOAT:
1417 case Token.LITERAL_DOUBLE:
1418 case Token.LITERAL_DECIMAL:
1419 case Token.LITERAL_CHARACTER:
1420 case Token.LITERAL_STRING:
1423 case Token.DELEGATE:
1433 case Token.UNCHECKED:
1440 // These can be part of a member access
1460 current_token = xtoken ();
1463 if (current_token != Token.DEFAULT)
1464 return current_token;
1469 current_token = Token.ERROR;
1470 else if (c == Token.OPEN_PARENS)
1471 current_token = Token.DEFAULT_OPEN_PARENS;
1472 else if (c == Token.COLON)
1473 current_token = Token.DEFAULT_COLON;
1477 return current_token;
1480 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1482 void get_cmd_arg (out string cmd, out string arg)
1486 tokens_seen = false;
1488 static_cmd_arg.Length = 0;
1490 // skip over white space
1491 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1494 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1495 if (is_identifier_part_character ((char) c)){
1496 static_cmd_arg.Append ((char) c);
1504 cmd = static_cmd_arg.ToString ();
1510 // skip over white space
1511 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1516 } else if (c == '\r'){
1518 } else if (c == -1){
1523 static_cmd_arg.Length = 0;
1524 static_cmd_arg.Append ((char) c);
1526 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1527 static_cmd_arg.Append ((char) c);
1530 arg = static_cmd_arg.ToString ().Trim ();
1534 // Handles the #line directive
1536 bool PreProcessLine (string arg)
1538 if (arg.Length == 0)
1541 if (arg == "default"){
1543 ref_name = file_name;
1544 Location.Push (ref_name);
1546 } else if (arg == "hidden"){
1548 // We ignore #line hidden
1556 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1557 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1560 char [] quotes = { '\"' };
1562 string name = arg.Substring (pos). Trim (quotes);
1563 ref_name = Location.LookupFile (name);
1564 file_name.HasLineDirective = true;
1565 ref_name.HasLineDirective = true;
1566 Location.Push (ref_name);
1568 ref_line = System.Int32.Parse (arg);
1578 // Handles #define and #undef
1580 void PreProcessDefinition (bool is_define, string arg)
1582 if (arg.Length == 0 || arg == "true" || arg == "false"){
1583 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1587 char[] whitespace = { ' ', '\t' };
1588 if (arg.IndexOfAny (whitespace) != -1){
1589 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1593 if (!is_identifier_start_character (arg [0]))
1594 Report.Error (1001, Location, "Identifier expected: " + arg);
1596 foreach (char c in arg.Substring (1)){
1597 if (!is_identifier_part_character (c)){
1598 Report.Error (1001, Location, "Identifier expected: " + arg);
1604 if (defines == null)
1605 defines = new Hashtable ();
1608 if (defines == null)
1610 if (defines.Contains (arg))
1611 defines.Remove (arg);
1616 /// Handles #pragma directive
1618 void PreProcessPragma (string arg)
1620 const string warning = "warning";
1621 const string w_disable = "warning disable";
1622 const string w_restore = "warning restore";
1624 if (arg == w_disable) {
1625 Report.RegisterWarningRegion (Location).WarningDisable (line);
1629 if (arg == w_restore) {
1630 Report.RegisterWarningRegion (Location).WarningEnable (line);
1634 if (arg.StartsWith (w_disable)) {
1635 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1636 foreach (int code in codes) {
1638 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1643 if (arg.StartsWith (w_restore)) {
1644 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1645 Hashtable w_table = Report.warning_ignore_table;
1646 foreach (int code in codes) {
1647 if (w_table != null && w_table.Contains (code))
1648 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1649 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1654 if (arg.StartsWith (warning)) {
1655 Report.Warning (1634, 1, Location, "Expected disable or restore");
1659 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1662 int[] ParseNumbers (string text)
1664 string[] string_array = text.Split (',');
1665 int[] values = new int [string_array.Length];
1667 foreach (string string_code in string_array) {
1669 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1671 catch (FormatException) {
1672 Report.Warning (1692, 1, Location, "Invalid number");
1678 bool eval_val (string s)
1685 if (defines == null)
1687 if (defines.Contains (s))
1693 bool pp_primary (ref string s)
1702 s = s.Substring (1);
1703 bool val = pp_expr (ref s);
1704 if (s.Length > 0 && s [0] == ')'){
1705 s = s.Substring (1);
1708 Error_InvalidDirective ();
1712 if (is_identifier_start_character (c)){
1718 if (is_identifier_part_character (c)){
1722 bool v = eval_val (s.Substring (0, j));
1723 s = s.Substring (j);
1726 bool vv = eval_val (s);
1731 Error_InvalidDirective ();
1735 bool pp_unary (ref string s)
1742 if (len > 1 && s [1] == '='){
1743 Error_InvalidDirective ();
1746 s = s.Substring (1);
1747 return ! pp_primary (ref s);
1749 return pp_primary (ref s);
1751 Error_InvalidDirective ();
1756 bool pp_eq (ref string s)
1758 bool va = pp_unary (ref s);
1764 if (len > 2 && s [1] == '='){
1765 s = s.Substring (2);
1766 return va == pp_unary (ref s);
1768 Error_InvalidDirective ();
1771 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1772 s = s.Substring (2);
1774 return va != pp_unary (ref s);
1783 bool pp_and (ref string s)
1785 bool va = pp_eq (ref s);
1791 if (len > 2 && s [1] == '&'){
1792 s = s.Substring (2);
1793 return (va & pp_and (ref s));
1795 Error_InvalidDirective ();
1804 // Evaluates an expression for `#if' or `#elif'
1806 bool pp_expr (ref string s)
1808 bool va = pp_and (ref s);
1815 if (len > 2 && s [1] == '|'){
1816 s = s.Substring (2);
1817 return va | pp_expr (ref s);
1819 Error_InvalidDirective ();
1828 bool eval (string s)
1830 bool v = pp_expr (ref s);
1839 void Error_NumericConstantTooLong ()
1841 Report.Error (1021, Location, "Numeric constant too long");
1844 void Error_InvalidDirective ()
1846 Report.Error (1517, Location, "Invalid preprocessor directive");
1849 void Error_UnexpectedDirective (string extra)
1853 "Unexpected processor directive (" + extra + ")");
1856 void Error_TokensSeen ()
1858 Report.Error (1032, Location,
1859 "Cannot define or undefine preprocessor symbols after first token in file");
1863 // Set to false to stop handling preprocesser directives
1865 bool process_directives = true;
1868 // if true, then the code continues processing the code
1869 // if false, the code stays in a loop until another directive is
1872 bool handle_preprocessing_directive (bool caller_is_taking)
1875 bool region_directive = false;
1877 get_cmd_arg (out cmd, out arg);
1879 // Eat any trailing whitespaces and single-line comments
1880 if (arg.IndexOf ("//") != -1)
1881 arg = arg.Substring (0, arg.IndexOf ("//"));
1882 arg = arg.TrimEnd (' ', '\t');
1885 // The first group of pre-processing instructions is always processed
1889 if (RootContext.Version == LanguageVersion.ISO_1) {
1890 Report.FeatureIsNotStandardized (Location, "#pragma");
1891 return caller_is_taking;
1894 PreProcessPragma (arg);
1895 return caller_is_taking;
1898 if (!PreProcessLine (arg))
1901 "The line number specified for #line directive is missing or invalid");
1902 return caller_is_taking;
1905 region_directive = true;
1910 region_directive = true;
1914 if (arg.Length == 0){
1915 Error_InvalidDirective ();
1918 bool taking = false;
1919 if (ifstack == null)
1920 ifstack = new Stack (2);
1922 if (ifstack.Count == 0){
1925 int state = (int) ifstack.Peek ();
1926 if ((state & TAKING) != 0)
1930 if (eval (arg) && taking){
1931 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1932 if (region_directive)
1934 ifstack.Push (push);
1937 int push = (taking ? PARENT_TAKING : 0);
1938 if (region_directive)
1940 ifstack.Push (push);
1945 if (ifstack == null || ifstack.Count == 0){
1946 Error_UnexpectedDirective ("no #if for this #endif");
1949 int pop = (int) ifstack.Pop ();
1951 if (region_directive && ((pop & REGION) == 0))
1952 Report.Error (1027, Location, "Expected `#endif' directive");
1953 else if (!region_directive && ((pop & REGION) != 0))
1954 Report.Error (1038, Location, "#endregion directive expected");
1956 if (!region_directive && arg.Length != 0) {
1957 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1960 if (ifstack.Count == 0)
1963 int state = (int) ifstack.Peek ();
1965 if ((state & TAKING) != 0)
1973 if (ifstack == null || ifstack.Count == 0){
1974 Error_UnexpectedDirective ("no #if for this #elif");
1977 int state = (int) ifstack.Peek ();
1979 if ((state & REGION) != 0) {
1980 Report.Error (1038, Location, "#endregion directive expected");
1984 if ((state & ELSE_SEEN) != 0){
1985 Error_UnexpectedDirective ("#elif not valid after #else");
1989 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1992 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1993 state = (int) ifstack.Pop ();
1994 ifstack.Push (state | TAKING | TAKEN_BEFORE);
2001 if (ifstack == null || ifstack.Count == 0){
2002 Error_UnexpectedDirective ("no #if for this #else");
2005 int state = (int) ifstack.Peek ();
2007 if ((state & REGION) != 0) {
2008 Report.Error (1038, Location, "#endregion directive expected");
2012 if ((state & ELSE_SEEN) != 0){
2013 Error_UnexpectedDirective ("#else within #else");
2020 if ((state & TAKEN_BEFORE) == 0){
2021 ret = ((state & PARENT_TAKING) != 0);
2030 ifstack.Push (state | ELSE_SEEN);
2037 // These are only processed if we are in a `taking' block
2039 if (!caller_is_taking)
2044 if (any_token_seen){
2045 Error_TokensSeen ();
2048 PreProcessDefinition (true, arg);
2052 if (any_token_seen){
2053 Error_TokensSeen ();
2056 PreProcessDefinition (false, arg);
2060 Report.Error (1029, Location, "#error: '" + arg + "'");
2064 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2068 Report.Error (1024, Location, "Wrong preprocessor directive");
2073 private int consume_string (bool quoted)
2076 string_builder.Length = 0;
2078 while ((c = getChar ()) != -1){
2080 if (quoted && peekChar () == '"'){
2081 string_builder.Append ((char) c);
2085 val = string_builder.ToString ();
2086 return Token.LITERAL_STRING;
2092 Report.Error (1010, Location, "Newline in constant");
2100 string_builder.Append ((char) c);
2103 Report.Error (1039, Location, "Unterminated string literal");
2107 private int consume_identifier (int s)
2109 int res = consume_identifier (s, false);
2111 if (doc_state == XmlCommentState.Allowed)
2112 doc_state = XmlCommentState.NotAllowed;
2115 case Token.NAMESPACE:
2116 check_incorrect_doc_comment ();
2120 if (res == Token.PARTIAL) {
2121 // Save current position and parse next token.
2124 int next_token = token ();
2125 bool ok = (next_token == Token.CLASS) ||
2126 (next_token == Token.STRUCT) ||
2127 (next_token == Token.INTERFACE);
2134 // Report.Error (267, Location, "The `partial' modifier can be used only immediately before keyword `class', `struct', or `interface'");
2135 val = new LocatedToken (Location, "partial");
2136 return Token.IDENTIFIER;
2142 private int consume_identifier (int s, bool quoted)
2147 id_builder [0] = (char) s;
2149 current_location = new Location (ref_line, Col);
2151 while ((c = getChar ()) != -1) {
2153 if (is_identifier_part_character ((char) c)){
2154 if (pos == max_id_size){
2155 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2159 id_builder [pos++] = (char) c;
2160 // putback_char = -1;
2161 } else if (c == '\\') {
2165 // putback_char = c;
2172 // Optimization: avoids doing the keyword lookup
2173 // on uppercase letters and _
2175 if (!quoted && (s >= 'a' || s == '_')){
2176 int keyword = GetKeyword (id_builder, pos);
2177 if (keyword != -1) {
2184 // Keep identifiers in an array of hashtables to avoid needless
2188 if (identifiers [pos] != null) {
2189 val = identifiers [pos][id_builder];
2191 val = new LocatedToken (Location, (string) val);
2193 escapedIdentifiers.Add (val);
2194 return Token.IDENTIFIER;
2198 identifiers [pos] = new CharArrayHashtable (pos);
2200 val = new String (id_builder, 0, pos);
2201 if (RootContext.Version == LanguageVersion.ISO_1) {
2202 for (int i = 1; i < id_builder.Length; i += 3) {
2203 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2204 Report.Error (1638, Location,
2205 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2211 char [] chars = new char [pos];
2212 Array.Copy (id_builder, chars, pos);
2214 identifiers [pos] [chars] = val;
2216 val = new LocatedToken (Location, (string) val);
2218 escapedIdentifiers.Add (val);
2219 return Token.IDENTIFIER;
2222 public int xtoken ()
2225 bool doread = false;
2228 // Whether we have seen comments on the current line
2229 bool comments_seen = false;
2232 // optimization: eliminate col and implement #directive semantic correctly.
2233 for (;(c = getChar ()) != -1;) {
2241 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
2245 if (peekChar () == '\n')
2248 any_token_seen |= tokens_seen;
2249 tokens_seen = false;
2250 comments_seen = false;
2254 // Handle double-slash comments.
2256 int d = peekChar ();
2260 if (RootContext.Documentation != null && peekChar () == '/') {
2262 // Don't allow ////.
2263 if ((d = peekChar ()) != '/') {
2264 update_comment_location ();
2265 if (doc_state == XmlCommentState.Allowed)
2266 handle_one_line_xml_comment ();
2267 else if (doc_state == XmlCommentState.NotAllowed)
2268 warn_incorrect_doc_comment ();
2271 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2274 any_token_seen |= tokens_seen;
2275 tokens_seen = false;
2276 comments_seen = false;
2278 } else if (d == '*'){
2280 bool docAppend = false;
2281 if (RootContext.Documentation != null && peekChar () == '*') {
2283 update_comment_location ();
2284 // But when it is /**/, just do nothing.
2285 if (peekChar () == '/') {
2289 if (doc_state == XmlCommentState.Allowed)
2291 else if (doc_state == XmlCommentState.NotAllowed)
2292 warn_incorrect_doc_comment ();
2295 int current_comment_start = 0;
2297 current_comment_start = xml_comment_buffer.Length;
2298 xml_comment_buffer.Append (Environment.NewLine);
2301 Location start_location = Location;
2303 while ((d = getChar ()) != -1){
2304 if (d == '*' && peekChar () == '/'){
2306 comments_seen = true;
2310 xml_comment_buffer.Append ((char) d);
2313 any_token_seen |= tokens_seen;
2314 tokens_seen = false;
2316 // Reset 'comments_seen' just to be consistent.
2317 // It doesn't matter either way, here.
2319 comments_seen = false;
2323 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2326 update_formatted_doc_comment (current_comment_start);
2329 goto is_punct_label;
2333 if (c == '\\' || is_identifier_start_character ((char)c)){
2335 return consume_identifier (c);
2339 current_location = new Location (ref_line, Col);
2340 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2350 any_token_seen |= tokens_seen;
2351 tokens_seen = false;
2352 comments_seen = false;
2356 if (c >= '0' && c <= '9'){
2358 return is_number (c);
2363 int peek = peekChar ();
2364 if (peek >= '0' && peek <= '9')
2365 return is_number (c);
2369 /* For now, ignore pre-processor commands */
2370 // FIXME: In C# the '#' is not limited to appear
2371 // on the first column.
2373 // return NONE if we're not processing directives (during token peeks)
2374 if (!process_directives)
2378 if (tokens_seen || comments_seen) {
2379 error_details = "Preprocessor directives must appear as the first" +
2380 " non-whitespace character on a line.";
2382 Report.Error (1040, Location, error_details);
2389 cont = handle_preprocessing_directive (cont);
2395 bool skipping = false;
2396 for (;(c = getChar ()) != -1;){
2399 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2403 if (c == '#' && !skipping)
2406 any_token_seen |= tokens_seen;
2407 tokens_seen = false;
2409 Report.Error (1027, Location, "Expected `#endif' directive");
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 int state = (int) ifstack.Pop ();
2579 if ((state & REGION) != 0)
2580 Report.Error (1038, Location, "#endregion directive expected");
2582 // Report.Error (1027, Location, "Expected `#endif' directive");
2588 // Indicates whether it accepts XML documentation or not.
2590 public enum XmlCommentState {
2591 // comment is allowed in this state.
2593 // comment is not allowed in this state.
2595 // once comments appeared when it is NotAllowed, then the
2596 // state is changed to it, until the state is changed to