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;
70 static Hashtable tokenValues;
72 private static Hashtable TokenValueName
75 if (tokenValues == null)
76 tokenValues = GetTokenValueNameHash ();
82 private static Hashtable GetTokenValueNameHash ()
84 Type t = typeof (Token);
85 FieldInfo [] fields = t.GetFields ();
86 Hashtable hash = new Hashtable ();
87 foreach (FieldInfo field in fields) {
88 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
89 hash.Add (field.GetValue (null), field.Name);
95 // Returns a verbose representation of the current location
97 public string location {
101 if (current_token == Token.ERROR)
102 det = "detail: " + error_details;
106 // return "Line: "+line+" Col: "+col + "\n" +
107 // "VirtLine: "+ref_line +
108 // " Token: "+current_token + " " + det;
109 string current_token_name = TokenValueName [current_token] as string;
110 if (current_token_name == null)
111 current_token_name = current_token.ToString ();
113 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
121 public bool PropertyParsing {
123 return handle_get_set;
127 handle_get_set = value;
131 public bool AssemblyTargetParsing {
133 return handle_assembly;
137 handle_assembly = value;
141 public bool EventParsing {
143 return handle_remove_add;
147 handle_remove_add = value;
151 public bool ConstraintsParsing {
153 return handle_constraints;
157 handle_constraints = value;
161 public bool TypeOfParsing {
163 return handle_typeof;
167 handle_typeof = value;
171 public XmlCommentState doc_state {
172 get { return xmlDocState; }
174 if (value == XmlCommentState.Allowed) {
175 check_incorrect_doc_comment ();
176 consume_doc_comment ();
185 static CharArrayHashtable[] keywords;
186 static NumberStyles styles;
187 static NumberFormatInfo csharp_format_info;
190 // Values for the associated token returned
200 const int TAKING = 1;
201 const int TAKEN_BEFORE = 2;
202 const int ELSE_SEEN = 4;
203 const int PARENT_TAKING = 8;
204 const int REGION = 16;
207 // pre-processor if stack state:
211 static System.Text.StringBuilder string_builder;
213 const int max_id_size = 512;
214 static char [] id_builder = new char [max_id_size];
216 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
218 const int max_number_size = 128;
219 static char [] number_builder = new char [max_number_size];
220 static int number_pos;
223 // Details about the error encoutered by the tokenizer
225 string error_details;
227 public string error {
229 return error_details;
245 static void AddKeyword (string kw, int token) {
246 if (keywords [kw.Length] == null) {
247 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
249 keywords [kw.Length] [kw.ToCharArray ()] = token;
252 static void InitTokens ()
254 keywords = new CharArrayHashtable [64];
256 AddKeyword ("__arglist", Token.ARGLIST);
257 AddKeyword ("abstract", Token.ABSTRACT);
258 AddKeyword ("as", Token.AS);
259 AddKeyword ("add", Token.ADD);
260 AddKeyword ("assembly", Token.ASSEMBLY);
261 AddKeyword ("base", Token.BASE);
262 AddKeyword ("bool", Token.BOOL);
263 AddKeyword ("break", Token.BREAK);
264 AddKeyword ("byte", Token.BYTE);
265 AddKeyword ("case", Token.CASE);
266 AddKeyword ("catch", Token.CATCH);
267 AddKeyword ("char", Token.CHAR);
268 AddKeyword ("checked", Token.CHECKED);
269 AddKeyword ("class", Token.CLASS);
270 AddKeyword ("const", Token.CONST);
271 AddKeyword ("continue", Token.CONTINUE);
272 AddKeyword ("decimal", Token.DECIMAL);
273 AddKeyword ("default", Token.DEFAULT);
274 AddKeyword ("delegate", Token.DELEGATE);
275 AddKeyword ("do", Token.DO);
276 AddKeyword ("double", Token.DOUBLE);
277 AddKeyword ("else", Token.ELSE);
278 AddKeyword ("enum", Token.ENUM);
279 AddKeyword ("event", Token.EVENT);
280 AddKeyword ("explicit", Token.EXPLICIT);
281 AddKeyword ("extern", Token.EXTERN);
282 AddKeyword ("false", Token.FALSE);
283 AddKeyword ("finally", Token.FINALLY);
284 AddKeyword ("fixed", Token.FIXED);
285 AddKeyword ("float", Token.FLOAT);
286 AddKeyword ("for", Token.FOR);
287 AddKeyword ("foreach", Token.FOREACH);
288 AddKeyword ("goto", Token.GOTO);
289 AddKeyword ("get", Token.GET);
290 AddKeyword ("if", Token.IF);
291 AddKeyword ("implicit", Token.IMPLICIT);
292 AddKeyword ("in", Token.IN);
293 AddKeyword ("int", Token.INT);
294 AddKeyword ("interface", Token.INTERFACE);
295 AddKeyword ("internal", Token.INTERNAL);
296 AddKeyword ("is", Token.IS);
297 AddKeyword ("lock", Token.LOCK);
298 AddKeyword ("long", Token.LONG);
299 AddKeyword ("namespace", Token.NAMESPACE);
300 AddKeyword ("new", Token.NEW);
301 AddKeyword ("null", Token.NULL);
302 AddKeyword ("object", Token.OBJECT);
303 AddKeyword ("operator", Token.OPERATOR);
304 AddKeyword ("out", Token.OUT);
305 AddKeyword ("override", Token.OVERRIDE);
306 AddKeyword ("params", Token.PARAMS);
307 AddKeyword ("private", Token.PRIVATE);
308 AddKeyword ("protected", Token.PROTECTED);
309 AddKeyword ("public", Token.PUBLIC);
310 AddKeyword ("readonly", Token.READONLY);
311 AddKeyword ("ref", Token.REF);
312 AddKeyword ("remove", Token.REMOVE);
313 AddKeyword ("return", Token.RETURN);
314 AddKeyword ("sbyte", Token.SBYTE);
315 AddKeyword ("sealed", Token.SEALED);
316 AddKeyword ("set", Token.SET);
317 AddKeyword ("short", Token.SHORT);
318 AddKeyword ("sizeof", Token.SIZEOF);
319 AddKeyword ("stackalloc", Token.STACKALLOC);
320 AddKeyword ("static", Token.STATIC);
321 AddKeyword ("string", Token.STRING);
322 AddKeyword ("struct", Token.STRUCT);
323 AddKeyword ("switch", Token.SWITCH);
324 AddKeyword ("this", Token.THIS);
325 AddKeyword ("throw", Token.THROW);
326 AddKeyword ("true", Token.TRUE);
327 AddKeyword ("try", Token.TRY);
328 AddKeyword ("typeof", Token.TYPEOF);
329 AddKeyword ("uint", Token.UINT);
330 AddKeyword ("ulong", Token.ULONG);
331 AddKeyword ("unchecked", Token.UNCHECKED);
332 AddKeyword ("unsafe", Token.UNSAFE);
333 AddKeyword ("ushort", Token.USHORT);
334 AddKeyword ("using", Token.USING);
335 AddKeyword ("virtual", Token.VIRTUAL);
336 AddKeyword ("void", Token.VOID);
337 AddKeyword ("volatile", Token.VOLATILE);
338 AddKeyword ("where", Token.WHERE);
339 AddKeyword ("while", Token.WHILE);
340 AddKeyword ("partial", Token.PARTIAL);
349 csharp_format_info = NumberFormatInfo.InvariantInfo;
350 styles = NumberStyles.Float;
352 string_builder = new System.Text.StringBuilder ();
355 int GetKeyword (char[] id, int id_len)
358 * Keywords are stored in an array of hashtables grouped by their
362 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
364 object o = keywords [id_len] [id];
371 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
373 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
375 if (handle_assembly == false && res == Token.ASSEMBLY)
377 if (handle_constraints == false && res == Token.WHERE)
384 public Location Location {
386 return new Location (ref_line);
390 void define (string def)
392 if (!RootContext.AllDefines.Contains (def)){
393 RootContext.AllDefines [def] = true;
395 if (defines.Contains (def))
397 defines [def] = true;
400 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
402 this.ref_name = file;
403 this.file_name = file;
409 defines = new Hashtable ();
410 foreach (string def in defs)
414 xml_comment_buffer = new StringBuilder ();
417 // FIXME: This could be `Location.Push' but we have to
418 // find out why the MS compiler allows this
420 Mono.CSharp.Location.Push (file);
423 public static void Cleanup () {
427 static bool is_identifier_start_character (char c)
429 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
432 static bool is_identifier_part_character (char c)
434 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
437 public static bool IsValidIdentifier (string s)
439 if (s == null || s.Length == 0)
442 if (!is_identifier_start_character (s [0]))
445 for (int i = 1; i < s.Length; i ++)
446 if (! is_identifier_part_character (s [i]))
452 bool parse_generic_dimension (out int dimension)
457 int the_token = token ();
458 if (the_token == Token.OP_GENERICS_GT)
460 else if (the_token == Token.COMMA) {
468 bool parse_less_than ()
471 int the_token = token ();
473 case Token.IDENTIFIER:
496 the_token = token ();
498 if (the_token == Token.OP_GENERICS_GT)
500 else if ((the_token == Token.COMMA) || (the_token == Token.DOT))
502 else if (the_token == Token.INTERR)
504 else if (the_token == Token.OP_GENERICS_LT) {
505 if (!parse_less_than ())
508 } else if (the_token == Token.OPEN_BRACKET) {
510 the_token = token ();
511 if (the_token == Token.CLOSE_BRACKET)
513 else if (the_token == Token.COMMA)
514 goto rank_specifiers;
521 bool parsing_less_than = false;
522 int parsing_generic_less_than = 0;
524 int is_punct (char c, ref bool doread)
533 return Token.OPEN_BRACE;
535 return Token.CLOSE_BRACE;
537 // To block doccomment inside attribute declaration.
538 if (doc_state == XmlCommentState.Allowed)
539 doc_state = XmlCommentState.NotAllowed;
540 return Token.OPEN_BRACKET;
542 return Token.CLOSE_BRACKET;
544 return Token.OPEN_PARENS;
546 if (deambiguate_close_parens == 0)
547 return Token.CLOSE_PARENS;
549 --deambiguate_close_parens;
551 // Save current position and parse next token.
552 int old = reader.Position;
553 int new_token = token ();
554 reader.Position = old;
557 if (new_token == Token.OPEN_PARENS)
558 return Token.CLOSE_PARENS_OPEN_PARENS;
559 else if (new_token == Token.MINUS)
560 return Token.CLOSE_PARENS_MINUS;
561 else if (IsCastToken (new_token))
562 return Token.CLOSE_PARENS_CAST;
564 return Token.CLOSE_PARENS_NO_CAST;
572 return Token.SEMICOLON;
580 if (parsing_generic_less_than++ > 0)
581 return Token.OP_GENERICS_LT;
583 int old = reader.Position;
586 if (parse_generic_dimension (out dimension)) {
588 return Token.GENERIC_DIMENSION;
590 reader.Position = old;
594 // Save current position and parse next token.
595 old = reader.Position;
596 bool is_generic_lt = parse_less_than ();
597 reader.Position = old;
601 parsing_generic_less_than++;
602 return Token.OP_GENERICS_LT;
604 parsing_generic_less_than = 0;
613 return Token.OP_SHIFT_LEFT_ASSIGN;
615 return Token.OP_SHIFT_LEFT;
616 } else if (d == '='){
621 } else if (c == '>') {
622 if (parsing_generic_less_than > 0) {
623 parsing_generic_less_than--;
624 return Token.OP_GENERICS_GT;
634 return Token.OP_SHIFT_RIGHT_ASSIGN;
636 return Token.OP_SHIFT_RIGHT;
637 } else if (d == '='){
650 t = Token.OP_ADD_ASSIGN;
660 t = Token.OP_SUB_ASSIGN;
689 } else if (d == '='){
691 return Token.OP_AND_ASSIGN;
693 return Token.BITWISE_AND;
700 } else if (d == '='){
702 return Token.OP_OR_ASSIGN;
704 return Token.BITWISE_OR;
710 return Token.OP_MULT_ASSIGN;
718 return Token.OP_DIV_ASSIGN;
726 return Token.OP_MOD_ASSIGN;
728 return Token.PERCENT;
734 return Token.OP_XOR_ASSIGN;
742 int deambiguate_close_parens = 0;
744 public void Deambiguate_CloseParens ()
747 deambiguate_close_parens++;
750 public void PutbackNullable ()
752 if (nullable_pos < 0)
753 throw new Exception ();
757 reader.Position = nullable_pos;
762 public void PutbackCloseParens ()
767 void Error_NumericConstantTooLong ()
769 Report.Error (1021, Location, "Numeric constant too long");
772 int nullable_pos = -1;
774 public void CheckNullable (bool is_nullable)
777 nullable_pos = reader.Position;
782 bool decimal_digits (int c)
785 bool seen_digits = false;
788 if (number_pos == max_number_size)
789 Error_NumericConstantTooLong ();
790 number_builder [number_pos++] = (char) c;
794 // We use peekChar2, because decimal_digits needs to do a
795 // 2-character look-ahead (5.ToString for example).
797 while ((d = peekChar2 ()) != -1){
798 if (d >= '0' && d <= '9'){
799 if (number_pos == max_number_size)
800 Error_NumericConstantTooLong ();
801 number_builder [number_pos++] = (char) d;
813 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
816 void hex_digits (int c)
819 number_builder [number_pos++] = (char) c;
823 int real_type_suffix (int c)
829 t = Token.LITERAL_FLOAT;
832 t = Token.LITERAL_DOUBLE;
835 t= Token.LITERAL_DECIMAL;
843 int integer_type_suffix (ulong ul, int c)
845 bool is_unsigned = false;
846 bool is_long = false;
849 bool scanning = true;
860 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
862 // if we have not seen anything in between
865 Report.Warning (78, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
868 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
893 if (is_long && is_unsigned){
895 return Token.LITERAL_INTEGER;
896 } else if (is_unsigned){
897 // uint if possible, or ulong else.
899 if ((ul & 0xffffffff00000000) == 0)
904 // long if possible, ulong otherwise
905 if ((ul & 0x8000000000000000) != 0)
910 // int, uint, long or ulong in that order
911 if ((ul & 0xffffffff00000000) == 0){
914 if ((ui & 0x80000000) != 0)
919 if ((ul & 0x8000000000000000) != 0)
925 return Token.LITERAL_INTEGER;
929 // given `c' as the next char in the input decide whether
930 // we need to convert to a special type, and then choose
931 // the best representation for the integer
933 int adjust_int (int c)
937 ulong ul = (uint) (number_builder [0] - '0');
939 for (int i = 1; i < number_pos; i++){
940 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
942 return integer_type_suffix (ul, c);
944 uint ui = (uint) (number_builder [0] - '0');
946 for (int i = 1; i < number_pos; i++){
947 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
949 return integer_type_suffix (ui, c);
951 } catch (OverflowException) {
952 error_details = "Integral constant is too large";
953 Report.Error (1021, Location, error_details);
955 return Token.LITERAL_INTEGER;
957 catch (FormatException) {
958 Report.Error (1013, Location, "Invalid number");
960 return Token.LITERAL_INTEGER;
964 int adjust_real (int t)
966 string s = new String (number_builder, 0, number_pos);
969 case Token.LITERAL_DECIMAL:
971 val = System.Decimal.Parse (s, styles, csharp_format_info);
972 } catch (OverflowException) {
974 error_details = "Floating-point constant is outside the range of the type 'decimal'";
975 Report.Error (594, Location, error_details);
978 case Token.LITERAL_FLOAT:
980 val = (float) System.Double.Parse (s, styles, csharp_format_info);
981 } catch (OverflowException) {
983 error_details = "Floating-point constant is outside the range of the type 'float'";
984 Report.Error (594, Location, error_details);
988 case Token.LITERAL_DOUBLE:
990 t = Token.LITERAL_DOUBLE;
992 val = System.Double.Parse (s, styles, csharp_format_info);
993 } catch (OverflowException) {
995 error_details = "Floating-point constant is outside the range of the type 'double'";
996 Report.Error (594, Location, error_details);
1009 while ((d = peekChar ()) != -1){
1011 number_builder [number_pos++] = (char) d;
1017 string s = new String (number_builder, 0, number_pos);
1019 if (number_pos <= 8)
1020 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1022 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1023 } catch (OverflowException){
1024 error_details = "Integral constant is too large";
1025 Report.Error (1021, Location, error_details);
1027 return Token.LITERAL_INTEGER;
1030 return integer_type_suffix (ul, peekChar ());
1034 // Invoked if we know we have .digits or digits
1036 int is_number (int c)
1038 bool is_real = false;
1043 if (c >= '0' && c <= '9'){
1045 int peek = peekChar ();
1047 if (peek == 'x' || peek == 'X')
1048 return handle_hex ();
1055 // We need to handle the case of
1056 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1059 if (decimal_digits ('.')){
1065 return adjust_int (-1);
1069 if (c == 'e' || c == 'E'){
1071 if (number_pos == max_number_size)
1072 Error_NumericConstantTooLong ();
1073 number_builder [number_pos++] = 'e';
1077 if (number_pos == max_number_size)
1078 Error_NumericConstantTooLong ();
1079 number_builder [number_pos++] = '+';
1081 } else if (c == '-') {
1082 if (number_pos == max_number_size)
1083 Error_NumericConstantTooLong ();
1084 number_builder [number_pos++] = '-';
1087 if (number_pos == max_number_size)
1088 Error_NumericConstantTooLong ();
1089 number_builder [number_pos++] = '+';
1096 type = real_type_suffix (c);
1097 if (type == Token.NONE && !is_real){
1099 return adjust_int (c);
1103 if (type == Token.NONE){
1108 return adjust_real (type);
1110 Console.WriteLine ("This should not be reached");
1111 throw new Exception ("Is Number should never reach this point");
1115 // Accepts exactly count (4 or 8) hex, no more no less
1117 int getHex (int count, out bool error)
1122 int top = count != -1 ? count : 4;
1126 for (i = 0; i < top; i++){
1129 if (c >= '0' && c <= '9')
1130 c = (int) c - (int) '0';
1131 else if (c >= 'A' && c <= 'F')
1132 c = (int) c - (int) 'A' + 10;
1133 else if (c >= 'a' && c <= 'f')
1134 c = (int) c - (int) 'a' + 10;
1140 total = (total * 16) + c;
1142 int p = peekChar ();
1145 if (!is_hex ((char)p))
1186 v = getHex (-1, out error);
1191 v = getHex (4, out error);
1196 v = getHex (8, out error);
1201 Report.Error (1009, Location, "Unrecognized escape sequence in " + (char)d);
1210 if (putback_char != -1){
1211 int x = putback_char;
1216 return reader.Read ();
1221 if (putback_char != -1)
1222 return putback_char;
1223 putback_char = reader.Read ();
1224 return putback_char;
1229 if (putback_char != -1)
1230 return putback_char;
1231 return reader.Peek ();
1234 void putback (int c)
1236 if (putback_char != -1){
1237 Console.WriteLine ("Col: " + col);
1238 Console.WriteLine ("Row: " + line);
1239 Console.WriteLine ("Name: " + ref_name.Name);
1240 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1241 throw new Exception ("This should not happen putback on putback");
1246 public bool advance ()
1248 return peekChar () != -1;
1251 public Object Value {
1257 public Object value ()
1262 bool IsCastToken (int token)
1267 case Token.IDENTIFIER:
1268 case Token.LITERAL_INTEGER:
1269 case Token.LITERAL_FLOAT:
1270 case Token.LITERAL_DOUBLE:
1271 case Token.LITERAL_DECIMAL:
1272 case Token.LITERAL_CHARACTER:
1273 case Token.LITERAL_STRING:
1285 case Token.UNCHECKED:
1289 // These can be part of a member access
1309 current_token = xtoken ();
1311 if (current_token != Token.DEFAULT)
1312 return current_token;
1314 int c = consume_whitespace ();
1316 current_token = Token.ERROR;
1318 current_token = Token.DEFAULT_OPEN_PARENS;
1322 return current_token;
1325 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1327 void get_cmd_arg (out string cmd, out string arg)
1331 tokens_seen = false;
1333 static_cmd_arg.Length = 0;
1335 // skip over white space
1336 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1339 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1340 if (is_identifier_part_character ((char) c)){
1341 static_cmd_arg.Append ((char) c);
1349 cmd = static_cmd_arg.ToString ();
1355 } else if (c == '\r')
1358 // skip over white space
1359 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1366 } else if (c == '\r'){
1371 static_cmd_arg.Length = 0;
1372 static_cmd_arg.Append ((char) c);
1374 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1375 static_cmd_arg.Append ((char) c);
1381 } else if (c == '\r')
1383 arg = static_cmd_arg.ToString ().Trim ();
1387 // Handles the #line directive
1389 bool PreProcessLine (string arg)
1394 if (arg == "default"){
1396 ref_name = file_name;
1397 Location.Push (ref_name);
1399 } else if (arg == "hidden"){
1401 // We ignore #line hidden
1409 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1410 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1413 char [] quotes = { '\"' };
1415 string name = arg.Substring (pos). Trim (quotes);
1416 ref_name = Location.LookupFile (name);
1417 file_name.HasLineDirective = true;
1418 ref_name.HasLineDirective = true;
1419 Location.Push (ref_name);
1421 ref_line = System.Int32.Parse (arg);
1431 // Handles #define and #undef
1433 void PreProcessDefinition (bool is_define, string arg)
1435 if (arg == "" || arg == "true" || arg == "false"){
1436 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1440 char[] whitespace = { ' ', '\t' };
1441 if (arg.IndexOfAny (whitespace) != -1){
1442 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1446 if (!is_identifier_start_character (arg [0]))
1447 Report.Error (1001, Location, "Identifier expected: " + arg);
1449 foreach (char c in arg.Substring (1)){
1450 if (!is_identifier_part_character (c)){
1451 Report.Error (1001, Location, "Identifier expected: " + arg);
1457 if (defines == null)
1458 defines = new Hashtable ();
1461 if (defines == null)
1463 if (defines.Contains (arg))
1464 defines.Remove (arg);
1469 /// Handles #pragma directive
1471 void PreProcessPragma (string arg)
1473 const string disable = "warning disable";
1474 const string restore = "warning restore";
1476 if (arg == disable) {
1477 Report.RegisterWarningRegion (Location).WarningDisable (line);
1481 if (arg == restore) {
1482 Report.RegisterWarningRegion (Location).WarningEnable (line);
1486 if (arg.StartsWith (disable)) {
1487 int[] codes = ParseNumbers (arg.Substring (disable.Length));
1488 foreach (int code in codes) {
1490 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1495 if (arg.StartsWith (restore)) {
1496 int[] codes = ParseNumbers (arg.Substring (restore.Length));
1497 foreach (int code in codes) {
1498 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1506 int[] ParseNumbers (string text)
1508 string[] string_array = text.Split (',');
1509 int[] values = new int [string_array.Length];
1511 foreach (string string_code in string_array) {
1513 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1515 catch (FormatException) {
1516 Report.Warning (1692, Location, "Invalid number");
1522 bool eval_val (string s)
1529 if (defines == null)
1531 if (defines.Contains (s))
1537 bool pp_primary (ref string s)
1546 s = s.Substring (1);
1547 bool val = pp_expr (ref s);
1548 if (s.Length > 0 && s [0] == ')'){
1549 s = s.Substring (1);
1552 Error_InvalidDirective ();
1556 if (is_identifier_start_character (c)){
1562 if (is_identifier_part_character (c)){
1566 bool v = eval_val (s.Substring (0, j));
1567 s = s.Substring (j);
1570 bool vv = eval_val (s);
1575 Error_InvalidDirective ();
1579 bool pp_unary (ref string s)
1586 if (len > 1 && s [1] == '='){
1587 Error_InvalidDirective ();
1590 s = s.Substring (1);
1591 return ! pp_primary (ref s);
1593 return pp_primary (ref s);
1595 Error_InvalidDirective ();
1600 bool pp_eq (ref string s)
1602 bool va = pp_unary (ref s);
1608 if (len > 2 && s [1] == '='){
1609 s = s.Substring (2);
1610 return va == pp_unary (ref s);
1612 Error_InvalidDirective ();
1615 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1616 s = s.Substring (2);
1618 return va != pp_unary (ref s);
1627 bool pp_and (ref string s)
1629 bool va = pp_eq (ref s);
1635 if (len > 2 && s [1] == '&'){
1636 s = s.Substring (2);
1637 return (va & pp_and (ref s));
1639 Error_InvalidDirective ();
1648 // Evaluates an expression for `#if' or `#elif'
1650 bool pp_expr (ref string s)
1652 bool va = pp_and (ref s);
1659 if (len > 2 && s [1] == '|'){
1660 s = s.Substring (2);
1661 return va | pp_expr (ref s);
1663 Error_InvalidDirective ();
1672 bool eval (string s)
1674 bool v = pp_expr (ref s);
1677 Error_InvalidDirective ();
1684 void Error_InvalidDirective ()
1686 Report.Error (1517, Location, "Invalid pre-processor directive");
1689 void Error_UnexpectedDirective (string extra)
1693 "Unexpected processor directive (" + extra + ")");
1696 void Error_TokensSeen ()
1700 "Cannot define or undefine pre-processor symbols after a token in the file");
1704 // if true, then the code continues processing the code
1705 // if false, the code stays in a loop until another directive is
1708 bool handle_preprocessing_directive (bool caller_is_taking)
1711 bool region_directive = false;
1713 get_cmd_arg (out cmd, out arg);
1715 // Eat any trailing whitespaces and single-line comments
1716 if (arg.IndexOf ("//") != -1)
1717 arg = arg.Substring (0, arg.IndexOf ("//"));
1718 arg = arg.TrimEnd (' ', '\t');
1721 // The first group of pre-processing instructions is always processed
1725 if (RootContext.Version == LanguageVersion.ISO_1) {
1726 Report.FeatureIsNotStandardized (Location, "#pragma");
1727 return caller_is_taking;
1730 PreProcessPragma (arg);
1731 return caller_is_taking;
1734 if (!PreProcessLine (arg))
1737 "Argument to #line directive is missing or invalid");
1738 return caller_is_taking;
1741 region_directive = true;
1746 region_directive = true;
1751 Error_InvalidDirective ();
1754 bool taking = false;
1755 if (ifstack == null)
1756 ifstack = new Stack ();
1758 if (ifstack.Count == 0){
1761 int state = (int) ifstack.Peek ();
1762 if ((state & TAKING) != 0)
1766 if (eval (arg) && taking){
1767 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1768 if (region_directive)
1770 ifstack.Push (push);
1773 int push = (taking ? PARENT_TAKING : 0);
1774 if (region_directive)
1776 ifstack.Push (push);
1781 if (ifstack == null || ifstack.Count == 0){
1782 Error_UnexpectedDirective ("no #if for this #endif");
1785 int pop = (int) ifstack.Pop ();
1787 if (region_directive && ((pop & REGION) == 0))
1788 Report.Error (1027, Location, "#endif directive expected");
1789 else if (!region_directive && ((pop & REGION) != 0))
1790 Report.Error (1038, Location, "#endregion directive expected");
1792 if (ifstack.Count == 0)
1795 int state = (int) ifstack.Peek ();
1797 if ((state & TAKING) != 0)
1805 if (ifstack == null || ifstack.Count == 0){
1806 Error_UnexpectedDirective ("no #if for this #elif");
1809 int state = (int) ifstack.Peek ();
1811 if ((state & REGION) != 0) {
1812 Report.Error (1038, Location, "#endregion directive expected");
1816 if ((state & ELSE_SEEN) != 0){
1817 Error_UnexpectedDirective ("#elif not valid after #else");
1821 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1824 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1825 state = (int) ifstack.Pop ();
1826 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1833 if (ifstack == null || ifstack.Count == 0){
1836 "Unexpected processor directive (no #if for this #else)");
1839 int state = (int) ifstack.Peek ();
1841 if ((state & REGION) != 0) {
1842 Report.Error (1038, Location, "#endregion directive expected");
1846 if ((state & ELSE_SEEN) != 0){
1847 Error_UnexpectedDirective ("#else within #else");
1854 if ((state & TAKEN_BEFORE) == 0){
1855 ret = ((state & PARENT_TAKING) != 0);
1864 ifstack.Push (state | ELSE_SEEN);
1871 // These are only processed if we are in a `taking' block
1873 if (!caller_is_taking)
1878 if (any_token_seen){
1879 Error_TokensSeen ();
1882 PreProcessDefinition (true, arg);
1886 if (any_token_seen){
1887 Error_TokensSeen ();
1890 PreProcessDefinition (false, arg);
1894 Report.Error (1029, Location, "#error: '" + arg + "'");
1898 Report.Warning (1030, Location, "#warning: '{0}'", arg);
1902 Report.Error (1024, Location, "Preprocessor directive expected (got: " + cmd + ")");
1907 private int consume_string (bool quoted)
1910 string_builder.Length = 0;
1912 while ((c = getChar ()) != -1){
1914 if (quoted && peekChar () == '"'){
1915 string_builder.Append ((char) c);
1919 val = string_builder.ToString ();
1920 return Token.LITERAL_STRING;
1926 Report.Error (1010, Location, "Newline in constant");
1938 string_builder.Append ((char) c);
1941 Report.Error (1039, Location, "Unterminated string literal");
1945 private int consume_identifier (int s)
1947 int res = consume_identifier (s, false);
1949 if (doc_state == XmlCommentState.Allowed)
1950 doc_state = XmlCommentState.NotAllowed;
1953 case Token.NAMESPACE:
1954 check_incorrect_doc_comment ();
1958 if (res == Token.PARTIAL) {
1959 // Save current position and parse next token.
1960 int old = reader.Position;
1961 int old_putback = putback_char;
1965 int next_token = token ();
1966 bool ok = (next_token == Token.CLASS) ||
1967 (next_token == Token.STRUCT) ||
1968 (next_token == Token.INTERFACE);
1970 reader.Position = old;
1971 putback_char = old_putback;
1977 return Token.IDENTIFIER;
1984 private int consume_identifier (int s, bool quoted)
1989 id_builder [0] = (char) s;
1991 while ((c = reader.Read ()) != -1) {
1992 if (is_identifier_part_character ((char) c)){
1993 if (pos == max_id_size){
1994 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1998 id_builder [pos++] = (char) c;
2008 // Optimization: avoids doing the keyword lookup
2009 // on uppercase letters and _
2011 if (!quoted && (s >= 'a' || s == '_')){
2012 int keyword = GetKeyword (id_builder, pos);
2018 // Keep identifiers in an array of hashtables to avoid needless
2022 if (identifiers [pos] != null) {
2023 val = identifiers [pos][id_builder];
2025 return Token.IDENTIFIER;
2029 identifiers [pos] = new CharArrayHashtable (pos);
2031 val = new String (id_builder, 0, pos);
2033 char [] chars = new char [pos];
2034 Array.Copy (id_builder, chars, pos);
2036 identifiers [pos] [chars] = val;
2038 return Token.IDENTIFIER;
2041 int consume_whitespace ()
2045 // Whether we have seen comments on the current line
2046 bool comments_seen = false;
2049 // optimization: eliminate col and implement #directive semantic correctly.
2050 for (;(c = getChar ()) != -1; col++) {
2055 col = (((col + 8) / 8) * 8) - 1;
2059 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
2063 if (peekChar () == '\n')
2069 any_token_seen |= tokens_seen;
2070 tokens_seen = false;
2071 comments_seen = false;
2075 // Handle double-slash comments.
2077 int d = peekChar ();
2081 if (RootContext.Documentation != null && peekChar () == '/') {
2083 // Don't allow ////.
2084 if ((d = peekChar ()) != '/') {
2085 if (doc_state == XmlCommentState.Allowed)
2086 handle_one_line_xml_comment ();
2087 else if (doc_state == XmlCommentState.NotAllowed)
2088 warn_incorrect_doc_comment ();
2091 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2098 any_token_seen |= tokens_seen;
2099 tokens_seen = false;
2100 comments_seen = false;
2102 } else if (d == '*'){
2104 bool docAppend = false;
2105 if (RootContext.Documentation != null && peekChar () == '*') {
2107 // But when it is /**/, just do nothing.
2108 if (peekChar () == '/') {
2112 if (doc_state == XmlCommentState.Allowed)
2114 else if (doc_state == XmlCommentState.NotAllowed)
2115 warn_incorrect_doc_comment ();
2118 int current_comment_start = 0;
2120 current_comment_start = xml_comment_buffer.Length;
2121 xml_comment_buffer.Append (Environment.NewLine);
2124 while ((d = getChar ()) != -1){
2125 if (d == '*' && peekChar () == '/'){
2128 comments_seen = true;
2132 xml_comment_buffer.Append ((char) d);
2138 any_token_seen |= tokens_seen;
2139 tokens_seen = false;
2141 // Reset 'comments_seen' just to be consistent.
2142 // It doesn't matter either way, here.
2144 comments_seen = false;
2148 update_formatted_doc_comment (current_comment_start);
2151 goto is_punct_label;
2160 any_token_seen |= tokens_seen;
2161 tokens_seen = false;
2162 comments_seen = false;
2166 /* For now, ignore pre-processor commands */
2167 // FIXME: In C# the '#' is not limited to appear
2168 // on the first column.
2172 if (tokens_seen || comments_seen) {
2173 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2174 "character on a line.";
2176 Report.Error (1040, Location, error_details);
2183 cont = handle_preprocessing_directive (cont);
2191 bool skipping = false;
2192 for (;(c = getChar ()) != -1; col++){
2198 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2202 if (c == '#' && !skipping)
2205 any_token_seen |= tokens_seen;
2206 tokens_seen = false;
2208 Report.Error (1027, Location, "#endif/#endregion expected");
2218 public int xtoken ()
2221 bool doread = false;
2225 // optimization: eliminate col and implement #directive semantic correctly.
2227 c = consume_whitespace ();
2231 if (is_identifier_start_character ((char)c)){
2233 return consume_identifier (c);
2237 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2246 if (c >= '0' && c <= '9'){
2248 return is_number (c);
2253 int peek = peekChar ();
2254 if (peek >= '0' && peek <= '9')
2255 return is_number (c);
2260 return consume_string (false);
2266 error_details = "Empty character literal";
2267 Report.Error (1011, Location, error_details);
2273 val = new System.Char ();
2278 error_details = "Too many characters in character literal";
2279 Report.Error (1012, Location, error_details);
2281 // Try to recover, read until newline or next "'"
2282 while ((c = getChar ()) != -1){
2283 if (c == '\n' || c == '\''){
2293 return Token.LITERAL_CHARACTER;
2300 return consume_string (true);
2301 } else if (is_identifier_start_character ((char) c)){
2302 return consume_identifier (c, true);
2304 Report.Error (1033, Location, "'@' must be followed by string constant or identifier");
2309 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2310 "character on a line.";
2312 Report.Error (1040, Location, error_details);
2317 error_details = ((char)c).ToString ();
2323 // Handles one line xml comment
2325 private void handle_one_line_xml_comment ()
2328 while ((c = peekChar ()) == ' ')
2329 getChar (); // skip heading whitespaces.
2330 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2332 xml_comment_buffer.Append ((char) getChar ());
2334 if (c == '\r' || c == '\n')
2335 xml_comment_buffer.Append (Environment.NewLine);
2339 // Remove heading "*" in Javadoc-like xml documentation.
2341 private void update_formatted_doc_comment (int current_comment_start)
2343 int length = xml_comment_buffer.Length - current_comment_start;
2344 string [] lines = xml_comment_buffer.ToString (
2345 current_comment_start,
2346 length).Replace ("\r", "").Split ('\n');
2348 // The first line starts with /**, thus it is not target
2349 // for the format check.
2350 for (int i = 1; i < lines.Length; i++) {
2351 string s = lines [i];
2352 int idx = s.IndexOf ('*');
2355 if (i < lines.Length - 1)
2359 head = s.Substring (0, idx);
2360 foreach (char c in head)
2363 lines [i] = s.Substring (idx + 1);
2365 xml_comment_buffer.Remove (current_comment_start, length);
2366 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2370 // Checks if there was incorrect doc comments and raise
2373 public void check_incorrect_doc_comment ()
2375 if (xml_comment_buffer.Length > 0)
2376 warn_incorrect_doc_comment ();
2380 // Raises a warning when tokenizer found incorrect doccomment
2383 private void warn_incorrect_doc_comment ()
2385 doc_state = XmlCommentState.Error;
2386 // in csc, it is 'XML comment is not placed on a valid
2387 // language element'. But that does not make sense.
2388 Report.Warning (1587, 2, Location, "XML comment is placed on an invalid language element which can not accept it.");
2392 // Consumes the saved xml comment lines (if any)
2393 // as for current target member or type.
2395 public string consume_doc_comment ()
2397 if (xml_comment_buffer.Length > 0) {
2398 string ret = xml_comment_buffer.ToString ();
2399 xml_comment_buffer.Length = 0;
2405 public void cleanup ()
2407 if (ifstack != null && ifstack.Count >= 1) {
2408 int state = (int) ifstack.Pop ();
2409 if ((state & REGION) != 0)
2410 Report.Error (1038, Location, "#endregion directive expected");
2412 Report.Error (1027, Location, "#endif directive expected");
2419 // Indicates whether it accepts XML documentation or not.
2421 public enum XmlCommentState {
2422 // comment is allowed in this state.
2424 // comment is not allowed in this state.
2426 // once comments appeared when it is NotAllowed, then the
2427 // state is changed to it, until the state is changed to