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)
14 * Make sure we accept the proper Unicode ranges, per the spec.
20 using System.Collections;
22 using System.Globalization;
23 using System.Reflection;
28 /// Tokenizer for C# source code.
31 public class Tokenizer : yyParser.yyInput
33 SeekableStreamReader reader;
34 public SourceFile ref_name;
35 public SourceFile file_name;
36 public int ref_line = 1;
39 public int current_token;
40 bool handle_get_set = false;
41 bool handle_remove_add = false;
42 bool handle_assembly = false;
45 // Whether tokens have been seen on this line
47 bool tokens_seen = false;
50 // Whether a token has been seen on the file
51 // This is needed because `define' is not allowed to be used
52 // after a token has been seen.
54 bool any_token_seen = false;
55 static Hashtable tokenValues;
57 private static Hashtable TokenValueName
60 if (tokenValues == null)
61 tokenValues = GetTokenValueNameHash ();
67 private static Hashtable GetTokenValueNameHash ()
69 Type t = typeof (Token);
70 FieldInfo [] fields = t.GetFields ();
71 Hashtable hash = new Hashtable ();
72 foreach (FieldInfo field in fields) {
73 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
74 hash.Add (field.GetValue (null), field.Name);
80 // Returns a verbose representation of the current location
82 public string location {
86 if (current_token == Token.ERROR)
87 det = "detail: " + error_details;
91 // return "Line: "+line+" Col: "+col + "\n" +
92 // "VirtLine: "+ref_line +
93 // " Token: "+current_token + " " + det;
94 string current_token_name = TokenValueName [current_token] as string;
95 if (current_token_name == null)
96 current_token_name = current_token.ToString ();
98 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
106 public bool PropertyParsing {
108 return handle_get_set;
112 handle_get_set = value;
116 public bool AssemblyTargetParsing {
118 return handle_assembly;
122 handle_assembly = value;
126 public bool EventParsing {
128 return handle_remove_add;
132 handle_remove_add = value;
139 static CharArrayHashtable[] keywords;
140 static NumberStyles styles;
141 static NumberFormatInfo csharp_format_info;
144 // Values for the associated token returned
154 const int TAKING = 1;
155 const int TAKEN_BEFORE = 2;
156 const int ELSE_SEEN = 4;
157 const int PARENT_TAKING = 8;
158 const int REGION = 16;
161 // pre-processor if stack state:
165 static System.Text.StringBuilder string_builder;
167 const int max_id_size = 512;
168 static char [] id_builder = new char [max_id_size];
170 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
172 const int max_number_size = 128;
173 static char [] number_builder = new char [max_number_size];
174 static int number_pos;
177 // Details about the error encoutered by the tokenizer
179 string error_details;
181 public string error {
183 return error_details;
199 static void AddKeyword (string kw, int token) {
200 if (keywords [kw.Length] == null) {
201 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
203 keywords [kw.Length] [kw.ToCharArray ()] = token;
206 static void InitTokens ()
208 keywords = new CharArrayHashtable [64];
210 AddKeyword ("__arglist", Token.ARGLIST);
211 AddKeyword ("abstract", Token.ABSTRACT);
212 AddKeyword ("as", Token.AS);
213 AddKeyword ("add", Token.ADD);
214 AddKeyword ("assembly", Token.ASSEMBLY);
215 AddKeyword ("base", Token.BASE);
216 AddKeyword ("bool", Token.BOOL);
217 AddKeyword ("break", Token.BREAK);
218 AddKeyword ("byte", Token.BYTE);
219 AddKeyword ("case", Token.CASE);
220 AddKeyword ("catch", Token.CATCH);
221 AddKeyword ("char", Token.CHAR);
222 AddKeyword ("checked", Token.CHECKED);
223 AddKeyword ("class", Token.CLASS);
224 AddKeyword ("const", Token.CONST);
225 AddKeyword ("continue", Token.CONTINUE);
226 AddKeyword ("decimal", Token.DECIMAL);
227 AddKeyword ("default", Token.DEFAULT);
228 AddKeyword ("delegate", Token.DELEGATE);
229 AddKeyword ("do", Token.DO);
230 AddKeyword ("double", Token.DOUBLE);
231 AddKeyword ("else", Token.ELSE);
232 AddKeyword ("enum", Token.ENUM);
233 AddKeyword ("event", Token.EVENT);
234 AddKeyword ("explicit", Token.EXPLICIT);
235 AddKeyword ("extern", Token.EXTERN);
236 AddKeyword ("false", Token.FALSE);
237 AddKeyword ("finally", Token.FINALLY);
238 AddKeyword ("fixed", Token.FIXED);
239 AddKeyword ("float", Token.FLOAT);
240 AddKeyword ("for", Token.FOR);
241 AddKeyword ("foreach", Token.FOREACH);
242 AddKeyword ("goto", Token.GOTO);
243 AddKeyword ("get", Token.GET);
244 AddKeyword ("if", Token.IF);
245 AddKeyword ("implicit", Token.IMPLICIT);
246 AddKeyword ("in", Token.IN);
247 AddKeyword ("int", Token.INT);
248 AddKeyword ("interface", Token.INTERFACE);
249 AddKeyword ("internal", Token.INTERNAL);
250 AddKeyword ("is", Token.IS);
251 AddKeyword ("lock", Token.LOCK);
252 AddKeyword ("long", Token.LONG);
253 AddKeyword ("namespace", Token.NAMESPACE);
254 AddKeyword ("new", Token.NEW);
255 AddKeyword ("null", Token.NULL);
256 AddKeyword ("object", Token.OBJECT);
257 AddKeyword ("operator", Token.OPERATOR);
258 AddKeyword ("out", Token.OUT);
259 AddKeyword ("override", Token.OVERRIDE);
260 AddKeyword ("params", Token.PARAMS);
261 AddKeyword ("private", Token.PRIVATE);
262 AddKeyword ("protected", Token.PROTECTED);
263 AddKeyword ("public", Token.PUBLIC);
264 AddKeyword ("readonly", Token.READONLY);
265 AddKeyword ("ref", Token.REF);
266 AddKeyword ("remove", Token.REMOVE);
267 AddKeyword ("return", Token.RETURN);
268 AddKeyword ("sbyte", Token.SBYTE);
269 AddKeyword ("sealed", Token.SEALED);
270 AddKeyword ("set", Token.SET);
271 AddKeyword ("short", Token.SHORT);
272 AddKeyword ("sizeof", Token.SIZEOF);
273 AddKeyword ("stackalloc", Token.STACKALLOC);
274 AddKeyword ("static", Token.STATIC);
275 AddKeyword ("string", Token.STRING);
276 AddKeyword ("struct", Token.STRUCT);
277 AddKeyword ("switch", Token.SWITCH);
278 AddKeyword ("this", Token.THIS);
279 AddKeyword ("throw", Token.THROW);
280 AddKeyword ("true", Token.TRUE);
281 AddKeyword ("try", Token.TRY);
282 AddKeyword ("typeof", Token.TYPEOF);
283 AddKeyword ("uint", Token.UINT);
284 AddKeyword ("ulong", Token.ULONG);
285 AddKeyword ("unchecked", Token.UNCHECKED);
286 AddKeyword ("unsafe", Token.UNSAFE);
287 AddKeyword ("ushort", Token.USHORT);
288 AddKeyword ("using", Token.USING);
289 AddKeyword ("virtual", Token.VIRTUAL);
290 AddKeyword ("void", Token.VOID);
291 AddKeyword ("volatile", Token.VOLATILE);
292 AddKeyword ("while", Token.WHILE);
293 AddKeyword ("partial", Token.PARTIAL);
302 csharp_format_info = NumberFormatInfo.InvariantInfo;
303 styles = NumberStyles.Float;
305 string_builder = new System.Text.StringBuilder ();
308 int GetKeyword (char[] id, int id_len)
311 * Keywords are stored in an array of hashtables grouped by their
315 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
317 object o = keywords [id_len] [id];
324 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
326 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
328 if (handle_assembly == false && res == Token.ASSEMBLY)
335 public Location Location {
337 return new Location (ref_line);
341 void define (string def)
343 if (!RootContext.AllDefines.Contains (def)){
344 RootContext.AllDefines [def] = true;
346 if (defines.Contains (def))
348 defines [def] = true;
351 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
353 this.ref_name = file;
354 this.file_name = file;
360 defines = new Hashtable ();
361 foreach (string def in defs)
366 // FIXME: This could be `Location.Push' but we have to
367 // find out why the MS compiler allows this
369 Mono.CSharp.Location.Push (file);
372 public static void Cleanup () {
376 static bool is_identifier_start_character (char c)
378 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
381 static bool is_identifier_part_character (char c)
383 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
386 public static bool IsValidIdentifier (string s)
388 if (s == null || s.Length == 0)
391 if (!is_identifier_start_character (s [0]))
394 for (int i = 1; i < s.Length; i ++)
395 if (! is_identifier_part_character (s [i]))
401 int is_punct (char c, ref bool doread)
410 return Token.OPEN_BRACE;
412 return Token.CLOSE_BRACE;
414 return Token.OPEN_BRACKET;
416 return Token.CLOSE_BRACKET;
418 return Token.OPEN_PARENS;
420 if (deambiguate_close_parens == 0)
421 return Token.CLOSE_PARENS;
423 --deambiguate_close_parens;
425 // Save current position and parse next token.
426 int old = reader.Position;
427 int new_token = token ();
428 reader.Position = old;
431 if (new_token == Token.OPEN_PARENS)
432 return Token.CLOSE_PARENS_OPEN_PARENS;
433 else if (new_token == Token.MINUS)
434 return Token.CLOSE_PARENS_MINUS;
435 else if (IsCastToken (new_token))
436 return Token.CLOSE_PARENS_CAST;
438 return Token.CLOSE_PARENS_NO_CAST;
446 return Token.SEMICOLON;
459 t = Token.OP_ADD_ASSIGN;
469 t = Token.OP_SUB_ASSIGN;
498 } else if (d == '='){
500 return Token.OP_AND_ASSIGN;
502 return Token.BITWISE_AND;
509 } else if (d == '='){
511 return Token.OP_OR_ASSIGN;
513 return Token.BITWISE_OR;
519 return Token.OP_MULT_ASSIGN;
527 return Token.OP_DIV_ASSIGN;
535 return Token.OP_MOD_ASSIGN;
537 return Token.PERCENT;
543 return Token.OP_XOR_ASSIGN;
555 return Token.OP_SHIFT_LEFT_ASSIGN;
557 return Token.OP_SHIFT_LEFT;
558 } else if (d == '='){
572 return Token.OP_SHIFT_RIGHT_ASSIGN;
574 return Token.OP_SHIFT_RIGHT;
575 } else if (d == '='){
584 int deambiguate_close_parens = 0;
586 public void Deambiguate_CloseParens ()
589 deambiguate_close_parens++;
592 void Error_NumericConstantTooLong ()
594 Report.Error (1021, Location, "Numeric constant too long");
597 bool decimal_digits (int c)
600 bool seen_digits = false;
603 if (number_pos == max_number_size)
604 Error_NumericConstantTooLong ();
605 number_builder [number_pos++] = (char) c;
609 // We use peekChar2, because decimal_digits needs to do a
610 // 2-character look-ahead (5.ToString for example).
612 while ((d = peekChar2 ()) != -1){
613 if (d >= '0' && d <= '9'){
614 if (number_pos == max_number_size)
615 Error_NumericConstantTooLong ();
616 number_builder [number_pos++] = (char) d;
628 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
631 void hex_digits (int c)
634 number_builder [number_pos++] = (char) c;
638 int real_type_suffix (int c)
644 t = Token.LITERAL_FLOAT;
647 t = Token.LITERAL_DOUBLE;
650 t= Token.LITERAL_DECIMAL;
658 int integer_type_suffix (ulong ul, int c)
660 bool is_unsigned = false;
661 bool is_long = false;
664 bool scanning = true;
675 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
677 // if we have not seen anything in between
680 Report.Warning (78, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
699 if (is_long && is_unsigned){
701 return Token.LITERAL_INTEGER;
702 } else if (is_unsigned){
703 // uint if possible, or ulong else.
705 if ((ul & 0xffffffff00000000) == 0)
710 // long if possible, ulong otherwise
711 if ((ul & 0x8000000000000000) != 0)
716 // int, uint, long or ulong in that order
717 if ((ul & 0xffffffff00000000) == 0){
720 if ((ui & 0x80000000) != 0)
725 if ((ul & 0x8000000000000000) != 0)
731 return Token.LITERAL_INTEGER;
735 // given `c' as the next char in the input decide whether
736 // we need to convert to a special type, and then choose
737 // the best representation for the integer
739 int adjust_int (int c)
743 ulong ul = (uint) (number_builder [0] - '0');
745 for (int i = 1; i < number_pos; i++){
746 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
748 return integer_type_suffix (ul, c);
750 uint ui = (uint) (number_builder [0] - '0');
752 for (int i = 1; i < number_pos; i++){
753 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
755 return integer_type_suffix (ui, c);
757 } catch (OverflowException) {
758 error_details = "Integral constant is too large";
759 Report.Error (1021, Location, error_details);
761 return Token.LITERAL_INTEGER;
765 int adjust_real (int t)
767 string s = new String (number_builder, 0, number_pos);
770 case Token.LITERAL_DECIMAL:
772 val = System.Decimal.Parse (s, styles, csharp_format_info);
773 } catch (OverflowException) {
775 error_details = "Floating-point constant is outside the range of the type 'decimal'";
776 Report.Error (594, Location, error_details);
779 case Token.LITERAL_FLOAT:
781 val = (float) System.Double.Parse (s, styles, csharp_format_info);
782 } catch (OverflowException) {
784 error_details = "Floating-point constant is outside the range of the type 'float'";
785 Report.Error (594, Location, error_details);
789 case Token.LITERAL_DOUBLE:
791 t = Token.LITERAL_DOUBLE;
793 val = System.Double.Parse (s, styles, csharp_format_info);
794 } catch (OverflowException) {
796 error_details = "Floating-point constant is outside the range of the type 'double'";
797 Report.Error (594, Location, error_details);
810 while ((d = peekChar ()) != -1){
812 number_builder [number_pos++] = (char) d;
818 string s = new String (number_builder, 0, number_pos);
821 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
823 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
824 } catch (OverflowException){
825 error_details = "Integral constant is too large";
826 Report.Error (1021, Location, error_details);
828 return Token.LITERAL_INTEGER;
831 return integer_type_suffix (ul, peekChar ());
835 // Invoked if we know we have .digits or digits
837 int is_number (int c)
839 bool is_real = false;
844 if (c >= '0' && c <= '9'){
846 int peek = peekChar ();
848 if (peek == 'x' || peek == 'X')
849 return handle_hex ();
856 // We need to handle the case of
857 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
860 if (decimal_digits ('.')){
866 return adjust_int (-1);
870 if (c == 'e' || c == 'E'){
872 if (number_pos == max_number_size)
873 Error_NumericConstantTooLong ();
874 number_builder [number_pos++] = 'e';
878 if (number_pos == max_number_size)
879 Error_NumericConstantTooLong ();
880 number_builder [number_pos++] = '+';
882 } else if (c == '-') {
883 if (number_pos == max_number_size)
884 Error_NumericConstantTooLong ();
885 number_builder [number_pos++] = '-';
888 if (number_pos == max_number_size)
889 Error_NumericConstantTooLong ();
890 number_builder [number_pos++] = '+';
897 type = real_type_suffix (c);
898 if (type == Token.NONE && !is_real){
900 return adjust_int (c);
904 if (type == Token.NONE){
909 return adjust_real (type);
911 Console.WriteLine ("This should not be reached");
912 throw new Exception ("Is Number should never reach this point");
916 // Accepts exactly count (4 or 8) hex, no more no less
918 int getHex (int count, out bool error)
923 int top = count != -1 ? count : 4;
927 for (i = 0; i < top; i++){
930 if (c >= '0' && c <= '9')
931 c = (int) c - (int) '0';
932 else if (c >= 'A' && c <= 'F')
933 c = (int) c - (int) 'A' + 10;
934 else if (c >= 'a' && c <= 'f')
935 c = (int) c - (int) 'a' + 10;
941 total = (total * 16) + c;
946 if (!is_hex ((char)p))
987 v = getHex (-1, out error);
992 v = getHex (4, out error);
997 v = getHex (8, out error);
1002 Report.Error (1009, Location, "Unrecognized escape sequence in " + (char)d);
1011 if (putback_char != -1){
1012 int x = putback_char;
1017 return reader.Read ();
1022 if (putback_char != -1)
1023 return putback_char;
1024 putback_char = reader.Read ();
1025 return putback_char;
1030 if (putback_char != -1)
1031 return putback_char;
1032 return reader.Peek ();
1035 void putback (int c)
1037 if (putback_char != -1){
1038 Console.WriteLine ("Col: " + col);
1039 Console.WriteLine ("Row: " + line);
1040 Console.WriteLine ("Name: " + ref_name.Name);
1041 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1042 throw new Exception ("This should not happen putback on putback");
1047 public bool advance ()
1049 return peekChar () != -1;
1052 public Object Value {
1058 public Object value ()
1063 bool IsCastToken (int token)
1068 case Token.IDENTIFIER:
1069 case Token.LITERAL_INTEGER:
1070 case Token.LITERAL_FLOAT:
1071 case Token.LITERAL_DOUBLE:
1072 case Token.LITERAL_DECIMAL:
1073 case Token.LITERAL_CHARACTER:
1074 case Token.LITERAL_STRING:
1086 case Token.UNCHECKED:
1090 // These can be part of a member access
1110 current_token = xtoken ();
1111 return current_token;
1114 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1116 void get_cmd_arg (out string cmd, out string arg)
1120 tokens_seen = false;
1122 static_cmd_arg.Length = 0;
1124 // skip over white space
1125 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1129 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1130 if (is_identifier_part_character ((char) c)){
1131 static_cmd_arg.Append ((char) c);
1139 cmd = static_cmd_arg.ToString ();
1145 } else if (c == '\r')
1148 // skip over white space
1149 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1156 } else if (c == '\r'){
1161 static_cmd_arg.Length = 0;
1162 static_cmd_arg.Append ((char) c);
1164 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1165 static_cmd_arg.Append ((char) c);
1171 } else if (c == '\r')
1173 arg = static_cmd_arg.ToString ().Trim ();
1177 // Handles the #line directive
1179 bool PreProcessLine (string arg)
1184 if (arg == "default"){
1186 ref_name = file_name;
1187 Location.Push (ref_name);
1189 } else if (arg == "hidden"){
1191 // We ignore #line hidden
1199 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1200 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1203 char [] quotes = { '\"' };
1205 string name = arg.Substring (pos). Trim (quotes);
1206 ref_name = Location.LookupFile (name);
1207 file_name.HasLineDirective = true;
1208 ref_name.HasLineDirective = true;
1209 Location.Push (ref_name);
1211 ref_line = System.Int32.Parse (arg);
1221 // Handles #define and #undef
1223 void PreProcessDefinition (bool is_define, string arg)
1225 if (arg == "" || arg == "true" || arg == "false"){
1226 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1230 char[] whitespace = { ' ', '\t' };
1231 if (arg.IndexOfAny (whitespace) != -1){
1232 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1236 if (!is_identifier_start_character (arg [0]))
1237 Report.Error (1001, Location, "Identifier expected: " + arg);
1239 foreach (char c in arg.Substring (1)){
1240 if (!is_identifier_part_character (c)){
1241 Report.Error (1001, Location, "Identifier expected: " + arg);
1247 if (defines == null)
1248 defines = new Hashtable ();
1251 if (defines == null)
1253 if (defines.Contains (arg))
1254 defines.Remove (arg);
1259 /// Handles #pragma directive
1261 void PreProcessPragma (string arg)
1263 const string disable = "warning disable";
1264 const string restore = "warning restore";
1266 if (arg == disable) {
1267 Report.RegisterWarningRegion (Location).WarningDisable (line);
1271 if (arg == restore) {
1272 Report.RegisterWarningRegion (Location).WarningEnable (line);
1276 if (arg.StartsWith (disable)) {
1277 int[] codes = ParseNumbers (arg.Substring (disable.Length));
1278 foreach (int code in codes) {
1280 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1285 if (arg.StartsWith (restore)) {
1286 int[] codes = ParseNumbers (arg.Substring (restore.Length));
1287 foreach (int code in codes) {
1288 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1296 int[] ParseNumbers (string text)
1298 string[] string_array = text.Split (',');
1299 int[] values = new int [string_array.Length];
1301 foreach (string string_code in string_array) {
1303 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1305 catch (FormatException) {
1306 Report.Warning (1692, Location, "Invalid number");
1312 bool eval_val (string s)
1319 if (defines == null)
1321 if (defines.Contains (s))
1327 bool pp_primary (ref string s)
1336 s = s.Substring (1);
1337 bool val = pp_expr (ref s);
1338 if (s.Length > 0 && s [0] == ')'){
1339 s = s.Substring (1);
1342 Error_InvalidDirective ();
1346 if (is_identifier_start_character (c)){
1352 if (is_identifier_part_character (c)){
1356 bool v = eval_val (s.Substring (0, j));
1357 s = s.Substring (j);
1360 bool vv = eval_val (s);
1365 Error_InvalidDirective ();
1369 bool pp_unary (ref string s)
1376 if (len > 1 && s [1] == '='){
1377 Error_InvalidDirective ();
1380 s = s.Substring (1);
1381 return ! pp_primary (ref s);
1383 return pp_primary (ref s);
1385 Error_InvalidDirective ();
1390 bool pp_eq (ref string s)
1392 bool va = pp_unary (ref s);
1398 if (len > 2 && s [1] == '='){
1399 s = s.Substring (2);
1400 return va == pp_unary (ref s);
1402 Error_InvalidDirective ();
1405 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1406 s = s.Substring (2);
1408 return va != pp_unary (ref s);
1417 bool pp_and (ref string s)
1419 bool va = pp_eq (ref s);
1425 if (len > 2 && s [1] == '&'){
1426 s = s.Substring (2);
1427 return (va & pp_eq (ref s));
1429 Error_InvalidDirective ();
1438 // Evaluates an expression for `#if' or `#elif'
1440 bool pp_expr (ref string s)
1442 bool va = pp_and (ref s);
1449 if (len > 2 && s [1] == '|'){
1450 s = s.Substring (2);
1451 return va | pp_expr (ref s);
1453 Error_InvalidDirective ();
1462 bool eval (string s)
1464 bool v = pp_expr (ref s);
1467 Error_InvalidDirective ();
1474 void Error_InvalidDirective ()
1476 Report.Error (1517, Location, "Invalid pre-processor directive");
1479 void Error_UnexpectedDirective (string extra)
1483 "Unexpected processor directive (" + extra + ")");
1486 void Error_TokensSeen ()
1490 "Cannot define or undefine pre-processor symbols after a token in the file");
1494 // if true, then the code continues processing the code
1495 // if false, the code stays in a loop until another directive is
1498 bool handle_preprocessing_directive (bool caller_is_taking)
1501 bool region_directive = false;
1503 get_cmd_arg (out cmd, out arg);
1505 // Eat any trailing whitespaces and single-line comments
1506 if (arg.IndexOf ("//") != -1)
1507 arg = arg.Substring (0, arg.IndexOf ("//"));
1508 arg = arg.TrimEnd (' ', '\t');
1511 // The first group of pre-processing instructions is always processed
1515 if (RootContext.Version == LanguageVersion.ISO_1) {
1516 Report.FeatureIsNotStandardized (Location, "#pragma");
1517 return caller_is_taking;
1520 PreProcessPragma (arg);
1521 return caller_is_taking;
1524 if (!PreProcessLine (arg))
1527 "Argument to #line directive is missing or invalid");
1528 return caller_is_taking;
1531 region_directive = true;
1536 region_directive = true;
1541 Error_InvalidDirective ();
1544 bool taking = false;
1545 if (ifstack == null)
1546 ifstack = new Stack ();
1548 if (ifstack.Count == 0){
1551 int state = (int) ifstack.Peek ();
1552 if ((state & TAKING) != 0)
1556 if (eval (arg) && taking){
1557 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1558 if (region_directive)
1560 ifstack.Push (push);
1563 int push = (taking ? PARENT_TAKING : 0);
1564 if (region_directive)
1566 ifstack.Push (push);
1571 if (ifstack == null || ifstack.Count == 0){
1572 Error_UnexpectedDirective ("no #if for this #endif");
1575 int pop = (int) ifstack.Pop ();
1577 if (region_directive && ((pop & REGION) == 0))
1578 Report.Error (1027, Location, "#endif directive expected");
1579 else if (!region_directive && ((pop & REGION) != 0))
1580 Report.Error (1038, Location, "#endregion directive expected");
1582 if (ifstack.Count == 0)
1585 int state = (int) ifstack.Peek ();
1587 if ((state & TAKING) != 0)
1595 if (ifstack == null || ifstack.Count == 0){
1596 Error_UnexpectedDirective ("no #if for this #elif");
1599 int state = (int) ifstack.Peek ();
1601 if ((state & REGION) != 0) {
1602 Report.Error (1038, Location, "#endregion directive expected");
1606 if ((state & ELSE_SEEN) != 0){
1607 Error_UnexpectedDirective ("#elif not valid after #else");
1611 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1614 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1615 state = (int) ifstack.Pop ();
1616 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1623 if (ifstack == null || ifstack.Count == 0){
1626 "Unexpected processor directive (no #if for this #else)");
1629 int state = (int) ifstack.Peek ();
1631 if ((state & REGION) != 0) {
1632 Report.Error (1038, Location, "#endregion directive expected");
1636 if ((state & ELSE_SEEN) != 0){
1637 Error_UnexpectedDirective ("#else within #else");
1644 if ((state & TAKEN_BEFORE) == 0){
1645 ret = ((state & PARENT_TAKING) != 0);
1654 ifstack.Push (state | ELSE_SEEN);
1661 // These are only processed if we are in a `taking' block
1663 if (!caller_is_taking)
1668 if (any_token_seen){
1669 Error_TokensSeen ();
1672 PreProcessDefinition (true, arg);
1676 if (any_token_seen){
1677 Error_TokensSeen ();
1680 PreProcessDefinition (false, arg);
1684 Report.Error (1029, Location, "#error: '" + arg + "'");
1688 Report.Warning (1030, Location, "#warning: '{0}'", arg);
1692 Report.Error (1024, Location, "Preprocessor directive expected (got: " + cmd + ")");
1697 private int consume_string (bool quoted)
1700 string_builder.Length = 0;
1702 while ((c = getChar ()) != -1){
1704 if (quoted && peekChar () == '"'){
1705 string_builder.Append ((char) c);
1709 val = string_builder.ToString ();
1710 return Token.LITERAL_STRING;
1716 Report.Error (1010, Location, "Newline in constant");
1728 string_builder.Append ((char) c);
1731 Report.Error (1039, Location, "Unterminated string literal");
1735 private int consume_identifier (int s)
1737 int res = consume_identifier (s, false);
1739 if (res == Token.PARTIAL) {
1740 // Save current position and parse next token.
1741 int old = reader.Position;
1742 int old_putback = putback_char;
1746 int next_token = token ();
1747 bool ok = (next_token == Token.CLASS) ||
1748 (next_token == Token.STRUCT) ||
1749 (next_token == Token.INTERFACE);
1751 reader.Position = old;
1752 putback_char = old_putback;
1758 return Token.IDENTIFIER;
1765 private int consume_identifier (int s, bool quoted)
1770 id_builder [0] = (char) s;
1772 while ((c = reader.Read ()) != -1) {
1773 if (is_identifier_part_character ((char) c)){
1774 if (pos == max_id_size){
1775 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1779 id_builder [pos++] = (char) c;
1789 // Optimization: avoids doing the keyword lookup
1790 // on uppercase letters and _
1792 if (!quoted && (s >= 'a' || s == '_')){
1793 int keyword = GetKeyword (id_builder, pos);
1799 // Keep identifiers in an array of hashtables to avoid needless
1803 if (identifiers [pos] != null) {
1804 val = identifiers [pos][id_builder];
1806 return Token.IDENTIFIER;
1810 identifiers [pos] = new CharArrayHashtable (pos);
1812 val = new String (id_builder, 0, pos);
1814 char [] chars = new char [pos];
1815 Array.Copy (id_builder, chars, pos);
1817 identifiers [pos] [chars] = val;
1819 return Token.IDENTIFIER;
1822 public int xtoken ()
1825 bool doread = false;
1829 // optimization: eliminate col and implement #directive semantic correctly.
1830 for (;(c = getChar ()) != -1; col++) {
1835 col = (((col + 8) / 8) * 8) - 1;
1839 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1843 if (peekChar () == '\n')
1849 any_token_seen |= tokens_seen;
1850 tokens_seen = false;
1854 // Handle double-slash comments.
1856 int d = peekChar ();
1860 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
1867 any_token_seen |= tokens_seen;
1868 tokens_seen = false;
1870 } else if (d == '*'){
1873 while ((d = getChar ()) != -1){
1874 if (d == '*' && peekChar () == '/'){
1883 any_token_seen |= tokens_seen;
1884 tokens_seen = false;
1889 goto is_punct_label;
1893 if (is_identifier_start_character ((char)c)){
1895 return consume_identifier (c);
1899 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
1913 any_token_seen |= tokens_seen;
1914 tokens_seen = false;
1918 if (c >= '0' && c <= '9'){
1920 return is_number (c);
1925 int peek = peekChar ();
1926 if (peek >= '0' && peek <= '9')
1927 return is_number (c);
1931 /* For now, ignore pre-processor commands */
1932 // FIXME: In C# the '#' is not limited to appear
1933 // on the first column.
1934 if (c == '#' && !tokens_seen){
1939 cont = handle_preprocessing_directive (cont);
1947 bool skipping = false;
1948 for (;(c = getChar ()) != -1; col++){
1954 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
1958 if (c == '#' && !skipping)
1961 any_token_seen |= tokens_seen;
1962 tokens_seen = false;
1964 Report.Error (1027, Location, "#endif/#endregion expected");
1969 return consume_string (false);
1975 error_details = "Empty character literal";
1976 Report.Error (1011, Location, error_details);
1982 val = new System.Char ();
1987 error_details = "Too many characters in character literal";
1988 Report.Error (1012, Location, error_details);
1990 // Try to recover, read until newline or next "'"
1991 while ((c = getChar ()) != -1){
1992 if (c == '\n' || c == '\''){
2003 return Token.LITERAL_CHARACTER;
2010 return consume_string (true);
2011 } else if (is_identifier_start_character ((char) c)){
2012 return consume_identifier (c, true);
2014 Report.Error (1033, Location, "'@' must be followed by string constant or identifier");
2019 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2020 "character on a line.";
2022 Report.Error (1040, Location, error_details);
2027 error_details = ((char)c).ToString ();
2035 public void cleanup ()
2037 if (ifstack != null && ifstack.Count >= 1) {
2038 int state = (int) ifstack.Pop ();
2039 if ((state & REGION) != 0)
2040 Report.Error (1038, "#endregion directive expected");
2042 Report.Error (1027, "#endif directive expected");