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;
67 static Hashtable tokenValues;
69 private static Hashtable TokenValueName
72 if (tokenValues == null)
73 tokenValues = GetTokenValueNameHash ();
79 private static Hashtable GetTokenValueNameHash ()
81 Type t = typeof (Token);
82 FieldInfo [] fields = t.GetFields ();
83 Hashtable hash = new Hashtable ();
84 foreach (FieldInfo field in fields) {
85 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
86 hash.Add (field.GetValue (null), field.Name);
92 // Returns a verbose representation of the current location
94 public string location {
98 if (current_token == Token.ERROR)
99 det = "detail: " + error_details;
103 // return "Line: "+line+" Col: "+col + "\n" +
104 // "VirtLine: "+ref_line +
105 // " Token: "+current_token + " " + det;
106 string current_token_name = TokenValueName [current_token] as string;
107 if (current_token_name == null)
108 current_token_name = current_token.ToString ();
110 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
118 public bool PropertyParsing {
120 return handle_get_set;
124 handle_get_set = value;
128 public bool AssemblyTargetParsing {
130 return handle_assembly;
134 handle_assembly = value;
138 public bool EventParsing {
140 return handle_remove_add;
144 handle_remove_add = value;
148 public XmlCommentState doc_state {
149 get { return xmlDocState; }
151 if (value == XmlCommentState.Allowed) {
152 check_incorrect_doc_comment ();
153 consume_doc_comment ();
163 static CharArrayHashtable[] keywords;
164 static NumberStyles styles;
165 static NumberFormatInfo csharp_format_info;
168 // Values for the associated token returned
178 const int TAKING = 1;
179 const int TAKEN_BEFORE = 2;
180 const int ELSE_SEEN = 4;
181 const int PARENT_TAKING = 8;
182 const int REGION = 16;
185 // pre-processor if stack state:
189 static System.Text.StringBuilder string_builder;
191 const int max_id_size = 512;
192 static char [] id_builder = new char [max_id_size];
194 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
196 const int max_number_size = 128;
197 static char [] number_builder = new char [max_number_size];
198 static int number_pos;
201 // Details about the error encoutered by the tokenizer
203 string error_details;
205 public string error {
207 return error_details;
223 static void AddKeyword (string kw, int token) {
224 if (keywords [kw.Length] == null) {
225 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
227 keywords [kw.Length] [kw.ToCharArray ()] = token;
230 static void InitTokens ()
232 keywords = new CharArrayHashtable [64];
234 AddKeyword ("__arglist", Token.ARGLIST);
235 AddKeyword ("abstract", Token.ABSTRACT);
236 AddKeyword ("as", Token.AS);
237 AddKeyword ("add", Token.ADD);
238 AddKeyword ("assembly", Token.ASSEMBLY);
239 AddKeyword ("base", Token.BASE);
240 AddKeyword ("bool", Token.BOOL);
241 AddKeyword ("break", Token.BREAK);
242 AddKeyword ("byte", Token.BYTE);
243 AddKeyword ("case", Token.CASE);
244 AddKeyword ("catch", Token.CATCH);
245 AddKeyword ("char", Token.CHAR);
246 AddKeyword ("checked", Token.CHECKED);
247 AddKeyword ("class", Token.CLASS);
248 AddKeyword ("const", Token.CONST);
249 AddKeyword ("continue", Token.CONTINUE);
250 AddKeyword ("decimal", Token.DECIMAL);
251 AddKeyword ("default", Token.DEFAULT);
252 AddKeyword ("delegate", Token.DELEGATE);
253 AddKeyword ("do", Token.DO);
254 AddKeyword ("double", Token.DOUBLE);
255 AddKeyword ("else", Token.ELSE);
256 AddKeyword ("enum", Token.ENUM);
257 AddKeyword ("event", Token.EVENT);
258 AddKeyword ("explicit", Token.EXPLICIT);
259 AddKeyword ("extern", Token.EXTERN);
260 AddKeyword ("false", Token.FALSE);
261 AddKeyword ("finally", Token.FINALLY);
262 AddKeyword ("fixed", Token.FIXED);
263 AddKeyword ("float", Token.FLOAT);
264 AddKeyword ("for", Token.FOR);
265 AddKeyword ("foreach", Token.FOREACH);
266 AddKeyword ("goto", Token.GOTO);
267 AddKeyword ("get", Token.GET);
268 AddKeyword ("if", Token.IF);
269 AddKeyword ("implicit", Token.IMPLICIT);
270 AddKeyword ("in", Token.IN);
271 AddKeyword ("int", Token.INT);
272 AddKeyword ("interface", Token.INTERFACE);
273 AddKeyword ("internal", Token.INTERNAL);
274 AddKeyword ("is", Token.IS);
275 AddKeyword ("lock", Token.LOCK);
276 AddKeyword ("long", Token.LONG);
277 AddKeyword ("namespace", Token.NAMESPACE);
278 AddKeyword ("new", Token.NEW);
279 AddKeyword ("null", Token.NULL);
280 AddKeyword ("object", Token.OBJECT);
281 AddKeyword ("operator", Token.OPERATOR);
282 AddKeyword ("out", Token.OUT);
283 AddKeyword ("override", Token.OVERRIDE);
284 AddKeyword ("params", Token.PARAMS);
285 AddKeyword ("private", Token.PRIVATE);
286 AddKeyword ("protected", Token.PROTECTED);
287 AddKeyword ("public", Token.PUBLIC);
288 AddKeyword ("readonly", Token.READONLY);
289 AddKeyword ("ref", Token.REF);
290 AddKeyword ("remove", Token.REMOVE);
291 AddKeyword ("return", Token.RETURN);
292 AddKeyword ("sbyte", Token.SBYTE);
293 AddKeyword ("sealed", Token.SEALED);
294 AddKeyword ("set", Token.SET);
295 AddKeyword ("short", Token.SHORT);
296 AddKeyword ("sizeof", Token.SIZEOF);
297 AddKeyword ("stackalloc", Token.STACKALLOC);
298 AddKeyword ("static", Token.STATIC);
299 AddKeyword ("string", Token.STRING);
300 AddKeyword ("struct", Token.STRUCT);
301 AddKeyword ("switch", Token.SWITCH);
302 AddKeyword ("this", Token.THIS);
303 AddKeyword ("throw", Token.THROW);
304 AddKeyword ("true", Token.TRUE);
305 AddKeyword ("try", Token.TRY);
306 AddKeyword ("typeof", Token.TYPEOF);
307 AddKeyword ("uint", Token.UINT);
308 AddKeyword ("ulong", Token.ULONG);
309 AddKeyword ("unchecked", Token.UNCHECKED);
310 AddKeyword ("unsafe", Token.UNSAFE);
311 AddKeyword ("ushort", Token.USHORT);
312 AddKeyword ("using", Token.USING);
313 AddKeyword ("virtual", Token.VIRTUAL);
314 AddKeyword ("void", Token.VOID);
315 AddKeyword ("volatile", Token.VOLATILE);
316 AddKeyword ("while", Token.WHILE);
317 AddKeyword ("partial", Token.PARTIAL);
326 csharp_format_info = NumberFormatInfo.InvariantInfo;
327 styles = NumberStyles.Float;
329 string_builder = new System.Text.StringBuilder ();
332 int GetKeyword (char[] id, int id_len)
335 * Keywords are stored in an array of hashtables grouped by their
339 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
341 object o = keywords [id_len] [id];
348 if (handle_get_set == false && (res == Token.GET || res == Token.SET))
350 if (handle_remove_add == false && (res == Token.REMOVE || res == Token.ADD))
352 if (handle_assembly == false && res == Token.ASSEMBLY)
359 public Location Location {
361 return new Location (ref_line);
365 void define (string def)
367 if (!RootContext.AllDefines.Contains (def)){
368 RootContext.AllDefines [def] = true;
370 if (defines.Contains (def))
372 defines [def] = true;
375 public Tokenizer (SeekableStreamReader input, SourceFile file, ArrayList defs)
377 this.ref_name = file;
378 this.file_name = file;
384 defines = new Hashtable ();
385 foreach (string def in defs)
389 xml_comment_buffer = new StringBuilder ();
392 // FIXME: This could be `Location.Push' but we have to
393 // find out why the MS compiler allows this
395 Mono.CSharp.Location.Push (file);
398 public static void Cleanup () {
402 static bool is_identifier_start_character (char c)
404 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || Char.IsLetter (c);
407 static bool is_identifier_part_character (char c)
409 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || Char.IsLetter (c);
412 public static bool IsValidIdentifier (string s)
414 if (s == null || s.Length == 0)
417 if (!is_identifier_start_character (s [0]))
420 for (int i = 1; i < s.Length; i ++)
421 if (! is_identifier_part_character (s [i]))
427 int is_punct (char c, ref bool doread)
436 return Token.OPEN_BRACE;
438 return Token.CLOSE_BRACE;
440 // To block doccomment inside attribute declaration.
441 if (doc_state == XmlCommentState.Allowed)
442 doc_state = XmlCommentState.NotAllowed;
443 return Token.OPEN_BRACKET;
445 return Token.CLOSE_BRACKET;
447 return Token.OPEN_PARENS;
449 if (deambiguate_close_parens == 0)
450 return Token.CLOSE_PARENS;
452 --deambiguate_close_parens;
454 // Save current position and parse next token.
455 int old = reader.Position;
456 int new_token = token ();
457 reader.Position = old;
460 if (new_token == Token.OPEN_PARENS)
461 return Token.CLOSE_PARENS_OPEN_PARENS;
462 else if (new_token == Token.MINUS)
463 return Token.CLOSE_PARENS_MINUS;
464 else if (IsCastToken (new_token))
465 return Token.CLOSE_PARENS_CAST;
467 return Token.CLOSE_PARENS_NO_CAST;
475 return Token.SEMICOLON;
488 t = Token.OP_ADD_ASSIGN;
498 t = Token.OP_SUB_ASSIGN;
527 } else if (d == '='){
529 return Token.OP_AND_ASSIGN;
531 return Token.BITWISE_AND;
538 } else if (d == '='){
540 return Token.OP_OR_ASSIGN;
542 return Token.BITWISE_OR;
548 return Token.OP_MULT_ASSIGN;
556 return Token.OP_DIV_ASSIGN;
564 return Token.OP_MOD_ASSIGN;
566 return Token.PERCENT;
572 return Token.OP_XOR_ASSIGN;
584 return Token.OP_SHIFT_LEFT_ASSIGN;
586 return Token.OP_SHIFT_LEFT;
587 } else if (d == '='){
601 return Token.OP_SHIFT_RIGHT_ASSIGN;
603 return Token.OP_SHIFT_RIGHT;
604 } else if (d == '='){
613 int deambiguate_close_parens = 0;
615 public void Deambiguate_CloseParens ()
618 deambiguate_close_parens++;
621 void Error_NumericConstantTooLong ()
623 Report.Error (1021, Location, "Numeric constant too long");
626 bool decimal_digits (int c)
629 bool seen_digits = false;
632 if (number_pos == max_number_size)
633 Error_NumericConstantTooLong ();
634 number_builder [number_pos++] = (char) c;
638 // We use peekChar2, because decimal_digits needs to do a
639 // 2-character look-ahead (5.ToString for example).
641 while ((d = peekChar2 ()) != -1){
642 if (d >= '0' && d <= '9'){
643 if (number_pos == max_number_size)
644 Error_NumericConstantTooLong ();
645 number_builder [number_pos++] = (char) d;
657 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
660 void hex_digits (int c)
663 number_builder [number_pos++] = (char) c;
667 int real_type_suffix (int c)
673 t = Token.LITERAL_FLOAT;
676 t = Token.LITERAL_DOUBLE;
679 t= Token.LITERAL_DECIMAL;
687 int integer_type_suffix (ulong ul, int c)
689 bool is_unsigned = false;
690 bool is_long = false;
693 bool scanning = true;
704 if (!is_unsigned && (RootContext.WarningLevel >= 4)){
706 // if we have not seen anything in between
709 Report.Warning (78, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
712 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
737 if (is_long && is_unsigned){
739 return Token.LITERAL_INTEGER;
740 } else if (is_unsigned){
741 // uint if possible, or ulong else.
743 if ((ul & 0xffffffff00000000) == 0)
748 // long if possible, ulong otherwise
749 if ((ul & 0x8000000000000000) != 0)
754 // int, uint, long or ulong in that order
755 if ((ul & 0xffffffff00000000) == 0){
758 if ((ui & 0x80000000) != 0)
763 if ((ul & 0x8000000000000000) != 0)
769 return Token.LITERAL_INTEGER;
773 // given `c' as the next char in the input decide whether
774 // we need to convert to a special type, and then choose
775 // the best representation for the integer
777 int adjust_int (int c)
781 ulong ul = (uint) (number_builder [0] - '0');
783 for (int i = 1; i < number_pos; i++){
784 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
786 return integer_type_suffix (ul, c);
788 uint ui = (uint) (number_builder [0] - '0');
790 for (int i = 1; i < number_pos; i++){
791 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
793 return integer_type_suffix (ui, c);
795 } catch (OverflowException) {
796 error_details = "Integral constant is too large";
797 Report.Error (1021, Location, error_details);
799 return Token.LITERAL_INTEGER;
803 int adjust_real (int t)
805 string s = new String (number_builder, 0, number_pos);
808 case Token.LITERAL_DECIMAL:
810 val = System.Decimal.Parse (s, styles, csharp_format_info);
811 } catch (OverflowException) {
813 error_details = "Floating-point constant is outside the range of the type 'decimal'";
814 Report.Error (594, Location, error_details);
817 case Token.LITERAL_FLOAT:
819 val = (float) System.Double.Parse (s, styles, csharp_format_info);
820 } catch (OverflowException) {
822 error_details = "Floating-point constant is outside the range of the type 'float'";
823 Report.Error (594, Location, error_details);
827 case Token.LITERAL_DOUBLE:
829 t = Token.LITERAL_DOUBLE;
831 val = System.Double.Parse (s, styles, csharp_format_info);
832 } catch (OverflowException) {
834 error_details = "Floating-point constant is outside the range of the type 'double'";
835 Report.Error (594, Location, error_details);
848 while ((d = peekChar ()) != -1){
850 number_builder [number_pos++] = (char) d;
856 string s = new String (number_builder, 0, number_pos);
859 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
861 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
862 } catch (OverflowException){
863 error_details = "Integral constant is too large";
864 Report.Error (1021, Location, error_details);
866 return Token.LITERAL_INTEGER;
868 catch (FormatException) {
869 Report.Error (1013, Location, "Invalid number");
871 return Token.LITERAL_INTEGER;
874 return integer_type_suffix (ul, peekChar ());
878 // Invoked if we know we have .digits or digits
880 int is_number (int c)
882 bool is_real = false;
887 if (c >= '0' && c <= '9'){
889 int peek = peekChar ();
891 if (peek == 'x' || peek == 'X')
892 return handle_hex ();
899 // We need to handle the case of
900 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
903 if (decimal_digits ('.')){
909 return adjust_int (-1);
913 if (c == 'e' || c == 'E'){
915 if (number_pos == max_number_size)
916 Error_NumericConstantTooLong ();
917 number_builder [number_pos++] = 'e';
921 if (number_pos == max_number_size)
922 Error_NumericConstantTooLong ();
923 number_builder [number_pos++] = '+';
925 } else if (c == '-') {
926 if (number_pos == max_number_size)
927 Error_NumericConstantTooLong ();
928 number_builder [number_pos++] = '-';
931 if (number_pos == max_number_size)
932 Error_NumericConstantTooLong ();
933 number_builder [number_pos++] = '+';
940 type = real_type_suffix (c);
941 if (type == Token.NONE && !is_real){
943 return adjust_int (c);
947 if (type == Token.NONE){
952 return adjust_real (type);
954 Console.WriteLine ("This should not be reached");
955 throw new Exception ("Is Number should never reach this point");
959 // Accepts exactly count (4 or 8) hex, no more no less
961 int getHex (int count, out bool error)
966 int top = count != -1 ? count : 4;
970 for (i = 0; i < top; i++){
973 if (c >= '0' && c <= '9')
974 c = (int) c - (int) '0';
975 else if (c >= 'A' && c <= 'F')
976 c = (int) c - (int) 'A' + 10;
977 else if (c >= 'a' && c <= 'f')
978 c = (int) c - (int) 'a' + 10;
984 total = (total * 16) + c;
989 if (!is_hex ((char)p))
1030 v = getHex (-1, out error);
1035 v = getHex (4, out error);
1040 v = getHex (8, out error);
1045 Report.Error (1009, Location, "Unrecognized escape sequence in " + (char)d);
1054 if (putback_char != -1){
1055 int x = putback_char;
1060 return reader.Read ();
1065 if (putback_char != -1)
1066 return putback_char;
1067 putback_char = reader.Read ();
1068 return putback_char;
1073 if (putback_char != -1)
1074 return putback_char;
1075 return reader.Peek ();
1078 void putback (int c)
1080 if (putback_char != -1){
1081 Console.WriteLine ("Col: " + col);
1082 Console.WriteLine ("Row: " + line);
1083 Console.WriteLine ("Name: " + ref_name.Name);
1084 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1085 throw new Exception ("This should not happen putback on putback");
1090 public bool advance ()
1092 return peekChar () != -1;
1095 public Object Value {
1101 public Object value ()
1106 bool IsCastToken (int token)
1111 case Token.IDENTIFIER:
1112 case Token.LITERAL_INTEGER:
1113 case Token.LITERAL_FLOAT:
1114 case Token.LITERAL_DOUBLE:
1115 case Token.LITERAL_DECIMAL:
1116 case Token.LITERAL_CHARACTER:
1117 case Token.LITERAL_STRING:
1129 case Token.UNCHECKED:
1133 // These can be part of a member access
1153 current_token = xtoken ();
1154 return current_token;
1157 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1159 void get_cmd_arg (out string cmd, out string arg)
1163 tokens_seen = false;
1165 static_cmd_arg.Length = 0;
1167 // skip over white space
1168 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1172 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1173 if (is_identifier_part_character ((char) c)){
1174 static_cmd_arg.Append ((char) c);
1182 cmd = static_cmd_arg.ToString ();
1188 } else if (c == '\r')
1191 // skip over white space
1192 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1199 } else if (c == '\r'){
1204 static_cmd_arg.Length = 0;
1205 static_cmd_arg.Append ((char) c);
1207 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1208 static_cmd_arg.Append ((char) c);
1214 } else if (c == '\r')
1216 arg = static_cmd_arg.ToString ().Trim ();
1220 // Handles the #line directive
1222 bool PreProcessLine (string arg)
1227 if (arg == "default"){
1229 ref_name = file_name;
1230 Location.Push (ref_name);
1232 } else if (arg == "hidden"){
1234 // We ignore #line hidden
1242 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1243 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1246 char [] quotes = { '\"' };
1248 string name = arg.Substring (pos). Trim (quotes);
1249 ref_name = Location.LookupFile (name);
1250 file_name.HasLineDirective = true;
1251 ref_name.HasLineDirective = true;
1252 Location.Push (ref_name);
1254 ref_line = System.Int32.Parse (arg);
1264 // Handles #define and #undef
1266 void PreProcessDefinition (bool is_define, string arg)
1268 if (arg == "" || arg == "true" || arg == "false"){
1269 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1273 char[] whitespace = { ' ', '\t' };
1274 if (arg.IndexOfAny (whitespace) != -1){
1275 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1279 if (!is_identifier_start_character (arg [0]))
1280 Report.Error (1001, Location, "Identifier expected: " + arg);
1282 foreach (char c in arg.Substring (1)){
1283 if (!is_identifier_part_character (c)){
1284 Report.Error (1001, Location, "Identifier expected: " + arg);
1290 if (defines == null)
1291 defines = new Hashtable ();
1294 if (defines == null)
1296 if (defines.Contains (arg))
1297 defines.Remove (arg);
1302 /// Handles #pragma directive
1304 void PreProcessPragma (string arg)
1306 const string disable = "warning disable";
1307 const string restore = "warning restore";
1309 if (arg == disable) {
1310 Report.RegisterWarningRegion (Location).WarningDisable (line);
1314 if (arg == restore) {
1315 Report.RegisterWarningRegion (Location).WarningEnable (line);
1319 if (arg.StartsWith (disable)) {
1320 int[] codes = ParseNumbers (arg.Substring (disable.Length));
1321 foreach (int code in codes) {
1323 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1328 if (arg.StartsWith (restore)) {
1329 int[] codes = ParseNumbers (arg.Substring (restore.Length));
1330 foreach (int code in codes) {
1331 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1339 int[] ParseNumbers (string text)
1341 string[] string_array = text.Split (',');
1342 int[] values = new int [string_array.Length];
1344 foreach (string string_code in string_array) {
1346 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1348 catch (FormatException) {
1349 Report.Warning (1692, Location, "Invalid number");
1355 bool eval_val (string s)
1362 if (defines == null)
1364 if (defines.Contains (s))
1370 bool pp_primary (ref string s)
1379 s = s.Substring (1);
1380 bool val = pp_expr (ref s);
1381 if (s.Length > 0 && s [0] == ')'){
1382 s = s.Substring (1);
1385 Error_InvalidDirective ();
1389 if (is_identifier_start_character (c)){
1395 if (is_identifier_part_character (c)){
1399 bool v = eval_val (s.Substring (0, j));
1400 s = s.Substring (j);
1403 bool vv = eval_val (s);
1408 Error_InvalidDirective ();
1412 bool pp_unary (ref string s)
1419 if (len > 1 && s [1] == '='){
1420 Error_InvalidDirective ();
1423 s = s.Substring (1);
1424 return ! pp_primary (ref s);
1426 return pp_primary (ref s);
1428 Error_InvalidDirective ();
1433 bool pp_eq (ref string s)
1435 bool va = pp_unary (ref s);
1441 if (len > 2 && s [1] == '='){
1442 s = s.Substring (2);
1443 return va == pp_unary (ref s);
1445 Error_InvalidDirective ();
1448 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1449 s = s.Substring (2);
1451 return va != pp_unary (ref s);
1460 bool pp_and (ref string s)
1462 bool va = pp_eq (ref s);
1468 if (len > 2 && s [1] == '&'){
1469 s = s.Substring (2);
1470 return (va & pp_eq (ref s));
1472 Error_InvalidDirective ();
1481 // Evaluates an expression for `#if' or `#elif'
1483 bool pp_expr (ref string s)
1485 bool va = pp_and (ref s);
1492 if (len > 2 && s [1] == '|'){
1493 s = s.Substring (2);
1494 return va | pp_expr (ref s);
1496 Error_InvalidDirective ();
1505 bool eval (string s)
1507 bool v = pp_expr (ref s);
1510 Error_InvalidDirective ();
1517 void Error_InvalidDirective ()
1519 Report.Error (1517, Location, "Invalid pre-processor directive");
1522 void Error_UnexpectedDirective (string extra)
1526 "Unexpected processor directive (" + extra + ")");
1529 void Error_TokensSeen ()
1533 "Cannot define or undefine pre-processor symbols after a token in the file");
1537 // if true, then the code continues processing the code
1538 // if false, the code stays in a loop until another directive is
1541 bool handle_preprocessing_directive (bool caller_is_taking)
1544 bool region_directive = false;
1546 get_cmd_arg (out cmd, out arg);
1548 // Eat any trailing whitespaces and single-line comments
1549 if (arg.IndexOf ("//") != -1)
1550 arg = arg.Substring (0, arg.IndexOf ("//"));
1551 arg = arg.TrimEnd (' ', '\t');
1554 // The first group of pre-processing instructions is always processed
1558 if (RootContext.Version == LanguageVersion.ISO_1) {
1559 Report.FeatureIsNotStandardized (Location, "#pragma");
1560 return caller_is_taking;
1563 PreProcessPragma (arg);
1564 return caller_is_taking;
1567 if (!PreProcessLine (arg))
1570 "Argument to #line directive is missing or invalid");
1571 return caller_is_taking;
1574 region_directive = true;
1579 region_directive = true;
1584 Error_InvalidDirective ();
1587 bool taking = false;
1588 if (ifstack == null)
1589 ifstack = new Stack ();
1591 if (ifstack.Count == 0){
1594 int state = (int) ifstack.Peek ();
1595 if ((state & TAKING) != 0)
1599 if (eval (arg) && taking){
1600 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1601 if (region_directive)
1603 ifstack.Push (push);
1606 int push = (taking ? PARENT_TAKING : 0);
1607 if (region_directive)
1609 ifstack.Push (push);
1614 if (ifstack == null || ifstack.Count == 0){
1615 Error_UnexpectedDirective ("no #if for this #endif");
1618 int pop = (int) ifstack.Pop ();
1620 if (region_directive && ((pop & REGION) == 0))
1621 Report.Error (1027, Location, "#endif directive expected");
1622 else if (!region_directive && ((pop & REGION) != 0))
1623 Report.Error (1038, Location, "#endregion directive expected");
1625 if (ifstack.Count == 0)
1628 int state = (int) ifstack.Peek ();
1630 if ((state & TAKING) != 0)
1638 if (ifstack == null || ifstack.Count == 0){
1639 Error_UnexpectedDirective ("no #if for this #elif");
1642 int state = (int) ifstack.Peek ();
1644 if ((state & REGION) != 0) {
1645 Report.Error (1038, Location, "#endregion directive expected");
1649 if ((state & ELSE_SEEN) != 0){
1650 Error_UnexpectedDirective ("#elif not valid after #else");
1654 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1657 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1658 state = (int) ifstack.Pop ();
1659 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1666 if (ifstack == null || ifstack.Count == 0){
1669 "Unexpected processor directive (no #if for this #else)");
1672 int state = (int) ifstack.Peek ();
1674 if ((state & REGION) != 0) {
1675 Report.Error (1038, Location, "#endregion directive expected");
1679 if ((state & ELSE_SEEN) != 0){
1680 Error_UnexpectedDirective ("#else within #else");
1687 if ((state & TAKEN_BEFORE) == 0){
1688 ret = ((state & PARENT_TAKING) != 0);
1697 ifstack.Push (state | ELSE_SEEN);
1704 // These are only processed if we are in a `taking' block
1706 if (!caller_is_taking)
1711 if (any_token_seen){
1712 Error_TokensSeen ();
1715 PreProcessDefinition (true, arg);
1719 if (any_token_seen){
1720 Error_TokensSeen ();
1723 PreProcessDefinition (false, arg);
1727 Report.Error (1029, Location, "#error: '" + arg + "'");
1731 Report.Warning (1030, Location, "#warning: '{0}'", arg);
1735 Report.Error (1024, Location, "Preprocessor directive expected (got: " + cmd + ")");
1740 private int consume_string (bool quoted)
1743 string_builder.Length = 0;
1745 while ((c = getChar ()) != -1){
1747 if (quoted && peekChar () == '"'){
1748 string_builder.Append ((char) c);
1752 val = string_builder.ToString ();
1753 return Token.LITERAL_STRING;
1759 Report.Error (1010, Location, "Newline in constant");
1771 string_builder.Append ((char) c);
1774 Report.Error (1039, Location, "Unterminated string literal");
1778 private int consume_identifier (int s)
1780 int res = consume_identifier (s, false);
1782 if (doc_state == XmlCommentState.Allowed)
1783 doc_state = XmlCommentState.NotAllowed;
1786 case Token.NAMESPACE:
1787 check_incorrect_doc_comment ();
1791 if (res == Token.PARTIAL) {
1792 // Save current position and parse next token.
1793 int old = reader.Position;
1794 int old_putback = putback_char;
1798 int next_token = token ();
1799 bool ok = (next_token == Token.CLASS) ||
1800 (next_token == Token.STRUCT) ||
1801 (next_token == Token.INTERFACE);
1803 reader.Position = old;
1804 putback_char = old_putback;
1810 return Token.IDENTIFIER;
1817 private int consume_identifier (int s, bool quoted)
1822 id_builder [0] = (char) s;
1824 while ((c = reader.Read ()) != -1) {
1825 if (is_identifier_part_character ((char) c)){
1826 if (pos == max_id_size){
1827 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1831 id_builder [pos++] = (char) c;
1841 // Optimization: avoids doing the keyword lookup
1842 // on uppercase letters and _
1844 if (!quoted && (s >= 'a' || s == '_')){
1845 int keyword = GetKeyword (id_builder, pos);
1851 // Keep identifiers in an array of hashtables to avoid needless
1855 if (identifiers [pos] != null) {
1856 val = identifiers [pos][id_builder];
1858 return Token.IDENTIFIER;
1862 identifiers [pos] = new CharArrayHashtable (pos);
1864 val = new String (id_builder, 0, pos);
1866 char [] chars = new char [pos];
1867 Array.Copy (id_builder, chars, pos);
1869 identifiers [pos] [chars] = val;
1871 return Token.IDENTIFIER;
1874 public int xtoken ()
1877 bool doread = false;
1881 // optimization: eliminate col and implement #directive semantic correctly.
1882 for (;(c = getChar ()) != -1; col++) {
1887 col = (((col + 8) / 8) * 8) - 1;
1891 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1895 if (peekChar () == '\n')
1901 any_token_seen |= tokens_seen;
1902 tokens_seen = false;
1906 // Handle double-slash comments.
1908 int d = peekChar ();
1912 if (RootContext.Documentation != null && peekChar () == '/') {
1914 // Don't allow ////.
1915 if ((d = peekChar ()) != '/') {
1916 if (doc_state == XmlCommentState.Allowed)
1917 handle_one_line_xml_comment ();
1918 else if (doc_state == XmlCommentState.NotAllowed)
1919 warn_incorrect_doc_comment ();
1922 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
1929 any_token_seen |= tokens_seen;
1930 tokens_seen = false;
1932 } else if (d == '*'){
1934 bool docAppend = false;
1935 if (RootContext.Documentation != null && peekChar () == '*') {
1937 // But when it is /**/, just do nothing.
1938 if (peekChar () == '/') {
1942 if (doc_state == XmlCommentState.Allowed)
1944 else if (doc_state == XmlCommentState.NotAllowed)
1945 warn_incorrect_doc_comment ();
1948 int currentCommentStart = 0;
1950 currentCommentStart = xml_comment_buffer.Length;
1951 xml_comment_buffer.Append (Environment.NewLine);
1954 while ((d = getChar ()) != -1){
1955 if (d == '*' && peekChar () == '/'){
1961 xml_comment_buffer.Append ((char) d);
1967 any_token_seen |= tokens_seen;
1968 tokens_seen = false;
1972 update_formatted_doc_comment (currentCommentStart);
1975 goto is_punct_label;
1979 if (is_identifier_start_character ((char)c)){
1981 return consume_identifier (c);
1985 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
1999 any_token_seen |= tokens_seen;
2000 tokens_seen = false;
2004 if (c >= '0' && c <= '9'){
2006 return is_number (c);
2011 int peek = peekChar ();
2012 if (peek >= '0' && peek <= '9')
2013 return is_number (c);
2017 /* For now, ignore pre-processor commands */
2018 // FIXME: In C# the '#' is not limited to appear
2019 // on the first column.
2020 if (c == '#' && !tokens_seen){
2025 cont = handle_preprocessing_directive (cont);
2033 bool skipping = false;
2034 for (;(c = getChar ()) != -1; col++){
2040 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2044 if (c == '#' && !skipping)
2047 any_token_seen |= tokens_seen;
2048 tokens_seen = false;
2050 Report.Error (1027, Location, "#endif/#endregion expected");
2055 return consume_string (false);
2061 error_details = "Empty character literal";
2062 Report.Error (1011, Location, error_details);
2068 val = new System.Char ();
2073 error_details = "Too many characters in character literal";
2074 Report.Error (1012, Location, error_details);
2076 // Try to recover, read until newline or next "'"
2077 while ((c = getChar ()) != -1){
2078 if (c == '\n' || c == '\''){
2089 return Token.LITERAL_CHARACTER;
2096 return consume_string (true);
2097 } else if (is_identifier_start_character ((char) c)){
2098 return consume_identifier (c, true);
2100 Report.Error (1033, Location, "'@' must be followed by string constant or identifier");
2105 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2106 "character on a line.";
2108 Report.Error (1040, Location, error_details);
2113 error_details = ((char)c).ToString ();
2122 // Handles one line xml comment
2124 private void handle_one_line_xml_comment ()
2127 while ((c = peekChar ()) == ' ')
2128 getChar (); // skip heading whitespaces.
2129 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2131 xml_comment_buffer.Append ((char) getChar ());
2133 if (c == '\r' || c == '\n')
2134 xml_comment_buffer.Append (Environment.NewLine);
2138 // Remove heading "*" in Javadoc-like xml documentation.
2140 private void update_formatted_doc_comment (int currentCommentStart)
2142 int length = xml_comment_buffer.Length - currentCommentStart;
2143 string [] lines = xml_comment_buffer.ToString (
2144 currentCommentStart,
2145 length).Replace ("\r", "").Split ('\n');
2146 // The first line starts with /**, thus it is not target
2147 // for the format check.
2148 for (int i = 1; i < lines.Length; i++) {
2149 string s = lines [i];
2150 int idx = s.IndexOf ('*');
2153 if (i < lines.Length - 1)
2158 head = s.Substring (0, idx);
2159 foreach (char c in head)
2162 lines [i] = s.Substring (idx + 1);
2164 xml_comment_buffer.Remove (currentCommentStart, length);
2165 xml_comment_buffer.Insert (
2166 currentCommentStart,
2167 String.Join (Environment.NewLine, lines));
2171 // Checks if there was incorrect doc comments and raise
2174 public void check_incorrect_doc_comment ()
2176 if (xml_comment_buffer.Length > 0)
2177 warn_incorrect_doc_comment ();
2181 // Raises a warning when tokenizer found incorrect doccomment
2184 private void warn_incorrect_doc_comment ()
2186 doc_state = XmlCommentState.Error;
2187 // in csc, it is 'XML comment is not placed on a valid
2188 // language element'. But that does not make sense.
2189 Report.Warning (1587, 2, Location, "XML comment is placed on an invalid language element which can not accept it.");
2193 // Consumes the saved xml comment lines (if any)
2194 // as for current target member or type.
2196 public string consume_doc_comment ()
2198 if (xml_comment_buffer.Length > 0) {
2199 string ret = xml_comment_buffer.ToString ();
2200 xml_comment_buffer.Length = 0;
2206 public void cleanup ()
2208 if (ifstack != null && ifstack.Count >= 1) {
2209 int state = (int) ifstack.Pop ();
2210 if ((state & REGION) != 0)
2211 Report.Error (1038, Location, "#endregion directive expected");
2213 Report.Error (1027, "#endif directive expected");
2220 // Indicates whether it accepts XML documentation or not.
2222 public enum XmlCommentState {
2223 // comment is allowed in this state.
2225 // comment is not allowed in this state.
2227 // once comments appeared when it is NotAllowed, then the
2228 // state is changed to it, until the state is changed to