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;
35 public SourceFile ref_name;
36 public SourceFile file_name;
37 public int ref_line = 1;
40 public int current_token;
41 bool handle_get_set = false;
42 bool handle_remove_add = false;
43 bool handle_assembly = false;
44 bool handle_constraints = false;
45 bool handle_typeof = false;
48 // XML documentation buffer. The save point is used to divide
49 // comments on types and comments on members.
51 StringBuilder xml_comment_buffer;
54 // See comment on XmlCommentState enumeration.
56 XmlCommentState xmlDocState = XmlCommentState.Allowed;
59 // Whether tokens have been seen on this line
61 bool tokens_seen = false;
64 // Whether a token has been seen on the file
65 // This is needed because `define' is not allowed to be used
66 // after a token has been seen.
68 bool any_token_seen = false;
69 static Hashtable tokenValues;
71 private static Hashtable TokenValueName
74 if (tokenValues == null)
75 tokenValues = GetTokenValueNameHash ();
81 private static Hashtable GetTokenValueNameHash ()
83 Type t = typeof (Token);
84 FieldInfo [] fields = t.GetFields ();
85 Hashtable hash = new Hashtable ();
86 foreach (FieldInfo field in fields) {
87 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
88 hash.Add (field.GetValue (null), field.Name);
94 // Returns a verbose representation of the current location
96 public string location {
100 if (current_token == Token.ERROR)
101 det = "detail: " + error_details;
105 // return "Line: "+line+" Col: "+col + "\n" +
106 // "VirtLine: "+ref_line +
107 // " Token: "+current_token + " " + det;
108 string current_token_name = TokenValueName [current_token] as string;
109 if (current_token_name == null)
110 current_token_name = current_token.ToString ();
112 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
120 public bool PropertyParsing {
122 return handle_get_set;
126 handle_get_set = value;
130 public bool AssemblyTargetParsing {
132 return handle_assembly;
136 handle_assembly = value;
140 public bool EventParsing {
142 return handle_remove_add;
146 handle_remove_add = value;
150 public bool ConstraintsParsing {
152 return handle_constraints;
156 handle_constraints = value;
160 public bool TypeOfParsing {
162 return handle_typeof;
166 handle_typeof = value;
170 public XmlCommentState doc_state {
171 get { return xmlDocState; }
173 if (value == XmlCommentState.Allowed) {
174 check_incorrect_doc_comment ();
175 consume_doc_comment ();
184 static CharArrayHashtable[] keywords;
185 static NumberStyles styles;
186 static NumberFormatInfo csharp_format_info;
189 // Values for the associated token returned
199 const int TAKING = 1;
200 const int TAKEN_BEFORE = 2;
201 const int ELSE_SEEN = 4;
202 const int PARENT_TAKING = 8;
203 const int REGION = 16;
206 // pre-processor if stack state:
210 static System.Text.StringBuilder string_builder;
212 const int max_id_size = 512;
213 static char [] id_builder = new char [max_id_size];
215 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
217 const int max_number_size = 128;
218 static char [] number_builder = new char [max_number_size];
219 static int number_pos;
222 // Details about the error encoutered by the tokenizer
224 string error_details;
226 public string error {
228 return error_details;
244 static void AddKeyword (string kw, int token) {
245 if (keywords [kw.Length] == null) {
246 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
248 keywords [kw.Length] [kw.ToCharArray ()] = token;
251 static void InitTokens ()
253 keywords = new CharArrayHashtable [64];
255 AddKeyword ("__arglist", Token.ARGLIST);
256 AddKeyword ("abstract", Token.ABSTRACT);
257 AddKeyword ("as", Token.AS);
258 AddKeyword ("add", Token.ADD);
259 AddKeyword ("assembly", Token.ASSEMBLY);
260 AddKeyword ("base", Token.BASE);
261 AddKeyword ("bool", Token.BOOL);
262 AddKeyword ("break", Token.BREAK);
263 AddKeyword ("byte", Token.BYTE);
264 AddKeyword ("case", Token.CASE);
265 AddKeyword ("catch", Token.CATCH);
266 AddKeyword ("char", Token.CHAR);
267 AddKeyword ("checked", Token.CHECKED);
268 AddKeyword ("class", Token.CLASS);
269 AddKeyword ("const", Token.CONST);
270 AddKeyword ("continue", Token.CONTINUE);
271 AddKeyword ("decimal", Token.DECIMAL);
272 AddKeyword ("default", Token.DEFAULT);
273 AddKeyword ("delegate", Token.DELEGATE);
274 AddKeyword ("do", Token.DO);
275 AddKeyword ("double", Token.DOUBLE);
276 AddKeyword ("else", Token.ELSE);
277 AddKeyword ("enum", Token.ENUM);
278 AddKeyword ("event", Token.EVENT);
279 AddKeyword ("explicit", Token.EXPLICIT);
280 AddKeyword ("extern", Token.EXTERN);
281 AddKeyword ("false", Token.FALSE);
282 AddKeyword ("finally", Token.FINALLY);
283 AddKeyword ("fixed", Token.FIXED);
284 AddKeyword ("float", Token.FLOAT);
285 AddKeyword ("for", Token.FOR);
286 AddKeyword ("foreach", Token.FOREACH);
287 AddKeyword ("goto", Token.GOTO);
288 AddKeyword ("get", Token.GET);
289 AddKeyword ("if", Token.IF);
290 AddKeyword ("implicit", Token.IMPLICIT);
291 AddKeyword ("in", Token.IN);
292 AddKeyword ("int", Token.INT);
293 AddKeyword ("interface", Token.INTERFACE);
294 AddKeyword ("internal", Token.INTERNAL);
295 AddKeyword ("is", Token.IS);
296 AddKeyword ("lock", Token.LOCK);
297 AddKeyword ("long", Token.LONG);
298 AddKeyword ("namespace", Token.NAMESPACE);
299 AddKeyword ("new", Token.NEW);
300 AddKeyword ("null", Token.NULL);
301 AddKeyword ("object", Token.OBJECT);
302 AddKeyword ("operator", Token.OPERATOR);
303 AddKeyword ("out", Token.OUT);
304 AddKeyword ("override", Token.OVERRIDE);
305 AddKeyword ("params", Token.PARAMS);
306 AddKeyword ("private", Token.PRIVATE);
307 AddKeyword ("protected", Token.PROTECTED);
308 AddKeyword ("public", Token.PUBLIC);
309 AddKeyword ("readonly", Token.READONLY);
310 AddKeyword ("ref", Token.REF);
311 AddKeyword ("remove", Token.REMOVE);
312 AddKeyword ("return", Token.RETURN);
313 AddKeyword ("sbyte", Token.SBYTE);
314 AddKeyword ("sealed", Token.SEALED);
315 AddKeyword ("set", Token.SET);
316 AddKeyword ("short", Token.SHORT);
317 AddKeyword ("sizeof", Token.SIZEOF);
318 AddKeyword ("stackalloc", Token.STACKALLOC);
319 AddKeyword ("static", Token.STATIC);
320 AddKeyword ("string", Token.STRING);
321 AddKeyword ("struct", Token.STRUCT);
322 AddKeyword ("switch", Token.SWITCH);
323 AddKeyword ("this", Token.THIS);
324 AddKeyword ("throw", Token.THROW);
325 AddKeyword ("true", Token.TRUE);
326 AddKeyword ("try", Token.TRY);
327 AddKeyword ("typeof", Token.TYPEOF);
328 AddKeyword ("uint", Token.UINT);
329 AddKeyword ("ulong", Token.ULONG);
330 AddKeyword ("unchecked", Token.UNCHECKED);
331 AddKeyword ("unsafe", Token.UNSAFE);
332 AddKeyword ("ushort", Token.USHORT);
333 AddKeyword ("using", Token.USING);
334 AddKeyword ("virtual", Token.VIRTUAL);
335 AddKeyword ("void", Token.VOID);
336 AddKeyword ("volatile", Token.VOLATILE);
337 AddKeyword ("where", Token.WHERE);
338 AddKeyword ("while", Token.WHILE);
339 AddKeyword ("partial", Token.PARTIAL);
348 csharp_format_info = NumberFormatInfo.InvariantInfo;
349 styles = NumberStyles.Float;
351 string_builder = new System.Text.StringBuilder ();
354 int GetKeyword (char[] id, int id_len)
357 * Keywords are stored in an array of hashtables grouped by their
361 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
363 object o = keywords [id_len] [id];
370 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
372 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
374 if (handle_assembly == false && res == Token.ASSEMBLY)
376 if (handle_constraints == false && res == Token.WHERE)
383 public Location Location {
385 return new Location (ref_line);
389 void define (string def)
391 if (!RootContext.AllDefines.Contains (def)){
392 RootContext.AllDefines [def] = true;
394 if (defines.Contains (def))
396 defines [def] = true;
399 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
401 this.ref_name = file;
402 this.file_name = file;
408 defines = new Hashtable ();
409 foreach (string def in defs)
413 xml_comment_buffer = new StringBuilder ();
416 // FIXME: This could be `Location.Push' but we have to
417 // find out why the MS compiler allows this
419 Mono.CSharp.Location.Push (file);
422 public static void Cleanup () {
426 static bool is_identifier_start_character (char c)
428 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
431 static bool is_identifier_part_character (char c)
433 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
436 public static bool IsValidIdentifier (string s)
438 if (s == null || s.Length == 0)
441 if (!is_identifier_start_character (s [0]))
444 for (int i = 1; i < s.Length; i ++)
445 if (! is_identifier_part_character (s [i]))
451 bool parse_generic_dimension (out int dimension)
456 int the_token = token ();
457 if (the_token == Token.OP_GENERICS_GT)
459 else if (the_token == Token.COMMA) {
467 bool parse_less_than ()
470 int the_token = token ();
472 case Token.IDENTIFIER:
495 the_token = token ();
497 if (the_token == Token.OP_GENERICS_GT)
499 else if ((the_token == Token.COMMA) || (the_token == Token.DOT))
501 else if (the_token == Token.OP_GENERICS_LT) {
502 if (!parse_less_than ())
505 } else if (the_token == Token.OPEN_BRACKET) {
507 the_token = token ();
508 if (the_token == Token.CLOSE_BRACKET)
510 else if (the_token == Token.COMMA)
511 goto rank_specifiers;
518 bool parsing_less_than = false;
519 int parsing_generic_less_than = 0;
521 int is_punct (char c, ref bool doread)
530 return Token.OPEN_BRACE;
532 return Token.CLOSE_BRACE;
534 // To block doccomment inside attribute declaration.
535 if (doc_state == XmlCommentState.Allowed)
536 doc_state = XmlCommentState.NotAllowed;
537 return Token.OPEN_BRACKET;
539 return Token.CLOSE_BRACKET;
541 return Token.OPEN_PARENS;
543 if (deambiguate_close_parens == 0)
544 return Token.CLOSE_PARENS;
546 --deambiguate_close_parens;
548 // Save current position and parse next token.
549 int old = reader.Position;
550 int new_token = token ();
551 reader.Position = old;
554 if (new_token == Token.OPEN_PARENS)
555 return Token.CLOSE_PARENS_OPEN_PARENS;
556 else if (new_token == Token.MINUS)
557 return Token.CLOSE_PARENS_MINUS;
558 else if (IsCastToken (new_token))
559 return Token.CLOSE_PARENS_CAST;
561 return Token.CLOSE_PARENS_NO_CAST;
569 return Token.SEMICOLON;
577 if (parsing_generic_less_than++ > 0)
578 return Token.OP_GENERICS_LT;
580 int old = reader.Position;
583 if (parse_generic_dimension (out dimension)) {
585 return Token.GENERIC_DIMENSION;
587 reader.Position = old;
591 // Save current position and parse next token.
592 old = reader.Position;
593 bool is_generic_lt = parse_less_than ();
594 reader.Position = old;
598 parsing_generic_less_than++;
599 return Token.OP_GENERICS_LT;
601 parsing_generic_less_than = 0;
610 return Token.OP_SHIFT_LEFT_ASSIGN;
612 return Token.OP_SHIFT_LEFT;
613 } else if (d == '='){
618 } else if (c == '>') {
619 if (parsing_generic_less_than > 0) {
620 parsing_generic_less_than--;
621 return Token.OP_GENERICS_GT;
631 return Token.OP_SHIFT_RIGHT_ASSIGN;
633 return Token.OP_SHIFT_RIGHT;
634 } else if (d == '='){
647 t = Token.OP_ADD_ASSIGN;
657 t = Token.OP_SUB_ASSIGN;
686 } else if (d == '='){
688 return Token.OP_AND_ASSIGN;
690 return Token.BITWISE_AND;
697 } else if (d == '='){
699 return Token.OP_OR_ASSIGN;
701 return Token.BITWISE_OR;
707 return Token.OP_MULT_ASSIGN;
715 return Token.OP_DIV_ASSIGN;
723 return Token.OP_MOD_ASSIGN;
725 return Token.PERCENT;
731 return Token.OP_XOR_ASSIGN;
739 int deambiguate_close_parens = 0;
741 public void Deambiguate_CloseParens ()
744 deambiguate_close_parens++;
747 void Error_NumericConstantTooLong ()
749 Report.Error (1021, Location, "Numeric constant too long");
752 bool decimal_digits (int c)
755 bool seen_digits = false;
758 if (number_pos == max_number_size)
759 Error_NumericConstantTooLong ();
760 number_builder [number_pos++] = (char) c;
764 // We use peekChar2, because decimal_digits needs to do a
765 // 2-character look-ahead (5.ToString for example).
767 while ((d = peekChar2 ()) != -1){
768 if (d >= '0' && d <= '9'){
769 if (number_pos == max_number_size)
770 Error_NumericConstantTooLong ();
771 number_builder [number_pos++] = (char) d;
783 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
786 void hex_digits (int c)
789 number_builder [number_pos++] = (char) c;
793 int real_type_suffix (int c)
799 t = Token.LITERAL_FLOAT;
802 t = Token.LITERAL_DOUBLE;
805 t= Token.LITERAL_DECIMAL;
813 int integer_type_suffix (ulong ul, int c)
815 bool is_unsigned = false;
816 bool is_long = false;
819 bool scanning = true;
830 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
832 // if we have not seen anything in between
835 Report.Warning (78, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
854 if (is_long && is_unsigned){
856 return Token.LITERAL_INTEGER;
857 } else if (is_unsigned){
858 // uint if possible, or ulong else.
860 if ((ul & 0xffffffff00000000) == 0)
865 // long if possible, ulong otherwise
866 if ((ul & 0x8000000000000000) != 0)
871 // int, uint, long or ulong in that order
872 if ((ul & 0xffffffff00000000) == 0){
875 if ((ui & 0x80000000) != 0)
880 if ((ul & 0x8000000000000000) != 0)
886 return Token.LITERAL_INTEGER;
890 // given `c' as the next char in the input decide whether
891 // we need to convert to a special type, and then choose
892 // the best representation for the integer
894 int adjust_int (int c)
898 ulong ul = (uint) (number_builder [0] - '0');
900 for (int i = 1; i < number_pos; i++){
901 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
903 return integer_type_suffix (ul, c);
905 uint ui = (uint) (number_builder [0] - '0');
907 for (int i = 1; i < number_pos; i++){
908 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
910 return integer_type_suffix (ui, c);
912 } catch (OverflowException) {
913 error_details = "Integral constant is too large";
914 Report.Error (1021, Location, error_details);
916 return Token.LITERAL_INTEGER;
918 catch (FormatException) {
919 Report.Error (1013, Location, "Invalid number");
921 return Token.LITERAL_INTEGER;
925 int adjust_real (int t)
927 string s = new String (number_builder, 0, number_pos);
930 case Token.LITERAL_DECIMAL:
932 val = System.Decimal.Parse (s, styles, csharp_format_info);
933 } catch (OverflowException) {
935 error_details = "Floating-point constant is outside the range of the type 'decimal'";
936 Report.Error (594, Location, error_details);
939 case Token.LITERAL_FLOAT:
941 val = (float) System.Double.Parse (s, styles, csharp_format_info);
942 } catch (OverflowException) {
944 error_details = "Floating-point constant is outside the range of the type 'float'";
945 Report.Error (594, Location, error_details);
949 case Token.LITERAL_DOUBLE:
951 t = Token.LITERAL_DOUBLE;
953 val = System.Double.Parse (s, styles, csharp_format_info);
954 } catch (OverflowException) {
956 error_details = "Floating-point constant is outside the range of the type 'double'";
957 Report.Error (594, Location, error_details);
970 while ((d = peekChar ()) != -1){
972 number_builder [number_pos++] = (char) d;
978 string s = new String (number_builder, 0, number_pos);
981 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
983 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
984 } catch (OverflowException){
985 error_details = "Integral constant is too large";
986 Report.Error (1021, Location, error_details);
988 return Token.LITERAL_INTEGER;
991 return integer_type_suffix (ul, peekChar ());
995 // Invoked if we know we have .digits or digits
997 int is_number (int c)
999 bool is_real = false;
1004 if (c >= '0' && c <= '9'){
1006 int peek = peekChar ();
1008 if (peek == 'x' || peek == 'X')
1009 return handle_hex ();
1016 // We need to handle the case of
1017 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1020 if (decimal_digits ('.')){
1026 return adjust_int (-1);
1030 if (c == 'e' || c == 'E'){
1032 if (number_pos == max_number_size)
1033 Error_NumericConstantTooLong ();
1034 number_builder [number_pos++] = 'e';
1038 if (number_pos == max_number_size)
1039 Error_NumericConstantTooLong ();
1040 number_builder [number_pos++] = '+';
1042 } else if (c == '-') {
1043 if (number_pos == max_number_size)
1044 Error_NumericConstantTooLong ();
1045 number_builder [number_pos++] = '-';
1048 if (number_pos == max_number_size)
1049 Error_NumericConstantTooLong ();
1050 number_builder [number_pos++] = '+';
1057 type = real_type_suffix (c);
1058 if (type == Token.NONE && !is_real){
1060 return adjust_int (c);
1064 if (type == Token.NONE){
1069 return adjust_real (type);
1071 Console.WriteLine ("This should not be reached");
1072 throw new Exception ("Is Number should never reach this point");
1076 // Accepts exactly count (4 or 8) hex, no more no less
1078 int getHex (int count, out bool error)
1083 int top = count != -1 ? count : 4;
1087 for (i = 0; i < top; i++){
1090 if (c >= '0' && c <= '9')
1091 c = (int) c - (int) '0';
1092 else if (c >= 'A' && c <= 'F')
1093 c = (int) c - (int) 'A' + 10;
1094 else if (c >= 'a' && c <= 'f')
1095 c = (int) c - (int) 'a' + 10;
1101 total = (total * 16) + c;
1103 int p = peekChar ();
1106 if (!is_hex ((char)p))
1147 v = getHex (-1, out error);
1152 v = getHex (4, out error);
1157 v = getHex (8, out error);
1162 Report.Error (1009, Location, "Unrecognized escape sequence in " + (char)d);
1171 if (putback_char != -1){
1172 int x = putback_char;
1177 return reader.Read ();
1182 if (putback_char != -1)
1183 return putback_char;
1184 putback_char = reader.Read ();
1185 return putback_char;
1190 if (putback_char != -1)
1191 return putback_char;
1192 return reader.Peek ();
1195 void putback (int c)
1197 if (putback_char != -1){
1198 Console.WriteLine ("Col: " + col);
1199 Console.WriteLine ("Row: " + line);
1200 Console.WriteLine ("Name: " + ref_name.Name);
1201 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1202 throw new Exception ("This should not happen putback on putback");
1207 public bool advance ()
1209 return peekChar () != -1;
1212 public Object Value {
1218 public Object value ()
1223 bool IsCastToken (int token)
1228 case Token.IDENTIFIER:
1229 case Token.LITERAL_INTEGER:
1230 case Token.LITERAL_FLOAT:
1231 case Token.LITERAL_DOUBLE:
1232 case Token.LITERAL_DECIMAL:
1233 case Token.LITERAL_CHARACTER:
1234 case Token.LITERAL_STRING:
1246 case Token.UNCHECKED:
1250 // These can be part of a member access
1270 current_token = xtoken ();
1272 if (current_token != Token.DEFAULT)
1273 return current_token;
1275 int c = consume_whitespace ();
1277 current_token = Token.ERROR;
1279 current_token = Token.DEFAULT_OPEN_PARENS;
1283 return current_token;
1286 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1288 void get_cmd_arg (out string cmd, out string arg)
1292 tokens_seen = false;
1294 static_cmd_arg.Length = 0;
1296 // skip over white space
1297 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1300 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1301 if (is_identifier_part_character ((char) c)){
1302 static_cmd_arg.Append ((char) c);
1310 cmd = static_cmd_arg.ToString ();
1316 } else if (c == '\r')
1319 // skip over white space
1320 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1327 } else if (c == '\r'){
1332 static_cmd_arg.Length = 0;
1333 static_cmd_arg.Append ((char) c);
1335 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1336 static_cmd_arg.Append ((char) c);
1342 } else if (c == '\r')
1344 arg = static_cmd_arg.ToString ().Trim ();
1348 // Handles the #line directive
1350 bool PreProcessLine (string arg)
1355 if (arg == "default"){
1357 ref_name = file_name;
1358 Location.Push (ref_name);
1360 } else if (arg == "hidden"){
1362 // We ignore #line hidden
1370 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1371 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1374 char [] quotes = { '\"' };
1376 string name = arg.Substring (pos). Trim (quotes);
1377 ref_name = Location.LookupFile (name);
1378 file_name.HasLineDirective = true;
1379 ref_name.HasLineDirective = true;
1380 Location.Push (ref_name);
1382 ref_line = System.Int32.Parse (arg);
1392 // Handles #define and #undef
1394 void PreProcessDefinition (bool is_define, string arg)
1396 if (arg == "" || arg == "true" || arg == "false"){
1397 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1401 char[] whitespace = { ' ', '\t' };
1402 if (arg.IndexOfAny (whitespace) != -1){
1403 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1407 if (!is_identifier_start_character (arg [0]))
1408 Report.Error (1001, Location, "Identifier expected: " + arg);
1410 foreach (char c in arg.Substring (1)){
1411 if (!is_identifier_part_character (c)){
1412 Report.Error (1001, Location, "Identifier expected: " + arg);
1418 if (defines == null)
1419 defines = new Hashtable ();
1422 if (defines == null)
1424 if (defines.Contains (arg))
1425 defines.Remove (arg);
1430 /// Handles #pragma directive
1432 void PreProcessPragma (string arg)
1434 const string disable = "warning disable";
1435 const string restore = "warning restore";
1437 if (arg == disable) {
1438 Report.RegisterWarningRegion (Location).WarningDisable (line);
1442 if (arg == restore) {
1443 Report.RegisterWarningRegion (Location).WarningEnable (line);
1447 if (arg.StartsWith (disable)) {
1448 int[] codes = ParseNumbers (arg.Substring (disable.Length));
1449 foreach (int code in codes) {
1451 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1456 if (arg.StartsWith (restore)) {
1457 int[] codes = ParseNumbers (arg.Substring (restore.Length));
1458 foreach (int code in codes) {
1459 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1467 int[] ParseNumbers (string text)
1469 string[] string_array = text.Split (',');
1470 int[] values = new int [string_array.Length];
1472 foreach (string string_code in string_array) {
1474 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1476 catch (FormatException) {
1477 Report.Warning (1692, Location, "Invalid number");
1483 bool eval_val (string s)
1490 if (defines == null)
1492 if (defines.Contains (s))
1498 bool pp_primary (ref string s)
1507 s = s.Substring (1);
1508 bool val = pp_expr (ref s);
1509 if (s.Length > 0 && s [0] == ')'){
1510 s = s.Substring (1);
1513 Error_InvalidDirective ();
1517 if (is_identifier_start_character (c)){
1523 if (is_identifier_part_character (c)){
1527 bool v = eval_val (s.Substring (0, j));
1528 s = s.Substring (j);
1531 bool vv = eval_val (s);
1536 Error_InvalidDirective ();
1540 bool pp_unary (ref string s)
1547 if (len > 1 && s [1] == '='){
1548 Error_InvalidDirective ();
1551 s = s.Substring (1);
1552 return ! pp_primary (ref s);
1554 return pp_primary (ref s);
1556 Error_InvalidDirective ();
1561 bool pp_eq (ref string s)
1563 bool va = pp_unary (ref s);
1569 if (len > 2 && s [1] == '='){
1570 s = s.Substring (2);
1571 return va == pp_unary (ref s);
1573 Error_InvalidDirective ();
1576 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1577 s = s.Substring (2);
1579 return va != pp_unary (ref s);
1588 bool pp_and (ref string s)
1590 bool va = pp_eq (ref s);
1596 if (len > 2 && s [1] == '&'){
1597 s = s.Substring (2);
1598 return (va & pp_eq (ref s));
1600 Error_InvalidDirective ();
1609 // Evaluates an expression for `#if' or `#elif'
1611 bool pp_expr (ref string s)
1613 bool va = pp_and (ref s);
1620 if (len > 2 && s [1] == '|'){
1621 s = s.Substring (2);
1622 return va | pp_expr (ref s);
1624 Error_InvalidDirective ();
1633 bool eval (string s)
1635 bool v = pp_expr (ref s);
1638 Error_InvalidDirective ();
1645 void Error_InvalidDirective ()
1647 Report.Error (1517, Location, "Invalid pre-processor directive");
1650 void Error_UnexpectedDirective (string extra)
1654 "Unexpected processor directive (" + extra + ")");
1657 void Error_TokensSeen ()
1661 "Cannot define or undefine pre-processor symbols after a token in the file");
1665 // if true, then the code continues processing the code
1666 // if false, the code stays in a loop until another directive is
1669 bool handle_preprocessing_directive (bool caller_is_taking)
1672 bool region_directive = false;
1674 get_cmd_arg (out cmd, out arg);
1676 // Eat any trailing whitespaces and single-line comments
1677 if (arg.IndexOf ("//") != -1)
1678 arg = arg.Substring (0, arg.IndexOf ("//"));
1679 arg = arg.TrimEnd (' ', '\t');
1682 // The first group of pre-processing instructions is always processed
1686 if (RootContext.Version == LanguageVersion.ISO_1) {
1687 Report.FeatureIsNotStandardized (Location, "#pragma");
1688 return caller_is_taking;
1691 PreProcessPragma (arg);
1692 return caller_is_taking;
1695 if (!PreProcessLine (arg))
1698 "Argument to #line directive is missing or invalid");
1699 return caller_is_taking;
1702 region_directive = true;
1707 region_directive = true;
1712 Error_InvalidDirective ();
1715 bool taking = false;
1716 if (ifstack == null)
1717 ifstack = new Stack ();
1719 if (ifstack.Count == 0){
1722 int state = (int) ifstack.Peek ();
1723 if ((state & TAKING) != 0)
1727 if (eval (arg) && taking){
1728 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1729 if (region_directive)
1731 ifstack.Push (push);
1734 int push = (taking ? PARENT_TAKING : 0);
1735 if (region_directive)
1737 ifstack.Push (push);
1742 if (ifstack == null || ifstack.Count == 0){
1743 Error_UnexpectedDirective ("no #if for this #endif");
1746 int pop = (int) ifstack.Pop ();
1748 if (region_directive && ((pop & REGION) == 0))
1749 Report.Error (1027, Location, "#endif directive expected");
1750 else if (!region_directive && ((pop & REGION) != 0))
1751 Report.Error (1038, Location, "#endregion directive expected");
1753 if (ifstack.Count == 0)
1756 int state = (int) ifstack.Peek ();
1758 if ((state & TAKING) != 0)
1766 if (ifstack == null || ifstack.Count == 0){
1767 Error_UnexpectedDirective ("no #if for this #elif");
1770 int state = (int) ifstack.Peek ();
1772 if ((state & REGION) != 0) {
1773 Report.Error (1038, Location, "#endregion directive expected");
1777 if ((state & ELSE_SEEN) != 0){
1778 Error_UnexpectedDirective ("#elif not valid after #else");
1782 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1785 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1786 state = (int) ifstack.Pop ();
1787 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1794 if (ifstack == null || ifstack.Count == 0){
1797 "Unexpected processor directive (no #if for this #else)");
1800 int state = (int) ifstack.Peek ();
1802 if ((state & REGION) != 0) {
1803 Report.Error (1038, Location, "#endregion directive expected");
1807 if ((state & ELSE_SEEN) != 0){
1808 Error_UnexpectedDirective ("#else within #else");
1815 if ((state & TAKEN_BEFORE) == 0){
1816 ret = ((state & PARENT_TAKING) != 0);
1825 ifstack.Push (state | ELSE_SEEN);
1832 // These are only processed if we are in a `taking' block
1834 if (!caller_is_taking)
1839 if (any_token_seen){
1840 Error_TokensSeen ();
1843 PreProcessDefinition (true, arg);
1847 if (any_token_seen){
1848 Error_TokensSeen ();
1851 PreProcessDefinition (false, arg);
1855 Report.Error (1029, Location, "#error: '" + arg + "'");
1859 Report.Warning (1030, Location, "#warning: '{0}'", arg);
1863 Report.Error (1024, Location, "Preprocessor directive expected (got: " + cmd + ")");
1868 private int consume_string (bool quoted)
1871 string_builder.Length = 0;
1873 while ((c = getChar ()) != -1){
1875 if (quoted && peekChar () == '"'){
1876 string_builder.Append ((char) c);
1880 val = string_builder.ToString ();
1881 return Token.LITERAL_STRING;
1887 Report.Error (1010, Location, "Newline in constant");
1899 string_builder.Append ((char) c);
1902 Report.Error (1039, Location, "Unterminated string literal");
1906 private int consume_identifier (int s)
1908 int res = consume_identifier (s, false);
1910 if (doc_state == XmlCommentState.Allowed)
1911 doc_state = XmlCommentState.NotAllowed;
1914 case Token.NAMESPACE:
1915 check_incorrect_doc_comment ();
1919 if (res == Token.PARTIAL) {
1920 // Save current position and parse next token.
1921 int old = reader.Position;
1922 int old_putback = putback_char;
1926 int next_token = token ();
1927 bool ok = (next_token == Token.CLASS) ||
1928 (next_token == Token.STRUCT) ||
1929 (next_token == Token.INTERFACE);
1931 reader.Position = old;
1932 putback_char = old_putback;
1938 return Token.IDENTIFIER;
1945 private int consume_identifier (int s, bool quoted)
1950 id_builder [0] = (char) s;
1952 while ((c = reader.Read ()) != -1) {
1953 if (is_identifier_part_character ((char) c)){
1954 if (pos == max_id_size){
1955 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1959 id_builder [pos++] = (char) c;
1969 // Optimization: avoids doing the keyword lookup
1970 // on uppercase letters and _
1972 if (!quoted && (s >= 'a' || s == '_')){
1973 int keyword = GetKeyword (id_builder, pos);
1979 // Keep identifiers in an array of hashtables to avoid needless
1983 if (identifiers [pos] != null) {
1984 val = identifiers [pos][id_builder];
1986 return Token.IDENTIFIER;
1990 identifiers [pos] = new CharArrayHashtable (pos);
1992 val = new String (id_builder, 0, pos);
1994 char [] chars = new char [pos];
1995 Array.Copy (id_builder, chars, pos);
1997 identifiers [pos] [chars] = val;
1999 return Token.IDENTIFIER;
2002 int consume_whitespace ()
2005 bool doread = false;
2009 // optimization: eliminate col and implement #directive semantic correctly.
2010 for (;(c = getChar ()) != -1; col++) {
2015 col = (((col + 8) / 8) * 8) - 1;
2019 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
2023 if (peekChar () == '\n')
2029 any_token_seen |= tokens_seen;
2030 tokens_seen = false;
2034 // Handle double-slash comments.
2036 int d = peekChar ();
2040 if (RootContext.Documentation != null && peekChar () == '/') {
2042 // Allow only ///ws.
2043 // Don't allow ////.
2044 if ((d = peekChar ()) == ' ' || d == '\t') {
2045 if (doc_state == XmlCommentState.Allowed)
2046 handle_one_line_xml_comment ();
2047 else if (doc_state == XmlCommentState.NotAllowed)
2048 warn_incorrect_doc_comment ();
2051 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2058 any_token_seen |= tokens_seen;
2059 tokens_seen = false;
2061 } else if (d == '*'){
2063 bool docAppend = false;
2064 if (RootContext.Documentation != null && peekChar () == '*') {
2066 // But when it is /**/, just do nothing.
2067 if (peekChar () == '/') {
2071 if (doc_state == XmlCommentState.Allowed)
2073 else if (doc_state == XmlCommentState.NotAllowed)
2074 warn_incorrect_doc_comment ();
2077 int currentCommentStart = 0;
2079 currentCommentStart = xml_comment_buffer.Length;
2080 xml_comment_buffer.Append (Environment.NewLine);
2083 while ((d = getChar ()) != -1){
2084 if (d == '*' && peekChar () == '/'){
2090 xml_comment_buffer.Append ((char) d);
2096 any_token_seen |= tokens_seen;
2097 tokens_seen = false;
2101 update_formatted_doc_comment (currentCommentStart);
2104 goto is_punct_label;
2113 any_token_seen |= tokens_seen;
2114 tokens_seen = false;
2118 /* For now, ignore pre-processor commands */
2119 // FIXME: In C# the '#' is not limited to appear
2120 // on the first column.
2121 if (c == '#' && !tokens_seen){
2126 cont = handle_preprocessing_directive (cont);
2134 bool skipping = false;
2135 for (;(c = getChar ()) != -1; col++){
2141 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2145 if (c == '#' && !skipping)
2148 any_token_seen |= tokens_seen;
2149 tokens_seen = false;
2151 Report.Error (1027, Location, "#endif/#endregion expected");
2161 public int xtoken ()
2164 bool doread = false;
2168 // optimization: eliminate col and implement #directive semantic correctly.
2170 c = consume_whitespace ();
2174 if (is_identifier_start_character ((char)c)){
2176 return consume_identifier (c);
2180 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2189 if (c >= '0' && c <= '9'){
2191 return is_number (c);
2196 int peek = peekChar ();
2197 if (peek >= '0' && peek <= '9')
2198 return is_number (c);
2203 return consume_string (false);
2209 error_details = "Empty character literal";
2210 Report.Error (1011, Location, error_details);
2216 val = new System.Char ();
2221 error_details = "Too many characters in character literal";
2222 Report.Error (1012, Location, error_details);
2224 // Try to recover, read until newline or next "'"
2225 while ((c = getChar ()) != -1){
2226 if (c == '\n' || c == '\''){
2236 return Token.LITERAL_CHARACTER;
2243 return consume_string (true);
2244 } else if (is_identifier_start_character ((char) c)){
2245 return consume_identifier (c, true);
2247 Report.Error (1033, Location, "'@' must be followed by string constant or identifier");
2252 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2253 "character on a line.";
2255 Report.Error (1040, Location, error_details);
2260 error_details = ((char)c).ToString ();
2266 // Handles one line xml comment
2268 private void handle_one_line_xml_comment ()
2271 while ((c = peekChar ()) == ' ')
2272 getChar (); // skip heading whitespaces.
2273 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2275 xml_comment_buffer.Append ((char) getChar ());
2277 if (c == '\r' || c == '\n')
2278 xml_comment_buffer.Append (Environment.NewLine);
2282 // Remove heading "*" in Javadoc-like xml documentation.
2284 private void update_formatted_doc_comment (int currentCommentStart)
2286 int length = xml_comment_buffer.Length - currentCommentStart;
2287 string [] lines = xml_comment_buffer.ToString (
2288 currentCommentStart,
2289 length).Replace ("\r", "").Split ('\n');
2290 // The first line starts with /**, thus it is not target
2291 // for the format check.
2292 for (int i = 1; i < lines.Length; i++) {
2293 string s = lines [i];
2294 int idx = s.IndexOf ('*');
2297 if (i < lines.Length - 1)
2302 head = s.Substring (0, idx);
2303 foreach (char c in head)
2306 lines [i] = s.Substring (idx + 1);
2308 xml_comment_buffer.Remove (currentCommentStart, length);
2309 xml_comment_buffer.Insert (
2310 currentCommentStart,
2311 String.Join (Environment.NewLine, lines));
2315 // Checks if there was incorrect doc comments and raise
2318 public void check_incorrect_doc_comment ()
2320 if (xml_comment_buffer.Length > 0)
2321 warn_incorrect_doc_comment ();
2325 // Raises a warning when tokenizer found incorrect doccomment
2328 private void warn_incorrect_doc_comment ()
2330 doc_state = XmlCommentState.Error;
2331 // in csc, it is 'XML comment is not placed on a valid
2332 // language element'. But that does not make sense.
2333 Report.Warning (1587, 2, Location, "XML comment is placed on an invalid language element which can not accept it.");
2337 // Consumes the saved xml comment lines (if any)
2338 // as for current target member or type.
2340 public string consume_doc_comment ()
2342 if (xml_comment_buffer.Length > 0) {
2343 string ret = xml_comment_buffer.ToString ();
2344 xml_comment_buffer.Length = 0;
2350 public void cleanup ()
2352 if (ifstack != null && ifstack.Count >= 1) {
2353 int state = (int) ifstack.Pop ();
2354 if ((state & REGION) != 0)
2355 Report.Error (1038, Location, "#endregion directive expected");
2357 Report.Error (1027, Location, "#endif directive expected");
2364 // Indicates whether it accepts XML documentation or not.
2366 public enum XmlCommentState {
2367 // comment is allowed in this state.
2369 // comment is not allowed in this state.
2371 // once comments appeared when it is NotAllowed, then the
2372 // state is changed to it, until the state is changed to