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)");
728 if (is_long && is_unsigned){
730 return Token.LITERAL_INTEGER;
731 } else if (is_unsigned){
732 // uint if possible, or ulong else.
734 if ((ul & 0xffffffff00000000) == 0)
739 // long if possible, ulong otherwise
740 if ((ul & 0x8000000000000000) != 0)
745 // int, uint, long or ulong in that order
746 if ((ul & 0xffffffff00000000) == 0){
749 if ((ui & 0x80000000) != 0)
754 if ((ul & 0x8000000000000000) != 0)
760 return Token.LITERAL_INTEGER;
764 // given `c' as the next char in the input decide whether
765 // we need to convert to a special type, and then choose
766 // the best representation for the integer
768 int adjust_int (int c)
772 ulong ul = (uint) (number_builder [0] - '0');
774 for (int i = 1; i < number_pos; i++){
775 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
777 return integer_type_suffix (ul, c);
779 uint ui = (uint) (number_builder [0] - '0');
781 for (int i = 1; i < number_pos; i++){
782 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
784 return integer_type_suffix (ui, c);
786 } catch (OverflowException) {
787 error_details = "Integral constant is too large";
788 Report.Error (1021, Location, error_details);
790 return Token.LITERAL_INTEGER;
794 int adjust_real (int t)
796 string s = new String (number_builder, 0, number_pos);
799 case Token.LITERAL_DECIMAL:
801 val = System.Decimal.Parse (s, styles, csharp_format_info);
802 } catch (OverflowException) {
804 error_details = "Floating-point constant is outside the range of the type 'decimal'";
805 Report.Error (594, Location, error_details);
808 case Token.LITERAL_FLOAT:
810 val = (float) System.Double.Parse (s, styles, csharp_format_info);
811 } catch (OverflowException) {
813 error_details = "Floating-point constant is outside the range of the type 'float'";
814 Report.Error (594, Location, error_details);
818 case Token.LITERAL_DOUBLE:
820 t = Token.LITERAL_DOUBLE;
822 val = System.Double.Parse (s, styles, csharp_format_info);
823 } catch (OverflowException) {
825 error_details = "Floating-point constant is outside the range of the type 'double'";
826 Report.Error (594, Location, error_details);
839 while ((d = peekChar ()) != -1){
841 number_builder [number_pos++] = (char) d;
847 string s = new String (number_builder, 0, number_pos);
850 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
852 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
853 } catch (OverflowException){
854 error_details = "Integral constant is too large";
855 Report.Error (1021, Location, error_details);
857 return Token.LITERAL_INTEGER;
859 catch (FormatException) {
860 Report.Error (1013, Location, "Invalid number");
862 return Token.LITERAL_INTEGER;
865 return integer_type_suffix (ul, peekChar ());
869 // Invoked if we know we have .digits or digits
871 int is_number (int c)
873 bool is_real = false;
878 if (c >= '0' && c <= '9'){
880 int peek = peekChar ();
882 if (peek == 'x' || peek == 'X')
883 return handle_hex ();
890 // We need to handle the case of
891 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
894 if (decimal_digits ('.')){
900 return adjust_int (-1);
904 if (c == 'e' || c == 'E'){
906 if (number_pos == max_number_size)
907 Error_NumericConstantTooLong ();
908 number_builder [number_pos++] = 'e';
912 if (number_pos == max_number_size)
913 Error_NumericConstantTooLong ();
914 number_builder [number_pos++] = '+';
916 } else if (c == '-') {
917 if (number_pos == max_number_size)
918 Error_NumericConstantTooLong ();
919 number_builder [number_pos++] = '-';
922 if (number_pos == max_number_size)
923 Error_NumericConstantTooLong ();
924 number_builder [number_pos++] = '+';
931 type = real_type_suffix (c);
932 if (type == Token.NONE && !is_real){
934 return adjust_int (c);
938 if (type == Token.NONE){
943 return adjust_real (type);
945 Console.WriteLine ("This should not be reached");
946 throw new Exception ("Is Number should never reach this point");
950 // Accepts exactly count (4 or 8) hex, no more no less
952 int getHex (int count, out bool error)
957 int top = count != -1 ? count : 4;
961 for (i = 0; i < top; i++){
964 if (c >= '0' && c <= '9')
965 c = (int) c - (int) '0';
966 else if (c >= 'A' && c <= 'F')
967 c = (int) c - (int) 'A' + 10;
968 else if (c >= 'a' && c <= 'f')
969 c = (int) c - (int) 'a' + 10;
975 total = (total * 16) + c;
980 if (!is_hex ((char)p))
1021 v = getHex (-1, out error);
1026 v = getHex (4, out error);
1031 v = getHex (8, out error);
1036 Report.Error (1009, Location, "Unrecognized escape sequence in " + (char)d);
1045 if (putback_char != -1){
1046 int x = putback_char;
1051 return reader.Read ();
1056 if (putback_char != -1)
1057 return putback_char;
1058 putback_char = reader.Read ();
1059 return putback_char;
1064 if (putback_char != -1)
1065 return putback_char;
1066 return reader.Peek ();
1069 void putback (int c)
1071 if (putback_char != -1){
1072 Console.WriteLine ("Col: " + col);
1073 Console.WriteLine ("Row: " + line);
1074 Console.WriteLine ("Name: " + ref_name.Name);
1075 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1076 throw new Exception ("This should not happen putback on putback");
1081 public bool advance ()
1083 return peekChar () != -1;
1086 public Object Value {
1092 public Object value ()
1097 bool IsCastToken (int token)
1102 case Token.IDENTIFIER:
1103 case Token.LITERAL_INTEGER:
1104 case Token.LITERAL_FLOAT:
1105 case Token.LITERAL_DOUBLE:
1106 case Token.LITERAL_DECIMAL:
1107 case Token.LITERAL_CHARACTER:
1108 case Token.LITERAL_STRING:
1120 case Token.UNCHECKED:
1124 // These can be part of a member access
1144 current_token = xtoken ();
1145 return current_token;
1148 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1150 void get_cmd_arg (out string cmd, out string arg)
1154 tokens_seen = false;
1156 static_cmd_arg.Length = 0;
1158 // skip over white space
1159 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1163 while ((c != -1) && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1164 if (is_identifier_part_character ((char) c)){
1165 static_cmd_arg.Append ((char) c);
1173 cmd = static_cmd_arg.ToString ();
1179 } else if (c == '\r')
1182 // skip over white space
1183 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1190 } else if (c == '\r'){
1195 static_cmd_arg.Length = 0;
1196 static_cmd_arg.Append ((char) c);
1198 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1199 static_cmd_arg.Append ((char) c);
1205 } else if (c == '\r')
1207 arg = static_cmd_arg.ToString ().Trim ();
1211 // Handles the #line directive
1213 bool PreProcessLine (string arg)
1218 if (arg == "default"){
1220 ref_name = file_name;
1221 Location.Push (ref_name);
1223 } else if (arg == "hidden"){
1225 // We ignore #line hidden
1233 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1234 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1237 char [] quotes = { '\"' };
1239 string name = arg.Substring (pos). Trim (quotes);
1240 ref_name = Location.LookupFile (name);
1241 file_name.HasLineDirective = true;
1242 ref_name.HasLineDirective = true;
1243 Location.Push (ref_name);
1245 ref_line = System.Int32.Parse (arg);
1255 // Handles #define and #undef
1257 void PreProcessDefinition (bool is_define, string arg)
1259 if (arg == "" || arg == "true" || arg == "false"){
1260 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1264 char[] whitespace = { ' ', '\t' };
1265 if (arg.IndexOfAny (whitespace) != -1){
1266 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1270 if (!is_identifier_start_character (arg [0]))
1271 Report.Error (1001, Location, "Identifier expected: " + arg);
1273 foreach (char c in arg.Substring (1)){
1274 if (!is_identifier_part_character (c)){
1275 Report.Error (1001, Location, "Identifier expected: " + arg);
1281 if (defines == null)
1282 defines = new Hashtable ();
1285 if (defines == null)
1287 if (defines.Contains (arg))
1288 defines.Remove (arg);
1293 /// Handles #pragma directive
1295 void PreProcessPragma (string arg)
1297 const string disable = "warning disable";
1298 const string restore = "warning restore";
1300 if (arg == disable) {
1301 Report.RegisterWarningRegion (Location).WarningDisable (line);
1305 if (arg == restore) {
1306 Report.RegisterWarningRegion (Location).WarningEnable (line);
1310 if (arg.StartsWith (disable)) {
1311 int[] codes = ParseNumbers (arg.Substring (disable.Length));
1312 foreach (int code in codes) {
1314 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1319 if (arg.StartsWith (restore)) {
1320 int[] codes = ParseNumbers (arg.Substring (restore.Length));
1321 foreach (int code in codes) {
1322 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1330 int[] ParseNumbers (string text)
1332 string[] string_array = text.Split (',');
1333 int[] values = new int [string_array.Length];
1335 foreach (string string_code in string_array) {
1337 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1339 catch (FormatException) {
1340 Report.Warning (1692, Location, "Invalid number");
1346 bool eval_val (string s)
1353 if (defines == null)
1355 if (defines.Contains (s))
1361 bool pp_primary (ref string s)
1370 s = s.Substring (1);
1371 bool val = pp_expr (ref s);
1372 if (s.Length > 0 && s [0] == ')'){
1373 s = s.Substring (1);
1376 Error_InvalidDirective ();
1380 if (is_identifier_start_character (c)){
1386 if (is_identifier_part_character (c)){
1390 bool v = eval_val (s.Substring (0, j));
1391 s = s.Substring (j);
1394 bool vv = eval_val (s);
1399 Error_InvalidDirective ();
1403 bool pp_unary (ref string s)
1410 if (len > 1 && s [1] == '='){
1411 Error_InvalidDirective ();
1414 s = s.Substring (1);
1415 return ! pp_primary (ref s);
1417 return pp_primary (ref s);
1419 Error_InvalidDirective ();
1424 bool pp_eq (ref string s)
1426 bool va = pp_unary (ref s);
1432 if (len > 2 && s [1] == '='){
1433 s = s.Substring (2);
1434 return va == pp_unary (ref s);
1436 Error_InvalidDirective ();
1439 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1440 s = s.Substring (2);
1442 return va != pp_unary (ref s);
1451 bool pp_and (ref string s)
1453 bool va = pp_eq (ref s);
1459 if (len > 2 && s [1] == '&'){
1460 s = s.Substring (2);
1461 return (va & pp_eq (ref s));
1463 Error_InvalidDirective ();
1472 // Evaluates an expression for `#if' or `#elif'
1474 bool pp_expr (ref string s)
1476 bool va = pp_and (ref s);
1483 if (len > 2 && s [1] == '|'){
1484 s = s.Substring (2);
1485 return va | pp_expr (ref s);
1487 Error_InvalidDirective ();
1496 bool eval (string s)
1498 bool v = pp_expr (ref s);
1501 Error_InvalidDirective ();
1508 void Error_InvalidDirective ()
1510 Report.Error (1517, Location, "Invalid pre-processor directive");
1513 void Error_UnexpectedDirective (string extra)
1517 "Unexpected processor directive (" + extra + ")");
1520 void Error_TokensSeen ()
1524 "Cannot define or undefine pre-processor symbols after a token in the file");
1528 // if true, then the code continues processing the code
1529 // if false, the code stays in a loop until another directive is
1532 bool handle_preprocessing_directive (bool caller_is_taking)
1535 bool region_directive = false;
1537 get_cmd_arg (out cmd, out arg);
1539 // Eat any trailing whitespaces and single-line comments
1540 if (arg.IndexOf ("//") != -1)
1541 arg = arg.Substring (0, arg.IndexOf ("//"));
1542 arg = arg.TrimEnd (' ', '\t');
1545 // The first group of pre-processing instructions is always processed
1549 if (RootContext.Version == LanguageVersion.ISO_1) {
1550 Report.FeatureIsNotStandardized (Location, "#pragma");
1551 return caller_is_taking;
1554 PreProcessPragma (arg);
1555 return caller_is_taking;
1558 if (!PreProcessLine (arg))
1561 "Argument to #line directive is missing or invalid");
1562 return caller_is_taking;
1565 region_directive = true;
1570 region_directive = true;
1575 Error_InvalidDirective ();
1578 bool taking = false;
1579 if (ifstack == null)
1580 ifstack = new Stack ();
1582 if (ifstack.Count == 0){
1585 int state = (int) ifstack.Peek ();
1586 if ((state & TAKING) != 0)
1590 if (eval (arg) && taking){
1591 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1592 if (region_directive)
1594 ifstack.Push (push);
1597 int push = (taking ? PARENT_TAKING : 0);
1598 if (region_directive)
1600 ifstack.Push (push);
1605 if (ifstack == null || ifstack.Count == 0){
1606 Error_UnexpectedDirective ("no #if for this #endif");
1609 int pop = (int) ifstack.Pop ();
1611 if (region_directive && ((pop & REGION) == 0))
1612 Report.Error (1027, Location, "#endif directive expected");
1613 else if (!region_directive && ((pop & REGION) != 0))
1614 Report.Error (1038, Location, "#endregion directive expected");
1616 if (ifstack.Count == 0)
1619 int state = (int) ifstack.Peek ();
1621 if ((state & TAKING) != 0)
1629 if (ifstack == null || ifstack.Count == 0){
1630 Error_UnexpectedDirective ("no #if for this #elif");
1633 int state = (int) ifstack.Peek ();
1635 if ((state & REGION) != 0) {
1636 Report.Error (1038, Location, "#endregion directive expected");
1640 if ((state & ELSE_SEEN) != 0){
1641 Error_UnexpectedDirective ("#elif not valid after #else");
1645 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1648 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1649 state = (int) ifstack.Pop ();
1650 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1657 if (ifstack == null || ifstack.Count == 0){
1660 "Unexpected processor directive (no #if for this #else)");
1663 int state = (int) ifstack.Peek ();
1665 if ((state & REGION) != 0) {
1666 Report.Error (1038, Location, "#endregion directive expected");
1670 if ((state & ELSE_SEEN) != 0){
1671 Error_UnexpectedDirective ("#else within #else");
1678 if ((state & TAKEN_BEFORE) == 0){
1679 ret = ((state & PARENT_TAKING) != 0);
1688 ifstack.Push (state | ELSE_SEEN);
1695 // These are only processed if we are in a `taking' block
1697 if (!caller_is_taking)
1702 if (any_token_seen){
1703 Error_TokensSeen ();
1706 PreProcessDefinition (true, arg);
1710 if (any_token_seen){
1711 Error_TokensSeen ();
1714 PreProcessDefinition (false, arg);
1718 Report.Error (1029, Location, "#error: '" + arg + "'");
1722 Report.Warning (1030, Location, "#warning: '{0}'", arg);
1726 Report.Error (1024, Location, "Preprocessor directive expected (got: " + cmd + ")");
1731 private int consume_string (bool quoted)
1734 string_builder.Length = 0;
1736 while ((c = getChar ()) != -1){
1738 if (quoted && peekChar () == '"'){
1739 string_builder.Append ((char) c);
1743 val = string_builder.ToString ();
1744 return Token.LITERAL_STRING;
1750 Report.Error (1010, Location, "Newline in constant");
1762 string_builder.Append ((char) c);
1765 Report.Error (1039, Location, "Unterminated string literal");
1769 private int consume_identifier (int s)
1771 int res = consume_identifier (s, false);
1773 if (doc_state == XmlCommentState.Allowed)
1774 doc_state = XmlCommentState.NotAllowed;
1777 case Token.NAMESPACE:
1778 check_incorrect_doc_comment ();
1782 if (res == Token.PARTIAL) {
1783 // Save current position and parse next token.
1784 int old = reader.Position;
1785 int old_putback = putback_char;
1789 int next_token = token ();
1790 bool ok = (next_token == Token.CLASS) ||
1791 (next_token == Token.STRUCT) ||
1792 (next_token == Token.INTERFACE);
1794 reader.Position = old;
1795 putback_char = old_putback;
1801 return Token.IDENTIFIER;
1808 private int consume_identifier (int s, bool quoted)
1813 id_builder [0] = (char) s;
1815 while ((c = reader.Read ()) != -1) {
1816 if (is_identifier_part_character ((char) c)){
1817 if (pos == max_id_size){
1818 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
1822 id_builder [pos++] = (char) c;
1832 // Optimization: avoids doing the keyword lookup
1833 // on uppercase letters and _
1835 if (!quoted && (s >= 'a' || s == '_')){
1836 int keyword = GetKeyword (id_builder, pos);
1842 // Keep identifiers in an array of hashtables to avoid needless
1846 if (identifiers [pos] != null) {
1847 val = identifiers [pos][id_builder];
1849 return Token.IDENTIFIER;
1853 identifiers [pos] = new CharArrayHashtable (pos);
1855 val = new String (id_builder, 0, pos);
1857 char [] chars = new char [pos];
1858 Array.Copy (id_builder, chars, pos);
1860 identifiers [pos] [chars] = val;
1862 return Token.IDENTIFIER;
1865 public int xtoken ()
1868 bool doread = false;
1872 // optimization: eliminate col and implement #directive semantic correctly.
1873 for (;(c = getChar ()) != -1; col++) {
1878 col = (((col + 8) / 8) * 8) - 1;
1882 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0)
1886 if (peekChar () == '\n')
1892 any_token_seen |= tokens_seen;
1893 tokens_seen = false;
1897 // Handle double-slash comments.
1899 int d = peekChar ();
1903 if (RootContext.Documentation != null && peekChar () == '/') {
1905 // Don't allow ////.
1906 if ((d = peekChar ()) != '/') {
1907 if (doc_state == XmlCommentState.Allowed)
1908 handle_one_line_xml_comment ();
1909 else if (doc_state == XmlCommentState.NotAllowed)
1910 warn_incorrect_doc_comment ();
1913 while ((d = getChar ()) != -1 && (d != '\n') && d != '\r')
1920 any_token_seen |= tokens_seen;
1921 tokens_seen = false;
1923 } else if (d == '*'){
1925 bool docAppend = false;
1926 if (RootContext.Documentation != null && peekChar () == '*') {
1928 // But when it is /**/, just do nothing.
1929 if (peekChar () == '/') {
1933 if (doc_state == XmlCommentState.Allowed)
1935 else if (doc_state == XmlCommentState.NotAllowed)
1936 warn_incorrect_doc_comment ();
1939 int currentCommentStart = 0;
1941 currentCommentStart = xml_comment_buffer.Length;
1942 xml_comment_buffer.Append (Environment.NewLine);
1945 while ((d = getChar ()) != -1){
1946 if (d == '*' && peekChar () == '/'){
1952 xml_comment_buffer.Append ((char) d);
1958 any_token_seen |= tokens_seen;
1959 tokens_seen = false;
1963 update_formatted_doc_comment (currentCommentStart);
1966 goto is_punct_label;
1970 if (is_identifier_start_character ((char)c)){
1972 return consume_identifier (c);
1976 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
1990 any_token_seen |= tokens_seen;
1991 tokens_seen = false;
1995 if (c >= '0' && c <= '9'){
1997 return is_number (c);
2002 int peek = peekChar ();
2003 if (peek >= '0' && peek <= '9')
2004 return is_number (c);
2008 /* For now, ignore pre-processor commands */
2009 // FIXME: In C# the '#' is not limited to appear
2010 // on the first column.
2011 if (c == '#' && !tokens_seen){
2016 cont = handle_preprocessing_directive (cont);
2024 bool skipping = false;
2025 for (;(c = getChar ()) != -1; col++){
2031 } else if (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0)
2035 if (c == '#' && !skipping)
2038 any_token_seen |= tokens_seen;
2039 tokens_seen = false;
2041 Report.Error (1027, Location, "#endif/#endregion expected");
2046 return consume_string (false);
2052 error_details = "Empty character literal";
2053 Report.Error (1011, Location, error_details);
2059 val = new System.Char ();
2064 error_details = "Too many characters in character literal";
2065 Report.Error (1012, Location, error_details);
2067 // Try to recover, read until newline or next "'"
2068 while ((c = getChar ()) != -1){
2069 if (c == '\n' || c == '\''){
2080 return Token.LITERAL_CHARACTER;
2087 return consume_string (true);
2088 } else if (is_identifier_start_character ((char) c)){
2089 return consume_identifier (c, true);
2091 Report.Error (1033, Location, "'@' must be followed by string constant or identifier");
2096 error_details = "Preprocessor directives must appear as the first non-whitespace " +
2097 "character on a line.";
2099 Report.Error (1040, Location, error_details);
2104 error_details = ((char)c).ToString ();
2113 // Handles one line xml comment
2115 private void handle_one_line_xml_comment ()
2118 while ((c = peekChar ()) == ' ')
2119 getChar (); // skip heading whitespaces.
2120 while ((c = peekChar ()) != -1 && c != '\n' && c != '\r') {
2122 xml_comment_buffer.Append ((char) getChar ());
2124 if (c == '\r' || c == '\n')
2125 xml_comment_buffer.Append (Environment.NewLine);
2129 // Remove heading "*" in Javadoc-like xml documentation.
2131 private void update_formatted_doc_comment (int currentCommentStart)
2133 int length = xml_comment_buffer.Length - currentCommentStart;
2134 string [] lines = xml_comment_buffer.ToString (
2135 currentCommentStart,
2136 length).Replace ("\r", "").Split ('\n');
2137 // The first line starts with /**, thus it is not target
2138 // for the format check.
2139 for (int i = 1; i < lines.Length; i++) {
2140 string s = lines [i];
2141 int idx = s.IndexOf ('*');
2144 if (i < lines.Length - 1)
2149 head = s.Substring (0, idx);
2150 foreach (char c in head)
2153 lines [i] = s.Substring (idx + 1);
2155 xml_comment_buffer.Remove (currentCommentStart, length);
2156 xml_comment_buffer.Insert (
2157 currentCommentStart,
2158 String.Join (Environment.NewLine, lines));
2162 // Checks if there was incorrect doc comments and raise
2165 public void check_incorrect_doc_comment ()
2167 if (xml_comment_buffer.Length > 0)
2168 warn_incorrect_doc_comment ();
2172 // Raises a warning when tokenizer found incorrect doccomment
2175 private void warn_incorrect_doc_comment ()
2177 doc_state = XmlCommentState.Error;
2178 // in csc, it is 'XML comment is not placed on a valid
2179 // language element'. But that does not make sense.
2180 Report.Warning (1587, 2, Location, "XML comment is placed on an invalid language element which can not accept it.");
2184 // Consumes the saved xml comment lines (if any)
2185 // as for current target member or type.
2187 public string consume_doc_comment ()
2189 if (xml_comment_buffer.Length > 0) {
2190 string ret = xml_comment_buffer.ToString ();
2191 xml_comment_buffer.Length = 0;
2197 public void cleanup ()
2199 if (ifstack != null && ifstack.Count >= 1) {
2200 int state = (int) ifstack.Pop ();
2201 if ((state & REGION) != 0)
2202 Report.Error (1038, Location, "#endregion directive expected");
2204 Report.Error (1027, "#endif directive expected");
2211 // Indicates whether it accepts XML documentation or not.
2213 public enum XmlCommentState {
2214 // comment is allowed in this state.
2216 // comment is not allowed in this state.
2218 // once comments appeared when it is NotAllowed, then the
2219 // state is changed to it, until the state is changed to