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:
1183 case Token.DELEGATE:
1193 case Token.UNCHECKED:
1197 // These can be part of a member access
1217 current_token = xtoken ();
1218 return current_token;
1221 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1223 void get_cmd_arg (out string cmd, out string arg)
1227 tokens_seen = false;
1229 static_cmd_arg.Length = 0;
1231 // skip over white space
1232 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1236 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1237 if (is_identifier_part_character ((char) c)){
1238 static_cmd_arg.Append ((char) c);
1246 cmd = static_cmd_arg.ToString ();
1252 // skip over white space
1253 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1258 } else if (c == '\r'){
1260 } else if (c == -1){
1265 static_cmd_arg.Length = 0;
1266 static_cmd_arg.Append ((char) c);
1268 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1269 static_cmd_arg.Append ((char) c);
1272 arg = static_cmd_arg.ToString ().Trim ();
1276 // Handles the #line directive
1278 bool PreProcessLine (string arg)
1280 if (arg.Length == 0)
1283 if (arg == "default"){
1285 ref_name = file_name;
1286 Location.Push (ref_name);
1288 } else if (arg == "hidden"){
1290 // We ignore #line hidden
1298 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1299 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1302 char [] quotes = { '\"' };
1304 string name = arg.Substring (pos). Trim (quotes);
1305 ref_name = Location.LookupFile (name);
1306 file_name.HasLineDirective = true;
1307 ref_name.HasLineDirective = true;
1308 Location.Push (ref_name);
1310 ref_line = System.Int32.Parse (arg);
1320 // Handles #define and #undef
1322 void PreProcessDefinition (bool is_define, string arg)
1324 if (arg.Length == 0 || arg == "true" || arg == "false"){
1325 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1329 char[] whitespace = { ' ', '\t' };
1330 if (arg.IndexOfAny (whitespace) != -1){
1331 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1335 if (!is_identifier_start_character (arg [0]))
1336 Report.Error (1001, Location, "Identifier expected: " + arg);
1338 foreach (char c in arg.Substring (1)){
1339 if (!is_identifier_part_character (c)){
1340 Report.Error (1001, Location, "Identifier expected: " + arg);
1346 if (defines == null)
1347 defines = new Hashtable ();
1350 if (defines == null)
1352 if (defines.Contains (arg))
1353 defines.Remove (arg);
1358 /// Handles #pragma directive
1360 void PreProcessPragma (string arg)
1362 const string warning = "warning";
1363 const string w_disable = "warning disable";
1364 const string w_restore = "warning restore";
1366 if (arg == w_disable) {
1367 Report.RegisterWarningRegion (Location).WarningDisable (line);
1371 if (arg == w_restore) {
1372 Report.RegisterWarningRegion (Location).WarningEnable (line);
1376 if (arg.StartsWith (w_disable)) {
1377 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1378 foreach (int code in codes) {
1380 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1385 if (arg.StartsWith (w_restore)) {
1386 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1387 Hashtable w_table = Report.warning_ignore_table;
1388 foreach (int code in codes) {
1389 if (w_table != null && w_table.Contains (code))
1390 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1391 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1396 if (arg.StartsWith (warning)) {
1397 Report.Warning (1634, 1, Location, "Expected disable or restore");
1401 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1404 int[] ParseNumbers (string text)
1406 string[] string_array = text.Split (',');
1407 int[] values = new int [string_array.Length];
1409 foreach (string string_code in string_array) {
1411 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1413 catch (FormatException) {
1414 Report.Warning (1692, 1, Location, "Invalid number");
1420 bool eval_val (string s)
1427 if (defines == null)
1429 if (defines.Contains (s))
1435 bool pp_primary (ref string s)
1444 s = s.Substring (1);
1445 bool val = pp_expr (ref s);
1446 if (s.Length > 0 && s [0] == ')'){
1447 s = s.Substring (1);
1450 Error_InvalidDirective ();
1454 if (is_identifier_start_character (c)){
1460 if (is_identifier_part_character (c)){
1464 bool v = eval_val (s.Substring (0, j));
1465 s = s.Substring (j);
1468 bool vv = eval_val (s);
1473 Error_InvalidDirective ();
1477 bool pp_unary (ref string s)
1484 if (len > 1 && s [1] == '='){
1485 Error_InvalidDirective ();
1488 s = s.Substring (1);
1489 return ! pp_primary (ref s);
1491 return pp_primary (ref s);
1493 Error_InvalidDirective ();
1498 bool pp_eq (ref string s)
1500 bool va = pp_unary (ref s);
1506 if (len > 2 && s [1] == '='){
1507 s = s.Substring (2);
1508 return va == pp_unary (ref s);
1510 Error_InvalidDirective ();
1513 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1514 s = s.Substring (2);
1516 return va != pp_unary (ref s);
1525 bool pp_and (ref string s)
1527 bool va = pp_eq (ref s);
1533 if (len > 2 && s [1] == '&'){
1534 s = s.Substring (2);
1535 return (va & pp_and (ref s));
1537 Error_InvalidDirective ();
1546 // Evaluates an expression for `#if' or `#elif'
1548 bool pp_expr (ref string s)
1550 bool va = pp_and (ref s);
1557 if (len > 2 && s [1] == '|'){
1558 s = s.Substring (2);
1559 return va | pp_expr (ref s);
1561 Error_InvalidDirective ();
1570 bool eval (string s)
1572 bool v = pp_expr (ref s);
1581 void Error_InvalidDirective ()
1583 Report.Error (1517, Location, "Invalid preprocessor directive");
1586 void Error_UnexpectedDirective (string extra)
1590 "Unexpected processor directive (" + extra + ")");
1593 void Error_TokensSeen ()
1595 Report.Error (1032, Location,
1596 "Cannot define or undefine preprocessor symbols after first token in file");
1600 // Set to false to stop handling preprocesser directives
1602 bool process_directives = true;
1605 // if true, then the code continues processing the code
1606 // if false, the code stays in a loop until another directive is
1609 bool handle_preprocessing_directive (bool caller_is_taking)
1612 bool region_directive = false;
1614 get_cmd_arg (out cmd, out arg);
1616 // Eat any trailing whitespaces and single-line comments
1617 if (arg.IndexOf ("//") != -1)
1618 arg = arg.Substring (0, arg.IndexOf ("//"));
1619 arg = arg.TrimEnd (' ', '\t');
1622 // The first group of pre-processing instructions is always processed
1626 if (RootContext.Version == LanguageVersion.ISO_1) {
1627 Report.FeatureIsNotStandardized (Location, "#pragma");
1628 return caller_is_taking;
1631 PreProcessPragma (arg);
1632 return caller_is_taking;
1635 if (!PreProcessLine (arg))
1638 "The line number specified for #line directive is missing or invalid");
1639 return caller_is_taking;
1642 region_directive = true;
1647 region_directive = true;
1651 if (arg.Length == 0){
1652 Error_InvalidDirective ();
1655 bool taking = false;
1656 if (ifstack == null)
1657 ifstack = new Stack (2);
1659 if (ifstack.Count == 0){
1662 int state = (int) ifstack.Peek ();
1663 if ((state & TAKING) != 0)
1667 if (eval (arg) && taking){
1668 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1669 if (region_directive)
1671 ifstack.Push (push);
1674 int push = (taking ? PARENT_TAKING : 0);
1675 if (region_directive)
1677 ifstack.Push (push);
1682 if (ifstack == null || ifstack.Count == 0){
1683 Error_UnexpectedDirective ("no #if for this #endif");
1686 int pop = (int) ifstack.Pop ();
1688 if (region_directive && ((pop & REGION) == 0))
1689 Report.Error (1027, Location, "Expected `#endif' directive");
1690 else if (!region_directive && ((pop & REGION) != 0))
1691 Report.Error (1038, Location, "#endregion directive expected");
1693 if (!region_directive && arg.Length != 0) {
1694 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1697 if (ifstack.Count == 0)
1700 int state = (int) ifstack.Peek ();
1702 if ((state & TAKING) != 0)
1710 if (ifstack == null || ifstack.Count == 0){
1711 Error_UnexpectedDirective ("no #if for this #elif");
1714 int state = (int) ifstack.Peek ();
1716 if ((state & REGION) != 0) {
1717 Report.Error (1038, Location, "#endregion directive expected");
1721 if ((state & ELSE_SEEN) != 0){
1722 Error_UnexpectedDirective ("#elif not valid after #else");
1726 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1729 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1730 state = (int) ifstack.Pop ();
1731 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1738 if (ifstack == null || ifstack.Count == 0){
1739 Error_UnexpectedDirective ("no #if for this #else");
1742 int state = (int) ifstack.Peek ();
1744 if ((state & REGION) != 0) {
1745 Report.Error (1038, Location, "#endregion directive expected");
1749 if ((state & ELSE_SEEN) != 0){
1750 Error_UnexpectedDirective ("#else within #else");
1757 if ((state & TAKEN_BEFORE) == 0){
1758 ret = ((state & PARENT_TAKING) != 0);
1767 ifstack.Push (state | ELSE_SEEN);
1774 // These are only processed if we are in a `taking' block
1776 if (!caller_is_taking)
1781 if (any_token_seen){
1782 Error_TokensSeen ();
1785 PreProcessDefinition (true, arg);
1789 if (any_token_seen){
1790 Error_TokensSeen ();
1793 PreProcessDefinition (false, arg);
1797 Report.Error (1029, Location, "#error: '" + arg + "'");
1801 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
1805 Report.Error (1024, Location, "Wrong preprocessor directive");
1810 private int consume_string (bool quoted)
1813 string_builder.Length = 0;
1815 while ((c = getChar ()) != -1){
1817 if (quoted && peekChar () == '"'){
1818 string_builder.Append ((char) c);
1822 val = string_builder.ToString ();
1823 return Token.LITERAL_STRING;
1829 Report.Error (1010, Location, "Newline in constant");
1837 string_builder.Append ((char) c);
1840 Report.Error (1039, Location, "Unterminated string literal");
1844 private int consume_identifier (int s)
1846 int res = consume_identifier (s, false);
1848 if (doc_state == XmlCommentState.Allowed)
1849 doc_state = XmlCommentState.NotAllowed;
1852 case Token.NAMESPACE:
1853 check_incorrect_doc_comment ();
1857 if (res == Token.PARTIAL) {
1858 // Save current position and parse next token.
1859 int old = reader.Position;
1860 int old_putback = putback_char;
1861 int old_ref_line = ref_line;
1866 int next_token = token ();
1867 bool ok = (next_token == Token.CLASS) ||
1868 (next_token == Token.STRUCT) ||
1869 (next_token == Token.INTERFACE) ||
1870 (next_token == Token.ENUM); // "partial" is a keyword in 'partial enum', even though it's not valid
1872 reader.Position = old;
1873 ref_line = old_ref_line;
1875 putback_char = old_putback;
1880 val = new LocatedToken (Location, "partial");
1881 return Token.IDENTIFIER;
1888 private int consume_identifier (int s, bool quoted)
1893 id_builder [0] = (char) s;
1895 current_location = new Location (ref_line, Col);
1897 while ((c = getChar ()) != -1) {
1899 if (is_identifier_part_character ((char) c)){
1900 if (pos == max_id_size){
1901 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1905 id_builder [pos++] = (char) c;
1906 // putback_char = -1;
1907 } else if (c == '\\') {
1911 // putback_char = c;
1918 // Optimization: avoids doing the keyword lookup
1919 // on uppercase letters and _
1921 if (!quoted && (s >= 'a' || s == '_')){
1922 int keyword = GetKeyword (id_builder, pos);
1923 if (keyword != -1) {
1930 // Keep identifiers in an array of hashtables to avoid needless
1934 if (identifiers [pos] != null) {
1935 val = identifiers [pos][id_builder];
1937 val = new LocatedToken (Location, (string) val);
1939 escapedIdentifiers.Add (val);
1940 return Token.IDENTIFIER;
1944 identifiers [pos] = new CharArrayHashtable (pos);
1946 val = new String (id_builder, 0, pos);
1947 if (RootContext.Version == LanguageVersion.ISO_1) {
1948 for (int i = 1; i < id_builder.Length; i += 3) {
1949 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
1950 Report.Error (1638, Location,
1951 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
1957 char [] chars = new char [pos];
1958 Array.Copy (id_builder, chars, pos);
1960 identifiers [pos] [chars] = val;
1962 val = new LocatedToken (Location, (string) val);
1964 escapedIdentifiers.Add (val);
1965 return Token.IDENTIFIER;
1968 public int xtoken ()
1971 bool doread = false;
1974 // Whether we have seen comments on the current line
1975 bool comments_seen = false;
1978 // optimization: eliminate col and implement #directive semantic correctly.
1979 for (;(c = getChar ()) != -1;) {
1987 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1991 if (peekChar () == '\n')
1994 any_token_seen |= tokens_seen;
1995 tokens_seen = false;
1996 comments_seen = false;
2000 // Handle double-slash comments.
2002 int d = peekChar ();
2006 if (RootContext.Documentation != null && peekChar () == '/') {
2008 // Don't allow ////.
2009 if ((d = peekChar ()) != '/') {
2010 update_comment_location ();
2011 if (doc_state == XmlCommentState.Allowed)
2012 handle_one_line_xml_comment ();
2013 else if (doc_state == XmlCommentState.NotAllowed)
2014 warn_incorrect_doc_comment ();
2017 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2020 any_token_seen |= tokens_seen;
2021 tokens_seen = false;
2022 comments_seen = false;
2024 } else if (d == '*'){
2026 bool docAppend = false;
2027 if (RootContext.Documentation != null && peekChar () == '*') {
2029 update_comment_location ();
2030 // But when it is /**/, just do nothing.
2031 if (peekChar () == '/') {
2035 if (doc_state == XmlCommentState.Allowed)
2037 else if (doc_state == XmlCommentState.NotAllowed)
2038 warn_incorrect_doc_comment ();
2041 int current_comment_start = 0;
2043 current_comment_start = xml_comment_buffer.Length;
2044 xml_comment_buffer.Append (Environment.NewLine);
2047 Location start_location = Location;
2049 while ((d = getChar ()) != -1){
2050 if (d == '*' && peekChar () == '/'){
2052 comments_seen = true;
2056 xml_comment_buffer.Append ((char) d);
2059 any_token_seen |= tokens_seen;
2060 tokens_seen = false;
2062 // Reset 'comments_seen' just to be consistent.
2063 // It doesn't matter either way, here.
2065 comments_seen = false;
2069 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2072 update_formatted_doc_comment (current_comment_start);
2075 goto is_punct_label;
2079 if (c == '\\' || is_identifier_start_character ((char)c)){
2081 return consume_identifier (c);
2085 current_location = new Location (ref_line, Col);
2086 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2096 any_token_seen |= tokens_seen;
2097 tokens_seen = false;
2098 comments_seen = false;
2102 if (c >= '0' && c <= '9'){
2104 return is_number (c);
2109 int peek = peekChar ();
2110 if (peek >= '0' && peek <= '9')
2111 return is_number (c);
2115 /* For now, ignore pre-processor commands */
2116 // FIXME: In C# the '#' is not limited to appear
2117 // on the first column.
2119 // return NONE if we're not processing directives (during token peeks)
2120 if (!process_directives)
2124 if (tokens_seen || comments_seen) {
2125 error_details = "Preprocessor directives must appear as the first" +
2126 " non-whitespace character on a line.";
2128 Report.Error (1040, Location, error_details);
2135 cont = handle_preprocessing_directive (cont);
2141 bool skipping = false;
2142 for (;(c = getChar ()) != -1;){
2145 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2149 if (c == '#' && !skipping)
2152 any_token_seen |= tokens_seen;
2153 tokens_seen = false;
2155 Report.Error (1027, Location, "Expected `#endif' directive");
2160 return consume_string (false);
2166 error_details = "Empty character literal";
2167 Report.Error (1011, Location, error_details);
2170 if (c == '\r' || c == '\n') {
2171 Report.Error (1010, Location, "Newline in constant");
2177 val = new System.Char ();
2182 error_details = "Too many characters in character literal";
2183 Report.Error (1012, Location, error_details);
2185 // Try to recover, read until newline or next "'"
2186 while ((c = getChar ()) != -1){
2195 return Token.LITERAL_CHARACTER;
2202 return consume_string (true);
2203 } else if (is_identifier_start_character ((char) c)){
2204 return consume_identifier (c, true);
2206 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2210 error_details = ((char)c).ToString ();
2219 // Handles one line xml comment
2221 private void handle_one_line_xml_comment ()
2224 while ((c = peekChar ()) == ' ')
2225 getChar (); // skip heading whitespaces.
2226 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2227 xml_comment_buffer.Append ((char) getChar ());
2229 if (c == '\r' || c == '\n')
2230 xml_comment_buffer.Append (Environment.NewLine);
2234 // Remove heading "*" in Javadoc-like xml documentation.
2236 private void update_formatted_doc_comment (int current_comment_start)
2238 int length = xml_comment_buffer.Length - current_comment_start;
2239 string [] lines = xml_comment_buffer.ToString (
2240 current_comment_start,
2241 length).Replace ("\r", "").Split ('\n');
2243 // The first line starts with /**, thus it is not target
2244 // for the format check.
2245 for (int i = 1; i < lines.Length; i++) {
2246 string s = lines [i];
2247 int idx = s.IndexOf ('*');
2250 if (i < lines.Length - 1)
2254 head = s.Substring (0, idx);
2255 foreach (char c in head)
2258 lines [i] = s.Substring (idx + 1);
2260 xml_comment_buffer.Remove (current_comment_start, length);
2261 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2265 // Updates current comment location.
2267 private void update_comment_location ()
2269 if (current_comment_location.IsNull) {
2270 // "-2" is for heading "//" or "/*"
2271 current_comment_location =
2272 new Location (ref_line, col - 2);
2277 // Checks if there was incorrect doc comments and raise
2280 public void check_incorrect_doc_comment ()
2282 if (xml_comment_buffer.Length > 0)
2283 warn_incorrect_doc_comment ();
2287 // Raises a warning when tokenizer found incorrect doccomment
2290 private void warn_incorrect_doc_comment ()
2292 if (doc_state != XmlCommentState.Error) {
2293 doc_state = XmlCommentState.Error;
2294 // in csc, it is 'XML comment is not placed on
2295 // a valid language element'. But that does not
2297 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2302 // Consumes the saved xml comment lines (if any)
2303 // as for current target member or type.
2305 public string consume_doc_comment ()
2307 if (xml_comment_buffer.Length > 0) {
2308 string ret = xml_comment_buffer.ToString ();
2309 reset_doc_comment ();
2315 void reset_doc_comment ()
2317 xml_comment_buffer.Length = 0;
2318 current_comment_location = Location.Null;
2321 public void cleanup ()
2323 if (ifstack != null && ifstack.Count >= 1) {
2324 int state = (int) ifstack.Pop ();
2325 if ((state & REGION) != 0)
2326 Report.Error (1038, Location, "#endregion directive expected");
2328 // Report.Error (1027, Location, "Expected `#endif' directive");
2334 // Indicates whether it accepts XML documentation or not.
2336 public enum XmlCommentState {
2337 // comment is allowed in this state.
2339 // comment is not allowed in this state.
2341 // once comments appeared when it is NotAllowed, then the
2342 // state is changed to it, until the state is changed to