2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 // This also implements the preprocessor
5 // Author: Miguel de Icaza (miguel@gnu.org)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
15 * Make sure we accept the proper Unicode ranges, per the spec.
21 using System.Collections;
23 using System.Globalization;
24 using System.Reflection;
29 /// Tokenizer for C# source code.
32 public class Tokenizer : yyParser.yyInput
34 SeekableStreamReader reader;
42 bool handle_get_set = false;
43 bool handle_remove_add = false;
44 bool handle_assembly = false;
45 Location current_location;
46 Location current_comment_location = Location.Null;
47 ArrayList escapedIdentifiers = new ArrayList ();
50 // XML documentation buffer. The save point is used to divide
51 // comments on types and comments on members.
53 StringBuilder xml_comment_buffer;
56 // See comment on XmlCommentState enumeration.
58 XmlCommentState xmlDocState = XmlCommentState.Allowed;
61 // Whether tokens have been seen on this line
63 bool tokens_seen = false;
66 // Whether a token has been seen on the file
67 // This is needed because `define' is not allowed to be used
68 // after a token has been seen.
70 bool any_token_seen = false;
72 static Hashtable tokenValues;
74 private static Hashtable TokenValueName
77 if (tokenValues == null)
78 tokenValues = GetTokenValueNameHash ();
84 private static Hashtable GetTokenValueNameHash ()
86 Type t = typeof (Token);
87 FieldInfo [] fields = t.GetFields ();
88 Hashtable hash = new Hashtable ();
89 foreach (FieldInfo field in fields) {
90 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
91 hash.Add (field.GetValue (null), field.Name);
97 // Returns a verbose representation of the current location
99 public string location {
103 if (current_token == Token.ERROR)
104 det = "detail: " + error_details;
108 // return "Line: "+line+" Col: "+col + "\n" +
109 // "VirtLine: "+ref_line +
110 // " Token: "+current_token + " " + det;
111 string current_token_name = TokenValueName [current_token] as string;
112 if (current_token_name == null)
113 current_token_name = current_token.ToString ();
115 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
123 public bool PropertyParsing {
125 return handle_get_set;
129 handle_get_set = value;
133 public bool AssemblyTargetParsing {
135 return handle_assembly;
139 handle_assembly = value;
143 public bool EventParsing {
145 return handle_remove_add;
149 handle_remove_add = value;
153 public XmlCommentState doc_state {
154 get { return xmlDocState; }
156 if (value == XmlCommentState.Allowed) {
157 check_incorrect_doc_comment ();
158 reset_doc_comment ();
164 public bool IsEscapedIdentifier (Location loc)
166 foreach (LocatedToken lt in escapedIdentifiers)
167 if (lt.Location.Equals (loc))
176 static CharArrayHashtable[] keywords;
177 static Hashtable keywordStrings = new Hashtable ();
178 static NumberStyles styles;
179 static NumberFormatInfo csharp_format_info;
182 // Values for the associated token returned
192 const int TAKING = 1;
193 const int TAKEN_BEFORE = 2;
194 const int ELSE_SEEN = 4;
195 const int PARENT_TAKING = 8;
196 const int REGION = 16;
199 // pre-processor if stack state:
203 static System.Text.StringBuilder string_builder;
205 const int max_id_size = 512;
206 static char [] id_builder = new char [max_id_size];
208 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
210 const int max_number_size = 512;
211 static char [] number_builder = new char [max_number_size];
212 static int number_pos;
215 // Details about the error encoutered by the tokenizer
217 string error_details;
219 public string error {
221 return error_details;
237 static void AddKeyword (string kw, int token) {
238 keywordStrings.Add (kw, kw);
239 if (keywords [kw.Length] == null) {
240 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
242 keywords [kw.Length] [kw.ToCharArray ()] = token;
245 static void InitTokens ()
247 keywords = new CharArrayHashtable [64];
249 AddKeyword ("__arglist", Token.ARGLIST);
250 AddKeyword ("abstract", Token.ABSTRACT);
251 AddKeyword ("as", Token.AS);
252 AddKeyword ("add", Token.ADD);
253 AddKeyword ("assembly", Token.ASSEMBLY);
254 AddKeyword ("base", Token.BASE);
255 AddKeyword ("bool", Token.BOOL);
256 AddKeyword ("break", Token.BREAK);
257 AddKeyword ("byte", Token.BYTE);
258 AddKeyword ("case", Token.CASE);
259 AddKeyword ("catch", Token.CATCH);
260 AddKeyword ("char", Token.CHAR);
261 AddKeyword ("checked", Token.CHECKED);
262 AddKeyword ("class", Token.CLASS);
263 AddKeyword ("const", Token.CONST);
264 AddKeyword ("continue", Token.CONTINUE);
265 AddKeyword ("decimal", Token.DECIMAL);
266 AddKeyword ("default", Token.DEFAULT);
267 AddKeyword ("delegate", Token.DELEGATE);
268 AddKeyword ("do", Token.DO);
269 AddKeyword ("double", Token.DOUBLE);
270 AddKeyword ("else", Token.ELSE);
271 AddKeyword ("enum", Token.ENUM);
272 AddKeyword ("event", Token.EVENT);
273 AddKeyword ("explicit", Token.EXPLICIT);
274 AddKeyword ("extern", Token.EXTERN);
275 AddKeyword ("false", Token.FALSE);
276 AddKeyword ("finally", Token.FINALLY);
277 AddKeyword ("fixed", Token.FIXED);
278 AddKeyword ("float", Token.FLOAT);
279 AddKeyword ("for", Token.FOR);
280 AddKeyword ("foreach", Token.FOREACH);
281 AddKeyword ("goto", Token.GOTO);
282 AddKeyword ("get", Token.GET);
283 AddKeyword ("if", Token.IF);
284 AddKeyword ("implicit", Token.IMPLICIT);
285 AddKeyword ("in", Token.IN);
286 AddKeyword ("int", Token.INT);
287 AddKeyword ("interface", Token.INTERFACE);
288 AddKeyword ("internal", Token.INTERNAL);
289 AddKeyword ("is", Token.IS);
290 AddKeyword ("lock", Token.LOCK);
291 AddKeyword ("long", Token.LONG);
292 AddKeyword ("namespace", Token.NAMESPACE);
293 AddKeyword ("new", Token.NEW);
294 AddKeyword ("null", Token.NULL);
295 AddKeyword ("object", Token.OBJECT);
296 AddKeyword ("operator", Token.OPERATOR);
297 AddKeyword ("out", Token.OUT);
298 AddKeyword ("override", Token.OVERRIDE);
299 AddKeyword ("params", Token.PARAMS);
300 AddKeyword ("private", Token.PRIVATE);
301 AddKeyword ("protected", Token.PROTECTED);
302 AddKeyword ("public", Token.PUBLIC);
303 AddKeyword ("readonly", Token.READONLY);
304 AddKeyword ("ref", Token.REF);
305 AddKeyword ("remove", Token.REMOVE);
306 AddKeyword ("return", Token.RETURN);
307 AddKeyword ("sbyte", Token.SBYTE);
308 AddKeyword ("sealed", Token.SEALED);
309 AddKeyword ("set", Token.SET);
310 AddKeyword ("short", Token.SHORT);
311 AddKeyword ("sizeof", Token.SIZEOF);
312 AddKeyword ("stackalloc", Token.STACKALLOC);
313 AddKeyword ("static", Token.STATIC);
314 AddKeyword ("string", Token.STRING);
315 AddKeyword ("struct", Token.STRUCT);
316 AddKeyword ("switch", Token.SWITCH);
317 AddKeyword ("this", Token.THIS);
318 AddKeyword ("throw", Token.THROW);
319 AddKeyword ("true", Token.TRUE);
320 AddKeyword ("try", Token.TRY);
321 AddKeyword ("typeof", Token.TYPEOF);
322 AddKeyword ("uint", Token.UINT);
323 AddKeyword ("ulong", Token.ULONG);
324 AddKeyword ("unchecked", Token.UNCHECKED);
325 AddKeyword ("unsafe", Token.UNSAFE);
326 AddKeyword ("ushort", Token.USHORT);
327 AddKeyword ("using", Token.USING);
328 AddKeyword ("virtual", Token.VIRTUAL);
329 AddKeyword ("void", Token.VOID);
330 AddKeyword ("volatile", Token.VOLATILE);
331 AddKeyword ("while", Token.WHILE);
332 AddKeyword ("partial", Token.PARTIAL);
341 csharp_format_info = NumberFormatInfo.InvariantInfo;
342 styles = NumberStyles.Float;
344 string_builder = new System.Text.StringBuilder ();
347 int GetKeyword (char[] id, int id_len)
350 * Keywords are stored in an array of hashtables grouped by their
354 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
356 object o = keywords [id_len] [id];
363 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
365 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
367 if (handle_assembly == false && res == Token.ASSEMBLY)
374 public Location Location {
375 get { return current_location; }
378 void define (string def)
380 if (!RootContext.AllDefines.Contains (def)){
381 RootContext.AllDefines [def] = true;
383 if (defines.Contains (def))
385 defines [def] = true;
388 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
390 this.ref_name = file;
391 this.file_name = file;
397 defines = new Hashtable ();
398 foreach (string def in defs)
402 xml_comment_buffer = new StringBuilder ();
405 // FIXME: This could be `Location.Push' but we have to
406 // find out why the MS compiler allows this
408 Mono.CSharp.Location.Push (file, 0);
411 static bool is_identifier_start_character (char c)
413 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
416 static bool is_identifier_part_character (char c)
418 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
421 public static bool IsKeyword (string s)
423 return keywordStrings [s] != null;
426 public static bool IsValidIdentifier (string s)
428 if (s == null || s.Length == 0)
431 if (!is_identifier_start_character (s [0]))
434 for (int i = 1; i < s.Length; i ++)
435 if (! is_identifier_part_character (s [i]))
441 int is_punct (char c, ref bool doread)
451 return Token.OPEN_BRACE;
454 return Token.CLOSE_BRACE;
456 // To block doccomment inside attribute declaration.
457 if (doc_state == XmlCommentState.Allowed)
458 doc_state = XmlCommentState.NotAllowed;
459 return Token.OPEN_BRACKET;
461 return Token.CLOSE_BRACKET;
463 return Token.OPEN_PARENS;
465 if (deambiguate_close_parens == 0)
466 return Token.CLOSE_PARENS;
468 --deambiguate_close_parens;
470 // Save current position and parse next token.
471 int old = reader.Position;
472 int old_ref_line = ref_line;
475 // disable preprocessing directives when peeking
476 process_directives = false;
477 int new_token = token ();
478 process_directives = true;
479 reader.Position = old;
480 ref_line = old_ref_line;
484 if (new_token == Token.OPEN_PARENS)
485 return Token.CLOSE_PARENS_OPEN_PARENS;
486 else if (new_token == Token.MINUS)
487 return Token.CLOSE_PARENS_MINUS;
488 else if (IsCastToken (new_token))
489 return Token.CLOSE_PARENS_CAST;
491 return Token.CLOSE_PARENS_NO_CAST;
498 return Token.SEMICOLON;
514 t = Token.OP_ADD_ASSIGN;
528 t = Token.OP_SUB_ASSIGN;
560 } else if (d == '='){
562 return Token.OP_AND_ASSIGN;
565 return Token.BITWISE_AND;
572 } else if (d == '='){
574 return Token.OP_OR_ASSIGN;
576 return Token.BITWISE_OR;
582 return Token.OP_MULT_ASSIGN;
591 return Token.OP_DIV_ASSIGN;
599 return Token.OP_MOD_ASSIGN;
601 return Token.PERCENT;
607 return Token.OP_XOR_ASSIGN;
619 return Token.OP_SHIFT_LEFT_ASSIGN;
621 return Token.OP_SHIFT_LEFT;
622 } else if (d == '='){
636 return Token.OP_SHIFT_RIGHT_ASSIGN;
638 return Token.OP_SHIFT_RIGHT;
639 } else if (d == '='){
648 return Token.DOUBLE_COLON;
657 int deambiguate_close_parens = 0;
659 public void Deambiguate_CloseParens ()
662 deambiguate_close_parens++;
665 void Error_NumericConstantTooLong ()
667 Report.Error (1021, Location, "Numeric constant too long");
670 bool decimal_digits (int c)
673 bool seen_digits = false;
676 if (number_pos == max_number_size)
677 Error_NumericConstantTooLong ();
678 number_builder [number_pos++] = (char) c;
682 // We use peekChar2, because decimal_digits needs to do a
683 // 2-character look-ahead (5.ToString for example).
685 while ((d = peekChar2 ()) != -1){
686 if (d >= '0' && d <= '9'){
687 if (number_pos == max_number_size)
688 Error_NumericConstantTooLong ();
689 number_builder [number_pos++] = (char) d;
701 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
704 int real_type_suffix (int c)
710 t = Token.LITERAL_FLOAT;
713 t = Token.LITERAL_DOUBLE;
716 t= Token.LITERAL_DECIMAL;
724 int integer_type_suffix (ulong ul, int c)
726 bool is_unsigned = false;
727 bool is_long = false;
730 bool scanning = true;
741 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
743 // if we have not seen anything in between
746 Report.Warning (78, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
749 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
774 if (is_long && is_unsigned){
776 return Token.LITERAL_INTEGER;
777 } else if (is_unsigned){
778 // uint if possible, or ulong else.
780 if ((ul & 0xffffffff00000000) == 0)
785 // long if possible, ulong otherwise
786 if ((ul & 0x8000000000000000) != 0)
791 // int, uint, long or ulong in that order
792 if ((ul & 0xffffffff00000000) == 0){
795 if ((ui & 0x80000000) != 0)
800 if ((ul & 0x8000000000000000) != 0)
806 return Token.LITERAL_INTEGER;
810 // given `c' as the next char in the input decide whether
811 // we need to convert to a special type, and then choose
812 // the best representation for the integer
814 int adjust_int (int c)
818 ulong ul = (uint) (number_builder [0] - '0');
820 for (int i = 1; i < number_pos; i++){
821 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
823 return integer_type_suffix (ul, c);
825 uint ui = (uint) (number_builder [0] - '0');
827 for (int i = 1; i < number_pos; i++){
828 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
830 return integer_type_suffix (ui, c);
832 } catch (OverflowException) {
833 error_details = "Integral constant is too large";
834 Report.Error (1021, Location, error_details);
836 return Token.LITERAL_INTEGER;
840 int adjust_real (int t)
842 string s = new String (number_builder, 0, number_pos);
843 const string error_details = "Floating-point constant is outside the range of type `{0}'";
846 case Token.LITERAL_DECIMAL:
848 val = System.Decimal.Parse (s, styles, csharp_format_info);
849 } catch (OverflowException) {
851 Report.Error (594, Location, error_details, "decimal");
854 case Token.LITERAL_FLOAT:
856 val = (float) System.Double.Parse (s, styles, csharp_format_info);
857 } catch (OverflowException) {
859 Report.Error (594, Location, error_details, "float");
863 case Token.LITERAL_DOUBLE:
865 t = Token.LITERAL_DOUBLE;
867 val = System.Double.Parse (s, styles, csharp_format_info);
868 } catch (OverflowException) {
870 Report.Error (594, Location, error_details, "double");
883 while ((d = peekChar ()) != -1){
885 number_builder [number_pos++] = (char) d;
891 string s = new String (number_builder, 0, number_pos);
894 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
896 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
897 } catch (OverflowException){
898 error_details = "Integral constant is too large";
899 Report.Error (1021, Location, error_details);
901 return Token.LITERAL_INTEGER;
903 catch (FormatException) {
904 Report.Error (1013, Location, "Invalid number");
906 return Token.LITERAL_INTEGER;
909 return integer_type_suffix (ul, peekChar ());
913 // Invoked if we know we have .digits or digits
915 int is_number (int c)
917 bool is_real = false;
922 if (c >= '0' && c <= '9'){
924 int peek = peekChar ();
926 if (peek == 'x' || peek == 'X')
927 return handle_hex ();
934 // We need to handle the case of
935 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
938 if (decimal_digits ('.')){
944 return adjust_int (-1);
948 if (c == 'e' || c == 'E'){
950 if (number_pos == max_number_size)
951 Error_NumericConstantTooLong ();
952 number_builder [number_pos++] = 'e';
956 if (number_pos == max_number_size)
957 Error_NumericConstantTooLong ();
958 number_builder [number_pos++] = '+';
960 } else if (c == '-') {
961 if (number_pos == max_number_size)
962 Error_NumericConstantTooLong ();
963 number_builder [number_pos++] = '-';
966 if (number_pos == max_number_size)
967 Error_NumericConstantTooLong ();
968 number_builder [number_pos++] = '+';
975 type = real_type_suffix (c);
976 if (type == Token.NONE && !is_real){
978 return adjust_int (c);
982 if (type == Token.NONE){
987 return adjust_real (type);
989 Console.WriteLine ("This should not be reached");
990 throw new Exception ("Is Number should never reach this point");
994 // Accepts exactly count (4 or 8) hex, no more no less
996 int getHex (int count, out bool error)
1001 int top = count != -1 ? count : 4;
1005 for (i = 0; i < top; i++){
1008 if (c >= '0' && c <= '9')
1009 c = (int) c - (int) '0';
1010 else if (c >= 'A' && c <= 'F')
1011 c = (int) c - (int) 'A' + 10;
1012 else if (c >= 'a' && c <= 'f')
1013 c = (int) c - (int) 'a' + 10;
1019 total = (total * 16) + c;
1021 int p = peekChar ();
1024 if (!is_hex ((char)p))
1065 v = getHex (-1, out error);
1070 v = getHex (4, out error);
1075 v = getHex (8, out error);
1080 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", (char)d);
1090 if (putback_char != -1) {
1109 if (putback_char != -1)
1110 return putback_char;
1111 putback_char = reader.Read ();
1112 return putback_char;
1117 if (putback_char != -1)
1118 return putback_char;
1119 return reader.Peek ();
1122 void putback (int c)
1124 if (putback_char != -1){
1125 Console.WriteLine ("Col: " + col);
1126 Console.WriteLine ("Row: " + line);
1127 Console.WriteLine ("Name: " + ref_name.Name);
1128 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1129 throw new Exception ("This should not happen putback on putback");
1131 if (c == '\n' || col == 0) {
1132 // It won't happen though.
1142 public bool advance ()
1144 return peekChar () != -1;
1147 public Object Value {
1153 public Object value ()
1158 bool IsCastToken (int token)
1163 case Token.IDENTIFIER:
1164 case Token.LITERAL_INTEGER:
1165 case Token.LITERAL_FLOAT:
1166 case Token.LITERAL_DOUBLE:
1167 case Token.LITERAL_DECIMAL:
1168 case Token.LITERAL_CHARACTER:
1169 case Token.LITERAL_STRING:
1181 case Token.UNCHECKED:
1185 // These can be part of a member access
1205 current_token = xtoken ();
1206 return current_token;
1209 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1211 void get_cmd_arg (out string cmd, out string arg)
1215 tokens_seen = false;
1217 static_cmd_arg.Length = 0;
1219 // skip over white space
1220 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1224 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1225 if (is_identifier_part_character ((char) c)){
1226 static_cmd_arg.Append ((char) c);
1234 cmd = static_cmd_arg.ToString ();
1240 // skip over white space
1241 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1246 } else if (c == '\r'){
1248 } else if (c == -1){
1253 static_cmd_arg.Length = 0;
1254 static_cmd_arg.Append ((char) c);
1256 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1257 static_cmd_arg.Append ((char) c);
1260 arg = static_cmd_arg.ToString ().Trim ();
1264 // Handles the #line directive
1266 bool PreProcessLine (string arg)
1271 if (arg == "default"){
1273 ref_name = file_name;
1274 Location.Push (ref_name, line);
1276 } else if (arg == "hidden"){
1278 // We ignore #line hidden
1286 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1287 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1290 char [] quotes = { '\"' };
1292 string name = arg.Substring (pos). Trim (quotes);
1293 ref_name = Location.LookupFile (name);
1294 file_name.HasLineDirective = true;
1295 ref_name.HasLineDirective = true;
1296 Location.Push (ref_name, ref_line);
1298 ref_line = System.Int32.Parse (arg);
1308 // Handles #define and #undef
1310 void PreProcessDefinition (bool is_define, string arg)
1312 if (arg == "" || arg == "true" || arg == "false"){
1313 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1317 char[] whitespace = { ' ', '\t' };
1318 if (arg.IndexOfAny (whitespace) != -1){
1319 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1323 if (!is_identifier_start_character (arg [0]))
1324 Report.Error (1001, Location, "Identifier expected: " + arg);
1326 foreach (char c in arg.Substring (1)){
1327 if (!is_identifier_part_character (c)){
1328 Report.Error (1001, Location, "Identifier expected: " + arg);
1334 if (defines == null)
1335 defines = new Hashtable ();
1338 if (defines == null)
1340 if (defines.Contains (arg))
1341 defines.Remove (arg);
1346 /// Handles #pragma directive
1348 void PreProcessPragma (string arg)
1350 const string warning = "warning";
1351 const string w_disable = "warning disable";
1352 const string w_restore = "warning restore";
1354 if (arg == w_disable) {
1355 Report.RegisterWarningRegion (Location).WarningDisable (line);
1359 if (arg == w_restore) {
1360 Report.RegisterWarningRegion (Location).WarningEnable (line);
1364 if (arg.StartsWith (w_disable)) {
1365 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1366 foreach (int code in codes) {
1368 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1373 if (arg.StartsWith (w_restore)) {
1374 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1375 Hashtable w_table = Report.warning_ignore_table;
1376 foreach (int code in codes) {
1377 if (w_table != null && w_table.Contains (code))
1378 Report.Warning (1635, 1, Location, "Cannot restore warning 'CS{0:0000}' because it was disabled globally", code);
1379 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1384 if (arg.StartsWith (warning)) {
1385 Report.Warning (1634, 1, Location, "Expected disable or restore");
1389 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1392 int[] ParseNumbers (string text)
1394 string[] string_array = text.Split (',');
1395 int[] values = new int [string_array.Length];
1397 foreach (string string_code in string_array) {
1399 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1401 catch (FormatException) {
1402 Report.Warning (1692, Location, "Invalid number");
1408 bool eval_val (string s)
1415 if (defines == null)
1417 if (defines.Contains (s))
1423 bool pp_primary (ref string s)
1432 s = s.Substring (1);
1433 bool val = pp_expr (ref s);
1434 if (s.Length > 0 && s [0] == ')'){
1435 s = s.Substring (1);
1438 Error_InvalidDirective ();
1442 if (is_identifier_start_character (c)){
1448 if (is_identifier_part_character (c)){
1452 bool v = eval_val (s.Substring (0, j));
1453 s = s.Substring (j);
1456 bool vv = eval_val (s);
1461 Error_InvalidDirective ();
1465 bool pp_unary (ref string s)
1472 if (len > 1 && s [1] == '='){
1473 Error_InvalidDirective ();
1476 s = s.Substring (1);
1477 return ! pp_primary (ref s);
1479 return pp_primary (ref s);
1481 Error_InvalidDirective ();
1486 bool pp_eq (ref string s)
1488 bool va = pp_unary (ref s);
1494 if (len > 2 && s [1] == '='){
1495 s = s.Substring (2);
1496 return va == pp_unary (ref s);
1498 Error_InvalidDirective ();
1501 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1502 s = s.Substring (2);
1504 return va != pp_unary (ref s);
1513 bool pp_and (ref string s)
1515 bool va = pp_eq (ref s);
1521 if (len > 2 && s [1] == '&'){
1522 s = s.Substring (2);
1523 return (va & pp_and (ref s));
1525 Error_InvalidDirective ();
1534 // Evaluates an expression for `#if' or `#elif'
1536 bool pp_expr (ref string s)
1538 bool va = pp_and (ref s);
1545 if (len > 2 && s [1] == '|'){
1546 s = s.Substring (2);
1547 return va | pp_expr (ref s);
1549 Error_InvalidDirective ();
1558 bool eval (string s)
1560 bool v = pp_expr (ref s);
1563 Error_InvalidDirective ();
1570 void Error_InvalidDirective ()
1572 Report.Error (1517, Location, "Invalid preprocessor directive");
1575 void Error_UnexpectedDirective (string extra)
1579 "Unexpected processor directive (" + extra + ")");
1582 void Error_TokensSeen ()
1584 Report.Error (1032, Location,
1585 "Cannot define or undefine preprocessor symbols after first token in file");
1589 // Set to false to stop handling preprocesser directives
1591 bool process_directives = true;
1594 // if true, then the code continues processing the code
1595 // if false, the code stays in a loop until another directive is
1598 bool handle_preprocessing_directive (bool caller_is_taking)
1601 bool region_directive = false;
1603 get_cmd_arg (out cmd, out arg);
1605 // Eat any trailing whitespaces and single-line comments
1606 if (arg.IndexOf ("//") != -1)
1607 arg = arg.Substring (0, arg.IndexOf ("//"));
1608 arg = arg.TrimEnd (' ', '\t');
1611 // The first group of pre-processing instructions is always processed
1615 if (RootContext.Version == LanguageVersion.ISO_1) {
1616 Report.FeatureIsNotStandardized (Location, "#pragma");
1617 return caller_is_taking;
1620 PreProcessPragma (arg);
1621 return caller_is_taking;
1624 if (!PreProcessLine (arg))
1627 "The line number specified for #line directive is missing or invalid");
1628 return caller_is_taking;
1631 region_directive = true;
1636 region_directive = true;
1641 Error_InvalidDirective ();
1644 bool taking = false;
1645 if (ifstack == null)
1646 ifstack = new Stack ();
1648 if (ifstack.Count == 0){
1651 int state = (int) ifstack.Peek ();
1652 if ((state & TAKING) != 0)
1656 if (eval (arg) && taking){
1657 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1658 if (region_directive)
1660 ifstack.Push (push);
1663 int push = (taking ? PARENT_TAKING : 0);
1664 if (region_directive)
1666 ifstack.Push (push);
1671 if (ifstack == null || ifstack.Count == 0){
1672 Error_UnexpectedDirective ("no #if for this #endif");
1675 int pop = (int) ifstack.Pop ();
1677 if (region_directive && ((pop & REGION) == 0))
1678 Report.Error (1027, Location, "Expected `#endif' directive");
1679 else if (!region_directive && ((pop & REGION) != 0))
1680 Report.Error (1038, Location, "#endregion directive expected");
1682 if (!region_directive && arg.Length != 0) {
1683 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1686 if (ifstack.Count == 0)
1689 int state = (int) ifstack.Peek ();
1691 if ((state & TAKING) != 0)
1699 if (ifstack == null || ifstack.Count == 0){
1700 Error_UnexpectedDirective ("no #if for this #elif");
1703 int state = (int) ifstack.Peek ();
1705 if ((state & REGION) != 0) {
1706 Report.Error (1038, Location, "#endregion directive expected");
1710 if ((state & ELSE_SEEN) != 0){
1711 Error_UnexpectedDirective ("#elif not valid after #else");
1715 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1718 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1719 state = (int) ifstack.Pop ();
1720 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1727 if (ifstack == null || ifstack.Count == 0){
1728 Error_UnexpectedDirective ("no #if for this #else");
1731 int state = (int) ifstack.Peek ();
1733 if ((state & REGION) != 0) {
1734 Report.Error (1038, Location, "#endregion directive expected");
1738 if ((state & ELSE_SEEN) != 0){
1739 Error_UnexpectedDirective ("#else within #else");
1746 if ((state & TAKEN_BEFORE) == 0){
1747 ret = ((state & PARENT_TAKING) != 0);
1756 ifstack.Push (state | ELSE_SEEN);
1763 // These are only processed if we are in a `taking' block
1765 if (!caller_is_taking)
1770 if (any_token_seen){
1771 Error_TokensSeen ();
1774 PreProcessDefinition (true, arg);
1778 if (any_token_seen){
1779 Error_TokensSeen ();
1782 PreProcessDefinition (false, arg);
1786 Report.Error (1029, Location, "#error: '" + arg + "'");
1790 Report.Warning (1030, Location, "#warning: `{0}'", arg);
1794 Report.Error (1024, Location, "Wrong preprocessor directive");
1799 private int consume_string (bool quoted)
1802 string_builder.Length = 0;
1804 while ((c = getChar ()) != -1){
1806 if (quoted && peekChar () == '"'){
1807 string_builder.Append ((char) c);
1811 val = string_builder.ToString ();
1812 return Token.LITERAL_STRING;
1818 Report.Error (1010, Location, "Newline in constant");
1826 string_builder.Append ((char) c);
1829 Report.Error (1039, Location, "Unterminated string literal");
1833 private int consume_identifier (int s)
1835 int res = consume_identifier (s, false);
1837 if (doc_state == XmlCommentState.Allowed)
1838 doc_state = XmlCommentState.NotAllowed;
1841 case Token.NAMESPACE:
1842 check_incorrect_doc_comment ();
1846 if (res == Token.PARTIAL) {
1847 // Save current position and parse next token.
1848 int old = reader.Position;
1849 int old_putback = putback_char;
1850 int old_ref_line = ref_line;
1855 int next_token = token ();
1856 bool ok = (next_token == Token.CLASS) ||
1857 (next_token == Token.STRUCT) ||
1858 (next_token == Token.INTERFACE) ||
1859 (next_token == Token.ENUM); // "partial" is a keyword in 'partial enum', even though it's not valid
1861 reader.Position = old;
1862 ref_line = old_ref_line;
1864 putback_char = old_putback;
1869 val = new LocatedToken (Location, "partial");
1870 return Token.IDENTIFIER;
1877 private int consume_identifier (int s, bool quoted)
1882 id_builder [0] = (char) s;
1884 current_location = new Location (ref_line, Col);
1886 while ((c = getChar ()) != -1) {
1887 if (is_identifier_part_character ((char) c)){
1888 if (pos == max_id_size){
1889 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1893 id_builder [pos++] = (char) c;
1894 // putback_char = -1;
1896 // putback_char = c;
1903 // Optimization: avoids doing the keyword lookup
1904 // on uppercase letters and _
1906 if (!quoted && (s >= 'a' || s == '_')){
1907 int keyword = GetKeyword (id_builder, pos);
1908 if (keyword != -1) {
1915 // Keep identifiers in an array of hashtables to avoid needless
1919 if (identifiers [pos] != null) {
1920 val = identifiers [pos][id_builder];
1922 val = new LocatedToken (Location, (string) val);
1924 escapedIdentifiers.Add (val);
1925 return Token.IDENTIFIER;
1929 identifiers [pos] = new CharArrayHashtable (pos);
1931 val = new String (id_builder, 0, pos);
1932 if (RootContext.Version == LanguageVersion.ISO_1 && id_builder [0] == '_' && id_builder [1] == '_') {
1933 Report.Error (1638, Location,
1934 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val);
1937 char [] chars = new char [pos];
1938 Array.Copy (id_builder, chars, pos);
1940 identifiers [pos] [chars] = val;
1942 val = new LocatedToken (Location, (string) val);
1944 escapedIdentifiers.Add (val);
1945 return Token.IDENTIFIER;
1948 public int xtoken ()
1951 bool doread = false;
1954 // Whether we have seen comments on the current line
1955 bool comments_seen = false;
1958 // optimization: eliminate col and implement #directive semantic correctly.
1959 for (;(c = getChar ()) != -1;) {
1967 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1971 if (peekChar () == '\n')
1974 any_token_seen |= tokens_seen;
1975 tokens_seen = false;
1976 comments_seen = false;
1980 // Handle double-slash comments.
1982 int d = peekChar ();
1986 if (RootContext.Documentation != null && peekChar () == '/') {
1988 // Don't allow ////.
1989 if ((d = peekChar ()) != '/') {
1990 update_comment_location ();
1991 if (doc_state == XmlCommentState.Allowed)
1992 handle_one_line_xml_comment ();
1993 else if (doc_state == XmlCommentState.NotAllowed)
1994 warn_incorrect_doc_comment ();
1997 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
2000 any_token_seen |= tokens_seen;
2001 tokens_seen = false;
2002 comments_seen = false;
2004 } else if (d == '*'){
2006 bool docAppend = false;
2007 if (RootContext.Documentation != null && peekChar () == '*') {
2009 update_comment_location ();
2010 // But when it is /**/, just do nothing.
2011 if (peekChar () == '/') {
2015 if (doc_state == XmlCommentState.Allowed)
2017 else if (doc_state == XmlCommentState.NotAllowed)
2018 warn_incorrect_doc_comment ();
2021 int current_comment_start = 0;
2023 current_comment_start = xml_comment_buffer.Length;
2024 xml_comment_buffer.Append (Environment.NewLine);
2027 Location start_location = Location;
2029 while ((d = getChar ()) != -1){
2030 if (d == '*' && peekChar () == '/'){
2032 comments_seen = true;
2036 xml_comment_buffer.Append ((char) d);
2039 any_token_seen |= tokens_seen;
2040 tokens_seen = false;
2042 // Reset 'comments_seen' just to be consistent.
2043 // It doesn't matter either way, here.
2045 comments_seen = false;
2049 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2052 update_formatted_doc_comment (current_comment_start);
2055 goto is_punct_label;
2059 if (is_identifier_start_character ((char)c)){
2061 return consume_identifier (c);
2065 current_location = new Location (ref_line, Col);
2066 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2076 any_token_seen |= tokens_seen;
2077 tokens_seen = false;
2078 comments_seen = false;
2082 if (c >= '0' && c <= '9'){
2084 return is_number (c);
2089 int peek = peekChar ();
2090 if (peek >= '0' && peek <= '9')
2091 return is_number (c);
2095 /* For now, ignore pre-processor commands */
2096 // FIXME: In C# the '#' is not limited to appear
2097 // on the first column.
2099 // return NONE if we're not processing directives (during token peeks)
2100 if (!process_directives)
2104 if (tokens_seen || comments_seen) {
2105 error_details = "Preprocessor directives must appear as the first" +
2106 " non-whitespace character on a line.";
2108 Report.Error (1040, Location, error_details);
2115 cont = handle_preprocessing_directive (cont);
2121 bool skipping = false;
2122 for (;(c = getChar ()) != -1;){
2125 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2129 if (c == '#' && !skipping)
2132 any_token_seen |= tokens_seen;
2133 tokens_seen = false;
2135 Report.Error (1027, Location, "Expected `#endif' directive");
2140 return consume_string (false);
2146 error_details = "Empty character literal";
2147 Report.Error (1011, Location, error_details);
2153 val = new System.Char ();
2158 error_details = "Too many characters in character literal";
2159 Report.Error (1012, Location, error_details);
2161 // Try to recover, read until newline or next "'"
2162 while ((c = getChar ()) != -1){
2171 return Token.LITERAL_CHARACTER;
2178 return consume_string (true);
2179 } else if (is_identifier_start_character ((char) c)){
2180 return consume_identifier (c, true);
2182 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2186 error_details = ((char)c).ToString ();
2195 // Handles one line xml comment
2197 private void handle_one_line_xml_comment ()
2200 while ((c = peekChar ()) == ' ')
2201 getChar (); // skip heading whitespaces.
2202 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2203 xml_comment_buffer.Append ((char) getChar ());
2205 if (c == '\r' || c == '\n')
2206 xml_comment_buffer.Append (Environment.NewLine);
2210 // Remove heading "*" in Javadoc-like xml documentation.
2212 private void update_formatted_doc_comment (int current_comment_start)
2214 int length = xml_comment_buffer.Length - current_comment_start;
2215 string [] lines = xml_comment_buffer.ToString (
2216 current_comment_start,
2217 length).Replace ("\r", "").Split ('\n');
2219 // The first line starts with /**, thus it is not target
2220 // for the format check.
2221 for (int i = 1; i < lines.Length; i++) {
2222 string s = lines [i];
2223 int idx = s.IndexOf ('*');
2226 if (i < lines.Length - 1)
2230 head = s.Substring (0, idx);
2231 foreach (char c in head)
2234 lines [i] = s.Substring (idx + 1);
2236 xml_comment_buffer.Remove (current_comment_start, length);
2237 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2241 // Updates current comment location.
2243 private void update_comment_location ()
2245 if (current_comment_location.IsNull) {
2246 // "-2" is for heading "//" or "/*"
2247 current_comment_location =
2248 new Location (ref_line, col - 2);
2253 // Checks if there was incorrect doc comments and raise
2256 public void check_incorrect_doc_comment ()
2258 if (xml_comment_buffer.Length > 0)
2259 warn_incorrect_doc_comment ();
2263 // Raises a warning when tokenizer found incorrect doccomment
2266 private void warn_incorrect_doc_comment ()
2268 if (doc_state != XmlCommentState.Error) {
2269 doc_state = XmlCommentState.Error;
2270 // in csc, it is 'XML comment is not placed on
2271 // a valid language element'. But that does not
2273 Report.Warning (1587, 2, Location, "XML comment is placed on an invalid language element.");
2278 // Consumes the saved xml comment lines (if any)
2279 // as for current target member or type.
2281 public string consume_doc_comment ()
2283 if (xml_comment_buffer.Length > 0) {
2284 string ret = xml_comment_buffer.ToString ();
2285 reset_doc_comment ();
2291 void reset_doc_comment ()
2293 xml_comment_buffer.Length = 0;
2294 current_comment_location = Location.Null;
2297 public void cleanup ()
2299 if (ifstack != null && ifstack.Count >= 1) {
2300 int state = (int) ifstack.Pop ();
2301 if ((state & REGION) != 0)
2302 Report.Error (1038, Location, "#endregion directive expected");
2304 Report.Error (1027, "Expected `#endif' directive");
2311 // Indicates whether it accepts XML documentation or not.
2313 public enum XmlCommentState {
2314 // comment is allowed in this state.
2316 // comment is not allowed in this state.
2318 // once comments appeared when it is NotAllowed, then the
2319 // state is changed to it, until the state is changed to