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, 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;
1060 return integer_type_suffix (ul, peekChar ());
1064 // Invoked if we know we have .digits or digits
1066 int is_number (int c)
1068 bool is_real = false;
1073 if (c >= '0' && c <= '9'){
1075 int peek = peekChar ();
1077 if (peek == 'x' || peek == 'X')
1078 return handle_hex ();
1085 // We need to handle the case of
1086 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1089 if (decimal_digits ('.')){
1095 return adjust_int (-1);
1099 if (c == 'e' || c == 'E'){
1101 if (number_pos == max_number_size)
1102 Error_NumericConstantTooLong ();
1103 number_builder [number_pos++] = 'e';
1107 if (number_pos == max_number_size)
1108 Error_NumericConstantTooLong ();
1109 number_builder [number_pos++] = '+';
1111 } else if (c == '-') {
1112 if (number_pos == max_number_size)
1113 Error_NumericConstantTooLong ();
1114 number_builder [number_pos++] = '-';
1117 if (number_pos == max_number_size)
1118 Error_NumericConstantTooLong ();
1119 number_builder [number_pos++] = '+';
1126 type = real_type_suffix (c);
1127 if (type == Token.NONE && !is_real){
1129 return adjust_int (c);
1133 if (type == Token.NONE){
1138 return adjust_real (type);
1140 Console.WriteLine ("This should not be reached");
1141 throw new Exception ("Is Number should never reach this point");
1145 // Accepts exactly count (4 or 8) hex, no more no less
1147 int getHex (int count, out bool error)
1152 int top = count != -1 ? count : 4;
1156 for (i = 0; i < top; i++){
1159 if (c >= '0' && c <= '9')
1160 c = (int) c - (int) '0';
1161 else if (c >= 'A' && c <= 'F')
1162 c = (int) c - (int) 'A' + 10;
1163 else if (c >= 'a' && c <= 'f')
1164 c = (int) c - (int) 'a' + 10;
1170 total = (total * 16) + c;
1172 int p = peekChar ();
1175 if (!is_hex ((char)p))
1216 v = getHex (-1, out error);
1221 v = getHex (4, out error);
1226 v = getHex (8, out error);
1231 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", (char)d);
1241 if (putback_char != -1) {
1260 if (putback_char != -1)
1261 return putback_char;
1262 putback_char = reader.Read ();
1263 return putback_char;
1268 if (putback_char != -1)
1269 return putback_char;
1270 return reader.Peek ();
1273 void putback (int c)
1275 if (putback_char != -1){
1276 Console.WriteLine ("Col: " + col);
1277 Console.WriteLine ("Row: " + line);
1278 Console.WriteLine ("Name: " + ref_name.Name);
1279 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1280 throw new Exception ("This should not happen putback on putback");
1282 if (c == '\n' || col == 0) {
1283 // It won't happen though.
1293 public bool advance ()
1295 return peekChar () != -1;
1298 public Object Value {
1304 public Object value ()
1309 bool IsCastToken (int token)
1314 case Token.IDENTIFIER:
1315 case Token.LITERAL_INTEGER:
1316 case Token.LITERAL_FLOAT:
1317 case Token.LITERAL_DOUBLE:
1318 case Token.LITERAL_DECIMAL:
1319 case Token.LITERAL_CHARACTER:
1320 case Token.LITERAL_STRING:
1332 case Token.UNCHECKED:
1336 // These can be part of a member access
1356 current_token = xtoken ();
1358 if (current_token != Token.DEFAULT)
1359 return current_token;
1361 int c = consume_whitespace ();
1363 current_token = Token.ERROR;
1365 current_token = Token.DEFAULT_OPEN_PARENS;
1369 return current_token;
1372 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1374 void get_cmd_arg (out string cmd, out string arg)
1378 tokens_seen = false;
1380 static_cmd_arg.Length = 0;
1382 // skip over white space
1383 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1386 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1387 if (is_identifier_part_character ((char) c)){
1388 static_cmd_arg.Append ((char) c);
1396 cmd = static_cmd_arg.ToString ();
1402 // skip over white space
1403 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1408 } else if (c == '\r'){
1410 } else if (c == -1){
1415 static_cmd_arg.Length = 0;
1416 static_cmd_arg.Append ((char) c);
1418 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1419 static_cmd_arg.Append ((char) c);
1422 arg = static_cmd_arg.ToString ().Trim ();
1426 // Handles the #line directive
1428 bool PreProcessLine (string arg)
1433 if (arg == "default"){
1435 ref_name = file_name;
1436 Location.Push (ref_name, line);
1438 } else if (arg == "hidden"){
1440 // We ignore #line hidden
1448 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1449 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1452 char [] quotes = { '\"' };
1454 string name = arg.Substring (pos). Trim (quotes);
1455 ref_name = Location.LookupFile (name);
1456 file_name.HasLineDirective = true;
1457 ref_name.HasLineDirective = true;
1458 Location.Push (ref_name, ref_line);
1460 ref_line = System.Int32.Parse (arg);
1470 // Handles #define and #undef
1472 void PreProcessDefinition (bool is_define, string arg)
1474 if (arg == "" || arg == "true" || arg == "false"){
1475 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1479 char[] whitespace = { ' ', '\t' };
1480 if (arg.IndexOfAny (whitespace) != -1){
1481 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1485 if (!is_identifier_start_character (arg [0]))
1486 Report.Error (1001, Location, "Identifier expected: " + arg);
1488 foreach (char c in arg.Substring (1)){
1489 if (!is_identifier_part_character (c)){
1490 Report.Error (1001, Location, "Identifier expected: " + arg);
1496 if (defines == null)
1497 defines = new Hashtable ();
1500 if (defines == null)
1502 if (defines.Contains (arg))
1503 defines.Remove (arg);
1508 /// Handles #pragma directive
1510 void PreProcessPragma (string arg)
1512 const string warning = "warning";
1513 const string w_disable = "warning disable";
1514 const string w_restore = "warning restore";
1516 if (arg == w_disable) {
1517 Report.RegisterWarningRegion (Location).WarningDisable (line);
1521 if (arg == w_restore) {
1522 Report.RegisterWarningRegion (Location).WarningEnable (line);
1526 if (arg.StartsWith (w_disable)) {
1527 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1528 foreach (int code in codes) {
1530 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1535 if (arg.StartsWith (w_restore)) {
1536 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1537 Hashtable w_table = Report.warning_ignore_table;
1538 foreach (int code in codes) {
1539 if (w_table != null && w_table.Contains (code))
1540 Report.Warning (1635, 1, Location, "Cannot restore warning 'CS{0:0000}' because it was disabled globally", code);
1541 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1546 if (arg.StartsWith (warning)) {
1547 Report.Warning (1634, 1, Location, "Expected disable or restore");
1551 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1554 int[] ParseNumbers (string text)
1556 string[] string_array = text.Split (',');
1557 int[] values = new int [string_array.Length];
1559 foreach (string string_code in string_array) {
1561 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1563 catch (FormatException) {
1564 Report.Warning (1692, Location, "Invalid number");
1570 bool eval_val (string s)
1577 if (defines == null)
1579 if (defines.Contains (s))
1585 bool pp_primary (ref string s)
1594 s = s.Substring (1);
1595 bool val = pp_expr (ref s);
1596 if (s.Length > 0 && s [0] == ')'){
1597 s = s.Substring (1);
1600 Error_InvalidDirective ();
1604 if (is_identifier_start_character (c)){
1610 if (is_identifier_part_character (c)){
1614 bool v = eval_val (s.Substring (0, j));
1615 s = s.Substring (j);
1618 bool vv = eval_val (s);
1623 Error_InvalidDirective ();
1627 bool pp_unary (ref string s)
1634 if (len > 1 && s [1] == '='){
1635 Error_InvalidDirective ();
1638 s = s.Substring (1);
1639 return ! pp_primary (ref s);
1641 return pp_primary (ref s);
1643 Error_InvalidDirective ();
1648 bool pp_eq (ref string s)
1650 bool va = pp_unary (ref s);
1656 if (len > 2 && s [1] == '='){
1657 s = s.Substring (2);
1658 return va == pp_unary (ref s);
1660 Error_InvalidDirective ();
1663 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1664 s = s.Substring (2);
1666 return va != pp_unary (ref s);
1675 bool pp_and (ref string s)
1677 bool va = pp_eq (ref s);
1683 if (len > 2 && s [1] == '&'){
1684 s = s.Substring (2);
1685 return (va & pp_and (ref s));
1687 Error_InvalidDirective ();
1696 // Evaluates an expression for `#if' or `#elif'
1698 bool pp_expr (ref string s)
1700 bool va = pp_and (ref s);
1707 if (len > 2 && s [1] == '|'){
1708 s = s.Substring (2);
1709 return va | pp_expr (ref s);
1711 Error_InvalidDirective ();
1720 bool eval (string s)
1722 bool v = pp_expr (ref s);
1725 Error_InvalidDirective ();
1732 void Error_InvalidDirective ()
1734 Report.Error (1517, Location, "Invalid preprocessor directive");
1737 void Error_UnexpectedDirective (string extra)
1741 "Unexpected processor directive (" + extra + ")");
1744 void Error_TokensSeen ()
1746 Report.Error (1032, Location,
1747 "Cannot define or undefine preprocessor symbols after first token in file");
1751 // if true, then the code continues processing the code
1752 // if false, the code stays in a loop until another directive is
1755 bool handle_preprocessing_directive (bool caller_is_taking)
1758 bool region_directive = false;
1760 current_location = new Location (ref_line, Col);
1762 get_cmd_arg (out cmd, out arg);
1764 // Eat any trailing whitespaces and single-line comments
1765 if (arg.IndexOf ("//") != -1)
1766 arg = arg.Substring (0, arg.IndexOf ("//"));
1767 arg = arg.TrimEnd (' ', '\t');
1770 // The first group of pre-processing instructions is always processed
1774 if (RootContext.Version == LanguageVersion.ISO_1) {
1775 Report.FeatureIsNotStandardized (Location, "#pragma");
1776 return caller_is_taking;
1779 PreProcessPragma (arg);
1780 return caller_is_taking;
1783 if (!PreProcessLine (arg))
1786 "The line number specified for #line directive is missing or invalid");
1787 return caller_is_taking;
1790 region_directive = true;
1795 region_directive = true;
1800 Error_InvalidDirective ();
1803 bool taking = false;
1804 if (ifstack == null)
1805 ifstack = new Stack ();
1807 if (ifstack.Count == 0){
1810 int state = (int) ifstack.Peek ();
1811 if ((state & TAKING) != 0)
1815 if (eval (arg) && taking){
1816 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1817 if (region_directive)
1819 ifstack.Push (push);
1822 int push = (taking ? PARENT_TAKING : 0);
1823 if (region_directive)
1825 ifstack.Push (push);
1830 if (ifstack == null || ifstack.Count == 0){
1831 Error_UnexpectedDirective ("no #if for this #endif");
1834 int pop = (int) ifstack.Pop ();
1836 if (region_directive && ((pop & REGION) == 0))
1837 Report.Error (1027, Location, "Expected `#endif' directive");
1838 else if (!region_directive && ((pop & REGION) != 0))
1839 Report.Error (1038, Location, "#endregion directive expected");
1841 if (!region_directive && arg.Length != 0) {
1842 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1845 if (ifstack.Count == 0)
1848 int state = (int) ifstack.Peek ();
1850 if ((state & TAKING) != 0)
1858 if (ifstack == null || ifstack.Count == 0){
1859 Error_UnexpectedDirective ("no #if for this #elif");
1862 int state = (int) ifstack.Peek ();
1864 if ((state & REGION) != 0) {
1865 Report.Error (1038, Location, "#endregion directive expected");
1869 if ((state & ELSE_SEEN) != 0){
1870 Error_UnexpectedDirective ("#elif not valid after #else");
1874 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1877 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1878 state = (int) ifstack.Pop ();
1879 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1886 if (ifstack == null || ifstack.Count == 0){
1889 "Unexpected processor directive (no #if for this #else)");
1892 int state = (int) ifstack.Peek ();
1894 if ((state & REGION) != 0) {
1895 Report.Error (1038, Location, "#endregion directive expected");
1899 if ((state & ELSE_SEEN) != 0){
1900 Error_UnexpectedDirective ("#else within #else");
1907 if ((state & TAKEN_BEFORE) == 0){
1908 ret = ((state & PARENT_TAKING) != 0);
1917 ifstack.Push (state | ELSE_SEEN);
1924 // These are only processed if we are in a `taking' block
1926 if (!caller_is_taking)
1931 if (any_token_seen){
1932 Error_TokensSeen ();
1935 PreProcessDefinition (true, arg);
1939 if (any_token_seen){
1940 Error_TokensSeen ();
1943 PreProcessDefinition (false, arg);
1947 Report.Error (1029, Location, "#error: '" + arg + "'");
1951 Report.Warning (1030, Location, "#warning: `{0}'", arg);
1955 Report.Error (1024, Location, "Wrong preprocessor directive");
1960 private int consume_string (bool quoted)
1963 string_builder.Length = 0;
1965 while ((c = getChar ()) != -1){
1967 if (quoted && peekChar () == '"'){
1968 string_builder.Append ((char) c);
1972 val = string_builder.ToString ();
1973 return Token.LITERAL_STRING;
1979 Report.Error (1010, Location, "Newline in constant");
1987 string_builder.Append ((char) c);
1990 Report.Error (1039, Location, "Unterminated string literal");
1994 private int consume_identifier (int s)
1996 int res = consume_identifier (s, false);
1998 if (doc_state == XmlCommentState.Allowed)
1999 doc_state = XmlCommentState.NotAllowed;
2002 case Token.NAMESPACE:
2003 check_incorrect_doc_comment ();
2007 if (res == Token.PARTIAL) {
2008 // Save current position and parse next token.
2009 int old = reader.Position;
2010 int old_putback = putback_char;
2011 int old_ref_line = ref_line;
2016 int next_token = token ();
2017 bool ok = (next_token == Token.CLASS) ||
2018 (next_token == Token.STRUCT) ||
2019 (next_token == Token.INTERFACE) ||
2020 (next_token == Token.ENUM); // "partial" is a keyword in 'partial enum', even though it's not valid
2022 reader.Position = old;
2023 ref_line = old_ref_line;
2025 putback_char = old_putback;
2030 val = new LocatedToken (Location, "partial");
2031 return Token.IDENTIFIER;
2038 private int consume_identifier (int s, bool quoted)
2043 id_builder [0] = (char) s;
2045 current_location = new Location (ref_line, Col);
2047 while ((c = getChar ()) != -1) {
2048 if (is_identifier_part_character ((char) c)){
2049 if (pos == max_id_size){
2050 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2054 id_builder [pos++] = (char) c;
2055 // putback_char = -1;
2057 // putback_char = c;
2064 // Optimization: avoids doing the keyword lookup
2065 // on uppercase letters and _
2067 if (!quoted && (s >= 'a' || s == '_')){
2068 int keyword = GetKeyword (id_builder, pos);
2069 if (keyword != -1) {
2076 // Keep identifiers in an array of hashtables to avoid needless
2080 if (identifiers [pos] != null) {
2081 val = identifiers [pos][id_builder];
2083 val = new LocatedToken (Location, (string) val);
2085 escapedIdentifiers.Add (val);
2086 return Token.IDENTIFIER;
2090 identifiers [pos] = new CharArrayHashtable (pos);
2092 val = new String (id_builder, 0, pos);
2093 if (RootContext.Version == LanguageVersion.ISO_1) {
2094 for (int i = 1; i < id_builder.Length; i += 3) {
2095 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2096 Report.Error (1638, Location,
2097 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val);
2103 char [] chars = new char [pos];
2104 Array.Copy (id_builder, chars, pos);
2106 identifiers [pos] [chars] = val;
2108 val = new LocatedToken (Location, (string) val);
2110 escapedIdentifiers.Add (val);
2111 return Token.IDENTIFIER;
2114 int consume_whitespace ()
2118 // Whether we have seen comments on the current line
2119 bool comments_seen = false;
2122 // optimization: eliminate col and implement #directive semantic correctly.
2123 for (;(c = getChar ()) != -1;) {
2131 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
2135 if (peekChar () == '\n')
2138 any_token_seen |= tokens_seen;
2139 tokens_seen = false;
2140 comments_seen = false;
2144 // Handle double-slash comments.
2146 int d = peekChar ();
2150 if (RootContext.Documentation != null && peekChar () == '/') {
2152 // Don't allow ////.
2153 if ((d = peekChar ()) != '/') {
2154 update_comment_location ();
2155 if (doc_state == XmlCommentState.Allowed)
2156 handle_one_line_xml_comment ();
2157 else if (doc_state == XmlCommentState.NotAllowed)
2158 warn_incorrect_doc_comment ();
2161 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2164 any_token_seen |= tokens_seen;
2165 tokens_seen = false;
2166 comments_seen = false;
2168 } else if (d == '*'){
2170 bool docAppend = false;
2171 if (RootContext.Documentation != null && peekChar () == '*') {
2173 update_comment_location ();
2174 // But when it is /**/, just do nothing.
2175 if (peekChar () == '/') {
2179 if (doc_state == XmlCommentState.Allowed)
2181 else if (doc_state == XmlCommentState.NotAllowed)
2182 warn_incorrect_doc_comment ();
2185 int current_comment_start = 0;
2187 current_comment_start = xml_comment_buffer.Length;
2188 xml_comment_buffer.Append (Environment.NewLine);
2191 Location start_location = Location;
2193 while ((d = getChar ()) != -1){
2194 if (d == '*' && peekChar () == '/'){
2196 comments_seen = true;
2200 xml_comment_buffer.Append ((char) d);
2203 any_token_seen |= tokens_seen;
2204 tokens_seen = false;
2206 // Reset 'comments_seen' just to be consistent.
2207 // It doesn't matter either way, here.
2209 comments_seen = false;
2213 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2216 update_formatted_doc_comment (current_comment_start);
2219 goto is_punct_label;
2225 any_token_seen |= tokens_seen;
2226 tokens_seen = false;
2227 comments_seen = false;
2231 /* For now, ignore pre-processor commands */
2232 // FIXME: In C# the '#' is not limited to appear
2233 // on the first column.
2237 if (tokens_seen || comments_seen) {
2238 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2239 "character on a line.";
2241 Report.Error (1040, Location, error_details);
2248 cont = handle_preprocessing_directive (cont);
2254 bool skipping = false;
2255 for (;(c = getChar ()) != -1;){
2258 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2262 if (c == '#' && !skipping)
2265 any_token_seen |= tokens_seen;
2266 tokens_seen = false;
2268 Report.Error (1027, Location, "Expected `#endif' directive");
2278 public int xtoken ()
2281 bool doread = false;
2285 // optimization: eliminate col and implement #directive semantic correctly.
2287 c = consume_whitespace ();
2291 if (is_identifier_start_character ((char)c)){
2293 return consume_identifier (c);
2296 current_location = new Location (ref_line, Col);
2297 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2306 if (c >= '0' && c <= '9'){
2308 return is_number (c);
2313 int peek = peekChar ();
2314 if (peek >= '0' && peek <= '9')
2315 return is_number (c);
2320 return consume_string (false);
2326 error_details = "Empty character literal";
2327 Report.Error (1011, Location, error_details);
2330 if (c == '\r' || c == '\n') {
2331 Report.Error (1010, Location, "Newline in constant");
2337 val = new System.Char ();
2342 error_details = "Too many characters in character literal";
2343 Report.Error (1012, Location, error_details);
2345 // Try to recover, read until newline or next "'"
2346 while ((c = getChar ()) != -1){
2355 return Token.LITERAL_CHARACTER;
2362 return consume_string (true);
2363 } else if (is_identifier_start_character ((char) c)){
2364 return consume_identifier (c, true);
2366 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2371 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2372 "character on a line.";
2374 Report.Error (1040, Location, error_details);
2379 error_details = ((char)c).ToString ();
2385 // Handles one line xml comment
2387 private void handle_one_line_xml_comment ()
2390 while ((c = peekChar ()) == ' ')
2391 getChar (); // skip heading whitespaces.
2392 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2393 xml_comment_buffer.Append ((char) getChar ());
2395 if (c == '\r' || c == '\n')
2396 xml_comment_buffer.Append (Environment.NewLine);
2400 // Remove heading "*" in Javadoc-like xml documentation.
2402 private void update_formatted_doc_comment (int current_comment_start)
2404 int length = xml_comment_buffer.Length - current_comment_start;
2405 string [] lines = xml_comment_buffer.ToString (
2406 current_comment_start,
2407 length).Replace ("\r", "").Split ('\n');
2409 // The first line starts with /**, thus it is not target
2410 // for the format check.
2411 for (int i = 1; i < lines.Length; i++) {
2412 string s = lines [i];
2413 int idx = s.IndexOf ('*');
2416 if (i < lines.Length - 1)
2420 head = s.Substring (0, idx);
2421 foreach (char c in head)
2424 lines [i] = s.Substring (idx + 1);
2426 xml_comment_buffer.Remove (current_comment_start, length);
2427 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2431 // Updates current comment location.
2433 private void update_comment_location ()
2435 if (current_comment_location.IsNull) {
2436 // "-2" is for heading "//" or "/*"
2437 current_comment_location =
2438 new Location (ref_line, col - 2);
2443 // Checks if there was incorrect doc comments and raise
2446 public void check_incorrect_doc_comment ()
2448 if (xml_comment_buffer.Length > 0)
2449 warn_incorrect_doc_comment ();
2453 // Raises a warning when tokenizer found incorrect doccomment
2456 private void warn_incorrect_doc_comment ()
2458 if (doc_state != XmlCommentState.Error) {
2459 doc_state = XmlCommentState.Error;
2460 // in csc, it is 'XML comment is not placed on
2461 // a valid language element'. But that does not
2463 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2468 // Consumes the saved xml comment lines (if any)
2469 // as for current target member or type.
2471 public string consume_doc_comment ()
2473 if (xml_comment_buffer.Length > 0) {
2474 string ret = xml_comment_buffer.ToString ();
2475 reset_doc_comment ();
2481 void reset_doc_comment ()
2483 xml_comment_buffer.Length = 0;
2484 current_comment_location = Location.Null;
2487 public void cleanup ()
2489 if (ifstack != null && ifstack.Count >= 1) {
2490 int state = (int) ifstack.Pop ();
2491 if ((state & REGION) != 0)
2492 Report.Error (1038, Location, "#endregion directive expected");
2494 Report.Error (1027, Location, "#endif directive expected");
2501 // Indicates whether it accepts XML documentation or not.
2503 public enum XmlCommentState {
2504 // comment is allowed in this state.
2506 // comment is not allowed in this state.
2508 // once comments appeared when it is NotAllowed, then the
2509 // state is changed to it, until the state is changed to