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;
35 public SourceFile ref_name;
36 public SourceFile file_name;
37 public int ref_line = 1;
40 public int current_token;
41 bool handle_get_set = false;
42 bool handle_remove_add = false;
43 bool handle_assembly = false;
46 // XML documentation buffer. The save point is used to divide
47 // comments on types and comments on members.
49 StringBuilder xml_comment_buffer;
52 // See comment on XmlCommentState enumeration.
54 XmlCommentState xmlDocState = XmlCommentState.Allowed;
57 // Whether tokens have been seen on this line
59 bool tokens_seen = false;
62 // Whether a token has been seen on the file
63 // This is needed because `define' is not allowed to be used
64 // after a token has been seen.
66 bool any_token_seen = false;
68 static Hashtable tokenValues;
70 private static Hashtable TokenValueName
73 if (tokenValues == null)
74 tokenValues = GetTokenValueNameHash ();
80 private static Hashtable GetTokenValueNameHash ()
82 Type t = typeof (Token);
83 FieldInfo [] fields = t.GetFields ();
84 Hashtable hash = new Hashtable ();
85 foreach (FieldInfo field in fields) {
86 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
87 hash.Add (field.GetValue (null), field.Name);
93 // Returns a verbose representation of the current location
95 public string location {
99 if (current_token == Token.ERROR)
100 det = "detail: " + error_details;
104 // return "Line: "+line+" Col: "+col + "\n" +
105 // "VirtLine: "+ref_line +
106 // " Token: "+current_token + " " + det;
107 string current_token_name = TokenValueName [current_token] as string;
108 if (current_token_name == null)
109 current_token_name = current_token.ToString ();
111 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
119 public bool PropertyParsing {
121 return handle_get_set;
125 handle_get_set = value;
129 public bool AssemblyTargetParsing {
131 return handle_assembly;
135 handle_assembly = value;
139 public bool EventParsing {
141 return handle_remove_add;
145 handle_remove_add = value;
149 public XmlCommentState doc_state {
150 get { return xmlDocState; }
152 if (value == XmlCommentState.Allowed) {
153 check_incorrect_doc_comment ();
154 consume_doc_comment ();
164 static CharArrayHashtable[] keywords;
165 static Hashtable keywordStrings = new Hashtable ();
166 static NumberStyles styles;
167 static NumberFormatInfo csharp_format_info;
170 // Values for the associated token returned
180 const int TAKING = 1;
181 const int TAKEN_BEFORE = 2;
182 const int ELSE_SEEN = 4;
183 const int PARENT_TAKING = 8;
184 const int REGION = 16;
187 // pre-processor if stack state:
191 static System.Text.StringBuilder string_builder;
193 const int max_id_size = 512;
194 static char [] id_builder = new char [max_id_size];
196 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
198 const int max_number_size = 512;
199 static char [] number_builder = new char [max_number_size];
200 static int number_pos;
203 // Details about the error encoutered by the tokenizer
205 string error_details;
207 public string error {
209 return error_details;
225 static void AddKeyword (string kw, int token) {
226 keywordStrings.Add (kw, kw);
227 if (keywords [kw.Length] == null) {
228 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
230 keywords [kw.Length] [kw.ToCharArray ()] = token;
233 static void InitTokens ()
235 keywords = new CharArrayHashtable [64];
237 AddKeyword ("__arglist", Token.ARGLIST);
238 AddKeyword ("abstract", Token.ABSTRACT);
239 AddKeyword ("as", Token.AS);
240 AddKeyword ("add", Token.ADD);
241 AddKeyword ("assembly", Token.ASSEMBLY);
242 AddKeyword ("base", Token.BASE);
243 AddKeyword ("bool", Token.BOOL);
244 AddKeyword ("break", Token.BREAK);
245 AddKeyword ("byte", Token.BYTE);
246 AddKeyword ("case", Token.CASE);
247 AddKeyword ("catch", Token.CATCH);
248 AddKeyword ("char", Token.CHAR);
249 AddKeyword ("checked", Token.CHECKED);
250 AddKeyword ("class", Token.CLASS);
251 AddKeyword ("const", Token.CONST);
252 AddKeyword ("continue", Token.CONTINUE);
253 AddKeyword ("decimal", Token.DECIMAL);
254 AddKeyword ("default", Token.DEFAULT);
255 AddKeyword ("delegate", Token.DELEGATE);
256 AddKeyword ("do", Token.DO);
257 AddKeyword ("double", Token.DOUBLE);
258 AddKeyword ("else", Token.ELSE);
259 AddKeyword ("enum", Token.ENUM);
260 AddKeyword ("event", Token.EVENT);
261 AddKeyword ("explicit", Token.EXPLICIT);
262 AddKeyword ("extern", Token.EXTERN);
263 AddKeyword ("false", Token.FALSE);
264 AddKeyword ("finally", Token.FINALLY);
265 AddKeyword ("fixed", Token.FIXED);
266 AddKeyword ("float", Token.FLOAT);
267 AddKeyword ("for", Token.FOR);
268 AddKeyword ("foreach", Token.FOREACH);
269 AddKeyword ("goto", Token.GOTO);
270 AddKeyword ("get", Token.GET);
271 AddKeyword ("if", Token.IF);
272 AddKeyword ("implicit", Token.IMPLICIT);
273 AddKeyword ("in", Token.IN);
274 AddKeyword ("int", Token.INT);
275 AddKeyword ("interface", Token.INTERFACE);
276 AddKeyword ("internal", Token.INTERNAL);
277 AddKeyword ("is", Token.IS);
278 AddKeyword ("lock", Token.LOCK);
279 AddKeyword ("long", Token.LONG);
280 AddKeyword ("namespace", Token.NAMESPACE);
281 AddKeyword ("new", Token.NEW);
282 AddKeyword ("null", Token.NULL);
283 AddKeyword ("object", Token.OBJECT);
284 AddKeyword ("operator", Token.OPERATOR);
285 AddKeyword ("out", Token.OUT);
286 AddKeyword ("override", Token.OVERRIDE);
287 AddKeyword ("params", Token.PARAMS);
288 AddKeyword ("private", Token.PRIVATE);
289 AddKeyword ("protected", Token.PROTECTED);
290 AddKeyword ("public", Token.PUBLIC);
291 AddKeyword ("readonly", Token.READONLY);
292 AddKeyword ("ref", Token.REF);
293 AddKeyword ("remove", Token.REMOVE);
294 AddKeyword ("return", Token.RETURN);
295 AddKeyword ("sbyte", Token.SBYTE);
296 AddKeyword ("sealed", Token.SEALED);
297 AddKeyword ("set", Token.SET);
298 AddKeyword ("short", Token.SHORT);
299 AddKeyword ("sizeof", Token.SIZEOF);
300 AddKeyword ("stackalloc", Token.STACKALLOC);
301 AddKeyword ("static", Token.STATIC);
302 AddKeyword ("string", Token.STRING);
303 AddKeyword ("struct", Token.STRUCT);
304 AddKeyword ("switch", Token.SWITCH);
305 AddKeyword ("this", Token.THIS);
306 AddKeyword ("throw", Token.THROW);
307 AddKeyword ("true", Token.TRUE);
308 AddKeyword ("try", Token.TRY);
309 AddKeyword ("typeof", Token.TYPEOF);
310 AddKeyword ("uint", Token.UINT);
311 AddKeyword ("ulong", Token.ULONG);
312 AddKeyword ("unchecked", Token.UNCHECKED);
313 AddKeyword ("unsafe", Token.UNSAFE);
314 AddKeyword ("ushort", Token.USHORT);
315 AddKeyword ("using", Token.USING);
316 AddKeyword ("virtual", Token.VIRTUAL);
317 AddKeyword ("void", Token.VOID);
318 AddKeyword ("volatile", Token.VOLATILE);
319 AddKeyword ("while", Token.WHILE);
320 AddKeyword ("partial", Token.PARTIAL);
329 csharp_format_info = NumberFormatInfo.InvariantInfo;
330 styles = NumberStyles.Float;
332 string_builder = new System.Text.StringBuilder ();
335 int GetKeyword (char[] id, int id_len)
338 * Keywords are stored in an array of hashtables grouped by their
342 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
344 object o = keywords [id_len] [id];
351 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
353 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
355 if (handle_assembly == false && res == Token.ASSEMBLY)
362 public Location Location {
364 return new Location (ref_line);
368 void define (string def)
370 if (!RootContext.AllDefines.Contains (def)){
371 RootContext.AllDefines [def] = true;
373 if (defines.Contains (def))
375 defines [def] = true;
378 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
380 this.ref_name = file;
381 this.file_name = file;
387 defines = new Hashtable ();
388 foreach (string def in defs)
392 xml_comment_buffer = new StringBuilder ();
395 // FIXME: This could be `Location.Push' but we have to
396 // find out why the MS compiler allows this
398 Mono.CSharp.Location.Push (file);
401 static bool is_identifier_start_character (char c)
403 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
406 static bool is_identifier_part_character (char c)
408 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
411 public static bool IsKeyword (string s)
413 return keywordStrings [s] != null;
416 public static bool IsValidIdentifier (string s)
418 if (s == null || s.Length == 0)
421 if (!is_identifier_start_character (s [0]))
424 for (int i = 1; i < s.Length; i ++)
425 if (! is_identifier_part_character (s [i]))
431 int is_punct (char c, ref bool doread)
440 return Token.OPEN_BRACE;
442 return Token.CLOSE_BRACE;
444 // To block doccomment inside attribute declaration.
445 if (doc_state == XmlCommentState.Allowed)
446 doc_state = XmlCommentState.NotAllowed;
447 return Token.OPEN_BRACKET;
449 return Token.CLOSE_BRACKET;
451 return Token.OPEN_PARENS;
453 if (deambiguate_close_parens == 0)
454 return Token.CLOSE_PARENS;
456 --deambiguate_close_parens;
458 // Save current position and parse next token.
459 int old = reader.Position;
461 // disable preprocessing directives when peeking
462 process_directives = false;
463 int new_token = token ();
464 process_directives = true;
465 reader.Position = old;
468 if (new_token == Token.OPEN_PARENS)
469 return Token.CLOSE_PARENS_OPEN_PARENS;
470 else if (new_token == Token.MINUS)
471 return Token.CLOSE_PARENS_MINUS;
472 else if (IsCastToken (new_token))
473 return Token.CLOSE_PARENS_CAST;
475 return Token.CLOSE_PARENS_NO_CAST;
483 return Token.SEMICOLON;
496 t = Token.OP_ADD_ASSIGN;
506 t = Token.OP_SUB_ASSIGN;
535 } else if (d == '='){
537 return Token.OP_AND_ASSIGN;
539 return Token.BITWISE_AND;
546 } else if (d == '='){
548 return Token.OP_OR_ASSIGN;
550 return Token.BITWISE_OR;
556 return Token.OP_MULT_ASSIGN;
564 return Token.OP_DIV_ASSIGN;
572 return Token.OP_MOD_ASSIGN;
574 return Token.PERCENT;
580 return Token.OP_XOR_ASSIGN;
592 return Token.OP_SHIFT_LEFT_ASSIGN;
594 return Token.OP_SHIFT_LEFT;
595 } else if (d == '='){
609 return Token.OP_SHIFT_RIGHT_ASSIGN;
611 return Token.OP_SHIFT_RIGHT;
612 } else if (d == '='){
621 int deambiguate_close_parens = 0;
623 public void Deambiguate_CloseParens ()
626 deambiguate_close_parens++;
629 void Error_NumericConstantTooLong ()
631 Report.Error (1021, Location, "Numeric constant too long");
634 bool decimal_digits (int c)
637 bool seen_digits = false;
640 if (number_pos == max_number_size)
641 Error_NumericConstantTooLong ();
642 number_builder [number_pos++] = (char) c;
646 // We use peekChar2, because decimal_digits needs to do a
647 // 2-character look-ahead (5.ToString for example).
649 while ((d = peekChar2 ()) != -1){
650 if (d >= '0' && d <= '9'){
651 if (number_pos == max_number_size)
652 Error_NumericConstantTooLong ();
653 number_builder [number_pos++] = (char) d;
665 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
668 int real_type_suffix (int c)
674 t = Token.LITERAL_FLOAT;
677 t = Token.LITERAL_DOUBLE;
680 t= Token.LITERAL_DECIMAL;
688 int integer_type_suffix (ulong ul, int c)
690 bool is_unsigned = false;
691 bool is_long = false;
694 bool scanning = true;
705 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
707 // if we have not seen anything in between
710 Report.Warning (78, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
713 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
738 if (is_long && is_unsigned){
740 return Token.LITERAL_INTEGER;
741 } else if (is_unsigned){
742 // uint if possible, or ulong else.
744 if ((ul & 0xffffffff00000000) == 0)
749 // long if possible, ulong otherwise
750 if ((ul & 0x8000000000000000) != 0)
755 // int, uint, long or ulong in that order
756 if ((ul & 0xffffffff00000000) == 0){
759 if ((ui & 0x80000000) != 0)
764 if ((ul & 0x8000000000000000) != 0)
770 return Token.LITERAL_INTEGER;
774 // given `c' as the next char in the input decide whether
775 // we need to convert to a special type, and then choose
776 // the best representation for the integer
778 int adjust_int (int c)
782 ulong ul = (uint) (number_builder [0] - '0');
784 for (int i = 1; i < number_pos; i++){
785 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
787 return integer_type_suffix (ul, c);
789 uint ui = (uint) (number_builder [0] - '0');
791 for (int i = 1; i < number_pos; i++){
792 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
794 return integer_type_suffix (ui, c);
796 } catch (OverflowException) {
797 error_details = "Integral constant is too large";
798 Report.Error (1021, Location, error_details);
800 return Token.LITERAL_INTEGER;
804 int adjust_real (int t)
806 string s = new String (number_builder, 0, number_pos);
807 const string error_details = "Floating-point constant is outside the range of type `{0}'";
810 case Token.LITERAL_DECIMAL:
812 val = System.Decimal.Parse (s, styles, csharp_format_info);
813 } catch (OverflowException) {
815 Report.Error (594, Location, error_details, "decimal");
818 case Token.LITERAL_FLOAT:
820 val = (float) System.Double.Parse (s, styles, csharp_format_info);
821 } catch (OverflowException) {
823 Report.Error (594, Location, error_details, "float");
827 case Token.LITERAL_DOUBLE:
829 t = Token.LITERAL_DOUBLE;
831 val = System.Double.Parse (s, styles, csharp_format_info);
832 } catch (OverflowException) {
834 Report.Error (594, Location, error_details, "double");
847 while ((d = peekChar ()) != -1){
849 number_builder [number_pos++] = (char) d;
855 string s = new String (number_builder, 0, number_pos);
858 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
860 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
861 } catch (OverflowException){
862 error_details = "Integral constant is too large";
863 Report.Error (1021, Location, error_details);
865 return Token.LITERAL_INTEGER;
867 catch (FormatException) {
868 Report.Error (1013, Location, "Invalid number");
870 return Token.LITERAL_INTEGER;
873 return integer_type_suffix (ul, peekChar ());
877 // Invoked if we know we have .digits or digits
879 int is_number (int c)
881 bool is_real = false;
886 if (c >= '0' && c <= '9'){
888 int peek = peekChar ();
890 if (peek == 'x' || peek == 'X')
891 return handle_hex ();
898 // We need to handle the case of
899 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
902 if (decimal_digits ('.')){
908 return adjust_int (-1);
912 if (c == 'e' || c == 'E'){
914 if (number_pos == max_number_size)
915 Error_NumericConstantTooLong ();
916 number_builder [number_pos++] = 'e';
920 if (number_pos == max_number_size)
921 Error_NumericConstantTooLong ();
922 number_builder [number_pos++] = '+';
924 } else if (c == '-') {
925 if (number_pos == max_number_size)
926 Error_NumericConstantTooLong ();
927 number_builder [number_pos++] = '-';
930 if (number_pos == max_number_size)
931 Error_NumericConstantTooLong ();
932 number_builder [number_pos++] = '+';
939 type = real_type_suffix (c);
940 if (type == Token.NONE && !is_real){
942 return adjust_int (c);
946 if (type == Token.NONE){
951 return adjust_real (type);
953 Console.WriteLine ("This should not be reached");
954 throw new Exception ("Is Number should never reach this point");
958 // Accepts exactly count (4 or 8) hex, no more no less
960 int getHex (int count, out bool error)
965 int top = count != -1 ? count : 4;
969 for (i = 0; i < top; i++){
972 if (c >= '0' && c <= '9')
973 c = (int) c - (int) '0';
974 else if (c >= 'A' && c <= 'F')
975 c = (int) c - (int) 'A' + 10;
976 else if (c >= 'a' && c <= 'f')
977 c = (int) c - (int) 'a' + 10;
983 total = (total * 16) + c;
988 if (!is_hex ((char)p))
1029 v = getHex (-1, out error);
1034 v = getHex (4, out error);
1039 v = getHex (8, out error);
1044 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", (char)d);
1053 if (putback_char != -1){
1054 int x = putback_char;
1059 return reader.Read ();
1064 if (putback_char != -1)
1065 return putback_char;
1066 putback_char = reader.Read ();
1067 return putback_char;
1072 if (putback_char != -1)
1073 return putback_char;
1074 return reader.Peek ();
1077 void putback (int c)
1079 if (putback_char != -1){
1080 Console.WriteLine ("Col: " + col);
1081 Console.WriteLine ("Row: " + line);
1082 Console.WriteLine ("Name: " + ref_name.Name);
1083 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1084 throw new Exception ("This should not happen putback on putback");
1089 public bool advance ()
1091 return peekChar () != -1;
1094 public Object Value {
1100 public Object value ()
1105 bool IsCastToken (int token)
1110 case Token.IDENTIFIER:
1111 case Token.LITERAL_INTEGER:
1112 case Token.LITERAL_FLOAT:
1113 case Token.LITERAL_DOUBLE:
1114 case Token.LITERAL_DECIMAL:
1115 case Token.LITERAL_CHARACTER:
1116 case Token.LITERAL_STRING:
1128 case Token.UNCHECKED:
1132 // These can be part of a member access
1152 current_token = xtoken ();
1153 return current_token;
1156 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1158 void get_cmd_arg (out string cmd, out string arg)
1162 tokens_seen = false;
1164 static_cmd_arg.Length = 0;
1166 // skip over white space
1167 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1171 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1172 if (is_identifier_part_character ((char) c)){
1173 static_cmd_arg.Append ((char) c);
1181 cmd = static_cmd_arg.ToString ();
1187 } else if (c == '\r')
1190 // skip over white space
1191 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1198 } else if (c == '\r'){
1201 } else if (c == -1){
1206 static_cmd_arg.Length = 0;
1207 static_cmd_arg.Append ((char) c);
1209 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1210 static_cmd_arg.Append ((char) c);
1216 } else if (c == '\r')
1218 arg = static_cmd_arg.ToString ().Trim ();
1222 // Handles the #line directive
1224 bool PreProcessLine (string arg)
1229 if (arg == "default"){
1231 ref_name = file_name;
1232 Location.Push (ref_name);
1234 } else if (arg == "hidden"){
1236 // We ignore #line hidden
1244 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1245 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1248 char [] quotes = { '\"' };
1250 string name = arg.Substring (pos). Trim (quotes);
1251 ref_name = Location.LookupFile (name);
1252 file_name.HasLineDirective = true;
1253 ref_name.HasLineDirective = true;
1254 Location.Push (ref_name);
1256 ref_line = System.Int32.Parse (arg);
1266 // Handles #define and #undef
1268 void PreProcessDefinition (bool is_define, string arg)
1270 if (arg == "" || arg == "true" || arg == "false"){
1271 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1275 char[] whitespace = { ' ', '\t' };
1276 if (arg.IndexOfAny (whitespace) != -1){
1277 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1281 if (!is_identifier_start_character (arg [0]))
1282 Report.Error (1001, Location, "Identifier expected: " + arg);
1284 foreach (char c in arg.Substring (1)){
1285 if (!is_identifier_part_character (c)){
1286 Report.Error (1001, Location, "Identifier expected: " + arg);
1292 if (defines == null)
1293 defines = new Hashtable ();
1296 if (defines == null)
1298 if (defines.Contains (arg))
1299 defines.Remove (arg);
1304 /// Handles #pragma directive
1306 void PreProcessPragma (string arg)
1308 const string warning = "warning";
1309 const string w_disable = "warning disable";
1310 const string w_restore = "warning restore";
1312 if (arg == w_disable) {
1313 Report.RegisterWarningRegion (Location).WarningDisable (line);
1317 if (arg == w_restore) {
1318 Report.RegisterWarningRegion (Location).WarningEnable (line);
1322 if (arg.StartsWith (w_disable)) {
1323 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1324 foreach (int code in codes) {
1326 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1331 if (arg.StartsWith (w_restore)) {
1332 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1333 Hashtable w_table = Report.warning_ignore_table;
1334 foreach (int code in codes) {
1335 if (w_table != null && w_table.Contains (code))
1336 Report.Warning (1635, 1, Location, "Cannot restore warning 'CS{0:0000}' because it was disabled globally", code);
1337 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1342 if (arg.StartsWith (warning)) {
1343 Report.Warning (1634, 1, Location, "Expected disable or restore");
1347 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1350 int[] ParseNumbers (string text)
1352 string[] string_array = text.Split (',');
1353 int[] values = new int [string_array.Length];
1355 foreach (string string_code in string_array) {
1357 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1359 catch (FormatException) {
1360 Report.Warning (1692, Location, "Invalid number");
1366 bool eval_val (string s)
1373 if (defines == null)
1375 if (defines.Contains (s))
1381 bool pp_primary (ref string s)
1390 s = s.Substring (1);
1391 bool val = pp_expr (ref s);
1392 if (s.Length > 0 && s [0] == ')'){
1393 s = s.Substring (1);
1396 Error_InvalidDirective ();
1400 if (is_identifier_start_character (c)){
1406 if (is_identifier_part_character (c)){
1410 bool v = eval_val (s.Substring (0, j));
1411 s = s.Substring (j);
1414 bool vv = eval_val (s);
1419 Error_InvalidDirective ();
1423 bool pp_unary (ref string s)
1430 if (len > 1 && s [1] == '='){
1431 Error_InvalidDirective ();
1434 s = s.Substring (1);
1435 return ! pp_primary (ref s);
1437 return pp_primary (ref s);
1439 Error_InvalidDirective ();
1444 bool pp_eq (ref string s)
1446 bool va = pp_unary (ref s);
1452 if (len > 2 && s [1] == '='){
1453 s = s.Substring (2);
1454 return va == pp_unary (ref s);
1456 Error_InvalidDirective ();
1459 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1460 s = s.Substring (2);
1462 return va != pp_unary (ref s);
1471 bool pp_and (ref string s)
1473 bool va = pp_eq (ref s);
1479 if (len > 2 && s [1] == '&'){
1480 s = s.Substring (2);
1481 return (va & pp_and (ref s));
1483 Error_InvalidDirective ();
1492 // Evaluates an expression for `#if' or `#elif'
1494 bool pp_expr (ref string s)
1496 bool va = pp_and (ref s);
1503 if (len > 2 && s [1] == '|'){
1504 s = s.Substring (2);
1505 return va | pp_expr (ref s);
1507 Error_InvalidDirective ();
1516 bool eval (string s)
1518 bool v = pp_expr (ref s);
1521 Error_InvalidDirective ();
1528 void Error_InvalidDirective ()
1530 Report.Error (1517, Location, "Invalid preprocessor directive");
1533 void Error_UnexpectedDirective (string extra)
1537 "Unexpected processor directive (" + extra + ")");
1540 void Error_TokensSeen ()
1542 Report.Error (1032, Location,
1543 "Cannot define or undefine preprocessor symbols after first token in file");
1547 // Set to false to stop handling preprocesser directives
1549 bool process_directives = true;
1552 // if true, then the code continues processing the code
1553 // if false, the code stays in a loop until another directive is
1556 bool handle_preprocessing_directive (bool caller_is_taking)
1559 bool region_directive = false;
1561 get_cmd_arg (out cmd, out arg);
1563 // Eat any trailing whitespaces and single-line comments
1564 if (arg.IndexOf ("//") != -1)
1565 arg = arg.Substring (0, arg.IndexOf ("//"));
1566 arg = arg.TrimEnd (' ', '\t');
1569 // The first group of pre-processing instructions is always processed
1573 if (RootContext.Version == LanguageVersion.ISO_1) {
1574 Report.FeatureIsNotStandardized (Location, "#pragma");
1575 return caller_is_taking;
1578 PreProcessPragma (arg);
1579 return caller_is_taking;
1582 if (!PreProcessLine (arg))
1585 "The line number specified for #line directive is missing or invalid");
1586 return caller_is_taking;
1589 region_directive = true;
1594 region_directive = true;
1599 Error_InvalidDirective ();
1602 bool taking = false;
1603 if (ifstack == null)
1604 ifstack = new Stack ();
1606 if (ifstack.Count == 0){
1609 int state = (int) ifstack.Peek ();
1610 if ((state & TAKING) != 0)
1614 if (eval (arg) && taking){
1615 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1616 if (region_directive)
1618 ifstack.Push (push);
1621 int push = (taking ? PARENT_TAKING : 0);
1622 if (region_directive)
1624 ifstack.Push (push);
1629 if (ifstack == null || ifstack.Count == 0){
1630 Error_UnexpectedDirective ("no #if for this #endif");
1633 int pop = (int) ifstack.Pop ();
1635 if (region_directive && ((pop & REGION) == 0))
1636 Report.Error (1027, Location, "Expected `#endif' directive");
1637 else if (!region_directive && ((pop & REGION) != 0))
1638 Report.Error (1038, Location, "#endregion directive expected");
1640 if (!region_directive && arg.Length != 0) {
1641 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1644 if (ifstack.Count == 0)
1647 int state = (int) ifstack.Peek ();
1649 if ((state & TAKING) != 0)
1657 if (ifstack == null || ifstack.Count == 0){
1658 Error_UnexpectedDirective ("no #if for this #elif");
1661 int state = (int) ifstack.Peek ();
1663 if ((state & REGION) != 0) {
1664 Report.Error (1038, Location, "#endregion directive expected");
1668 if ((state & ELSE_SEEN) != 0){
1669 Error_UnexpectedDirective ("#elif not valid after #else");
1673 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1676 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1677 state = (int) ifstack.Pop ();
1678 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1685 if (ifstack == null || ifstack.Count == 0){
1686 Error_UnexpectedDirective ("no #if for this #else");
1689 int state = (int) ifstack.Peek ();
1691 if ((state & REGION) != 0) {
1692 Report.Error (1038, Location, "#endregion directive expected");
1696 if ((state & ELSE_SEEN) != 0){
1697 Error_UnexpectedDirective ("#else within #else");
1704 if ((state & TAKEN_BEFORE) == 0){
1705 ret = ((state & PARENT_TAKING) != 0);
1714 ifstack.Push (state | ELSE_SEEN);
1721 // These are only processed if we are in a `taking' block
1723 if (!caller_is_taking)
1728 if (any_token_seen){
1729 Error_TokensSeen ();
1732 PreProcessDefinition (true, arg);
1736 if (any_token_seen){
1737 Error_TokensSeen ();
1740 PreProcessDefinition (false, arg);
1744 Report.Error (1029, Location, "#error: '" + arg + "'");
1748 Report.Warning (1030, Location, "#warning: `{0}'", arg);
1752 Report.Error (1024, Location, "Wrong preprocessor directive");
1757 private int consume_string (bool quoted)
1760 string_builder.Length = 0;
1762 while ((c = getChar ()) != -1){
1764 if (quoted && peekChar () == '"'){
1765 string_builder.Append ((char) c);
1769 val = string_builder.ToString ();
1770 return Token.LITERAL_STRING;
1776 Report.Error (1010, Location, "Newline in constant");
1788 string_builder.Append ((char) c);
1791 Report.Error (1039, Location, "Unterminated string literal");
1795 private int consume_identifier (int s)
1797 int res = consume_identifier (s, false);
1799 if (doc_state == XmlCommentState.Allowed)
1800 doc_state = XmlCommentState.NotAllowed;
1803 case Token.NAMESPACE:
1804 check_incorrect_doc_comment ();
1808 if (res == Token.PARTIAL) {
1809 // Save current position and parse next token.
1810 int old = reader.Position;
1811 int old_putback = putback_char;
1815 int next_token = token ();
1816 bool ok = (next_token == Token.CLASS) ||
1817 (next_token == Token.STRUCT) ||
1818 (next_token == Token.INTERFACE) ||
1819 (next_token == Token.ENUM); // "partial" is a keyword in 'partial enum', even though it's not valid
1821 reader.Position = old;
1822 putback_char = old_putback;
1828 return Token.IDENTIFIER;
1835 private int consume_identifier (int s, bool quoted)
1840 id_builder [0] = (char) s;
1842 while ((c = reader.Read ()) != -1) {
1843 if (is_identifier_part_character ((char) c)){
1844 if (pos == max_id_size){
1845 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1849 id_builder [pos++] = (char) c;
1859 // Optimization: avoids doing the keyword lookup
1860 // on uppercase letters and _
1862 if (!quoted && (s >= 'a' || s == '_')){
1863 int keyword = GetKeyword (id_builder, pos);
1869 // Keep identifiers in an array of hashtables to avoid needless
1873 if (identifiers [pos] != null) {
1874 val = identifiers [pos][id_builder];
1876 return Token.IDENTIFIER;
1880 identifiers [pos] = new CharArrayHashtable (pos);
1882 val = new String (id_builder, 0, pos);
1883 if (RootContext.Version == LanguageVersion.ISO_1 && id_builder [0] == '_' && id_builder [1] == '_') {
1884 Report.Error (1638, Location,
1885 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val);
1888 char [] chars = new char [pos];
1889 Array.Copy (id_builder, chars, pos);
1891 identifiers [pos] [chars] = val;
1893 return Token.IDENTIFIER;
1896 public int xtoken ()
1899 bool doread = false;
1902 // Whether we have seen comments on the current line
1903 bool comments_seen = false;
1906 // optimization: eliminate col and implement #directive semantic correctly.
1907 for (;(c = getChar ()) != -1; col++) {
1912 col = (((col + 8) / 8) * 8) - 1;
1916 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1920 if (peekChar () == '\n')
1926 any_token_seen |= tokens_seen;
1927 tokens_seen = false;
1928 comments_seen = false;
1932 // Handle double-slash comments.
1934 int d = peekChar ();
1938 if (RootContext.Documentation != null && peekChar () == '/') {
1940 // Don't allow ////.
1941 if ((d = peekChar ()) != '/') {
1942 if (doc_state == XmlCommentState.Allowed)
1943 handle_one_line_xml_comment ();
1944 else if (doc_state == XmlCommentState.NotAllowed)
1945 warn_incorrect_doc_comment ();
1948 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
1955 any_token_seen |= tokens_seen;
1956 tokens_seen = false;
1957 comments_seen = false;
1959 } else if (d == '*'){
1961 bool docAppend = false;
1962 if (RootContext.Documentation != null && peekChar () == '*') {
1964 // But when it is /**/, just do nothing.
1965 if (peekChar () == '/') {
1969 if (doc_state == XmlCommentState.Allowed)
1971 else if (doc_state == XmlCommentState.NotAllowed)
1972 warn_incorrect_doc_comment ();
1975 int current_comment_start = 0;
1977 current_comment_start = xml_comment_buffer.Length;
1978 xml_comment_buffer.Append (Environment.NewLine);
1981 Location start_location = Location;
1983 while ((d = getChar ()) != -1){
1984 if (d == '*' && peekChar () == '/'){
1987 comments_seen = true;
1991 xml_comment_buffer.Append ((char) d);
1997 any_token_seen |= tokens_seen;
1998 tokens_seen = false;
2000 // Reset 'comments_seen' just to be consistent.
2001 // It doesn't matter either way, here.
2003 comments_seen = false;
2007 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2010 update_formatted_doc_comment (current_comment_start);
2013 goto is_punct_label;
2017 if (is_identifier_start_character ((char)c)){
2019 return consume_identifier (c);
2023 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2037 any_token_seen |= tokens_seen;
2038 tokens_seen = false;
2039 comments_seen = false;
2043 if (c >= '0' && c <= '9'){
2045 return is_number (c);
2050 int peek = peekChar ();
2051 if (peek >= '0' && peek <= '9')
2052 return is_number (c);
2056 /* For now, ignore pre-processor commands */
2057 // FIXME: In C# the '#' is not limited to appear
2058 // on the first column.
2060 // return NONE if we're not processing directives (during token peeks)
2061 if (!process_directives)
2065 if (tokens_seen || comments_seen) {
2066 error_details = "Preprocessor directives must appear as the first" +
2067 " non-whitespace character on a line.";
2069 Report.Error (1040, Location, error_details);
2076 cont = handle_preprocessing_directive (cont);
2084 bool skipping = false;
2085 for (;(c = getChar ()) != -1; col++){
2091 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2095 if (c == '#' && !skipping)
2098 any_token_seen |= tokens_seen;
2099 tokens_seen = false;
2101 Report.Error (1027, Location, "Expected `#endif' directive");
2106 return consume_string (false);
2112 error_details = "Empty character literal";
2113 Report.Error (1011, Location, error_details);
2119 val = new System.Char ();
2124 error_details = "Too many characters in character literal";
2125 Report.Error (1012, Location, error_details);
2127 // Try to recover, read until newline or next "'"
2128 while ((c = getChar ()) != -1){
2129 if (c == '\n' || c == '\''){
2140 return Token.LITERAL_CHARACTER;
2147 return consume_string (true);
2148 } else if (is_identifier_start_character ((char) c)){
2149 return consume_identifier (c, true);
2151 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2155 error_details = ((char)c).ToString ();
2164 // Handles one line xml comment
2166 private void handle_one_line_xml_comment ()
2169 while ((c = peekChar ()) == ' ')
2170 getChar (); // skip heading whitespaces.
2171 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2173 xml_comment_buffer.Append ((char) getChar ());
2175 if (c == '\r' || c == '\n')
2176 xml_comment_buffer.Append (Environment.NewLine);
2180 // Remove heading "*" in Javadoc-like xml documentation.
2182 private void update_formatted_doc_comment (int current_comment_start)
2184 int length = xml_comment_buffer.Length - current_comment_start;
2185 string [] lines = xml_comment_buffer.ToString (
2186 current_comment_start,
2187 length).Replace ("\r", "").Split ('\n');
2189 // The first line starts with /**, thus it is not target
2190 // for the format check.
2191 for (int i = 1; i < lines.Length; i++) {
2192 string s = lines [i];
2193 int idx = s.IndexOf ('*');
2196 if (i < lines.Length - 1)
2200 head = s.Substring (0, idx);
2201 foreach (char c in head)
2204 lines [i] = s.Substring (idx + 1);
2206 xml_comment_buffer.Remove (current_comment_start, length);
2207 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2211 // Checks if there was incorrect doc comments and raise
2214 public void check_incorrect_doc_comment ()
2216 if (xml_comment_buffer.Length > 0)
2217 warn_incorrect_doc_comment ();
2221 // Raises a warning when tokenizer found incorrect doccomment
2224 private void warn_incorrect_doc_comment ()
2226 doc_state = XmlCommentState.Error;
2227 // in csc, it is 'XML comment is not placed on a valid
2228 // language element'. But that does not make sense.
2229 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2233 // Consumes the saved xml comment lines (if any)
2234 // as for current target member or type.
2236 public string consume_doc_comment ()
2238 if (xml_comment_buffer.Length > 0) {
2239 string ret = xml_comment_buffer.ToString ();
2240 xml_comment_buffer.Length = 0;
2246 public void cleanup ()
2248 if (ifstack != null && ifstack.Count >= 1) {
2249 int state = (int) ifstack.Pop ();
2250 if ((state & REGION) != 0)
2251 Report.Error (1038, Location, "#endregion directive expected");
2253 Report.Error (1027, "Expected `#endif' directive");
2260 // Indicates whether it accepts XML documentation or not.
2262 public enum XmlCommentState {
2263 // comment is allowed in this state.
2265 // comment is not allowed in this state.
2267 // once comments appeared when it is NotAllowed, then the
2268 // state is changed to it, until the state is changed to