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;
830 catch (FormatException) {
831 Report.Error (1013, Location, "Invalid number");
833 return Token.LITERAL_INTEGER;
836 return integer_type_suffix (ul, peekChar ());
840 // Invoked if we know we have .digits or digits
842 int is_number (int c)
844 bool is_real = false;
849 if (c >= '0' && c <= '9'){
851 int peek = peekChar ();
853 if (peek == 'x' || peek == 'X')
854 return handle_hex ();
861 // We need to handle the case of
862 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
865 if (decimal_digits ('.')){
871 return adjust_int (-1);
875 if (c == 'e' || c == 'E'){
877 if (number_pos == max_number_size)
878 Error_NumericConstantTooLong ();
879 number_builder [number_pos++] = 'e';
883 if (number_pos == max_number_size)
884 Error_NumericConstantTooLong ();
885 number_builder [number_pos++] = '+';
887 } else if (c == '-') {
888 if (number_pos == max_number_size)
889 Error_NumericConstantTooLong ();
890 number_builder [number_pos++] = '-';
893 if (number_pos == max_number_size)
894 Error_NumericConstantTooLong ();
895 number_builder [number_pos++] = '+';
902 type = real_type_suffix (c);
903 if (type == Token.NONE && !is_real){
905 return adjust_int (c);
909 if (type == Token.NONE){
914 return adjust_real (type);
916 Console.WriteLine ("This should not be reached");
917 throw new Exception ("Is Number should never reach this point");
921 // Accepts exactly count (4 or 8) hex, no more no less
923 int getHex (int count, out bool error)
928 int top = count != -1 ? count : 4;
932 for (i = 0; i < top; i++){
935 if (c >= '0' && c <= '9')
936 c = (int) c - (int) '0';
937 else if (c >= 'A' && c <= 'F')
938 c = (int) c - (int) 'A' + 10;
939 else if (c >= 'a' && c <= 'f')
940 c = (int) c - (int) 'a' + 10;
946 total = (total * 16) + c;
951 if (!is_hex ((char)p))
992 v = getHex (-1, out error);
997 v = getHex (4, out error);
1002 v = getHex (8, out error);
1007 Report.Error (1009, Location, "Unrecognized escape sequence in " + (char)d);
1016 if (putback_char != -1){
1017 int x = putback_char;
1022 return reader.Read ();
1027 if (putback_char != -1)
1028 return putback_char;
1029 putback_char = reader.Read ();
1030 return putback_char;
1035 if (putback_char != -1)
1036 return putback_char;
1037 return reader.Peek ();
1040 void putback (int c)
1042 if (putback_char != -1){
1043 Console.WriteLine ("Col: " + col);
1044 Console.WriteLine ("Row: " + line);
1045 Console.WriteLine ("Name: " + ref_name.Name);
1046 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1047 throw new Exception ("This should not happen putback on putback");
1052 public bool advance ()
1054 return peekChar () != -1;
1057 public Object Value {
1063 public Object value ()
1068 bool IsCastToken (int token)
1073 case Token.IDENTIFIER:
1074 case Token.LITERAL_INTEGER:
1075 case Token.LITERAL_FLOAT:
1076 case Token.LITERAL_DOUBLE:
1077 case Token.LITERAL_DECIMAL:
1078 case Token.LITERAL_CHARACTER:
1079 case Token.LITERAL_STRING:
1091 case Token.UNCHECKED:
1095 // These can be part of a member access
1115 current_token = xtoken ();
1116 return current_token;
1119 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1121 void get_cmd_arg (out string cmd, out string arg)
1125 tokens_seen = false;
1127 static_cmd_arg.Length = 0;
1129 // skip over white space
1130 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1134 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1135 if (is_identifier_part_character ((char) c)){
1136 static_cmd_arg.Append ((char) c);
1144 cmd = static_cmd_arg.ToString ();
1150 } else if (c == '\r')
1153 // skip over white space
1154 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1161 } else if (c == '\r'){
1166 static_cmd_arg.Length = 0;
1167 static_cmd_arg.Append ((char) c);
1169 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1170 static_cmd_arg.Append ((char) c);
1176 } else if (c == '\r')
1178 arg = static_cmd_arg.ToString ().Trim ();
1182 // Handles the #line directive
1184 bool PreProcessLine (string arg)
1189 if (arg == "default"){
1191 ref_name = file_name;
1192 Location.Push (ref_name);
1194 } else if (arg == "hidden"){
1196 // We ignore #line hidden
1204 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1205 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1208 char [] quotes = { '\"' };
1210 string name = arg.Substring (pos). Trim (quotes);
1211 ref_name = Location.LookupFile (name);
1212 file_name.HasLineDirective = true;
1213 ref_name.HasLineDirective = true;
1214 Location.Push (ref_name);
1216 ref_line = System.Int32.Parse (arg);
1226 // Handles #define and #undef
1228 void PreProcessDefinition (bool is_define, string arg)
1230 if (arg == "" || arg == "true" || arg == "false"){
1231 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1235 char[] whitespace = { ' ', '\t' };
1236 if (arg.IndexOfAny (whitespace) != -1){
1237 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1241 if (!is_identifier_start_character (arg [0]))
1242 Report.Error (1001, Location, "Identifier expected: " + arg);
1244 foreach (char c in arg.Substring (1)){
1245 if (!is_identifier_part_character (c)){
1246 Report.Error (1001, Location, "Identifier expected: " + arg);
1252 if (defines == null)
1253 defines = new Hashtable ();
1256 if (defines == null)
1258 if (defines.Contains (arg))
1259 defines.Remove (arg);
1264 /// Handles #pragma directive
1266 void PreProcessPragma (string arg)
1268 const string disable = "warning disable";
1269 const string restore = "warning restore";
1271 if (arg == disable) {
1272 Report.RegisterWarningRegion (Location).WarningDisable (line);
1276 if (arg == restore) {
1277 Report.RegisterWarningRegion (Location).WarningEnable (line);
1281 if (arg.StartsWith (disable)) {
1282 int[] codes = ParseNumbers (arg.Substring (disable.Length));
1283 foreach (int code in codes) {
1285 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1290 if (arg.StartsWith (restore)) {
1291 int[] codes = ParseNumbers (arg.Substring (restore.Length));
1292 foreach (int code in codes) {
1293 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1301 int[] ParseNumbers (string text)
1303 string[] string_array = text.Split (',');
1304 int[] values = new int [string_array.Length];
1306 foreach (string string_code in string_array) {
1308 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1310 catch (FormatException) {
1311 Report.Warning (1692, Location, "Invalid number");
1317 bool eval_val (string s)
1324 if (defines == null)
1326 if (defines.Contains (s))
1332 bool pp_primary (ref string s)
1341 s = s.Substring (1);
1342 bool val = pp_expr (ref s);
1343 if (s.Length > 0 && s [0] == ')'){
1344 s = s.Substring (1);
1347 Error_InvalidDirective ();
1351 if (is_identifier_start_character (c)){
1357 if (is_identifier_part_character (c)){
1361 bool v = eval_val (s.Substring (0, j));
1362 s = s.Substring (j);
1365 bool vv = eval_val (s);
1370 Error_InvalidDirective ();
1374 bool pp_unary (ref string s)
1381 if (len > 1 && s [1] == '='){
1382 Error_InvalidDirective ();
1385 s = s.Substring (1);
1386 return ! pp_primary (ref s);
1388 return pp_primary (ref s);
1390 Error_InvalidDirective ();
1395 bool pp_eq (ref string s)
1397 bool va = pp_unary (ref s);
1403 if (len > 2 && s [1] == '='){
1404 s = s.Substring (2);
1405 return va == pp_unary (ref s);
1407 Error_InvalidDirective ();
1410 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1411 s = s.Substring (2);
1413 return va != pp_unary (ref s);
1422 bool pp_and (ref string s)
1424 bool va = pp_eq (ref s);
1430 if (len > 2 && s [1] == '&'){
1431 s = s.Substring (2);
1432 return (va & pp_eq (ref s));
1434 Error_InvalidDirective ();
1443 // Evaluates an expression for `#if' or `#elif'
1445 bool pp_expr (ref string s)
1447 bool va = pp_and (ref s);
1454 if (len > 2 && s [1] == '|'){
1455 s = s.Substring (2);
1456 return va | pp_expr (ref s);
1458 Error_InvalidDirective ();
1467 bool eval (string s)
1469 bool v = pp_expr (ref s);
1472 Error_InvalidDirective ();
1479 void Error_InvalidDirective ()
1481 Report.Error (1517, Location, "Invalid pre-processor directive");
1484 void Error_UnexpectedDirective (string extra)
1488 "Unexpected processor directive (" + extra + ")");
1491 void Error_TokensSeen ()
1495 "Cannot define or undefine pre-processor symbols after a token in the file");
1499 // if true, then the code continues processing the code
1500 // if false, the code stays in a loop until another directive is
1503 bool handle_preprocessing_directive (bool caller_is_taking)
1506 bool region_directive = false;
1508 get_cmd_arg (out cmd, out arg);
1510 // Eat any trailing whitespaces and single-line comments
1511 if (arg.IndexOf ("//") != -1)
1512 arg = arg.Substring (0, arg.IndexOf ("//"));
1513 arg = arg.TrimEnd (' ', '\t');
1516 // The first group of pre-processing instructions is always processed
1520 if (RootContext.Version == LanguageVersion.ISO_1) {
1521 Report.FeatureIsNotStandardized (Location, "#pragma");
1522 return caller_is_taking;
1525 PreProcessPragma (arg);
1526 return caller_is_taking;
1529 if (!PreProcessLine (arg))
1532 "Argument to #line directive is missing or invalid");
1533 return caller_is_taking;
1536 region_directive = true;
1541 region_directive = true;
1546 Error_InvalidDirective ();
1549 bool taking = false;
1550 if (ifstack == null)
1551 ifstack = new Stack ();
1553 if (ifstack.Count == 0){
1556 int state = (int) ifstack.Peek ();
1557 if ((state & TAKING) != 0)
1561 if (eval (arg) && taking){
1562 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1563 if (region_directive)
1565 ifstack.Push (push);
1568 int push = (taking ? PARENT_TAKING : 0);
1569 if (region_directive)
1571 ifstack.Push (push);
1576 if (ifstack == null || ifstack.Count == 0){
1577 Error_UnexpectedDirective ("no #if for this #endif");
1580 int pop = (int) ifstack.Pop ();
1582 if (region_directive && ((pop & REGION) == 0))
1583 Report.Error (1027, Location, "#endif directive expected");
1584 else if (!region_directive && ((pop & REGION) != 0))
1585 Report.Error (1038, Location, "#endregion directive expected");
1587 if (ifstack.Count == 0)
1590 int state = (int) ifstack.Peek ();
1592 if ((state & TAKING) != 0)
1600 if (ifstack == null || ifstack.Count == 0){
1601 Error_UnexpectedDirective ("no #if for this #elif");
1604 int state = (int) ifstack.Peek ();
1606 if ((state & REGION) != 0) {
1607 Report.Error (1038, Location, "#endregion directive expected");
1611 if ((state & ELSE_SEEN) != 0){
1612 Error_UnexpectedDirective ("#elif not valid after #else");
1616 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1619 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1620 state = (int) ifstack.Pop ();
1621 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1628 if (ifstack == null || ifstack.Count == 0){
1631 "Unexpected processor directive (no #if for this #else)");
1634 int state = (int) ifstack.Peek ();
1636 if ((state & REGION) != 0) {
1637 Report.Error (1038, Location, "#endregion directive expected");
1641 if ((state & ELSE_SEEN) != 0){
1642 Error_UnexpectedDirective ("#else within #else");
1649 if ((state & TAKEN_BEFORE) == 0){
1650 ret = ((state & PARENT_TAKING) != 0);
1659 ifstack.Push (state | ELSE_SEEN);
1666 // These are only processed if we are in a `taking' block
1668 if (!caller_is_taking)
1673 if (any_token_seen){
1674 Error_TokensSeen ();
1677 PreProcessDefinition (true, arg);
1681 if (any_token_seen){
1682 Error_TokensSeen ();
1685 PreProcessDefinition (false, arg);
1689 Report.Error (1029, Location, "#error: '" + arg + "'");
1693 Report.Warning (1030, Location, "#warning: '{0}'", arg);
1697 Report.Error (1024, Location, "Preprocessor directive expected (got: " + cmd + ")");
1702 private int consume_string (bool quoted)
1705 string_builder.Length = 0;
1707 while ((c = getChar ()) != -1){
1709 if (quoted && peekChar () == '"'){
1710 string_builder.Append ((char) c);
1714 val = string_builder.ToString ();
1715 return Token.LITERAL_STRING;
1721 Report.Error (1010, Location, "Newline in constant");
1733 string_builder.Append ((char) c);
1736 Report.Error (1039, Location, "Unterminated string literal");
1740 private int consume_identifier (int s)
1742 int res = consume_identifier (s, false);
1744 if (res == Token.PARTIAL) {
1745 // Save current position and parse next token.
1746 int old = reader.Position;
1747 int old_putback = putback_char;
1751 int next_token = token ();
1752 bool ok = (next_token == Token.CLASS) ||
1753 (next_token == Token.STRUCT) ||
1754 (next_token == Token.INTERFACE);
1756 reader.Position = old;
1757 putback_char = old_putback;
1763 return Token.IDENTIFIER;
1770 private int consume_identifier (int s, bool quoted)
1775 id_builder [0] = (char) s;
1777 while ((c = reader.Read ()) != -1) {
1778 if (is_identifier_part_character ((char) c)){
1779 if (pos == max_id_size){
1780 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1784 id_builder [pos++] = (char) c;
1794 // Optimization: avoids doing the keyword lookup
1795 // on uppercase letters and _
1797 if (!quoted && (s >= 'a' || s == '_')){
1798 int keyword = GetKeyword (id_builder, pos);
1804 // Keep identifiers in an array of hashtables to avoid needless
1808 if (identifiers [pos] != null) {
1809 val = identifiers [pos][id_builder];
1811 return Token.IDENTIFIER;
1815 identifiers [pos] = new CharArrayHashtable (pos);
1817 val = new String (id_builder, 0, pos);
1819 char [] chars = new char [pos];
1820 Array.Copy (id_builder, chars, pos);
1822 identifiers [pos] [chars] = val;
1824 return Token.IDENTIFIER;
1827 public int xtoken ()
1830 bool doread = false;
1834 // optimization: eliminate col and implement #directive semantic correctly.
1835 for (;(c = getChar ()) != -1; col++) {
1840 col = (((col + 8) / 8) * 8) - 1;
1844 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1848 if (peekChar () == '\n')
1854 any_token_seen |= tokens_seen;
1855 tokens_seen = false;
1859 // Handle double-slash comments.
1861 int d = peekChar ();
1865 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
1872 any_token_seen |= tokens_seen;
1873 tokens_seen = false;
1875 } else if (d == '*'){
1878 while ((d = getChar ()) != -1){
1879 if (d == '*' && peekChar () == '/'){
1888 any_token_seen |= tokens_seen;
1889 tokens_seen = false;
1894 goto is_punct_label;
1898 if (is_identifier_start_character ((char)c)){
1900 return consume_identifier (c);
1904 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
1918 any_token_seen |= tokens_seen;
1919 tokens_seen = false;
1923 if (c >= '0' && c <= '9'){
1925 return is_number (c);
1930 int peek = peekChar ();
1931 if (peek >= '0' && peek <= '9')
1932 return is_number (c);
1936 /* For now, ignore pre-processor commands */
1937 // FIXME: In C# the '#' is not limited to appear
1938 // on the first column.
1939 if (c == '#' && !tokens_seen){
1944 cont = handle_preprocessing_directive (cont);
1952 bool skipping = false;
1953 for (;(c = getChar ()) != -1; col++){
1959 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
1963 if (c == '#' && !skipping)
1966 any_token_seen |= tokens_seen;
1967 tokens_seen = false;
1969 Report.Error (1027, Location, "#endif/#endregion expected");
1974 return consume_string (false);
1980 error_details = "Empty character literal";
1981 Report.Error (1011, Location, error_details);
1987 val = new System.Char ();
1992 error_details = "Too many characters in character literal";
1993 Report.Error (1012, Location, error_details);
1995 // Try to recover, read until newline or next "'"
1996 while ((c = getChar ()) != -1){
1997 if (c == '\n' || c == '\''){
2008 return Token.LITERAL_CHARACTER;
2015 return consume_string (true);
2016 } else if (is_identifier_start_character ((char) c)){
2017 return consume_identifier (c, true);
2019 Report.Error (1033, Location, "'@' must be followed by string constant or identifier");
2024 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2025 "character on a line.";
2027 Report.Error (1040, Location, error_details);
2032 error_details = ((char)c).ToString ();
2040 public void cleanup ()
2042 if (ifstack != null && ifstack.Count >= 1) {
2043 int state = (int) ifstack.Pop ();
2044 if ((state & REGION) != 0)
2045 Report.Error (1038, Location, "#endregion directive expected");
2047 Report.Error (1027, "#endif directive expected");