2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 // This also implements the preprocessor
5 // Author: Miguel de Icaza (miguel@gnu.org)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
15 * Make sure we accept the proper Unicode ranges, per the spec.
21 using System.Collections;
23 using System.Globalization;
24 using System.Reflection;
29 /// Tokenizer for C# source code.
32 public class Tokenizer : yyParser.yyInput
34 SeekableStreamReader reader;
42 bool handle_get_set = false;
43 bool handle_remove_add = false;
44 bool handle_assembly = false;
45 Location current_location;
46 Location current_comment_location = Location.Null;
47 ArrayList escapedIdentifiers = new ArrayList ();
50 // XML documentation buffer. The save point is used to divide
51 // comments on types and comments on members.
53 StringBuilder xml_comment_buffer;
56 // See comment on XmlCommentState enumeration.
58 XmlCommentState xmlDocState = XmlCommentState.Allowed;
61 // Whether tokens have been seen on this line
63 bool tokens_seen = false;
66 // Whether a token has been seen on the file
67 // This is needed because `define' is not allowed to be used
68 // after a token has been seen.
70 bool any_token_seen = false;
72 static Hashtable tokenValues;
74 private static Hashtable TokenValueName
77 if (tokenValues == null)
78 tokenValues = GetTokenValueNameHash ();
84 private static Hashtable GetTokenValueNameHash ()
86 Type t = typeof (Token);
87 FieldInfo [] fields = t.GetFields ();
88 Hashtable hash = new Hashtable ();
89 foreach (FieldInfo field in fields) {
90 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
91 hash.Add (field.GetValue (null), field.Name);
97 // Returns a verbose representation of the current location
99 public string location {
103 if (current_token == Token.ERROR)
104 det = "detail: " + error_details;
108 // return "Line: "+line+" Col: "+col + "\n" +
109 // "VirtLine: "+ref_line +
110 // " Token: "+current_token + " " + det;
111 string current_token_name = TokenValueName [current_token] as string;
112 if (current_token_name == null)
113 current_token_name = current_token.ToString ();
115 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
123 public bool PropertyParsing {
125 return handle_get_set;
129 handle_get_set = value;
133 public bool AssemblyTargetParsing {
135 return handle_assembly;
139 handle_assembly = value;
143 public bool EventParsing {
145 return handle_remove_add;
149 handle_remove_add = value;
153 public XmlCommentState doc_state {
154 get { return xmlDocState; }
156 if (value == XmlCommentState.Allowed) {
157 check_incorrect_doc_comment ();
158 reset_doc_comment ();
164 public bool IsEscapedIdentifier (Location loc)
166 foreach (LocatedToken lt in escapedIdentifiers)
167 if (lt.Location.Equals (loc))
176 static CharArrayHashtable[] keywords;
177 static Hashtable keywordStrings = new Hashtable ();
178 static NumberStyles styles;
179 static NumberFormatInfo csharp_format_info;
182 // Values for the associated token returned
192 const int TAKING = 1;
193 const int TAKEN_BEFORE = 2;
194 const int ELSE_SEEN = 4;
195 const int PARENT_TAKING = 8;
196 const int REGION = 16;
199 // pre-processor if stack state:
203 static System.Text.StringBuilder string_builder;
205 const int max_id_size = 512;
206 static char [] id_builder = new char [max_id_size];
208 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
210 const int max_number_size = 512;
211 static char [] number_builder = new char [max_number_size];
212 static int number_pos;
215 // Details about the error encoutered by the tokenizer
217 string error_details;
219 public string error {
221 return error_details;
237 static void AddKeyword (string kw, int token) {
238 keywordStrings.Add (kw, kw);
239 if (keywords [kw.Length] == null) {
240 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
242 keywords [kw.Length] [kw.ToCharArray ()] = token;
245 static void InitTokens ()
247 keywords = new CharArrayHashtable [64];
249 AddKeyword ("__arglist", Token.ARGLIST);
250 AddKeyword ("abstract", Token.ABSTRACT);
251 AddKeyword ("as", Token.AS);
252 AddKeyword ("add", Token.ADD);
253 AddKeyword ("assembly", Token.ASSEMBLY);
254 AddKeyword ("base", Token.BASE);
255 AddKeyword ("bool", Token.BOOL);
256 AddKeyword ("break", Token.BREAK);
257 AddKeyword ("byte", Token.BYTE);
258 AddKeyword ("case", Token.CASE);
259 AddKeyword ("catch", Token.CATCH);
260 AddKeyword ("char", Token.CHAR);
261 AddKeyword ("checked", Token.CHECKED);
262 AddKeyword ("class", Token.CLASS);
263 AddKeyword ("const", Token.CONST);
264 AddKeyword ("continue", Token.CONTINUE);
265 AddKeyword ("decimal", Token.DECIMAL);
266 AddKeyword ("default", Token.DEFAULT);
267 AddKeyword ("delegate", Token.DELEGATE);
268 AddKeyword ("do", Token.DO);
269 AddKeyword ("double", Token.DOUBLE);
270 AddKeyword ("else", Token.ELSE);
271 AddKeyword ("enum", Token.ENUM);
272 AddKeyword ("event", Token.EVENT);
273 AddKeyword ("explicit", Token.EXPLICIT);
274 AddKeyword ("extern", Token.EXTERN);
275 AddKeyword ("false", Token.FALSE);
276 AddKeyword ("finally", Token.FINALLY);
277 AddKeyword ("fixed", Token.FIXED);
278 AddKeyword ("float", Token.FLOAT);
279 AddKeyword ("for", Token.FOR);
280 AddKeyword ("foreach", Token.FOREACH);
281 AddKeyword ("goto", Token.GOTO);
282 AddKeyword ("get", Token.GET);
283 AddKeyword ("if", Token.IF);
284 AddKeyword ("implicit", Token.IMPLICIT);
285 AddKeyword ("in", Token.IN);
286 AddKeyword ("int", Token.INT);
287 AddKeyword ("interface", Token.INTERFACE);
288 AddKeyword ("internal", Token.INTERNAL);
289 AddKeyword ("is", Token.IS);
290 AddKeyword ("lock", Token.LOCK);
291 AddKeyword ("long", Token.LONG);
292 AddKeyword ("namespace", Token.NAMESPACE);
293 AddKeyword ("new", Token.NEW);
294 AddKeyword ("null", Token.NULL);
295 AddKeyword ("object", Token.OBJECT);
296 AddKeyword ("operator", Token.OPERATOR);
297 AddKeyword ("out", Token.OUT);
298 AddKeyword ("override", Token.OVERRIDE);
299 AddKeyword ("params", Token.PARAMS);
300 AddKeyword ("private", Token.PRIVATE);
301 AddKeyword ("protected", Token.PROTECTED);
302 AddKeyword ("public", Token.PUBLIC);
303 AddKeyword ("readonly", Token.READONLY);
304 AddKeyword ("ref", Token.REF);
305 AddKeyword ("remove", Token.REMOVE);
306 AddKeyword ("return", Token.RETURN);
307 AddKeyword ("sbyte", Token.SBYTE);
308 AddKeyword ("sealed", Token.SEALED);
309 AddKeyword ("set", Token.SET);
310 AddKeyword ("short", Token.SHORT);
311 AddKeyword ("sizeof", Token.SIZEOF);
312 AddKeyword ("stackalloc", Token.STACKALLOC);
313 AddKeyword ("static", Token.STATIC);
314 AddKeyword ("string", Token.STRING);
315 AddKeyword ("struct", Token.STRUCT);
316 AddKeyword ("switch", Token.SWITCH);
317 AddKeyword ("this", Token.THIS);
318 AddKeyword ("throw", Token.THROW);
319 AddKeyword ("true", Token.TRUE);
320 AddKeyword ("try", Token.TRY);
321 AddKeyword ("typeof", Token.TYPEOF);
322 AddKeyword ("uint", Token.UINT);
323 AddKeyword ("ulong", Token.ULONG);
324 AddKeyword ("unchecked", Token.UNCHECKED);
325 AddKeyword ("unsafe", Token.UNSAFE);
326 AddKeyword ("ushort", Token.USHORT);
327 AddKeyword ("using", Token.USING);
328 AddKeyword ("virtual", Token.VIRTUAL);
329 AddKeyword ("void", Token.VOID);
330 AddKeyword ("volatile", Token.VOLATILE);
331 AddKeyword ("while", Token.WHILE);
332 AddKeyword ("partial", Token.PARTIAL);
341 csharp_format_info = NumberFormatInfo.InvariantInfo;
342 styles = NumberStyles.Float;
344 string_builder = new System.Text.StringBuilder ();
347 int GetKeyword (char[] id, int id_len)
350 * Keywords are stored in an array of hashtables grouped by their
354 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
356 object o = keywords [id_len] [id];
363 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
365 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
367 if (handle_assembly == false && res == Token.ASSEMBLY)
374 public Location Location {
375 get { return current_location; }
378 void define (string def)
380 if (!RootContext.AllDefines.Contains (def)){
381 RootContext.AllDefines [def] = true;
383 if (defines.Contains (def))
385 defines [def] = true;
388 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
390 this.ref_name = file;
391 this.file_name = file;
397 defines = new Hashtable ();
398 foreach (string def in defs)
402 xml_comment_buffer = new StringBuilder ();
405 // FIXME: This could be `Location.Push' but we have to
406 // find out why the MS compiler allows this
408 Mono.CSharp.Location.Push (file);
411 static bool is_identifier_start_character (char c)
413 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
416 static bool is_identifier_part_character (char c)
418 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
421 public static bool IsKeyword (string s)
423 return keywordStrings [s] != null;
426 public static bool IsValidIdentifier (string s)
428 if (s == null || s.Length == 0)
431 if (!is_identifier_start_character (s [0]))
434 for (int i = 1; i < s.Length; i ++)
435 if (! is_identifier_part_character (s [i]))
441 int is_punct (char c, ref bool doread)
451 return Token.OPEN_BRACE;
454 return Token.CLOSE_BRACE;
456 // To block doccomment inside attribute declaration.
457 if (doc_state == XmlCommentState.Allowed)
458 doc_state = XmlCommentState.NotAllowed;
459 return Token.OPEN_BRACKET;
461 return Token.CLOSE_BRACKET;
463 return Token.OPEN_PARENS;
465 if (deambiguate_close_parens == 0)
466 return Token.CLOSE_PARENS;
468 --deambiguate_close_parens;
470 // Save current position and parse next token.
471 int old = reader.Position;
472 int old_ref_line = ref_line;
475 // disable preprocessing directives when peeking
476 process_directives = false;
477 int new_token = token ();
478 process_directives = true;
479 reader.Position = old;
480 ref_line = old_ref_line;
484 if (new_token == Token.OPEN_PARENS)
485 return Token.CLOSE_PARENS_OPEN_PARENS;
486 else if (new_token == Token.MINUS)
487 return Token.CLOSE_PARENS_MINUS;
488 else if (IsCastToken (new_token))
489 return Token.CLOSE_PARENS_CAST;
491 return Token.CLOSE_PARENS_NO_CAST;
498 return Token.SEMICOLON;
514 t = Token.OP_ADD_ASSIGN;
528 t = Token.OP_SUB_ASSIGN;
560 } else if (d == '='){
562 return Token.OP_AND_ASSIGN;
565 return Token.BITWISE_AND;
572 } else if (d == '='){
574 return Token.OP_OR_ASSIGN;
576 return Token.BITWISE_OR;
582 return Token.OP_MULT_ASSIGN;
591 return Token.OP_DIV_ASSIGN;
599 return Token.OP_MOD_ASSIGN;
601 return Token.PERCENT;
607 return Token.OP_XOR_ASSIGN;
619 return Token.OP_SHIFT_LEFT_ASSIGN;
621 return Token.OP_SHIFT_LEFT;
622 } else if (d == '='){
636 return Token.OP_SHIFT_RIGHT_ASSIGN;
638 return Token.OP_SHIFT_RIGHT;
639 } else if (d == '='){
648 return Token.DOUBLE_COLON;
657 int deambiguate_close_parens = 0;
659 public void Deambiguate_CloseParens ()
662 deambiguate_close_parens++;
665 void Error_NumericConstantTooLong ()
667 Report.Error (1021, Location, "Numeric constant too long");
670 bool decimal_digits (int c)
673 bool seen_digits = false;
676 if (number_pos == max_number_size)
677 Error_NumericConstantTooLong ();
678 number_builder [number_pos++] = (char) c;
682 // We use peekChar2, because decimal_digits needs to do a
683 // 2-character look-ahead (5.ToString for example).
685 while ((d = peekChar2 ()) != -1){
686 if (d >= '0' && d <= '9'){
687 if (number_pos == max_number_size)
688 Error_NumericConstantTooLong ();
689 number_builder [number_pos++] = (char) d;
699 static bool is_hex (int e)
701 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
704 static int real_type_suffix (int c)
710 t = Token.LITERAL_FLOAT;
713 t = Token.LITERAL_DOUBLE;
716 t= Token.LITERAL_DECIMAL;
724 int integer_type_suffix (ulong ul, int c)
726 bool is_unsigned = false;
727 bool is_long = false;
730 bool scanning = true;
741 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
743 // if we have not seen anything in between
746 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
749 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
774 if (is_long && is_unsigned){
776 return Token.LITERAL_INTEGER;
777 } else if (is_unsigned){
778 // uint if possible, or ulong else.
780 if ((ul & 0xffffffff00000000) == 0)
785 // long if possible, ulong otherwise
786 if ((ul & 0x8000000000000000) != 0)
791 // int, uint, long or ulong in that order
792 if ((ul & 0xffffffff00000000) == 0){
795 if ((ui & 0x80000000) != 0)
800 if ((ul & 0x8000000000000000) != 0)
806 return Token.LITERAL_INTEGER;
810 // given `c' as the next char in the input decide whether
811 // we need to convert to a special type, and then choose
812 // the best representation for the integer
814 int adjust_int (int c)
818 ulong ul = (uint) (number_builder [0] - '0');
820 for (int i = 1; i < number_pos; i++){
821 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
823 return integer_type_suffix (ul, c);
825 uint ui = (uint) (number_builder [0] - '0');
827 for (int i = 1; i < number_pos; i++){
828 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
830 return integer_type_suffix (ui, c);
832 } catch (OverflowException) {
833 error_details = "Integral constant is too large";
834 Report.Error (1021, Location, error_details);
836 return Token.LITERAL_INTEGER;
838 catch (FormatException) {
839 Report.Error (1013, Location, "Invalid number");
841 return Token.LITERAL_INTEGER;
845 int adjust_real (int t)
847 string s = new String (number_builder, 0, number_pos);
848 const string error_details = "Floating-point constant is outside the range of type `{0}'";
851 case Token.LITERAL_DECIMAL:
853 val = System.Decimal.Parse (s, styles, csharp_format_info);
854 } catch (OverflowException) {
856 Report.Error (594, Location, error_details, "decimal");
859 case Token.LITERAL_FLOAT:
861 val = float.Parse (s, styles, csharp_format_info);
862 } catch (OverflowException) {
864 Report.Error (594, Location, error_details, "float");
868 case Token.LITERAL_DOUBLE:
870 t = Token.LITERAL_DOUBLE;
872 val = System.Double.Parse (s, styles, csharp_format_info);
873 } catch (OverflowException) {
875 Report.Error (594, Location, error_details, "double");
888 while ((d = peekChar ()) != -1){
890 number_builder [number_pos++] = (char) d;
896 string s = new String (number_builder, 0, number_pos);
899 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
901 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
902 } catch (OverflowException){
903 error_details = "Integral constant is too large";
904 Report.Error (1021, Location, error_details);
906 return Token.LITERAL_INTEGER;
908 catch (FormatException) {
909 Report.Error (1013, Location, "Invalid number");
911 return Token.LITERAL_INTEGER;
914 return integer_type_suffix (ul, peekChar ());
918 // Invoked if we know we have .digits or digits
920 int is_number (int c)
922 bool is_real = false;
927 if (c >= '0' && c <= '9'){
929 int peek = peekChar ();
931 if (peek == 'x' || peek == 'X')
932 return handle_hex ();
939 // We need to handle the case of
940 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
943 if (decimal_digits ('.')){
949 return adjust_int (-1);
953 if (c == 'e' || c == 'E'){
955 if (number_pos == max_number_size)
956 Error_NumericConstantTooLong ();
957 number_builder [number_pos++] = 'e';
961 if (number_pos == max_number_size)
962 Error_NumericConstantTooLong ();
963 number_builder [number_pos++] = '+';
965 } else if (c == '-') {
966 if (number_pos == max_number_size)
967 Error_NumericConstantTooLong ();
968 number_builder [number_pos++] = '-';
971 if (number_pos == max_number_size)
972 Error_NumericConstantTooLong ();
973 number_builder [number_pos++] = '+';
980 type = real_type_suffix (c);
981 if (type == Token.NONE && !is_real){
983 return adjust_int (c);
987 if (type == Token.NONE){
992 return adjust_real (type);
994 Console.WriteLine ("This should not be reached");
995 throw new Exception ("Is Number should never reach this point");
999 // Accepts exactly count (4 or 8) hex, no more no less
1001 int getHex (int count, out bool error)
1006 int top = count != -1 ? count : 4;
1010 for (i = 0; i < top; i++){
1013 if (c >= '0' && c <= '9')
1014 c = (int) c - (int) '0';
1015 else if (c >= 'A' && c <= 'F')
1016 c = (int) c - (int) 'A' + 10;
1017 else if (c >= 'a' && c <= 'f')
1018 c = (int) c - (int) 'a' + 10;
1024 total = (total * 16) + c;
1026 int p = peekChar ();
1029 if (!is_hex ((char)p))
1070 v = getHex (-1, out error);
1075 v = getHex (4, out error);
1080 v = getHex (8, out error);
1085 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1095 if (putback_char != -1) {
1114 if (putback_char != -1)
1115 return putback_char;
1116 putback_char = reader.Read ();
1117 return putback_char;
1122 if (putback_char != -1)
1123 return putback_char;
1124 return reader.Peek ();
1127 void putback (int c)
1129 if (putback_char != -1){
1130 Console.WriteLine ("Col: " + col);
1131 Console.WriteLine ("Row: " + line);
1132 Console.WriteLine ("Name: " + ref_name.Name);
1133 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1134 throw new Exception ("This should not happen putback on putback");
1136 if (c == '\n' || col == 0) {
1137 // It won't happen though.
1147 public bool advance ()
1149 return peekChar () != -1;
1152 public Object Value {
1158 public Object value ()
1163 static bool IsCastToken (int token)
1168 case Token.IDENTIFIER:
1169 case Token.LITERAL_INTEGER:
1170 case Token.LITERAL_FLOAT:
1171 case Token.LITERAL_DOUBLE:
1172 case Token.LITERAL_DECIMAL:
1173 case Token.LITERAL_CHARACTER:
1174 case Token.LITERAL_STRING:
1186 case Token.UNCHECKED:
1190 // These can be part of a member access
1210 current_token = xtoken ();
1211 return current_token;
1214 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1216 void get_cmd_arg (out string cmd, out string arg)
1220 tokens_seen = false;
1222 static_cmd_arg.Length = 0;
1224 // skip over white space
1225 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1229 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1230 if (is_identifier_part_character ((char) c)){
1231 static_cmd_arg.Append ((char) c);
1239 cmd = static_cmd_arg.ToString ();
1245 // skip over white space
1246 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1251 } else if (c == '\r'){
1253 } else if (c == -1){
1258 static_cmd_arg.Length = 0;
1259 static_cmd_arg.Append ((char) c);
1261 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1262 static_cmd_arg.Append ((char) c);
1265 arg = static_cmd_arg.ToString ().Trim ();
1269 // Handles the #line directive
1271 bool PreProcessLine (string arg)
1273 if (arg.Length == 0)
1276 if (arg == "default"){
1278 ref_name = file_name;
1279 Location.Push (ref_name);
1281 } else if (arg == "hidden"){
1283 // We ignore #line hidden
1291 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1292 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1295 char [] quotes = { '\"' };
1297 string name = arg.Substring (pos). Trim (quotes);
1298 ref_name = Location.LookupFile (name);
1299 file_name.HasLineDirective = true;
1300 ref_name.HasLineDirective = true;
1301 Location.Push (ref_name);
1303 ref_line = System.Int32.Parse (arg);
1313 // Handles #define and #undef
1315 void PreProcessDefinition (bool is_define, string arg)
1317 if (arg.Length == 0 || arg == "true" || arg == "false"){
1318 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1322 char[] whitespace = { ' ', '\t' };
1323 if (arg.IndexOfAny (whitespace) != -1){
1324 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1328 if (!is_identifier_start_character (arg [0]))
1329 Report.Error (1001, Location, "Identifier expected: " + arg);
1331 foreach (char c in arg.Substring (1)){
1332 if (!is_identifier_part_character (c)){
1333 Report.Error (1001, Location, "Identifier expected: " + arg);
1339 if (defines == null)
1340 defines = new Hashtable ();
1343 if (defines == null)
1345 if (defines.Contains (arg))
1346 defines.Remove (arg);
1351 /// Handles #pragma directive
1353 void PreProcessPragma (string arg)
1355 const string warning = "warning";
1356 const string w_disable = "warning disable";
1357 const string w_restore = "warning restore";
1359 if (arg == w_disable) {
1360 Report.RegisterWarningRegion (Location).WarningDisable (line);
1364 if (arg == w_restore) {
1365 Report.RegisterWarningRegion (Location).WarningEnable (line);
1369 if (arg.StartsWith (w_disable)) {
1370 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1371 foreach (int code in codes) {
1373 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1378 if (arg.StartsWith (w_restore)) {
1379 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1380 Hashtable w_table = Report.warning_ignore_table;
1381 foreach (int code in codes) {
1382 if (w_table != null && w_table.Contains (code))
1383 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1384 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1389 if (arg.StartsWith (warning)) {
1390 Report.Warning (1634, 1, Location, "Expected disable or restore");
1394 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1397 int[] ParseNumbers (string text)
1399 string[] string_array = text.Split (',');
1400 int[] values = new int [string_array.Length];
1402 foreach (string string_code in string_array) {
1404 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1406 catch (FormatException) {
1407 Report.Warning (1692, 1, Location, "Invalid number");
1413 bool eval_val (string s)
1420 if (defines == null)
1422 if (defines.Contains (s))
1428 bool pp_primary (ref string s)
1437 s = s.Substring (1);
1438 bool val = pp_expr (ref s);
1439 if (s.Length > 0 && s [0] == ')'){
1440 s = s.Substring (1);
1443 Error_InvalidDirective ();
1447 if (is_identifier_start_character (c)){
1453 if (is_identifier_part_character (c)){
1457 bool v = eval_val (s.Substring (0, j));
1458 s = s.Substring (j);
1461 bool vv = eval_val (s);
1466 Error_InvalidDirective ();
1470 bool pp_unary (ref string s)
1477 if (len > 1 && s [1] == '='){
1478 Error_InvalidDirective ();
1481 s = s.Substring (1);
1482 return ! pp_primary (ref s);
1484 return pp_primary (ref s);
1486 Error_InvalidDirective ();
1491 bool pp_eq (ref string s)
1493 bool va = pp_unary (ref s);
1499 if (len > 2 && s [1] == '='){
1500 s = s.Substring (2);
1501 return va == pp_unary (ref s);
1503 Error_InvalidDirective ();
1506 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1507 s = s.Substring (2);
1509 return va != pp_unary (ref s);
1518 bool pp_and (ref string s)
1520 bool va = pp_eq (ref s);
1526 if (len > 2 && s [1] == '&'){
1527 s = s.Substring (2);
1528 return (va & pp_and (ref s));
1530 Error_InvalidDirective ();
1539 // Evaluates an expression for `#if' or `#elif'
1541 bool pp_expr (ref string s)
1543 bool va = pp_and (ref s);
1550 if (len > 2 && s [1] == '|'){
1551 s = s.Substring (2);
1552 return va | pp_expr (ref s);
1554 Error_InvalidDirective ();
1563 bool eval (string s)
1565 bool v = pp_expr (ref s);
1568 Error_InvalidDirective ();
1575 void Error_InvalidDirective ()
1577 Report.Error (1517, Location, "Invalid preprocessor directive");
1580 void Error_UnexpectedDirective (string extra)
1584 "Unexpected processor directive (" + extra + ")");
1587 void Error_TokensSeen ()
1589 Report.Error (1032, Location,
1590 "Cannot define or undefine preprocessor symbols after first token in file");
1594 // Set to false to stop handling preprocesser directives
1596 bool process_directives = true;
1599 // if true, then the code continues processing the code
1600 // if false, the code stays in a loop until another directive is
1603 bool handle_preprocessing_directive (bool caller_is_taking)
1606 bool region_directive = false;
1608 get_cmd_arg (out cmd, out arg);
1610 // Eat any trailing whitespaces and single-line comments
1611 if (arg.IndexOf ("//") != -1)
1612 arg = arg.Substring (0, arg.IndexOf ("//"));
1613 arg = arg.TrimEnd (' ', '\t');
1616 // The first group of pre-processing instructions is always processed
1620 if (RootContext.Version == LanguageVersion.ISO_1) {
1621 Report.FeatureIsNotStandardized (Location, "#pragma");
1622 return caller_is_taking;
1625 PreProcessPragma (arg);
1626 return caller_is_taking;
1629 if (!PreProcessLine (arg))
1632 "The line number specified for #line directive is missing or invalid");
1633 return caller_is_taking;
1636 region_directive = true;
1641 region_directive = true;
1645 if (arg.Length == 0){
1646 Error_InvalidDirective ();
1649 bool taking = false;
1650 if (ifstack == null)
1651 ifstack = new Stack (2);
1653 if (ifstack.Count == 0){
1656 int state = (int) ifstack.Peek ();
1657 if ((state & TAKING) != 0)
1661 if (eval (arg) && taking){
1662 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1663 if (region_directive)
1665 ifstack.Push (push);
1668 int push = (taking ? PARENT_TAKING : 0);
1669 if (region_directive)
1671 ifstack.Push (push);
1676 if (ifstack == null || ifstack.Count == 0){
1677 Error_UnexpectedDirective ("no #if for this #endif");
1680 int pop = (int) ifstack.Pop ();
1682 if (region_directive && ((pop & REGION) == 0))
1683 Report.Error (1027, Location, "Expected `#endif' directive");
1684 else if (!region_directive && ((pop & REGION) != 0))
1685 Report.Error (1038, Location, "#endregion directive expected");
1687 if (!region_directive && arg.Length != 0) {
1688 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1691 if (ifstack.Count == 0)
1694 int state = (int) ifstack.Peek ();
1696 if ((state & TAKING) != 0)
1704 if (ifstack == null || ifstack.Count == 0){
1705 Error_UnexpectedDirective ("no #if for this #elif");
1708 int state = (int) ifstack.Peek ();
1710 if ((state & REGION) != 0) {
1711 Report.Error (1038, Location, "#endregion directive expected");
1715 if ((state & ELSE_SEEN) != 0){
1716 Error_UnexpectedDirective ("#elif not valid after #else");
1720 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1723 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1724 state = (int) ifstack.Pop ();
1725 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1732 if (ifstack == null || ifstack.Count == 0){
1733 Error_UnexpectedDirective ("no #if for this #else");
1736 int state = (int) ifstack.Peek ();
1738 if ((state & REGION) != 0) {
1739 Report.Error (1038, Location, "#endregion directive expected");
1743 if ((state & ELSE_SEEN) != 0){
1744 Error_UnexpectedDirective ("#else within #else");
1751 if ((state & TAKEN_BEFORE) == 0){
1752 ret = ((state & PARENT_TAKING) != 0);
1761 ifstack.Push (state | ELSE_SEEN);
1768 // These are only processed if we are in a `taking' block
1770 if (!caller_is_taking)
1775 if (any_token_seen){
1776 Error_TokensSeen ();
1779 PreProcessDefinition (true, arg);
1783 if (any_token_seen){
1784 Error_TokensSeen ();
1787 PreProcessDefinition (false, arg);
1791 Report.Error (1029, Location, "#error: '" + arg + "'");
1795 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
1799 Report.Error (1024, Location, "Wrong preprocessor directive");
1804 private int consume_string (bool quoted)
1807 string_builder.Length = 0;
1809 while ((c = getChar ()) != -1){
1811 if (quoted && peekChar () == '"'){
1812 string_builder.Append ((char) c);
1816 val = string_builder.ToString ();
1817 return Token.LITERAL_STRING;
1823 Report.Error (1010, Location, "Newline in constant");
1831 string_builder.Append ((char) c);
1834 Report.Error (1039, Location, "Unterminated string literal");
1838 private int consume_identifier (int s)
1840 int res = consume_identifier (s, false);
1842 if (doc_state == XmlCommentState.Allowed)
1843 doc_state = XmlCommentState.NotAllowed;
1846 case Token.NAMESPACE:
1847 check_incorrect_doc_comment ();
1851 if (res == Token.PARTIAL) {
1852 // Save current position and parse next token.
1853 int old = reader.Position;
1854 int old_putback = putback_char;
1855 int old_ref_line = ref_line;
1860 int next_token = token ();
1861 bool ok = (next_token == Token.CLASS) ||
1862 (next_token == Token.STRUCT) ||
1863 (next_token == Token.INTERFACE) ||
1864 (next_token == Token.ENUM); // "partial" is a keyword in 'partial enum', even though it's not valid
1866 reader.Position = old;
1867 ref_line = old_ref_line;
1869 putback_char = old_putback;
1874 val = new LocatedToken (Location, "partial");
1875 return Token.IDENTIFIER;
1882 private int consume_identifier (int s, bool quoted)
1887 id_builder [0] = (char) s;
1889 current_location = new Location (ref_line, Col);
1891 while ((c = getChar ()) != -1) {
1892 if (is_identifier_part_character ((char) c)){
1893 if (pos == max_id_size){
1894 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1898 id_builder [pos++] = (char) c;
1899 // putback_char = -1;
1901 // putback_char = c;
1908 // Optimization: avoids doing the keyword lookup
1909 // on uppercase letters and _
1911 if (!quoted && (s >= 'a' || s == '_')){
1912 int keyword = GetKeyword (id_builder, pos);
1913 if (keyword != -1) {
1920 // Keep identifiers in an array of hashtables to avoid needless
1924 if (identifiers [pos] != null) {
1925 val = identifiers [pos][id_builder];
1927 val = new LocatedToken (Location, (string) val);
1929 escapedIdentifiers.Add (val);
1930 return Token.IDENTIFIER;
1934 identifiers [pos] = new CharArrayHashtable (pos);
1936 val = new String (id_builder, 0, pos);
1937 if (RootContext.Version == LanguageVersion.ISO_1) {
1938 for (int i = 1; i < id_builder.Length; i += 3) {
1939 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
1940 Report.Error (1638, Location,
1941 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
1947 char [] chars = new char [pos];
1948 Array.Copy (id_builder, chars, pos);
1950 identifiers [pos] [chars] = val;
1952 val = new LocatedToken (Location, (string) val);
1954 escapedIdentifiers.Add (val);
1955 return Token.IDENTIFIER;
1958 public int xtoken ()
1961 bool doread = false;
1964 // Whether we have seen comments on the current line
1965 bool comments_seen = false;
1968 // optimization: eliminate col and implement #directive semantic correctly.
1969 for (;(c = getChar ()) != -1;) {
1977 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1981 if (peekChar () == '\n')
1984 any_token_seen |= tokens_seen;
1985 tokens_seen = false;
1986 comments_seen = false;
1990 // Handle double-slash comments.
1992 int d = peekChar ();
1996 if (RootContext.Documentation != null && peekChar () == '/') {
1998 // Don't allow ////.
1999 if ((d = peekChar ()) != '/') {
2000 update_comment_location ();
2001 if (doc_state == XmlCommentState.Allowed)
2002 handle_one_line_xml_comment ();
2003 else if (doc_state == XmlCommentState.NotAllowed)
2004 warn_incorrect_doc_comment ();
2007 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2010 any_token_seen |= tokens_seen;
2011 tokens_seen = false;
2012 comments_seen = false;
2014 } else if (d == '*'){
2016 bool docAppend = false;
2017 if (RootContext.Documentation != null && peekChar () == '*') {
2019 update_comment_location ();
2020 // But when it is /**/, just do nothing.
2021 if (peekChar () == '/') {
2025 if (doc_state == XmlCommentState.Allowed)
2027 else if (doc_state == XmlCommentState.NotAllowed)
2028 warn_incorrect_doc_comment ();
2031 int current_comment_start = 0;
2033 current_comment_start = xml_comment_buffer.Length;
2034 xml_comment_buffer.Append (Environment.NewLine);
2037 Location start_location = Location;
2039 while ((d = getChar ()) != -1){
2040 if (d == '*' && peekChar () == '/'){
2042 comments_seen = true;
2046 xml_comment_buffer.Append ((char) d);
2049 any_token_seen |= tokens_seen;
2050 tokens_seen = false;
2052 // Reset 'comments_seen' just to be consistent.
2053 // It doesn't matter either way, here.
2055 comments_seen = false;
2059 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2062 update_formatted_doc_comment (current_comment_start);
2065 goto is_punct_label;
2069 if (is_identifier_start_character ((char)c)){
2071 return consume_identifier (c);
2075 current_location = new Location (ref_line, Col);
2076 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2086 any_token_seen |= tokens_seen;
2087 tokens_seen = false;
2088 comments_seen = false;
2092 if (c >= '0' && c <= '9'){
2094 return is_number (c);
2099 int peek = peekChar ();
2100 if (peek >= '0' && peek <= '9')
2101 return is_number (c);
2105 /* For now, ignore pre-processor commands */
2106 // FIXME: In C# the '#' is not limited to appear
2107 // on the first column.
2109 // return NONE if we're not processing directives (during token peeks)
2110 if (!process_directives)
2114 if (tokens_seen || comments_seen) {
2115 error_details = "Preprocessor directives must appear as the first" +
2116 " non-whitespace character on a line.";
2118 Report.Error (1040, Location, error_details);
2125 cont = handle_preprocessing_directive (cont);
2131 bool skipping = false;
2132 for (;(c = getChar ()) != -1;){
2135 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2139 if (c == '#' && !skipping)
2142 any_token_seen |= tokens_seen;
2143 tokens_seen = false;
2145 Report.Error (1027, Location, "Expected `#endif' directive");
2150 return consume_string (false);
2156 error_details = "Empty character literal";
2157 Report.Error (1011, Location, error_details);
2160 if (c == '\r' || c == '\n') {
2161 Report.Error (1010, Location, "Newline in constant");
2167 val = new System.Char ();
2172 error_details = "Too many characters in character literal";
2173 Report.Error (1012, Location, error_details);
2175 // Try to recover, read until newline or next "'"
2176 while ((c = getChar ()) != -1){
2185 return Token.LITERAL_CHARACTER;
2192 return consume_string (true);
2193 } else if (is_identifier_start_character ((char) c)){
2194 return consume_identifier (c, true);
2196 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2200 error_details = ((char)c).ToString ();
2209 // Handles one line xml comment
2211 private void handle_one_line_xml_comment ()
2214 while ((c = peekChar ()) == ' ')
2215 getChar (); // skip heading whitespaces.
2216 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2217 xml_comment_buffer.Append ((char) getChar ());
2219 if (c == '\r' || c == '\n')
2220 xml_comment_buffer.Append (Environment.NewLine);
2224 // Remove heading "*" in Javadoc-like xml documentation.
2226 private void update_formatted_doc_comment (int current_comment_start)
2228 int length = xml_comment_buffer.Length - current_comment_start;
2229 string [] lines = xml_comment_buffer.ToString (
2230 current_comment_start,
2231 length).Replace ("\r", "").Split ('\n');
2233 // The first line starts with /**, thus it is not target
2234 // for the format check.
2235 for (int i = 1; i < lines.Length; i++) {
2236 string s = lines [i];
2237 int idx = s.IndexOf ('*');
2240 if (i < lines.Length - 1)
2244 head = s.Substring (0, idx);
2245 foreach (char c in head)
2248 lines [i] = s.Substring (idx + 1);
2250 xml_comment_buffer.Remove (current_comment_start, length);
2251 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2255 // Updates current comment location.
2257 private void update_comment_location ()
2259 if (current_comment_location.IsNull) {
2260 // "-2" is for heading "//" or "/*"
2261 current_comment_location =
2262 new Location (ref_line, col - 2);
2267 // Checks if there was incorrect doc comments and raise
2270 public void check_incorrect_doc_comment ()
2272 if (xml_comment_buffer.Length > 0)
2273 warn_incorrect_doc_comment ();
2277 // Raises a warning when tokenizer found incorrect doccomment
2280 private void warn_incorrect_doc_comment ()
2282 if (doc_state != XmlCommentState.Error) {
2283 doc_state = XmlCommentState.Error;
2284 // in csc, it is 'XML comment is not placed on
2285 // a valid language element'. But that does not
2287 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2292 // Consumes the saved xml comment lines (if any)
2293 // as for current target member or type.
2295 public string consume_doc_comment ()
2297 if (xml_comment_buffer.Length > 0) {
2298 string ret = xml_comment_buffer.ToString ();
2299 reset_doc_comment ();
2305 void reset_doc_comment ()
2307 xml_comment_buffer.Length = 0;
2308 current_comment_location = Location.Null;
2311 public void cleanup ()
2313 if (ifstack != null && ifstack.Count >= 1) {
2314 int state = (int) ifstack.Pop ();
2315 if ((state & REGION) != 0)
2316 Report.Error (1038, Location, "#endregion directive expected");
2318 Report.Error (1027, Location, "Expected `#endif' directive");
2325 // Indicates whether it accepts XML documentation or not.
2327 public enum XmlCommentState {
2328 // comment is allowed in this state.
2330 // comment is not allowed in this state.
2332 // once comments appeared when it is NotAllowed, then the
2333 // state is changed to it, until the state is changed to