2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 // This also implements the preprocessor
5 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
16 * Make sure we accept the proper Unicode ranges, per the spec.
22 using System.Collections;
24 using System.Globalization;
25 using System.Reflection;
30 /// Tokenizer for C# source code.
33 public class Tokenizer : yyParser.yyInput
35 SeekableStreamReader reader;
43 bool handle_get_set = false;
44 bool handle_remove_add = false;
45 bool handle_assembly = false;
46 Location current_location;
47 Location current_comment_location = Location.Null;
48 ArrayList escapedIdentifiers = new ArrayList ();
51 // XML documentation buffer. The save point is used to divide
52 // comments on types and comments on members.
54 StringBuilder xml_comment_buffer;
57 // See comment on XmlCommentState enumeration.
59 XmlCommentState xmlDocState = XmlCommentState.Allowed;
62 // Whether tokens have been seen on this line
64 bool tokens_seen = false;
67 // Whether a token has been seen on the file
68 // This is needed because `define' is not allowed to be used
69 // after a token has been seen.
71 bool any_token_seen = false;
73 static Hashtable tokenValues;
75 private static Hashtable TokenValueName
78 if (tokenValues == null)
79 tokenValues = GetTokenValueNameHash ();
85 private static Hashtable GetTokenValueNameHash ()
87 Type t = typeof (Token);
88 FieldInfo [] fields = t.GetFields ();
89 Hashtable hash = new Hashtable ();
90 foreach (FieldInfo field in fields) {
91 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
92 hash.Add (field.GetValue (null), field.Name);
98 // Returns a verbose representation of the current location
100 public string location {
104 if (current_token == Token.ERROR)
105 det = "detail: " + error_details;
109 // return "Line: "+line+" Col: "+col + "\n" +
110 // "VirtLine: "+ref_line +
111 // " Token: "+current_token + " " + det;
112 string current_token_name = TokenValueName [current_token] as string;
113 if (current_token_name == null)
114 current_token_name = current_token.ToString ();
116 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
124 public bool PropertyParsing {
126 return handle_get_set;
130 handle_get_set = value;
134 public bool AssemblyTargetParsing {
136 return handle_assembly;
140 handle_assembly = value;
144 public bool EventParsing {
146 return handle_remove_add;
150 handle_remove_add = value;
154 public XmlCommentState doc_state {
155 get { return xmlDocState; }
157 if (value == XmlCommentState.Allowed) {
158 check_incorrect_doc_comment ();
159 reset_doc_comment ();
165 public bool IsEscapedIdentifier (Location loc)
167 foreach (LocatedToken lt in escapedIdentifiers)
168 if (lt.Location.Equals (loc))
177 static CharArrayHashtable[] keywords;
178 static Hashtable keywordStrings = new Hashtable ();
179 static NumberStyles styles;
180 static NumberFormatInfo csharp_format_info;
183 // Values for the associated token returned
193 const int TAKING = 1;
194 const int TAKEN_BEFORE = 2;
195 const int ELSE_SEEN = 4;
196 const int PARENT_TAKING = 8;
197 const int REGION = 16;
200 // pre-processor if stack state:
204 static System.Text.StringBuilder string_builder;
206 const int max_id_size = 512;
207 static char [] id_builder = new char [max_id_size];
209 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
211 const int max_number_size = 512;
212 static char [] number_builder = new char [max_number_size];
213 static int number_pos;
216 // Details about the error encoutered by the tokenizer
218 string error_details;
220 public string error {
222 return error_details;
238 static void AddKeyword (string kw, int token) {
239 keywordStrings.Add (kw, kw);
240 if (keywords [kw.Length] == null) {
241 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
243 keywords [kw.Length] [kw.ToCharArray ()] = token;
246 static void InitTokens ()
248 keywords = new CharArrayHashtable [64];
250 AddKeyword ("__arglist", Token.ARGLIST);
251 AddKeyword ("abstract", Token.ABSTRACT);
252 AddKeyword ("as", Token.AS);
253 AddKeyword ("add", Token.ADD);
254 AddKeyword ("assembly", Token.ASSEMBLY);
255 AddKeyword ("base", Token.BASE);
256 AddKeyword ("bool", Token.BOOL);
257 AddKeyword ("break", Token.BREAK);
258 AddKeyword ("byte", Token.BYTE);
259 AddKeyword ("case", Token.CASE);
260 AddKeyword ("catch", Token.CATCH);
261 AddKeyword ("char", Token.CHAR);
262 AddKeyword ("checked", Token.CHECKED);
263 AddKeyword ("class", Token.CLASS);
264 AddKeyword ("const", Token.CONST);
265 AddKeyword ("continue", Token.CONTINUE);
266 AddKeyword ("decimal", Token.DECIMAL);
267 AddKeyword ("default", Token.DEFAULT);
268 AddKeyword ("delegate", Token.DELEGATE);
269 AddKeyword ("do", Token.DO);
270 AddKeyword ("double", Token.DOUBLE);
271 AddKeyword ("else", Token.ELSE);
272 AddKeyword ("enum", Token.ENUM);
273 AddKeyword ("event", Token.EVENT);
274 AddKeyword ("explicit", Token.EXPLICIT);
275 AddKeyword ("extern", Token.EXTERN);
276 AddKeyword ("false", Token.FALSE);
277 AddKeyword ("finally", Token.FINALLY);
278 AddKeyword ("fixed", Token.FIXED);
279 AddKeyword ("float", Token.FLOAT);
280 AddKeyword ("for", Token.FOR);
281 AddKeyword ("foreach", Token.FOREACH);
282 AddKeyword ("goto", Token.GOTO);
283 AddKeyword ("get", Token.GET);
284 AddKeyword ("if", Token.IF);
285 AddKeyword ("implicit", Token.IMPLICIT);
286 AddKeyword ("in", Token.IN);
287 AddKeyword ("int", Token.INT);
288 AddKeyword ("interface", Token.INTERFACE);
289 AddKeyword ("internal", Token.INTERNAL);
290 AddKeyword ("is", Token.IS);
291 AddKeyword ("lock", Token.LOCK);
292 AddKeyword ("long", Token.LONG);
293 AddKeyword ("namespace", Token.NAMESPACE);
294 AddKeyword ("new", Token.NEW);
295 AddKeyword ("null", Token.NULL);
296 AddKeyword ("object", Token.OBJECT);
297 AddKeyword ("operator", Token.OPERATOR);
298 AddKeyword ("out", Token.OUT);
299 AddKeyword ("override", Token.OVERRIDE);
300 AddKeyword ("params", Token.PARAMS);
301 AddKeyword ("private", Token.PRIVATE);
302 AddKeyword ("protected", Token.PROTECTED);
303 AddKeyword ("public", Token.PUBLIC);
304 AddKeyword ("readonly", Token.READONLY);
305 AddKeyword ("ref", Token.REF);
306 AddKeyword ("remove", Token.REMOVE);
307 AddKeyword ("return", Token.RETURN);
308 AddKeyword ("sbyte", Token.SBYTE);
309 AddKeyword ("sealed", Token.SEALED);
310 AddKeyword ("set", Token.SET);
311 AddKeyword ("short", Token.SHORT);
312 AddKeyword ("sizeof", Token.SIZEOF);
313 AddKeyword ("stackalloc", Token.STACKALLOC);
314 AddKeyword ("static", Token.STATIC);
315 AddKeyword ("string", Token.STRING);
316 AddKeyword ("struct", Token.STRUCT);
317 AddKeyword ("switch", Token.SWITCH);
318 AddKeyword ("this", Token.THIS);
319 AddKeyword ("throw", Token.THROW);
320 AddKeyword ("true", Token.TRUE);
321 AddKeyword ("try", Token.TRY);
322 AddKeyword ("typeof", Token.TYPEOF);
323 AddKeyword ("uint", Token.UINT);
324 AddKeyword ("ulong", Token.ULONG);
325 AddKeyword ("unchecked", Token.UNCHECKED);
326 AddKeyword ("unsafe", Token.UNSAFE);
327 AddKeyword ("ushort", Token.USHORT);
328 AddKeyword ("using", Token.USING);
329 AddKeyword ("virtual", Token.VIRTUAL);
330 AddKeyword ("void", Token.VOID);
331 AddKeyword ("volatile", Token.VOLATILE);
332 AddKeyword ("while", Token.WHILE);
333 AddKeyword ("partial", Token.PARTIAL);
342 csharp_format_info = NumberFormatInfo.InvariantInfo;
343 styles = NumberStyles.Float;
345 string_builder = new System.Text.StringBuilder ();
348 int GetKeyword (char[] id, int id_len)
351 * Keywords are stored in an array of hashtables grouped by their
355 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
357 object o = keywords [id_len] [id];
364 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
366 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
368 if (handle_assembly == false && res == Token.ASSEMBLY)
375 public Location Location {
376 get { return current_location; }
379 void define (string def)
381 if (!RootContext.AllDefines.Contains (def)){
382 RootContext.AllDefines [def] = true;
384 if (defines.Contains (def))
386 defines [def] = true;
389 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
391 this.ref_name = file;
392 this.file_name = file;
398 defines = new Hashtable ();
399 foreach (string def in defs)
403 xml_comment_buffer = new StringBuilder ();
406 // FIXME: This could be `Location.Push' but we have to
407 // find out why the MS compiler allows this
409 Mono.CSharp.Location.Push (file);
412 static bool is_identifier_start_character (char c)
414 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
417 static bool is_identifier_part_character (char c)
419 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
422 public static bool IsKeyword (string s)
424 return keywordStrings [s] != null;
427 public static bool IsValidIdentifier (string s)
429 if (s == null || s.Length == 0)
432 if (!is_identifier_start_character (s [0]))
435 for (int i = 1; i < s.Length; i ++)
436 if (! is_identifier_part_character (s [i]))
442 int is_punct (char c, ref bool doread)
452 return Token.OPEN_BRACE;
455 return Token.CLOSE_BRACE;
457 // To block doccomment inside attribute declaration.
458 if (doc_state == XmlCommentState.Allowed)
459 doc_state = XmlCommentState.NotAllowed;
460 return Token.OPEN_BRACKET;
462 return Token.CLOSE_BRACKET;
464 return Token.OPEN_PARENS;
466 if (deambiguate_close_parens == 0)
467 return Token.CLOSE_PARENS;
469 --deambiguate_close_parens;
471 // Save current position and parse next token.
472 int old = reader.Position;
473 int old_ref_line = ref_line;
476 // disable preprocessing directives when peeking
477 process_directives = false;
478 int new_token = token ();
479 process_directives = true;
480 reader.Position = old;
481 ref_line = old_ref_line;
485 if (new_token == Token.OPEN_PARENS)
486 return Token.CLOSE_PARENS_OPEN_PARENS;
487 else if (new_token == Token.MINUS)
488 return Token.CLOSE_PARENS_MINUS;
489 else if (IsCastToken (new_token))
490 return Token.CLOSE_PARENS_CAST;
492 return Token.CLOSE_PARENS_NO_CAST;
499 return Token.SEMICOLON;
515 t = Token.OP_ADD_ASSIGN;
529 t = Token.OP_SUB_ASSIGN;
561 } else if (d == '='){
563 return Token.OP_AND_ASSIGN;
566 return Token.BITWISE_AND;
573 } else if (d == '='){
575 return Token.OP_OR_ASSIGN;
577 return Token.BITWISE_OR;
583 return Token.OP_MULT_ASSIGN;
592 return Token.OP_DIV_ASSIGN;
600 return Token.OP_MOD_ASSIGN;
602 return Token.PERCENT;
608 return Token.OP_XOR_ASSIGN;
620 return Token.OP_SHIFT_LEFT_ASSIGN;
622 return Token.OP_SHIFT_LEFT;
623 } else if (d == '='){
637 return Token.OP_SHIFT_RIGHT_ASSIGN;
639 return Token.OP_SHIFT_RIGHT;
640 } else if (d == '='){
649 return Token.DOUBLE_COLON;
658 int deambiguate_close_parens = 0;
660 public void Deambiguate_CloseParens (object expression)
664 // When any binary operation is used we are sure it is not a cast
665 if (expression is Binary)
668 deambiguate_close_parens++;
671 void Error_NumericConstantTooLong ()
673 Report.Error (1021, Location, "Numeric constant too long");
676 bool decimal_digits (int c)
679 bool seen_digits = false;
682 if (number_pos == max_number_size)
683 Error_NumericConstantTooLong ();
684 number_builder [number_pos++] = (char) c;
688 // We use peekChar2, because decimal_digits needs to do a
689 // 2-character look-ahead (5.ToString for example).
691 while ((d = peekChar2 ()) != -1){
692 if (d >= '0' && d <= '9'){
693 if (number_pos == max_number_size)
694 Error_NumericConstantTooLong ();
695 number_builder [number_pos++] = (char) d;
705 static bool is_hex (int e)
707 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
710 static int real_type_suffix (int c)
716 t = Token.LITERAL_FLOAT;
719 t = Token.LITERAL_DOUBLE;
722 t= Token.LITERAL_DECIMAL;
730 int integer_type_suffix (ulong ul, int c)
732 bool is_unsigned = false;
733 bool is_long = false;
736 bool scanning = true;
747 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
749 // if we have not seen anything in between
752 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
755 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
780 if (is_long && is_unsigned){
782 return Token.LITERAL_INTEGER;
783 } else if (is_unsigned){
784 // uint if possible, or ulong else.
786 if ((ul & 0xffffffff00000000) == 0)
791 // long if possible, ulong otherwise
792 if ((ul & 0x8000000000000000) != 0)
797 // int, uint, long or ulong in that order
798 if ((ul & 0xffffffff00000000) == 0){
801 if ((ui & 0x80000000) != 0)
806 if ((ul & 0x8000000000000000) != 0)
812 return Token.LITERAL_INTEGER;
816 // given `c' as the next char in the input decide whether
817 // we need to convert to a special type, and then choose
818 // the best representation for the integer
820 int adjust_int (int c)
824 ulong ul = (uint) (number_builder [0] - '0');
826 for (int i = 1; i < number_pos; i++){
827 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
829 return integer_type_suffix (ul, c);
831 uint ui = (uint) (number_builder [0] - '0');
833 for (int i = 1; i < number_pos; i++){
834 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
836 return integer_type_suffix (ui, c);
838 } catch (OverflowException) {
839 error_details = "Integral constant is too large";
840 Report.Error (1021, Location, error_details);
842 return Token.LITERAL_INTEGER;
844 catch (FormatException) {
845 Report.Error (1013, Location, "Invalid number");
847 return Token.LITERAL_INTEGER;
851 int adjust_real (int t)
853 string s = new String (number_builder, 0, number_pos);
854 const string error_details = "Floating-point constant is outside the range of type `{0}'";
857 case Token.LITERAL_DECIMAL:
859 val = System.Decimal.Parse (s, styles, csharp_format_info);
860 } catch (OverflowException) {
862 Report.Error (594, Location, error_details, "decimal");
865 case Token.LITERAL_FLOAT:
867 val = float.Parse (s, styles, csharp_format_info);
868 } catch (OverflowException) {
870 Report.Error (594, Location, error_details, "float");
874 case Token.LITERAL_DOUBLE:
876 t = Token.LITERAL_DOUBLE;
878 val = System.Double.Parse (s, styles, csharp_format_info);
879 } catch (OverflowException) {
881 Report.Error (594, Location, error_details, "double");
894 while ((d = peekChar ()) != -1){
896 number_builder [number_pos++] = (char) d;
902 string s = new String (number_builder, 0, number_pos);
905 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
907 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
908 } catch (OverflowException){
909 error_details = "Integral constant is too large";
910 Report.Error (1021, Location, error_details);
912 return Token.LITERAL_INTEGER;
914 catch (FormatException) {
915 Report.Error (1013, Location, "Invalid number");
917 return Token.LITERAL_INTEGER;
920 return integer_type_suffix (ul, peekChar ());
924 // Invoked if we know we have .digits or digits
926 int is_number (int c)
928 bool is_real = false;
933 if (c >= '0' && c <= '9'){
935 int peek = peekChar ();
937 if (peek == 'x' || peek == 'X')
938 return handle_hex ();
945 // We need to handle the case of
946 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
949 if (decimal_digits ('.')){
955 return adjust_int (-1);
959 if (c == 'e' || c == 'E'){
961 if (number_pos == max_number_size)
962 Error_NumericConstantTooLong ();
963 number_builder [number_pos++] = 'e';
967 if (number_pos == max_number_size)
968 Error_NumericConstantTooLong ();
969 number_builder [number_pos++] = '+';
971 } else if (c == '-') {
972 if (number_pos == max_number_size)
973 Error_NumericConstantTooLong ();
974 number_builder [number_pos++] = '-';
977 if (number_pos == max_number_size)
978 Error_NumericConstantTooLong ();
979 number_builder [number_pos++] = '+';
986 type = real_type_suffix (c);
987 if (type == Token.NONE && !is_real){
989 return adjust_int (c);
993 if (type == Token.NONE){
998 return adjust_real (type);
1000 Console.WriteLine ("This should not be reached");
1001 throw new Exception ("Is Number should never reach this point");
1005 // Accepts exactly count (4 or 8) hex, no more no less
1007 int getHex (int count, out bool error)
1012 int top = count != -1 ? count : 4;
1016 for (i = 0; i < top; i++){
1019 if (c >= '0' && c <= '9')
1020 c = (int) c - (int) '0';
1021 else if (c >= 'A' && c <= 'F')
1022 c = (int) c - (int) 'A' + 10;
1023 else if (c >= 'a' && c <= 'f')
1024 c = (int) c - (int) 'a' + 10;
1030 total = (total * 16) + c;
1032 int p = peekChar ();
1035 if (!is_hex ((char)p))
1076 v = getHex (-1, out error);
1081 v = getHex (4, out error);
1086 v = getHex (8, out error);
1091 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1101 if (putback_char != -1) {
1120 if (putback_char != -1)
1121 return putback_char;
1122 putback_char = reader.Read ();
1123 return putback_char;
1128 if (putback_char != -1)
1129 return putback_char;
1130 return reader.Peek ();
1133 void putback (int c)
1135 if (putback_char != -1){
1136 Console.WriteLine ("Col: " + col);
1137 Console.WriteLine ("Row: " + line);
1138 Console.WriteLine ("Name: " + ref_name.Name);
1139 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1140 throw new Exception ("This should not happen putback on putback");
1142 if (c == '\n' || col == 0) {
1143 // It won't happen though.
1153 public bool advance ()
1155 return peekChar () != -1;
1158 public Object Value {
1164 public Object value ()
1169 static bool IsCastToken (int token)
1174 case Token.IDENTIFIER:
1175 case Token.LITERAL_INTEGER:
1176 case Token.LITERAL_FLOAT:
1177 case Token.LITERAL_DOUBLE:
1178 case Token.LITERAL_DECIMAL:
1179 case Token.LITERAL_CHARACTER:
1180 case Token.LITERAL_STRING:
1192 case Token.UNCHECKED:
1196 // These can be part of a member access
1216 current_token = xtoken ();
1217 return current_token;
1220 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1222 void get_cmd_arg (out string cmd, out string arg)
1226 tokens_seen = false;
1228 static_cmd_arg.Length = 0;
1230 // skip over white space
1231 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1235 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1236 if (is_identifier_part_character ((char) c)){
1237 static_cmd_arg.Append ((char) c);
1245 cmd = static_cmd_arg.ToString ();
1251 // skip over white space
1252 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1257 } else if (c == '\r'){
1259 } else if (c == -1){
1264 static_cmd_arg.Length = 0;
1265 static_cmd_arg.Append ((char) c);
1267 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1268 static_cmd_arg.Append ((char) c);
1271 arg = static_cmd_arg.ToString ().Trim ();
1275 // Handles the #line directive
1277 bool PreProcessLine (string arg)
1279 if (arg.Length == 0)
1282 if (arg == "default"){
1284 ref_name = file_name;
1285 Location.Push (ref_name);
1287 } else if (arg == "hidden"){
1289 // We ignore #line hidden
1297 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1298 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1301 char [] quotes = { '\"' };
1303 string name = arg.Substring (pos). Trim (quotes);
1304 ref_name = Location.LookupFile (name);
1305 file_name.HasLineDirective = true;
1306 ref_name.HasLineDirective = true;
1307 Location.Push (ref_name);
1309 ref_line = System.Int32.Parse (arg);
1319 // Handles #define and #undef
1321 void PreProcessDefinition (bool is_define, string arg)
1323 if (arg.Length == 0 || arg == "true" || arg == "false"){
1324 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1328 char[] whitespace = { ' ', '\t' };
1329 if (arg.IndexOfAny (whitespace) != -1){
1330 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1334 if (!is_identifier_start_character (arg [0]))
1335 Report.Error (1001, Location, "Identifier expected: " + arg);
1337 foreach (char c in arg.Substring (1)){
1338 if (!is_identifier_part_character (c)){
1339 Report.Error (1001, Location, "Identifier expected: " + arg);
1345 if (defines == null)
1346 defines = new Hashtable ();
1349 if (defines == null)
1351 if (defines.Contains (arg))
1352 defines.Remove (arg);
1357 /// Handles #pragma directive
1359 void PreProcessPragma (string arg)
1361 const string warning = "warning";
1362 const string w_disable = "warning disable";
1363 const string w_restore = "warning restore";
1365 if (arg == w_disable) {
1366 Report.RegisterWarningRegion (Location).WarningDisable (line);
1370 if (arg == w_restore) {
1371 Report.RegisterWarningRegion (Location).WarningEnable (line);
1375 if (arg.StartsWith (w_disable)) {
1376 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1377 foreach (int code in codes) {
1379 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1384 if (arg.StartsWith (w_restore)) {
1385 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1386 Hashtable w_table = Report.warning_ignore_table;
1387 foreach (int code in codes) {
1388 if (w_table != null && w_table.Contains (code))
1389 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1390 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1395 if (arg.StartsWith (warning)) {
1396 Report.Warning (1634, 1, Location, "Expected disable or restore");
1400 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1403 int[] ParseNumbers (string text)
1405 string[] string_array = text.Split (',');
1406 int[] values = new int [string_array.Length];
1408 foreach (string string_code in string_array) {
1410 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1412 catch (FormatException) {
1413 Report.Warning (1692, 1, Location, "Invalid number");
1419 bool eval_val (string s)
1426 if (defines == null)
1428 if (defines.Contains (s))
1434 bool pp_primary (ref string s)
1443 s = s.Substring (1);
1444 bool val = pp_expr (ref s);
1445 if (s.Length > 0 && s [0] == ')'){
1446 s = s.Substring (1);
1449 Error_InvalidDirective ();
1453 if (is_identifier_start_character (c)){
1459 if (is_identifier_part_character (c)){
1463 bool v = eval_val (s.Substring (0, j));
1464 s = s.Substring (j);
1467 bool vv = eval_val (s);
1472 Error_InvalidDirective ();
1476 bool pp_unary (ref string s)
1483 if (len > 1 && s [1] == '='){
1484 Error_InvalidDirective ();
1487 s = s.Substring (1);
1488 return ! pp_primary (ref s);
1490 return pp_primary (ref s);
1492 Error_InvalidDirective ();
1497 bool pp_eq (ref string s)
1499 bool va = pp_unary (ref s);
1505 if (len > 2 && s [1] == '='){
1506 s = s.Substring (2);
1507 return va == pp_unary (ref s);
1509 Error_InvalidDirective ();
1512 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1513 s = s.Substring (2);
1515 return va != pp_unary (ref s);
1524 bool pp_and (ref string s)
1526 bool va = pp_eq (ref s);
1532 if (len > 2 && s [1] == '&'){
1533 s = s.Substring (2);
1534 return (va & pp_and (ref s));
1536 Error_InvalidDirective ();
1545 // Evaluates an expression for `#if' or `#elif'
1547 bool pp_expr (ref string s)
1549 bool va = pp_and (ref s);
1556 if (len > 2 && s [1] == '|'){
1557 s = s.Substring (2);
1558 return va | pp_expr (ref s);
1560 Error_InvalidDirective ();
1569 bool eval (string s)
1571 bool v = pp_expr (ref s);
1580 void Error_InvalidDirective ()
1582 Report.Error (1517, Location, "Invalid preprocessor directive");
1585 void Error_UnexpectedDirective (string extra)
1589 "Unexpected processor directive (" + extra + ")");
1592 void Error_TokensSeen ()
1594 Report.Error (1032, Location,
1595 "Cannot define or undefine preprocessor symbols after first token in file");
1599 // Set to false to stop handling preprocesser directives
1601 bool process_directives = true;
1604 // if true, then the code continues processing the code
1605 // if false, the code stays in a loop until another directive is
1608 bool handle_preprocessing_directive (bool caller_is_taking)
1611 bool region_directive = false;
1613 get_cmd_arg (out cmd, out arg);
1615 // Eat any trailing whitespaces and single-line comments
1616 if (arg.IndexOf ("//") != -1)
1617 arg = arg.Substring (0, arg.IndexOf ("//"));
1618 arg = arg.TrimEnd (' ', '\t');
1621 // The first group of pre-processing instructions is always processed
1625 if (RootContext.Version == LanguageVersion.ISO_1) {
1626 Report.FeatureIsNotStandardized (Location, "#pragma");
1627 return caller_is_taking;
1630 PreProcessPragma (arg);
1631 return caller_is_taking;
1634 if (!PreProcessLine (arg))
1637 "The line number specified for #line directive is missing or invalid");
1638 return caller_is_taking;
1641 region_directive = true;
1646 region_directive = true;
1650 if (arg.Length == 0){
1651 Error_InvalidDirective ();
1654 bool taking = false;
1655 if (ifstack == null)
1656 ifstack = new Stack (2);
1658 if (ifstack.Count == 0){
1661 int state = (int) ifstack.Peek ();
1662 if ((state & TAKING) != 0)
1666 if (eval (arg) && taking){
1667 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1668 if (region_directive)
1670 ifstack.Push (push);
1673 int push = (taking ? PARENT_TAKING : 0);
1674 if (region_directive)
1676 ifstack.Push (push);
1681 if (ifstack == null || ifstack.Count == 0){
1682 Error_UnexpectedDirective ("no #if for this #endif");
1685 int pop = (int) ifstack.Pop ();
1687 if (region_directive && ((pop & REGION) == 0))
1688 Report.Error (1027, Location, "Expected `#endif' directive");
1689 else if (!region_directive && ((pop & REGION) != 0))
1690 Report.Error (1038, Location, "#endregion directive expected");
1692 if (!region_directive && arg.Length != 0) {
1693 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1696 if (ifstack.Count == 0)
1699 int state = (int) ifstack.Peek ();
1701 if ((state & TAKING) != 0)
1709 if (ifstack == null || ifstack.Count == 0){
1710 Error_UnexpectedDirective ("no #if for this #elif");
1713 int state = (int) ifstack.Peek ();
1715 if ((state & REGION) != 0) {
1716 Report.Error (1038, Location, "#endregion directive expected");
1720 if ((state & ELSE_SEEN) != 0){
1721 Error_UnexpectedDirective ("#elif not valid after #else");
1725 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1728 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1729 state = (int) ifstack.Pop ();
1730 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1737 if (ifstack == null || ifstack.Count == 0){
1738 Error_UnexpectedDirective ("no #if for this #else");
1741 int state = (int) ifstack.Peek ();
1743 if ((state & REGION) != 0) {
1744 Report.Error (1038, Location, "#endregion directive expected");
1748 if ((state & ELSE_SEEN) != 0){
1749 Error_UnexpectedDirective ("#else within #else");
1756 if ((state & TAKEN_BEFORE) == 0){
1757 ret = ((state & PARENT_TAKING) != 0);
1766 ifstack.Push (state | ELSE_SEEN);
1773 // These are only processed if we are in a `taking' block
1775 if (!caller_is_taking)
1780 if (any_token_seen){
1781 Error_TokensSeen ();
1784 PreProcessDefinition (true, arg);
1788 if (any_token_seen){
1789 Error_TokensSeen ();
1792 PreProcessDefinition (false, arg);
1796 Report.Error (1029, Location, "#error: '" + arg + "'");
1800 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
1804 Report.Error (1024, Location, "Wrong preprocessor directive");
1809 private int consume_string (bool quoted)
1812 string_builder.Length = 0;
1814 while ((c = getChar ()) != -1){
1816 if (quoted && peekChar () == '"'){
1817 string_builder.Append ((char) c);
1821 val = string_builder.ToString ();
1822 return Token.LITERAL_STRING;
1828 Report.Error (1010, Location, "Newline in constant");
1836 string_builder.Append ((char) c);
1839 Report.Error (1039, Location, "Unterminated string literal");
1843 private int consume_identifier (int s)
1845 int res = consume_identifier (s, false);
1847 if (doc_state == XmlCommentState.Allowed)
1848 doc_state = XmlCommentState.NotAllowed;
1851 case Token.NAMESPACE:
1852 check_incorrect_doc_comment ();
1856 if (res == Token.PARTIAL) {
1857 // Save current position and parse next token.
1858 int old = reader.Position;
1859 int old_putback = putback_char;
1860 int old_ref_line = ref_line;
1865 int next_token = token ();
1866 bool ok = (next_token == Token.CLASS) ||
1867 (next_token == Token.STRUCT) ||
1868 (next_token == Token.INTERFACE) ||
1869 (next_token == Token.ENUM); // "partial" is a keyword in 'partial enum', even though it's not valid
1871 reader.Position = old;
1872 ref_line = old_ref_line;
1874 putback_char = old_putback;
1879 val = new LocatedToken (Location, "partial");
1880 return Token.IDENTIFIER;
1887 private int consume_identifier (int s, bool quoted)
1892 id_builder [0] = (char) s;
1894 current_location = new Location (ref_line, Col);
1896 while ((c = getChar ()) != -1) {
1898 if (is_identifier_part_character ((char) c)){
1899 if (pos == max_id_size){
1900 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1904 id_builder [pos++] = (char) c;
1905 // putback_char = -1;
1906 } else if (c == '\\') {
1910 // putback_char = c;
1917 // Optimization: avoids doing the keyword lookup
1918 // on uppercase letters and _
1920 if (!quoted && (s >= 'a' || s == '_')){
1921 int keyword = GetKeyword (id_builder, pos);
1922 if (keyword != -1) {
1929 // Keep identifiers in an array of hashtables to avoid needless
1933 if (identifiers [pos] != null) {
1934 val = identifiers [pos][id_builder];
1936 val = new LocatedToken (Location, (string) val);
1938 escapedIdentifiers.Add (val);
1939 return Token.IDENTIFIER;
1943 identifiers [pos] = new CharArrayHashtable (pos);
1945 val = new String (id_builder, 0, pos);
1946 if (RootContext.Version == LanguageVersion.ISO_1) {
1947 for (int i = 1; i < id_builder.Length; i += 3) {
1948 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
1949 Report.Error (1638, Location,
1950 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
1956 char [] chars = new char [pos];
1957 Array.Copy (id_builder, chars, pos);
1959 identifiers [pos] [chars] = val;
1961 val = new LocatedToken (Location, (string) val);
1963 escapedIdentifiers.Add (val);
1964 return Token.IDENTIFIER;
1967 public int xtoken ()
1970 bool doread = false;
1973 // Whether we have seen comments on the current line
1974 bool comments_seen = false;
1977 // optimization: eliminate col and implement #directive semantic correctly.
1978 for (;(c = getChar ()) != -1;) {
1986 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1990 if (peekChar () == '\n')
1993 any_token_seen |= tokens_seen;
1994 tokens_seen = false;
1995 comments_seen = false;
1999 // Handle double-slash comments.
2001 int d = peekChar ();
2005 if (RootContext.Documentation != null && peekChar () == '/') {
2007 // Don't allow ////.
2008 if ((d = peekChar ()) != '/') {
2009 update_comment_location ();
2010 if (doc_state == XmlCommentState.Allowed)
2011 handle_one_line_xml_comment ();
2012 else if (doc_state == XmlCommentState.NotAllowed)
2013 warn_incorrect_doc_comment ();
2016 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2019 any_token_seen |= tokens_seen;
2020 tokens_seen = false;
2021 comments_seen = false;
2023 } else if (d == '*'){
2025 bool docAppend = false;
2026 if (RootContext.Documentation != null && peekChar () == '*') {
2028 update_comment_location ();
2029 // But when it is /**/, just do nothing.
2030 if (peekChar () == '/') {
2034 if (doc_state == XmlCommentState.Allowed)
2036 else if (doc_state == XmlCommentState.NotAllowed)
2037 warn_incorrect_doc_comment ();
2040 int current_comment_start = 0;
2042 current_comment_start = xml_comment_buffer.Length;
2043 xml_comment_buffer.Append (Environment.NewLine);
2046 Location start_location = Location;
2048 while ((d = getChar ()) != -1){
2049 if (d == '*' && peekChar () == '/'){
2051 comments_seen = true;
2055 xml_comment_buffer.Append ((char) d);
2058 any_token_seen |= tokens_seen;
2059 tokens_seen = false;
2061 // Reset 'comments_seen' just to be consistent.
2062 // It doesn't matter either way, here.
2064 comments_seen = false;
2068 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2071 update_formatted_doc_comment (current_comment_start);
2074 goto is_punct_label;
2078 if (c == '\\' || is_identifier_start_character ((char)c)){
2080 return consume_identifier (c);
2084 current_location = new Location (ref_line, Col);
2085 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2095 any_token_seen |= tokens_seen;
2096 tokens_seen = false;
2097 comments_seen = false;
2101 if (c >= '0' && c <= '9'){
2103 return is_number (c);
2108 int peek = peekChar ();
2109 if (peek >= '0' && peek <= '9')
2110 return is_number (c);
2114 /* For now, ignore pre-processor commands */
2115 // FIXME: In C# the '#' is not limited to appear
2116 // on the first column.
2118 // return NONE if we're not processing directives (during token peeks)
2119 if (!process_directives)
2123 if (tokens_seen || comments_seen) {
2124 error_details = "Preprocessor directives must appear as the first" +
2125 " non-whitespace character on a line.";
2127 Report.Error (1040, Location, error_details);
2134 cont = handle_preprocessing_directive (cont);
2140 bool skipping = false;
2141 for (;(c = getChar ()) != -1;){
2144 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2148 if (c == '#' && !skipping)
2151 any_token_seen |= tokens_seen;
2152 tokens_seen = false;
2154 Report.Error (1027, Location, "Expected `#endif' directive");
2159 return consume_string (false);
2165 error_details = "Empty character literal";
2166 Report.Error (1011, Location, error_details);
2169 if (c == '\r' || c == '\n') {
2170 Report.Error (1010, Location, "Newline in constant");
2176 val = new System.Char ();
2181 error_details = "Too many characters in character literal";
2182 Report.Error (1012, Location, error_details);
2184 // Try to recover, read until newline or next "'"
2185 while ((c = getChar ()) != -1){
2194 return Token.LITERAL_CHARACTER;
2201 return consume_string (true);
2202 } else if (is_identifier_start_character ((char) c)){
2203 return consume_identifier (c, true);
2205 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2209 error_details = ((char)c).ToString ();
2218 // Handles one line xml comment
2220 private void handle_one_line_xml_comment ()
2223 while ((c = peekChar ()) == ' ')
2224 getChar (); // skip heading whitespaces.
2225 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2226 xml_comment_buffer.Append ((char) getChar ());
2228 if (c == '\r' || c == '\n')
2229 xml_comment_buffer.Append (Environment.NewLine);
2233 // Remove heading "*" in Javadoc-like xml documentation.
2235 private void update_formatted_doc_comment (int current_comment_start)
2237 int length = xml_comment_buffer.Length - current_comment_start;
2238 string [] lines = xml_comment_buffer.ToString (
2239 current_comment_start,
2240 length).Replace ("\r", "").Split ('\n');
2242 // The first line starts with /**, thus it is not target
2243 // for the format check.
2244 for (int i = 1; i < lines.Length; i++) {
2245 string s = lines [i];
2246 int idx = s.IndexOf ('*');
2249 if (i < lines.Length - 1)
2253 head = s.Substring (0, idx);
2254 foreach (char c in head)
2257 lines [i] = s.Substring (idx + 1);
2259 xml_comment_buffer.Remove (current_comment_start, length);
2260 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2264 // Updates current comment location.
2266 private void update_comment_location ()
2268 if (current_comment_location.IsNull) {
2269 // "-2" is for heading "//" or "/*"
2270 current_comment_location =
2271 new Location (ref_line, col - 2);
2276 // Checks if there was incorrect doc comments and raise
2279 public void check_incorrect_doc_comment ()
2281 if (xml_comment_buffer.Length > 0)
2282 warn_incorrect_doc_comment ();
2286 // Raises a warning when tokenizer found incorrect doccomment
2289 private void warn_incorrect_doc_comment ()
2291 if (doc_state != XmlCommentState.Error) {
2292 doc_state = XmlCommentState.Error;
2293 // in csc, it is 'XML comment is not placed on
2294 // a valid language element'. But that does not
2296 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2301 // Consumes the saved xml comment lines (if any)
2302 // as for current target member or type.
2304 public string consume_doc_comment ()
2306 if (xml_comment_buffer.Length > 0) {
2307 string ret = xml_comment_buffer.ToString ();
2308 reset_doc_comment ();
2314 void reset_doc_comment ()
2316 xml_comment_buffer.Length = 0;
2317 current_comment_location = Location.Null;
2320 public void cleanup ()
2322 if (ifstack != null && ifstack.Count >= 1) {
2323 int state = (int) ifstack.Pop ();
2324 if ((state & REGION) != 0)
2325 Report.Error (1038, Location, "#endregion directive expected");
2327 // Report.Error (1027, Location, "Expected `#endif' directive");
2333 // Indicates whether it accepts XML documentation or not.
2335 public enum XmlCommentState {
2336 // comment is allowed in this state.
2338 // comment is not allowed in this state.
2340 // once comments appeared when it is NotAllowed, then the
2341 // state is changed to it, until the state is changed to