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;
258 static void AddKeyword (string kw, int token) {
259 keywordStrings.Add (kw, kw);
260 if (keywords [kw.Length] == null) {
261 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
263 keywords [kw.Length] [kw.ToCharArray ()] = token;
266 static void InitTokens ()
268 keywords = new CharArrayHashtable [64];
270 AddKeyword ("__arglist", Token.ARGLIST);
271 AddKeyword ("abstract", Token.ABSTRACT);
272 AddKeyword ("as", Token.AS);
273 AddKeyword ("add", Token.ADD);
274 AddKeyword ("assembly", Token.ASSEMBLY);
275 AddKeyword ("base", Token.BASE);
276 AddKeyword ("bool", Token.BOOL);
277 AddKeyword ("break", Token.BREAK);
278 AddKeyword ("byte", Token.BYTE);
279 AddKeyword ("case", Token.CASE);
280 AddKeyword ("catch", Token.CATCH);
281 AddKeyword ("char", Token.CHAR);
282 AddKeyword ("checked", Token.CHECKED);
283 AddKeyword ("class", Token.CLASS);
284 AddKeyword ("const", Token.CONST);
285 AddKeyword ("continue", Token.CONTINUE);
286 AddKeyword ("decimal", Token.DECIMAL);
287 AddKeyword ("default", Token.DEFAULT);
288 AddKeyword ("delegate", Token.DELEGATE);
289 AddKeyword ("do", Token.DO);
290 AddKeyword ("double", Token.DOUBLE);
291 AddKeyword ("else", Token.ELSE);
292 AddKeyword ("enum", Token.ENUM);
293 AddKeyword ("event", Token.EVENT);
294 AddKeyword ("explicit", Token.EXPLICIT);
295 AddKeyword ("extern", Token.EXTERN);
296 AddKeyword ("false", Token.FALSE);
297 AddKeyword ("finally", Token.FINALLY);
298 AddKeyword ("fixed", Token.FIXED);
299 AddKeyword ("float", Token.FLOAT);
300 AddKeyword ("for", Token.FOR);
301 AddKeyword ("foreach", Token.FOREACH);
302 AddKeyword ("goto", Token.GOTO);
303 AddKeyword ("get", Token.GET);
304 AddKeyword ("if", Token.IF);
305 AddKeyword ("implicit", Token.IMPLICIT);
306 AddKeyword ("in", Token.IN);
307 AddKeyword ("int", Token.INT);
308 AddKeyword ("interface", Token.INTERFACE);
309 AddKeyword ("internal", Token.INTERNAL);
310 AddKeyword ("is", Token.IS);
311 AddKeyword ("lock", Token.LOCK);
312 AddKeyword ("long", Token.LONG);
313 AddKeyword ("namespace", Token.NAMESPACE);
314 AddKeyword ("new", Token.NEW);
315 AddKeyword ("null", Token.NULL);
316 AddKeyword ("object", Token.OBJECT);
317 AddKeyword ("operator", Token.OPERATOR);
318 AddKeyword ("out", Token.OUT);
319 AddKeyword ("override", Token.OVERRIDE);
320 AddKeyword ("params", Token.PARAMS);
321 AddKeyword ("private", Token.PRIVATE);
322 AddKeyword ("protected", Token.PROTECTED);
323 AddKeyword ("public", Token.PUBLIC);
324 AddKeyword ("readonly", Token.READONLY);
325 AddKeyword ("ref", Token.REF);
326 AddKeyword ("remove", Token.REMOVE);
327 AddKeyword ("return", Token.RETURN);
328 AddKeyword ("sbyte", Token.SBYTE);
329 AddKeyword ("sealed", Token.SEALED);
330 AddKeyword ("set", Token.SET);
331 AddKeyword ("short", Token.SHORT);
332 AddKeyword ("sizeof", Token.SIZEOF);
333 AddKeyword ("stackalloc", Token.STACKALLOC);
334 AddKeyword ("static", Token.STATIC);
335 AddKeyword ("string", Token.STRING);
336 AddKeyword ("struct", Token.STRUCT);
337 AddKeyword ("switch", Token.SWITCH);
338 AddKeyword ("this", Token.THIS);
339 AddKeyword ("throw", Token.THROW);
340 AddKeyword ("true", Token.TRUE);
341 AddKeyword ("try", Token.TRY);
342 AddKeyword ("typeof", Token.TYPEOF);
343 AddKeyword ("uint", Token.UINT);
344 AddKeyword ("ulong", Token.ULONG);
345 AddKeyword ("unchecked", Token.UNCHECKED);
346 AddKeyword ("unsafe", Token.UNSAFE);
347 AddKeyword ("ushort", Token.USHORT);
348 AddKeyword ("using", Token.USING);
349 AddKeyword ("virtual", Token.VIRTUAL);
350 AddKeyword ("void", Token.VOID);
351 AddKeyword ("volatile", Token.VOLATILE);
352 AddKeyword ("where", Token.WHERE);
353 AddKeyword ("while", Token.WHILE);
354 AddKeyword ("partial", Token.PARTIAL);
363 csharp_format_info = NumberFormatInfo.InvariantInfo;
364 styles = NumberStyles.Float;
366 string_builder = new System.Text.StringBuilder ();
369 int GetKeyword (char[] id, int id_len)
372 * Keywords are stored in an array of hashtables grouped by their
376 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
378 object o = keywords [id_len] [id];
385 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
387 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
389 if (handle_assembly == false && res == Token.ASSEMBLY)
391 if (handle_constraints == false && res == Token.WHERE)
398 public Location Location {
399 get { return current_location; }
402 void define (string def)
404 if (!RootContext.AllDefines.Contains (def)){
405 RootContext.AllDefines [def] = true;
407 if (defines.Contains (def))
409 defines [def] = true;
412 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
414 this.ref_name = file;
415 this.file_name = file;
421 defines = new Hashtable ();
422 foreach (string def in defs)
426 xml_comment_buffer = new StringBuilder ();
429 // FIXME: This could be `Location.Push' but we have to
430 // find out why the MS compiler allows this
432 Mono.CSharp.Location.Push (file, 0);
435 static bool is_identifier_start_character (char c)
437 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
440 static bool is_identifier_part_character (char c)
442 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
445 public static bool IsKeyword (string s)
447 return keywordStrings [s] != null;
450 public static bool IsValidIdentifier (string s)
452 if (s == null || s.Length == 0)
455 if (!is_identifier_start_character (s [0]))
458 for (int i = 1; i < s.Length; i ++)
459 if (! is_identifier_part_character (s [i]))
465 bool parse_generic_dimension (out int dimension)
470 int the_token = token ();
471 if (the_token == Token.OP_GENERICS_GT)
473 else if (the_token == Token.COMMA) {
481 bool parse_less_than ()
484 int the_token = token ();
486 case Token.IDENTIFIER:
509 the_token = token ();
511 if (the_token == Token.OP_GENERICS_GT)
513 else if ((the_token == Token.COMMA) || (the_token == Token.DOT))
515 else if (the_token == Token.INTERR)
517 else if (the_token == Token.OP_GENERICS_LT) {
518 if (!parse_less_than ())
521 } else if (the_token == Token.OPEN_BRACKET) {
523 the_token = token ();
524 if (the_token == Token.CLOSE_BRACKET)
526 else if (the_token == Token.COMMA)
527 goto rank_specifiers;
534 int parsing_generic_less_than = 0;
536 int is_punct (char c, ref bool doread)
546 return Token.OPEN_BRACE;
549 return Token.CLOSE_BRACE;
551 // To block doccomment inside attribute declaration.
552 if (doc_state == XmlCommentState.Allowed)
553 doc_state = XmlCommentState.NotAllowed;
554 return Token.OPEN_BRACKET;
556 return Token.CLOSE_BRACKET;
558 return Token.OPEN_PARENS;
560 if (deambiguate_close_parens == 0)
561 return Token.CLOSE_PARENS;
563 --deambiguate_close_parens;
565 // Save current position and parse next token.
566 int old = reader.Position;
567 int old_ref_line = ref_line;
570 int new_token = token ();
571 reader.Position = old;
572 ref_line = old_ref_line;
576 if (new_token == Token.OPEN_PARENS)
577 return Token.CLOSE_PARENS_OPEN_PARENS;
578 else if (new_token == Token.MINUS)
579 return Token.CLOSE_PARENS_MINUS;
580 else if (IsCastToken (new_token))
581 return Token.CLOSE_PARENS_CAST;
583 return Token.CLOSE_PARENS_NO_CAST;
590 return Token.SEMICOLON;
599 if (parsing_generic_less_than++ > 0)
600 return Token.OP_GENERICS_LT;
602 int old = reader.Position;
605 if (parse_generic_dimension (out dimension)) {
607 return Token.GENERIC_DIMENSION;
609 reader.Position = old;
613 // Save current position and parse next token.
614 old = reader.Position;
615 bool is_generic_lt = parse_less_than ();
616 reader.Position = old;
620 parsing_generic_less_than++;
621 return Token.OP_GENERICS_LT;
623 parsing_generic_less_than = 0;
632 return Token.OP_SHIFT_LEFT_ASSIGN;
634 return Token.OP_SHIFT_LEFT;
635 } else if (d == '='){
640 } else if (c == '>') {
641 if (parsing_generic_less_than > 0) {
642 parsing_generic_less_than--;
643 return Token.OP_GENERICS_GT;
653 return Token.OP_SHIFT_RIGHT_ASSIGN;
655 return Token.OP_SHIFT_RIGHT;
656 } else if (d == '='){
671 t = Token.OP_ADD_ASSIGN;
685 t = Token.OP_SUB_ASSIGN;
717 } else if (d == '='){
719 return Token.OP_AND_ASSIGN;
722 return Token.BITWISE_AND;
729 } else if (d == '='){
731 return Token.OP_OR_ASSIGN;
733 return Token.BITWISE_OR;
739 return Token.OP_MULT_ASSIGN;
748 return Token.OP_DIV_ASSIGN;
756 return Token.OP_MOD_ASSIGN;
758 return Token.PERCENT;
764 return Token.OP_XOR_ASSIGN;
772 return Token.DOUBLE_COLON;
781 int deambiguate_close_parens = 0;
783 public void Deambiguate_CloseParens ()
786 deambiguate_close_parens++;
789 public void PutbackNullable ()
791 if (nullable_pos < 0)
792 throw new Exception ();
796 reader.Position = nullable_pos;
801 public void PutbackCloseParens ()
806 void Error_NumericConstantTooLong ()
808 Report.Error (1021, Location, "Numeric constant too long");
811 int nullable_pos = -1;
813 public void CheckNullable (bool is_nullable)
816 nullable_pos = reader.Position;
821 bool decimal_digits (int c)
824 bool seen_digits = false;
827 if (number_pos == max_number_size)
828 Error_NumericConstantTooLong ();
829 number_builder [number_pos++] = (char) c;
833 // We use peekChar2, because decimal_digits needs to do a
834 // 2-character look-ahead (5.ToString for example).
836 while ((d = peekChar2 ()) != -1){
837 if (d >= '0' && d <= '9'){
838 if (number_pos == max_number_size)
839 Error_NumericConstantTooLong ();
840 number_builder [number_pos++] = (char) d;
852 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
855 int real_type_suffix (int c)
861 t = Token.LITERAL_FLOAT;
864 t = Token.LITERAL_DOUBLE;
867 t= Token.LITERAL_DECIMAL;
875 int integer_type_suffix (ulong ul, int c)
877 bool is_unsigned = false;
878 bool is_long = false;
881 bool scanning = true;
892 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
894 // if we have not seen anything in between
897 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
900 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
925 if (is_long && is_unsigned){
927 return Token.LITERAL_INTEGER;
928 } else if (is_unsigned){
929 // uint if possible, or ulong else.
931 if ((ul & 0xffffffff00000000) == 0)
936 // long if possible, ulong otherwise
937 if ((ul & 0x8000000000000000) != 0)
942 // int, uint, long or ulong in that order
943 if ((ul & 0xffffffff00000000) == 0){
946 if ((ui & 0x80000000) != 0)
951 if ((ul & 0x8000000000000000) != 0)
957 return Token.LITERAL_INTEGER;
961 // given `c' as the next char in the input decide whether
962 // we need to convert to a special type, and then choose
963 // the best representation for the integer
965 int adjust_int (int c)
969 ulong ul = (uint) (number_builder [0] - '0');
971 for (int i = 1; i < number_pos; i++){
972 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
974 return integer_type_suffix (ul, c);
976 uint ui = (uint) (number_builder [0] - '0');
978 for (int i = 1; i < number_pos; i++){
979 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
981 return integer_type_suffix (ui, c);
983 } catch (OverflowException) {
984 error_details = "Integral constant is too large";
985 Report.Error (1021, Location, error_details);
987 return Token.LITERAL_INTEGER;
989 catch (FormatException) {
990 Report.Error (1013, Location, "Invalid number");
992 return Token.LITERAL_INTEGER;
996 int adjust_real (int t)
998 string s = new String (number_builder, 0, number_pos);
999 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1002 case Token.LITERAL_DECIMAL:
1004 val = System.Decimal.Parse (s, styles, csharp_format_info);
1005 } catch (OverflowException) {
1007 Report.Error (594, Location, error_details, "decimal");
1010 case Token.LITERAL_FLOAT:
1012 val = (float) System.Double.Parse (s, styles, csharp_format_info);
1013 } catch (OverflowException) {
1015 Report.Error (594, Location, error_details, "float");
1019 case Token.LITERAL_DOUBLE:
1021 t = Token.LITERAL_DOUBLE;
1023 val = System.Double.Parse (s, styles, csharp_format_info);
1024 } catch (OverflowException) {
1026 Report.Error (594, Location, error_details, "double");
1039 while ((d = peekChar ()) != -1){
1041 number_builder [number_pos++] = (char) d;
1047 string s = new String (number_builder, 0, number_pos);
1049 if (number_pos <= 8)
1050 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1052 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1053 } catch (OverflowException){
1054 error_details = "Integral constant is too large";
1055 Report.Error (1021, Location, error_details);
1057 return Token.LITERAL_INTEGER;
1059 catch (FormatException) {
1060 Report.Error (1013, Location, "Invalid number");
1062 return Token.LITERAL_INTEGER;
1065 return integer_type_suffix (ul, peekChar ());
1069 // Invoked if we know we have .digits or digits
1071 int is_number (int c)
1073 bool is_real = false;
1078 if (c >= '0' && c <= '9'){
1080 int peek = peekChar ();
1082 if (peek == 'x' || peek == 'X')
1083 return handle_hex ();
1090 // We need to handle the case of
1091 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1094 if (decimal_digits ('.')){
1100 return adjust_int (-1);
1104 if (c == 'e' || c == 'E'){
1106 if (number_pos == max_number_size)
1107 Error_NumericConstantTooLong ();
1108 number_builder [number_pos++] = 'e';
1112 if (number_pos == max_number_size)
1113 Error_NumericConstantTooLong ();
1114 number_builder [number_pos++] = '+';
1116 } else if (c == '-') {
1117 if (number_pos == max_number_size)
1118 Error_NumericConstantTooLong ();
1119 number_builder [number_pos++] = '-';
1122 if (number_pos == max_number_size)
1123 Error_NumericConstantTooLong ();
1124 number_builder [number_pos++] = '+';
1131 type = real_type_suffix (c);
1132 if (type == Token.NONE && !is_real){
1134 return adjust_int (c);
1138 if (type == Token.NONE){
1143 return adjust_real (type);
1145 Console.WriteLine ("This should not be reached");
1146 throw new Exception ("Is Number should never reach this point");
1150 // Accepts exactly count (4 or 8) hex, no more no less
1152 int getHex (int count, out bool error)
1157 int top = count != -1 ? count : 4;
1161 for (i = 0; i < top; i++){
1164 if (c >= '0' && c <= '9')
1165 c = (int) c - (int) '0';
1166 else if (c >= 'A' && c <= 'F')
1167 c = (int) c - (int) 'A' + 10;
1168 else if (c >= 'a' && c <= 'f')
1169 c = (int) c - (int) 'a' + 10;
1175 total = (total * 16) + c;
1177 int p = peekChar ();
1180 if (!is_hex ((char)p))
1221 v = getHex (-1, out error);
1226 v = getHex (4, out error);
1231 v = getHex (8, out error);
1236 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1246 if (putback_char != -1) {
1265 if (putback_char != -1)
1266 return putback_char;
1267 putback_char = reader.Read ();
1268 return putback_char;
1273 if (putback_char != -1)
1274 return putback_char;
1275 return reader.Peek ();
1278 void putback (int c)
1280 if (putback_char != -1){
1281 Console.WriteLine ("Col: " + col);
1282 Console.WriteLine ("Row: " + line);
1283 Console.WriteLine ("Name: " + ref_name.Name);
1284 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1285 throw new Exception ("This should not happen putback on putback");
1287 if (c == '\n' || col == 0) {
1288 // It won't happen though.
1298 public bool advance ()
1300 return peekChar () != -1;
1303 public Object Value {
1309 public Object value ()
1314 bool IsCastToken (int token)
1319 case Token.IDENTIFIER:
1320 case Token.LITERAL_INTEGER:
1321 case Token.LITERAL_FLOAT:
1322 case Token.LITERAL_DOUBLE:
1323 case Token.LITERAL_DECIMAL:
1324 case Token.LITERAL_CHARACTER:
1325 case Token.LITERAL_STRING:
1337 case Token.UNCHECKED:
1341 // These can be part of a member access
1361 current_token = xtoken ();
1363 if (current_token != Token.DEFAULT)
1364 return current_token;
1366 int c = consume_whitespace ();
1368 current_token = Token.ERROR;
1370 current_token = Token.DEFAULT_OPEN_PARENS;
1374 return current_token;
1377 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1379 void get_cmd_arg (out string cmd, out string arg)
1383 tokens_seen = false;
1385 static_cmd_arg.Length = 0;
1387 // skip over white space
1388 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1391 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1392 if (is_identifier_part_character ((char) c)){
1393 static_cmd_arg.Append ((char) c);
1401 cmd = static_cmd_arg.ToString ();
1407 // skip over white space
1408 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1413 } else if (c == '\r'){
1415 } else if (c == -1){
1420 static_cmd_arg.Length = 0;
1421 static_cmd_arg.Append ((char) c);
1423 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1424 static_cmd_arg.Append ((char) c);
1427 arg = static_cmd_arg.ToString ().Trim ();
1431 // Handles the #line directive
1433 bool PreProcessLine (string arg)
1438 if (arg == "default"){
1440 ref_name = file_name;
1441 Location.Push (ref_name, line);
1443 } else if (arg == "hidden"){
1445 // We ignore #line hidden
1453 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1454 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1457 char [] quotes = { '\"' };
1459 string name = arg.Substring (pos). Trim (quotes);
1460 ref_name = Location.LookupFile (name);
1461 file_name.HasLineDirective = true;
1462 ref_name.HasLineDirective = true;
1463 Location.Push (ref_name, ref_line);
1465 ref_line = System.Int32.Parse (arg);
1475 // Handles #define and #undef
1477 void PreProcessDefinition (bool is_define, string arg)
1479 if (arg == "" || arg == "true" || arg == "false"){
1480 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1484 char[] whitespace = { ' ', '\t' };
1485 if (arg.IndexOfAny (whitespace) != -1){
1486 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1490 if (!is_identifier_start_character (arg [0]))
1491 Report.Error (1001, Location, "Identifier expected: " + arg);
1493 foreach (char c in arg.Substring (1)){
1494 if (!is_identifier_part_character (c)){
1495 Report.Error (1001, Location, "Identifier expected: " + arg);
1501 if (defines == null)
1502 defines = new Hashtable ();
1505 if (defines == null)
1507 if (defines.Contains (arg))
1508 defines.Remove (arg);
1513 /// Handles #pragma directive
1515 void PreProcessPragma (string arg)
1517 const string warning = "warning";
1518 const string w_disable = "warning disable";
1519 const string w_restore = "warning restore";
1521 if (arg == w_disable) {
1522 Report.RegisterWarningRegion (Location).WarningDisable (line);
1526 if (arg == w_restore) {
1527 Report.RegisterWarningRegion (Location).WarningEnable (line);
1531 if (arg.StartsWith (w_disable)) {
1532 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1533 foreach (int code in codes) {
1535 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1540 if (arg.StartsWith (w_restore)) {
1541 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1542 Hashtable w_table = Report.warning_ignore_table;
1543 foreach (int code in codes) {
1544 if (w_table != null && w_table.Contains (code))
1545 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1546 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1551 if (arg.StartsWith (warning)) {
1552 Report.Warning (1634, 1, Location, "Expected disable or restore");
1556 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1559 int[] ParseNumbers (string text)
1561 string[] string_array = text.Split (',');
1562 int[] values = new int [string_array.Length];
1564 foreach (string string_code in string_array) {
1566 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1568 catch (FormatException) {
1569 Report.Warning (1692, 1, Location, "Invalid number");
1575 bool eval_val (string s)
1582 if (defines == null)
1584 if (defines.Contains (s))
1590 bool pp_primary (ref string s)
1599 s = s.Substring (1);
1600 bool val = pp_expr (ref s);
1601 if (s.Length > 0 && s [0] == ')'){
1602 s = s.Substring (1);
1605 Error_InvalidDirective ();
1609 if (is_identifier_start_character (c)){
1615 if (is_identifier_part_character (c)){
1619 bool v = eval_val (s.Substring (0, j));
1620 s = s.Substring (j);
1623 bool vv = eval_val (s);
1628 Error_InvalidDirective ();
1632 bool pp_unary (ref string s)
1639 if (len > 1 && s [1] == '='){
1640 Error_InvalidDirective ();
1643 s = s.Substring (1);
1644 return ! pp_primary (ref s);
1646 return pp_primary (ref s);
1648 Error_InvalidDirective ();
1653 bool pp_eq (ref string s)
1655 bool va = pp_unary (ref s);
1661 if (len > 2 && s [1] == '='){
1662 s = s.Substring (2);
1663 return va == pp_unary (ref s);
1665 Error_InvalidDirective ();
1668 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1669 s = s.Substring (2);
1671 return va != pp_unary (ref s);
1680 bool pp_and (ref string s)
1682 bool va = pp_eq (ref s);
1688 if (len > 2 && s [1] == '&'){
1689 s = s.Substring (2);
1690 return (va & pp_and (ref s));
1692 Error_InvalidDirective ();
1701 // Evaluates an expression for `#if' or `#elif'
1703 bool pp_expr (ref string s)
1705 bool va = pp_and (ref s);
1712 if (len > 2 && s [1] == '|'){
1713 s = s.Substring (2);
1714 return va | pp_expr (ref s);
1716 Error_InvalidDirective ();
1725 bool eval (string s)
1727 bool v = pp_expr (ref s);
1730 Error_InvalidDirective ();
1737 void Error_InvalidDirective ()
1739 Report.Error (1517, Location, "Invalid preprocessor directive");
1742 void Error_UnexpectedDirective (string extra)
1746 "Unexpected processor directive (" + extra + ")");
1749 void Error_TokensSeen ()
1751 Report.Error (1032, Location,
1752 "Cannot define or undefine preprocessor symbols after first token in file");
1756 // if true, then the code continues processing the code
1757 // if false, the code stays in a loop until another directive is
1760 bool handle_preprocessing_directive (bool caller_is_taking)
1763 bool region_directive = false;
1765 current_location = new Location (ref_line, Col);
1767 get_cmd_arg (out cmd, out arg);
1769 // Eat any trailing whitespaces and single-line comments
1770 if (arg.IndexOf ("//") != -1)
1771 arg = arg.Substring (0, arg.IndexOf ("//"));
1772 arg = arg.TrimEnd (' ', '\t');
1775 // The first group of pre-processing instructions is always processed
1779 if (RootContext.Version == LanguageVersion.ISO_1) {
1780 Report.FeatureIsNotStandardized (Location, "#pragma");
1781 return caller_is_taking;
1784 PreProcessPragma (arg);
1785 return caller_is_taking;
1788 if (!PreProcessLine (arg))
1791 "The line number specified for #line directive is missing or invalid");
1792 return caller_is_taking;
1795 region_directive = true;
1800 region_directive = true;
1805 Error_InvalidDirective ();
1808 bool taking = false;
1809 if (ifstack == null)
1810 ifstack = new Stack ();
1812 if (ifstack.Count == 0){
1815 int state = (int) ifstack.Peek ();
1816 if ((state & TAKING) != 0)
1820 if (eval (arg) && taking){
1821 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1822 if (region_directive)
1824 ifstack.Push (push);
1827 int push = (taking ? PARENT_TAKING : 0);
1828 if (region_directive)
1830 ifstack.Push (push);
1835 if (ifstack == null || ifstack.Count == 0){
1836 Error_UnexpectedDirective ("no #if for this #endif");
1839 int pop = (int) ifstack.Pop ();
1841 if (region_directive && ((pop & REGION) == 0))
1842 Report.Error (1027, Location, "Expected `#endif' directive");
1843 else if (!region_directive && ((pop & REGION) != 0))
1844 Report.Error (1038, Location, "#endregion directive expected");
1846 if (!region_directive && arg.Length != 0) {
1847 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1850 if (ifstack.Count == 0)
1853 int state = (int) ifstack.Peek ();
1855 if ((state & TAKING) != 0)
1863 if (ifstack == null || ifstack.Count == 0){
1864 Error_UnexpectedDirective ("no #if for this #elif");
1867 int state = (int) ifstack.Peek ();
1869 if ((state & REGION) != 0) {
1870 Report.Error (1038, Location, "#endregion directive expected");
1874 if ((state & ELSE_SEEN) != 0){
1875 Error_UnexpectedDirective ("#elif not valid after #else");
1879 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1882 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1883 state = (int) ifstack.Pop ();
1884 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1891 if (ifstack == null || ifstack.Count == 0){
1892 Error_UnexpectedDirective ("no #if for this #else");
1895 int state = (int) ifstack.Peek ();
1897 if ((state & REGION) != 0) {
1898 Report.Error (1038, Location, "#endregion directive expected");
1902 if ((state & ELSE_SEEN) != 0){
1903 Error_UnexpectedDirective ("#else within #else");
1910 if ((state & TAKEN_BEFORE) == 0){
1911 ret = ((state & PARENT_TAKING) != 0);
1920 ifstack.Push (state | ELSE_SEEN);
1927 // These are only processed if we are in a `taking' block
1929 if (!caller_is_taking)
1934 if (any_token_seen){
1935 Error_TokensSeen ();
1938 PreProcessDefinition (true, arg);
1942 if (any_token_seen){
1943 Error_TokensSeen ();
1946 PreProcessDefinition (false, arg);
1950 Report.Error (1029, Location, "#error: '" + arg + "'");
1954 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
1958 Report.Error (1024, Location, "Wrong preprocessor directive");
1963 private int consume_string (bool quoted)
1966 string_builder.Length = 0;
1968 while ((c = getChar ()) != -1){
1970 if (quoted && peekChar () == '"'){
1971 string_builder.Append ((char) c);
1975 val = string_builder.ToString ();
1976 return Token.LITERAL_STRING;
1982 Report.Error (1010, Location, "Newline in constant");
1990 string_builder.Append ((char) c);
1993 Report.Error (1039, Location, "Unterminated string literal");
1997 private int consume_identifier (int s)
1999 int res = consume_identifier (s, false);
2001 if (doc_state == XmlCommentState.Allowed)
2002 doc_state = XmlCommentState.NotAllowed;
2005 case Token.NAMESPACE:
2006 check_incorrect_doc_comment ();
2010 if (res == Token.PARTIAL) {
2011 // Save current position and parse next token.
2012 int old = reader.Position;
2013 int old_putback = putback_char;
2014 int old_ref_line = ref_line;
2019 int next_token = token ();
2020 bool ok = (next_token == Token.CLASS) ||
2021 (next_token == Token.STRUCT) ||
2022 (next_token == Token.INTERFACE) ||
2023 (next_token == Token.ENUM); // "partial" is a keyword in 'partial enum', even though it's not valid
2025 reader.Position = old;
2026 ref_line = old_ref_line;
2028 putback_char = old_putback;
2033 val = new LocatedToken (Location, "partial");
2034 return Token.IDENTIFIER;
2041 private int consume_identifier (int s, bool quoted)
2046 id_builder [0] = (char) s;
2048 current_location = new Location (ref_line, Col);
2050 while ((c = getChar ()) != -1) {
2051 if (is_identifier_part_character ((char) c)){
2052 if (pos == max_id_size){
2053 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2057 id_builder [pos++] = (char) c;
2058 // putback_char = -1;
2060 // putback_char = c;
2067 // Optimization: avoids doing the keyword lookup
2068 // on uppercase letters and _
2070 if (!quoted && (s >= 'a' || s == '_')){
2071 int keyword = GetKeyword (id_builder, pos);
2072 if (keyword != -1) {
2079 // Keep identifiers in an array of hashtables to avoid needless
2083 if (identifiers [pos] != null) {
2084 val = identifiers [pos][id_builder];
2086 val = new LocatedToken (Location, (string) val);
2088 escapedIdentifiers.Add (val);
2089 return Token.IDENTIFIER;
2093 identifiers [pos] = new CharArrayHashtable (pos);
2095 val = new String (id_builder, 0, pos);
2096 if (RootContext.Version == LanguageVersion.ISO_1) {
2097 for (int i = 1; i < id_builder.Length; i += 3) {
2098 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2099 Report.Error (1638, Location,
2100 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2106 char [] chars = new char [pos];
2107 Array.Copy (id_builder, chars, pos);
2109 identifiers [pos] [chars] = val;
2111 val = new LocatedToken (Location, (string) val);
2113 escapedIdentifiers.Add (val);
2114 return Token.IDENTIFIER;
2117 int consume_whitespace ()
2121 // Whether we have seen comments on the current line
2122 bool comments_seen = false;
2125 // optimization: eliminate col and implement #directive semantic correctly.
2126 for (;(c = getChar ()) != -1;) {
2134 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
2138 if (peekChar () == '\n')
2141 any_token_seen |= tokens_seen;
2142 tokens_seen = false;
2143 comments_seen = false;
2147 // Handle double-slash comments.
2149 int d = peekChar ();
2153 if (RootContext.Documentation != null && peekChar () == '/') {
2155 // Don't allow ////.
2156 if ((d = peekChar ()) != '/') {
2157 update_comment_location ();
2158 if (doc_state == XmlCommentState.Allowed)
2159 handle_one_line_xml_comment ();
2160 else if (doc_state == XmlCommentState.NotAllowed)
2161 warn_incorrect_doc_comment ();
2164 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2167 any_token_seen |= tokens_seen;
2168 tokens_seen = false;
2169 comments_seen = false;
2171 } else if (d == '*'){
2173 bool docAppend = false;
2174 if (RootContext.Documentation != null && peekChar () == '*') {
2176 update_comment_location ();
2177 // But when it is /**/, just do nothing.
2178 if (peekChar () == '/') {
2182 if (doc_state == XmlCommentState.Allowed)
2184 else if (doc_state == XmlCommentState.NotAllowed)
2185 warn_incorrect_doc_comment ();
2188 int current_comment_start = 0;
2190 current_comment_start = xml_comment_buffer.Length;
2191 xml_comment_buffer.Append (Environment.NewLine);
2194 Location start_location = Location;
2196 while ((d = getChar ()) != -1){
2197 if (d == '*' && peekChar () == '/'){
2199 comments_seen = true;
2203 xml_comment_buffer.Append ((char) d);
2206 any_token_seen |= tokens_seen;
2207 tokens_seen = false;
2209 // Reset 'comments_seen' just to be consistent.
2210 // It doesn't matter either way, here.
2212 comments_seen = false;
2216 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2219 update_formatted_doc_comment (current_comment_start);
2222 goto is_punct_label;
2228 any_token_seen |= tokens_seen;
2229 tokens_seen = false;
2230 comments_seen = false;
2234 /* For now, ignore pre-processor commands */
2235 // FIXME: In C# the '#' is not limited to appear
2236 // on the first column.
2240 if (tokens_seen || comments_seen) {
2241 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2242 "character on a line.";
2244 Report.Error (1040, Location, error_details);
2251 cont = handle_preprocessing_directive (cont);
2257 bool skipping = false;
2258 for (;(c = getChar ()) != -1;){
2261 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2265 if (c == '#' && !skipping)
2268 any_token_seen |= tokens_seen;
2269 tokens_seen = false;
2271 Report.Error (1027, Location, "Expected `#endif' directive");
2281 public int xtoken ()
2284 bool doread = false;
2288 // optimization: eliminate col and implement #directive semantic correctly.
2290 c = consume_whitespace ();
2294 if (is_identifier_start_character ((char)c)){
2296 return consume_identifier (c);
2299 current_location = new Location (ref_line, Col);
2300 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2309 if (c >= '0' && c <= '9'){
2311 return is_number (c);
2316 int peek = peekChar ();
2317 if (peek >= '0' && peek <= '9')
2318 return is_number (c);
2323 return consume_string (false);
2329 error_details = "Empty character literal";
2330 Report.Error (1011, Location, error_details);
2333 if (c == '\r' || c == '\n') {
2334 Report.Error (1010, Location, "Newline in constant");
2340 val = new System.Char ();
2345 error_details = "Too many characters in character literal";
2346 Report.Error (1012, Location, error_details);
2348 // Try to recover, read until newline or next "'"
2349 while ((c = getChar ()) != -1){
2358 return Token.LITERAL_CHARACTER;
2365 return consume_string (true);
2366 } else if (is_identifier_start_character ((char) c)){
2367 return consume_identifier (c, true);
2369 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2374 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2375 "character on a line.";
2377 Report.Error (1040, Location, error_details);
2382 error_details = ((char)c).ToString ();
2388 // Handles one line xml comment
2390 private void handle_one_line_xml_comment ()
2393 while ((c = peekChar ()) == ' ')
2394 getChar (); // skip heading whitespaces.
2395 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2396 xml_comment_buffer.Append ((char) getChar ());
2398 if (c == '\r' || c == '\n')
2399 xml_comment_buffer.Append (Environment.NewLine);
2403 // Remove heading "*" in Javadoc-like xml documentation.
2405 private void update_formatted_doc_comment (int current_comment_start)
2407 int length = xml_comment_buffer.Length - current_comment_start;
2408 string [] lines = xml_comment_buffer.ToString (
2409 current_comment_start,
2410 length).Replace ("\r", "").Split ('\n');
2412 // The first line starts with /**, thus it is not target
2413 // for the format check.
2414 for (int i = 1; i < lines.Length; i++) {
2415 string s = lines [i];
2416 int idx = s.IndexOf ('*');
2419 if (i < lines.Length - 1)
2423 head = s.Substring (0, idx);
2424 foreach (char c in head)
2427 lines [i] = s.Substring (idx + 1);
2429 xml_comment_buffer.Remove (current_comment_start, length);
2430 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2434 // Updates current comment location.
2436 private void update_comment_location ()
2438 if (current_comment_location.IsNull) {
2439 // "-2" is for heading "//" or "/*"
2440 current_comment_location =
2441 new Location (ref_line, col - 2);
2446 // Checks if there was incorrect doc comments and raise
2449 public void check_incorrect_doc_comment ()
2451 if (xml_comment_buffer.Length > 0)
2452 warn_incorrect_doc_comment ();
2456 // Raises a warning when tokenizer found incorrect doccomment
2459 private void warn_incorrect_doc_comment ()
2461 if (doc_state != XmlCommentState.Error) {
2462 doc_state = XmlCommentState.Error;
2463 // in csc, it is 'XML comment is not placed on
2464 // a valid language element'. But that does not
2466 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2471 // Consumes the saved xml comment lines (if any)
2472 // as for current target member or type.
2474 public string consume_doc_comment ()
2476 if (xml_comment_buffer.Length > 0) {
2477 string ret = xml_comment_buffer.ToString ();
2478 reset_doc_comment ();
2484 void reset_doc_comment ()
2486 xml_comment_buffer.Length = 0;
2487 current_comment_location = Location.Null;
2490 public void cleanup ()
2492 if (ifstack != null && ifstack.Count >= 1) {
2493 int state = (int) ifstack.Pop ();
2494 if ((state & REGION) != 0)
2495 Report.Error (1038, Location, "#endregion directive expected");
2497 Report.Error (1027, "Expected `#endif' directive");
2504 // Indicates whether it accepts XML documentation or not.
2506 public enum XmlCommentState {
2507 // comment is allowed in this state.
2509 // comment is not allowed in this state.
2511 // once comments appeared when it is NotAllowed, then the
2512 // state is changed to it, until the state is changed to