2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 // This also implements the preprocessor
5 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
17 using System.Collections;
19 using System.Globalization;
20 using System.Reflection;
25 /// Tokenizer for C# source code.
28 public class Tokenizer : yyParser.yyInput
30 SeekableStreamReader reader;
32 CompilationUnit file_name;
39 bool handle_get_set = false;
40 bool handle_remove_add = false;
41 bool handle_where = false;
42 bool handle_typeof = false;
43 bool lambda_arguments_parsing;
44 Location current_comment_location = Location.Null;
45 ArrayList escaped_identifiers;
46 int parsing_generic_less_than;
49 // Used mainly for parser optimizations. Some expressions for instance
50 // can appear only in block (including initializer, base initializer)
53 public int parsing_block;
54 internal bool query_parsing;
57 // When parsing type only, useful for ambiguous nullable types
59 public int parsing_type;
62 // Set when parsing generic declaration (type or method header)
64 public bool parsing_generic_declaration;
67 // The value indicates that we have not reach any declaration or
70 public int parsing_declaration;
73 // The special character to inject on streams to trigger the EXPRESSION_PARSE
74 // token to be returned. It just happens to be a Unicode character that
75 // would never be part of a program (can not be an identifier).
77 // This character is only tested just before the tokenizer is about to report
78 // an error; So on the regular operation mode, this addition will have no
79 // impact on the tokenizer's performance.
82 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
83 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
84 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
87 // XML documentation buffer. The save point is used to divide
88 // comments on types and comments on members.
90 StringBuilder xml_comment_buffer;
93 // See comment on XmlCommentState enumeration.
95 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
98 // Whether tokens have been seen on this line
100 bool tokens_seen = false;
103 // Whether a token has been seen on the file
104 // This is needed because `define' is not allowed to be used
105 // after a token has been seen.
107 bool any_token_seen = false;
109 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
111 public bool PropertyParsing {
112 get { return handle_get_set; }
113 set { handle_get_set = value; }
116 public bool EventParsing {
117 get { return handle_remove_add; }
118 set { handle_remove_add = value; }
121 public bool ConstraintsParsing {
122 get { return handle_where; }
123 set { handle_where = value; }
126 public bool TypeOfParsing {
127 get { return handle_typeof; }
128 set { handle_typeof = value; }
131 public XmlCommentState doc_state {
132 get { return xml_doc_state; }
134 if (value == XmlCommentState.Allowed) {
135 check_incorrect_doc_comment ();
136 reset_doc_comment ();
138 xml_doc_state = value;
142 void AddEscapedIdentifier (LocatedToken lt)
144 if (escaped_identifiers == null)
145 escaped_identifiers = new ArrayList ();
147 escaped_identifiers.Add (lt);
150 public bool IsEscapedIdentifier (Location loc)
152 if (escaped_identifiers != null) {
153 foreach (LocatedToken lt in escaped_identifiers)
154 if (lt.Location.Equals (loc))
164 static CharArrayHashtable[] keywords;
165 static Hashtable keyword_strings;
166 static NumberStyles styles;
167 static NumberFormatInfo csharp_format_info;
170 // Values for the associated token returned
172 internal int putback_char; // Used by repl only
178 const int TAKING = 1;
179 const int ELSE_SEEN = 4;
180 const int PARENT_TAKING = 8;
181 const int REGION = 16;
184 // pre-processor if stack state:
188 static System.Text.StringBuilder string_builder;
190 const int max_id_size = 512;
191 static char [] id_builder = new char [max_id_size];
193 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
195 const int max_number_size = 512;
196 static char [] number_builder = new char [max_number_size];
197 static int number_pos;
200 // Details about the error encoutered by the tokenizer
202 string error_details;
204 public string error {
206 return error_details;
217 // This is used when the tokenizer needs to save
218 // the current position as it needs to do some parsing
219 // on its own to deamiguate a token in behalf of the
222 Stack position_stack = new Stack (2);
229 public int putback_char;
230 public int previous_col;
231 public Stack ifstack;
232 public int parsing_generic_less_than;
233 public int current_token;
235 public Position (Tokenizer t)
237 position = t.reader.Position;
239 ref_line = t.ref_line;
242 putback_char = t.putback_char;
243 previous_col = t.previous_col;
244 if (t.ifstack != null && t.ifstack.Count != 0)
245 ifstack = (Stack)t.ifstack.Clone ();
246 parsing_generic_less_than = t.parsing_generic_less_than;
247 current_token = t.current_token;
251 public void PushPosition ()
253 position_stack.Push (new Position (this));
256 public void PopPosition ()
258 Position p = (Position) position_stack.Pop ();
260 reader.Position = p.position;
261 ref_line = p.ref_line;
265 putback_char = p.putback_char;
266 previous_col = p.previous_col;
268 parsing_generic_less_than = p.parsing_generic_less_than;
269 current_token = p.current_token;
272 // Do not reset the position, ignore it.
273 public void DiscardPosition ()
275 position_stack.Pop ();
278 static void AddKeyword (string kw, int token)
280 keyword_strings.Add (kw, kw);
281 if (keywords [kw.Length] == null) {
282 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
284 keywords [kw.Length] [kw.ToCharArray ()] = token;
287 static void InitTokens ()
289 keyword_strings = new Hashtable ();
290 keywords = new CharArrayHashtable [64];
292 AddKeyword ("__arglist", Token.ARGLIST);
293 AddKeyword ("abstract", Token.ABSTRACT);
294 AddKeyword ("as", Token.AS);
295 AddKeyword ("add", Token.ADD);
296 AddKeyword ("base", Token.BASE);
297 AddKeyword ("bool", Token.BOOL);
298 AddKeyword ("break", Token.BREAK);
299 AddKeyword ("byte", Token.BYTE);
300 AddKeyword ("case", Token.CASE);
301 AddKeyword ("catch", Token.CATCH);
302 AddKeyword ("char", Token.CHAR);
303 AddKeyword ("checked", Token.CHECKED);
304 AddKeyword ("class", Token.CLASS);
305 AddKeyword ("const", Token.CONST);
306 AddKeyword ("continue", Token.CONTINUE);
307 AddKeyword ("decimal", Token.DECIMAL);
308 AddKeyword ("default", Token.DEFAULT);
309 AddKeyword ("delegate", Token.DELEGATE);
310 AddKeyword ("do", Token.DO);
311 AddKeyword ("double", Token.DOUBLE);
312 AddKeyword ("else", Token.ELSE);
313 AddKeyword ("enum", Token.ENUM);
314 AddKeyword ("event", Token.EVENT);
315 AddKeyword ("explicit", Token.EXPLICIT);
316 AddKeyword ("extern", Token.EXTERN);
317 AddKeyword ("false", Token.FALSE);
318 AddKeyword ("finally", Token.FINALLY);
319 AddKeyword ("fixed", Token.FIXED);
320 AddKeyword ("float", Token.FLOAT);
321 AddKeyword ("for", Token.FOR);
322 AddKeyword ("foreach", Token.FOREACH);
323 AddKeyword ("goto", Token.GOTO);
324 AddKeyword ("get", Token.GET);
325 AddKeyword ("if", Token.IF);
326 AddKeyword ("implicit", Token.IMPLICIT);
327 AddKeyword ("in", Token.IN);
328 AddKeyword ("int", Token.INT);
329 AddKeyword ("interface", Token.INTERFACE);
330 AddKeyword ("internal", Token.INTERNAL);
331 AddKeyword ("is", Token.IS);
332 AddKeyword ("lock", Token.LOCK);
333 AddKeyword ("long", Token.LONG);
334 AddKeyword ("namespace", Token.NAMESPACE);
335 AddKeyword ("new", Token.NEW);
336 AddKeyword ("null", Token.NULL);
337 AddKeyword ("object", Token.OBJECT);
338 AddKeyword ("operator", Token.OPERATOR);
339 AddKeyword ("out", Token.OUT);
340 AddKeyword ("override", Token.OVERRIDE);
341 AddKeyword ("params", Token.PARAMS);
342 AddKeyword ("private", Token.PRIVATE);
343 AddKeyword ("protected", Token.PROTECTED);
344 AddKeyword ("public", Token.PUBLIC);
345 AddKeyword ("readonly", Token.READONLY);
346 AddKeyword ("ref", Token.REF);
347 AddKeyword ("remove", Token.REMOVE);
348 AddKeyword ("return", Token.RETURN);
349 AddKeyword ("sbyte", Token.SBYTE);
350 AddKeyword ("sealed", Token.SEALED);
351 AddKeyword ("set", Token.SET);
352 AddKeyword ("short", Token.SHORT);
353 AddKeyword ("sizeof", Token.SIZEOF);
354 AddKeyword ("stackalloc", Token.STACKALLOC);
355 AddKeyword ("static", Token.STATIC);
356 AddKeyword ("string", Token.STRING);
357 AddKeyword ("struct", Token.STRUCT);
358 AddKeyword ("switch", Token.SWITCH);
359 AddKeyword ("this", Token.THIS);
360 AddKeyword ("throw", Token.THROW);
361 AddKeyword ("true", Token.TRUE);
362 AddKeyword ("try", Token.TRY);
363 AddKeyword ("typeof", Token.TYPEOF);
364 AddKeyword ("uint", Token.UINT);
365 AddKeyword ("ulong", Token.ULONG);
366 AddKeyword ("unchecked", Token.UNCHECKED);
367 AddKeyword ("unsafe", Token.UNSAFE);
368 AddKeyword ("ushort", Token.USHORT);
369 AddKeyword ("using", Token.USING);
370 AddKeyword ("virtual", Token.VIRTUAL);
371 AddKeyword ("void", Token.VOID);
372 AddKeyword ("volatile", Token.VOLATILE);
373 AddKeyword ("while", Token.WHILE);
374 AddKeyword ("partial", Token.PARTIAL);
375 AddKeyword ("where", Token.WHERE);
378 AddKeyword ("from", Token.FROM);
379 AddKeyword ("join", Token.JOIN);
380 AddKeyword ("on", Token.ON);
381 AddKeyword ("equals", Token.EQUALS);
382 AddKeyword ("select", Token.SELECT);
383 AddKeyword ("group", Token.GROUP);
384 AddKeyword ("by", Token.BY);
385 AddKeyword ("let", Token.LET);
386 AddKeyword ("orderby", Token.ORDERBY);
387 AddKeyword ("ascending", Token.ASCENDING);
388 AddKeyword ("descending", Token.DESCENDING);
389 AddKeyword ("into", Token.INTO);
400 public static void Reset ()
403 csharp_format_info = NumberFormatInfo.InvariantInfo;
404 styles = NumberStyles.Float;
406 string_builder = new System.Text.StringBuilder ();
409 int GetKeyword (char[] id, int id_len)
412 * Keywords are stored in an array of hashtables grouped by their
416 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
418 object o = keywords [id_len] [id];
433 if (!handle_remove_add)
437 if (parsing_declaration == 0)
438 res = Token.EXTERN_ALIAS;
441 if (peek_token () == Token.COLON) {
443 res = Token.DEFAULT_COLON;
447 if (!handle_where && !query_parsing)
452 // A query expression is any expression that starts with `from identifier'
453 // followed by any token except ; , =
455 if (!query_parsing) {
456 if (lambda_arguments_parsing) {
462 // HACK: to disable generics micro-parser, because PushPosition does not
463 // store identifiers array
464 parsing_generic_less_than = 1;
466 case Token.IDENTIFIER:
478 next_token = xtoken ();
479 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
482 res = Token.FROM_FIRST;
483 query_parsing = true;
484 if (RootContext.Version <= LanguageVersion.ISO_2)
485 Report.FeatureIsNotAvailable (Location, "query expressions");
488 Expression.Error_VoidInvalidInTheContext (Location);
492 // HACK: A token is not a keyword so we need to restore identifiers buffer
493 // which has been overwritten before we grabbed the identifier
494 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
508 case Token.ASCENDING:
509 case Token.DESCENDING:
516 case Token.NAMESPACE:
517 // TODO: some explanation needed
518 check_incorrect_doc_comment ();
522 if (parsing_block > 0) {
527 // Save current position and parse next token.
530 next_token = token ();
531 bool ok = (next_token == Token.CLASS) ||
532 (next_token == Token.STRUCT) ||
533 (next_token == Token.INTERFACE) ||
534 (next_token == Token.VOID);
539 if (next_token == Token.VOID) {
540 if (RootContext.Version == LanguageVersion.ISO_1 ||
541 RootContext.Version == LanguageVersion.ISO_2)
542 Report.FeatureIsNotAvailable (Location, "partial methods");
543 } else if (RootContext.Version == LanguageVersion.ISO_1)
544 Report.FeatureIsNotAvailable (Location, "partial types");
549 if (next_token < Token.LAST_KEYWORD) {
550 Report.Error (267, Location,
551 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
562 public Location Location {
564 return new Location (ref_line, hidden ? -1 : col);
568 public Tokenizer (SeekableStreamReader input, CompilationUnit file)
570 this.ref_name = file;
571 this.file_name = file;
576 xml_comment_buffer = new StringBuilder ();
579 // FIXME: This could be `Location.Push' but we have to
580 // find out why the MS compiler allows this
582 Mono.CSharp.Location.Push (file, file);
585 static bool is_identifier_start_character (int c)
587 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
590 static bool is_identifier_part_character (char c)
592 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') ||
593 Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
596 public static bool IsKeyword (string s)
598 return keyword_strings [s] != null;
602 // Open parens micro parser. Detects both lambda and cast ambiguity.
605 int TokenizeOpenParens ()
610 int bracket_level = 0;
611 bool is_type = false;
612 bool can_be_type = false;
615 ptoken = current_token;
618 switch (current_token) {
619 case Token.CLOSE_PARENS:
623 // Expression inside parens is lambda, (int i) =>
625 if (current_token == Token.ARROW) {
626 if (RootContext.Version <= LanguageVersion.ISO_2)
627 Report.FeatureIsNotAvailable (Location, "lambda expressions");
629 return Token.OPEN_PARENS_LAMBDA;
633 // Expression inside parens is single type, (int[])
636 return Token.OPEN_PARENS_CAST;
639 // Expression is possible cast, look at next token, (T)null
642 switch (current_token) {
643 case Token.OPEN_PARENS:
646 case Token.IDENTIFIER:
647 case Token.LITERAL_INTEGER:
648 case Token.LITERAL_FLOAT:
649 case Token.LITERAL_DOUBLE:
650 case Token.LITERAL_DECIMAL:
651 case Token.LITERAL_CHARACTER:
652 case Token.LITERAL_STRING:
665 case Token.UNCHECKED:
670 // These can be part of a member access
684 return Token.OPEN_PARENS_CAST;
687 return Token.OPEN_PARENS;
690 case Token.DOUBLE_COLON:
691 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
696 case Token.IDENTIFIER:
699 case Token.OP_GENERICS_LT:
701 case Token.DOUBLE_COLON:
703 if (bracket_level == 0)
707 can_be_type = is_type = false;
727 if (bracket_level == 0)
732 if (bracket_level == 0) {
734 can_be_type = is_type = false;
738 case Token.OP_GENERICS_LT:
739 case Token.OPEN_BRACKET:
740 if (bracket_level++ == 0)
744 case Token.OP_GENERICS_GT:
745 case Token.CLOSE_BRACKET:
749 case Token.INTERR_NULLABLE:
751 if (bracket_level == 0)
757 can_be_type = is_type = false;
761 return Token.OPEN_PARENS;
766 public static bool IsValidIdentifier (string s)
768 if (s == null || s.Length == 0)
771 if (!is_identifier_start_character (s [0]))
774 for (int i = 1; i < s.Length; i ++)
775 if (! is_identifier_part_character (s [i]))
781 bool parse_less_than ()
784 int the_token = token ();
785 if (the_token == Token.OPEN_BRACKET) {
787 the_token = token ();
788 } while (the_token != Token.CLOSE_BRACKET);
789 the_token = token ();
792 case Token.IDENTIFIER:
811 case Token.OP_GENERICS_GT:
818 the_token = token ();
820 if (the_token == Token.OP_GENERICS_GT)
822 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
824 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
826 else if (the_token == Token.OP_GENERICS_LT) {
827 if (!parse_less_than ())
830 } else if (the_token == Token.OPEN_BRACKET) {
832 the_token = token ();
833 if (the_token == Token.CLOSE_BRACKET)
835 else if (the_token == Token.COMMA)
836 goto rank_specifiers;
843 bool parse_generic_dimension (out int dimension)
848 int the_token = token ();
849 if (the_token == Token.OP_GENERICS_GT)
851 else if (the_token == Token.COMMA) {
859 public int peek_token ()
864 the_token = token ();
871 // Tonizes `?' using custom disambiguous rules to return one
872 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
874 // Tricky expression look like:
876 // Foo ? a = x ? b : c;
878 int TokenizePossibleNullableType ()
880 if (parsing_block == 0 || parsing_type > 0)
881 return Token.INTERR_NULLABLE;
883 int d = peek_char ();
886 return Token.OP_COALESCING;
889 switch (current_token) {
890 case Token.CLOSE_PARENS:
894 case Token.LITERAL_INTEGER:
895 case Token.LITERAL_STRING:
900 if (d == ',' || d == ';' || d == '>')
901 return Token.INTERR_NULLABLE;
902 if (d == '*' || (d >= '0' && d <= '9'))
907 current_token = Token.NONE;
910 case Token.LITERAL_INTEGER:
911 case Token.LITERAL_STRING:
912 case Token.LITERAL_CHARACTER:
913 case Token.LITERAL_DECIMAL:
914 case Token.LITERAL_DOUBLE:
915 case Token.LITERAL_FLOAT:
921 next_token = Token.INTERR;
924 case Token.SEMICOLON:
926 case Token.CLOSE_PARENS:
927 case Token.OPEN_BRACKET:
928 case Token.OP_GENERICS_GT:
929 next_token = Token.INTERR_NULLABLE;
937 if (next_token == -1) {
940 case Token.SEMICOLON:
941 case Token.OPEN_BRACE:
942 case Token.CLOSE_PARENS:
944 next_token = Token.INTERR_NULLABLE;
948 next_token = Token.INTERR;
956 // All shorcuts failed, do it hard way
958 while ((ntoken = xtoken ()) != Token.EOF) {
959 if (ntoken == Token.SEMICOLON)
962 if (ntoken == Token.COLON) {
963 if (++colons == interrs)
968 if (ntoken == Token.INTERR) {
974 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
983 bool decimal_digits (int c)
986 bool seen_digits = false;
989 if (number_pos == max_number_size)
990 Error_NumericConstantTooLong ();
991 number_builder [number_pos++] = (char) c;
995 // We use peek_char2, because decimal_digits needs to do a
996 // 2-character look-ahead (5.ToString for example).
998 while ((d = peek_char2 ()) != -1){
999 if (d >= '0' && d <= '9'){
1000 if (number_pos == max_number_size)
1001 Error_NumericConstantTooLong ();
1002 number_builder [number_pos++] = (char) d;
1012 static bool is_hex (int e)
1014 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1017 static int real_type_suffix (int c)
1023 t = Token.LITERAL_FLOAT;
1026 t = Token.LITERAL_DOUBLE;
1029 t= Token.LITERAL_DECIMAL;
1037 int integer_type_suffix (ulong ul, int c)
1039 bool is_unsigned = false;
1040 bool is_long = false;
1043 bool scanning = true;
1056 // if we have not seen anything in between
1057 // report this error
1059 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1062 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1063 // work around that.
1087 if (is_long && is_unsigned){
1089 return Token.LITERAL_INTEGER;
1090 } else if (is_unsigned){
1091 // uint if possible, or ulong else.
1093 if ((ul & 0xffffffff00000000) == 0)
1097 } else if (is_long){
1098 // long if possible, ulong otherwise
1099 if ((ul & 0x8000000000000000) != 0)
1104 // int, uint, long or ulong in that order
1105 if ((ul & 0xffffffff00000000) == 0){
1106 uint ui = (uint) ul;
1108 if ((ui & 0x80000000) != 0)
1113 if ((ul & 0x8000000000000000) != 0)
1119 return Token.LITERAL_INTEGER;
1123 // given `c' as the next char in the input decide whether
1124 // we need to convert to a special type, and then choose
1125 // the best representation for the integer
1127 int adjust_int (int c)
1130 if (number_pos > 9){
1131 ulong ul = (uint) (number_builder [0] - '0');
1133 for (int i = 1; i < number_pos; i++){
1134 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1136 return integer_type_suffix (ul, c);
1138 uint ui = (uint) (number_builder [0] - '0');
1140 for (int i = 1; i < number_pos; i++){
1141 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1143 return integer_type_suffix (ui, c);
1145 } catch (OverflowException) {
1146 error_details = "Integral constant is too large";
1147 Report.Error (1021, Location, error_details);
1149 return Token.LITERAL_INTEGER;
1151 catch (FormatException) {
1152 Report.Error (1013, Location, "Invalid number");
1154 return Token.LITERAL_INTEGER;
1158 int adjust_real (int t)
1160 string s = new String (number_builder, 0, number_pos);
1161 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1164 case Token.LITERAL_DECIMAL:
1166 val = System.Decimal.Parse (s, styles, csharp_format_info);
1167 } catch (OverflowException) {
1169 Report.Error (594, Location, error_details, "decimal");
1172 case Token.LITERAL_FLOAT:
1174 val = float.Parse (s, styles, csharp_format_info);
1175 } catch (OverflowException) {
1177 Report.Error (594, Location, error_details, "float");
1181 case Token.LITERAL_DOUBLE:
1183 t = Token.LITERAL_DOUBLE;
1185 val = System.Double.Parse (s, styles, csharp_format_info);
1186 } catch (OverflowException) {
1188 Report.Error (594, Location, error_details, "double");
1201 while ((d = peek_char ()) != -1){
1203 number_builder [number_pos++] = (char) d;
1209 string s = new String (number_builder, 0, number_pos);
1211 if (number_pos <= 8)
1212 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1214 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1215 } catch (OverflowException){
1216 error_details = "Integral constant is too large";
1217 Report.Error (1021, Location, error_details);
1219 return Token.LITERAL_INTEGER;
1221 catch (FormatException) {
1222 Report.Error (1013, Location, "Invalid number");
1224 return Token.LITERAL_INTEGER;
1227 return integer_type_suffix (ul, peek_char ());
1231 // Invoked if we know we have .digits or digits
1233 int is_number (int c)
1235 bool is_real = false;
1240 if (c >= '0' && c <= '9'){
1242 int peek = peek_char ();
1244 if (peek == 'x' || peek == 'X')
1245 return handle_hex ();
1252 // We need to handle the case of
1253 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1256 if (decimal_digits ('.')){
1262 return adjust_int (-1);
1266 if (c == 'e' || c == 'E'){
1268 if (number_pos == max_number_size)
1269 Error_NumericConstantTooLong ();
1270 number_builder [number_pos++] = 'e';
1274 if (number_pos == max_number_size)
1275 Error_NumericConstantTooLong ();
1276 number_builder [number_pos++] = '+';
1278 } else if (c == '-') {
1279 if (number_pos == max_number_size)
1280 Error_NumericConstantTooLong ();
1281 number_builder [number_pos++] = '-';
1284 if (number_pos == max_number_size)
1285 Error_NumericConstantTooLong ();
1286 number_builder [number_pos++] = '+';
1293 type = real_type_suffix (c);
1294 if (type == Token.NONE && !is_real){
1296 return adjust_int (c);
1300 if (type == Token.NONE){
1305 return adjust_real (type);
1307 Console.WriteLine ("This should not be reached");
1308 throw new Exception ("Is Number should never reach this point");
1312 // Accepts exactly count (4 or 8) hex, no more no less
1314 int getHex (int count, out int surrogate, out bool error)
1319 int top = count != -1 ? count : 4;
1324 for (i = 0; i < top; i++){
1327 if (c >= '0' && c <= '9')
1328 c = (int) c - (int) '0';
1329 else if (c >= 'A' && c <= 'F')
1330 c = (int) c - (int) 'A' + 10;
1331 else if (c >= 'a' && c <= 'f')
1332 c = (int) c - (int) 'a' + 10;
1338 total = (total * 16) + c;
1340 int p = peek_char ();
1343 if (!is_hex ((char)p))
1349 if (total > 0x0010FFFF) {
1354 if (total >= 0x00010000) {
1355 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1356 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1363 int escape (int c, out int surrogate)
1399 v = getHex (-1, out surrogate, out error);
1405 return EscapeUnicode (d, out surrogate);
1408 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1417 int EscapeUnicode (int ch, out int surrogate)
1421 ch = getHex (8, out surrogate, out error);
1423 ch = getHex (4, out surrogate, out error);
1427 Report.Error (1009, Location, "Unrecognized escape sequence");
1435 if (putback_char != -1) {
1448 void advance_line ()
1458 if (putback_char == -1)
1459 putback_char = reader.Read ();
1460 return putback_char;
1465 if (putback_char != -1)
1466 return putback_char;
1467 return reader.Peek ();
1470 void putback (int c)
1472 if (putback_char != -1){
1473 Console.WriteLine ("Col: " + col);
1474 Console.WriteLine ("Row: " + line);
1475 Console.WriteLine ("Name: " + ref_name.Name);
1476 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1477 throw new Exception ("This should not happen putback on putback");
1479 if (c == '\n' || col == 0) {
1480 // It won't happen though.
1490 public bool advance ()
1492 return peek_char () != -1;
1495 public Object Value {
1501 public Object value ()
1508 current_token = xtoken ();
1509 return current_token;
1512 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1514 void get_cmd_arg (out string cmd, out string arg)
1518 tokens_seen = false;
1521 // skip over white space
1524 } while (c == '\r' || c == ' ' || c == '\t');
1526 static_cmd_arg.Length = 0;
1527 while (c != -1 && is_identifier_part_character ((char)c)) {
1528 static_cmd_arg.Append ((char)c);
1531 int peek = peek_char ();
1532 if (peek == 'U' || peek == 'u') {
1534 c = EscapeUnicode (c, out surrogate);
1535 if (surrogate != 0) {
1536 if (is_identifier_part_character ((char) c))
1537 static_cmd_arg.Append ((char) c);
1544 cmd = static_cmd_arg.ToString ();
1546 // skip over white space
1547 while (c == '\r' || c == ' ' || c == '\t')
1550 static_cmd_arg.Length = 0;
1551 int has_identifier_argument = 0;
1553 while (c != -1 && c != '\n' && c != '\r') {
1554 if (c == '\\' && has_identifier_argument >= 0) {
1555 if (has_identifier_argument != 0 || (cmd == "define" || cmd == "if" || cmd == "elif" || cmd == "undef")) {
1556 has_identifier_argument = 1;
1558 int peek = peek_char ();
1559 if (peek == 'U' || peek == 'u') {
1561 c = EscapeUnicode (c, out surrogate);
1562 if (surrogate != 0) {
1563 if (is_identifier_part_character ((char) c))
1564 static_cmd_arg.Append ((char) c);
1569 has_identifier_argument = -1;
1572 static_cmd_arg.Append ((char) c);
1576 if (static_cmd_arg.Length != 0)
1577 arg = static_cmd_arg.ToString ();
1581 // Handles the #line directive
1583 bool PreProcessLine (string arg)
1585 if (arg.Length == 0)
1588 if (arg == "default"){
1590 ref_name = file_name;
1592 Location.Push (file_name, ref_name);
1594 } else if (arg == "hidden"){
1602 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1603 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1606 char [] quotes = { '\"' };
1608 string name = arg.Substring (pos). Trim (quotes);
1609 ref_name = Location.LookupFile (file_name, name);
1610 file_name.AddFile (ref_name);
1612 Location.Push (file_name, ref_name);
1614 ref_line = System.Int32.Parse (arg);
1625 // Handles #define and #undef
1627 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1629 if (ident.Length == 0 || ident == "true" || ident == "false"){
1630 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1634 if (ident.IndexOfAny (simple_whitespaces) != -1){
1635 Error_EndLineExpected ();
1639 if (!is_identifier_start_character (ident [0]))
1640 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1642 foreach (char c in ident.Substring (1)){
1643 if (!is_identifier_part_character (c)){
1644 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1649 if (!caller_is_taking)
1656 if (RootContext.IsConditionalDefined (ident))
1659 file_name.AddDefine (ident);
1664 file_name.AddUndefine (ident);
1668 static byte read_hex (string arg, int pos, out bool error)
1675 if ((c >= '0') && (c <= '9'))
1676 total = (int) c - (int) '0';
1677 else if ((c >= 'A') && (c <= 'F'))
1678 total = (int) c - (int) 'A' + 10;
1679 else if ((c >= 'a') && (c <= 'f'))
1680 total = (int) c - (int) 'a' + 10;
1689 if ((c >= '0') && (c <= '9'))
1690 total += (int) c - (int) '0';
1691 else if ((c >= 'A') && (c <= 'F'))
1692 total += (int) c - (int) 'A' + 10;
1693 else if ((c >= 'a') && (c <= 'f'))
1694 total += (int) c - (int) 'a' + 10;
1700 return (byte) total;
1704 /// Handles #pragma checksum
1706 bool PreProcessPragmaChecksum (string arg)
1708 if ((arg [0] != ' ') && (arg [0] != '\t'))
1711 arg = arg.Trim (simple_whitespaces);
1712 if ((arg.Length < 2) || (arg [0] != '"'))
1715 StringBuilder file_sb = new StringBuilder ();
1719 while ((ch = arg [pos++]) != '"') {
1720 if (pos >= arg.Length)
1724 if (pos+1 >= arg.Length)
1729 file_sb.Append (ch);
1732 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1735 arg = arg.Substring (pos).Trim (simple_whitespaces);
1736 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1737 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1738 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1742 byte[] guid_bytes = new byte [16];
1744 for (int i = 0; i < 4; i++) {
1745 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1749 for (int i = 0; i < 2; i++) {
1750 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1753 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1756 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1761 for (int i = 0; i < 6; i++) {
1762 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1767 arg = arg.Substring (40).Trim (simple_whitespaces);
1768 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1771 byte[] checksum_bytes = new byte [16];
1772 for (int i = 0; i < 16; i++) {
1773 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1778 arg = arg.Substring (34).Trim (simple_whitespaces);
1782 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1783 file.SetChecksum (guid_bytes, checksum_bytes);
1784 ref_name.AutoGenerated = true;
1789 /// Handles #pragma directive
1791 void PreProcessPragma (string arg)
1793 const string warning = "warning";
1794 const string w_disable = "warning disable";
1795 const string w_restore = "warning restore";
1796 const string checksum = "checksum";
1798 if (arg == w_disable) {
1799 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1803 if (arg == w_restore) {
1804 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1808 if (arg.StartsWith (w_disable)) {
1809 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1810 foreach (int code in codes) {
1812 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1817 if (arg.StartsWith (w_restore)) {
1818 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1819 Hashtable w_table = Report.warning_ignore_table;
1820 foreach (int code in codes) {
1821 if (w_table != null && w_table.Contains (code))
1822 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1823 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1828 if (arg.StartsWith (warning)) {
1829 Report.Warning (1634, 1, Location, "Expected disable or restore");
1833 if (arg.StartsWith (checksum)) {
1834 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1835 Warning_InvalidPragmaChecksum ();
1839 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1842 int[] ParseNumbers (string text)
1844 string[] string_array = text.Split (',');
1845 int[] values = new int [string_array.Length];
1847 foreach (string string_code in string_array) {
1849 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1851 catch (FormatException) {
1852 Report.Warning (1692, 1, Location, "Invalid number");
1858 bool eval_val (string s)
1865 return file_name.IsConditionalDefined (s);
1868 bool pp_primary (ref string s)
1877 s = s.Substring (1);
1878 bool val = pp_expr (ref s, false);
1879 if (s.Length > 0 && s [0] == ')'){
1880 s = s.Substring (1);
1883 Error_InvalidDirective ();
1887 if (is_identifier_start_character (c)){
1893 if (is_identifier_part_character (c)){
1897 bool v = eval_val (s.Substring (0, j));
1898 s = s.Substring (j);
1901 bool vv = eval_val (s);
1906 Error_InvalidDirective ();
1910 bool pp_unary (ref string s)
1917 if (len > 1 && s [1] == '='){
1918 Error_InvalidDirective ();
1921 s = s.Substring (1);
1922 return ! pp_primary (ref s);
1924 return pp_primary (ref s);
1926 Error_InvalidDirective ();
1931 bool pp_eq (ref string s)
1933 bool va = pp_unary (ref s);
1939 if (len > 2 && s [1] == '='){
1940 s = s.Substring (2);
1941 return va == pp_unary (ref s);
1943 Error_InvalidDirective ();
1946 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1947 s = s.Substring (2);
1949 return va != pp_unary (ref s);
1958 bool pp_and (ref string s)
1960 bool va = pp_eq (ref s);
1966 if (len > 2 && s [1] == '&'){
1967 s = s.Substring (2);
1968 return (va & pp_and (ref s));
1970 Error_InvalidDirective ();
1979 // Evaluates an expression for `#if' or `#elif'
1981 bool pp_expr (ref string s, bool isTerm)
1983 bool va = pp_and (ref s);
1990 if (len > 2 && s [1] == '|'){
1991 s = s.Substring (2);
1992 return va | pp_expr (ref s, isTerm);
1994 Error_InvalidDirective ();
1999 Error_EndLineExpected ();
2007 bool eval (string s)
2009 bool v = pp_expr (ref s, true);
2018 void Error_NumericConstantTooLong ()
2020 Report.Error (1021, Location, "Numeric constant too long");
2023 void Error_InvalidDirective ()
2025 Report.Error (1517, Location, "Invalid preprocessor directive");
2028 void Error_UnexpectedDirective (string extra)
2032 "Unexpected processor directive ({0})", extra);
2035 void Error_TokensSeen ()
2037 Report.Error (1032, Location,
2038 "Cannot define or undefine preprocessor symbols after first token in file");
2041 void Eror_WrongPreprocessorLocation ()
2043 Report.Error (1040, Location,
2044 "Preprocessor directives must appear as the first non-whitespace character on a line");
2047 void Error_EndLineExpected ()
2049 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2052 void Warning_InvalidPragmaChecksum ()
2054 Report.Warning (1695, 1, Location,
2055 "Invalid #pragma checksum syntax; should be " +
2056 "#pragma checksum \"filename\" " +
2057 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2060 // if true, then the code continues processing the code
2061 // if false, the code stays in a loop until another directive is
2063 // When caller_is_taking is false we ignore all directives except the ones
2064 // which can help us to identify where the #if block ends
2065 bool handle_preprocessing_directive (bool caller_is_taking)
2068 bool region_directive = false;
2070 get_cmd_arg (out cmd, out arg);
2072 // Eat any trailing whitespaces and single-line comments
2073 if (arg.IndexOf ("//") != -1)
2074 arg = arg.Substring (0, arg.IndexOf ("//"));
2075 arg = arg.Trim (simple_whitespaces);
2078 // The first group of pre-processing instructions is always processed
2082 region_directive = true;
2087 if (ifstack == null || ifstack.Count == 0){
2088 Error_UnexpectedDirective ("no #region for this #endregion");
2091 int pop = (int) ifstack.Pop ();
2093 if ((pop & REGION) == 0)
2094 Report.Error (1027, Location, "Expected `#endif' directive");
2096 return caller_is_taking;
2099 if (ifstack == null)
2100 ifstack = new Stack (2);
2102 int flags = region_directive ? REGION : 0;
2103 if (ifstack.Count == 0){
2104 flags |= PARENT_TAKING;
2106 int state = (int) ifstack.Peek ();
2107 if ((state & TAKING) != 0) {
2108 flags |= PARENT_TAKING;
2112 if (caller_is_taking && eval (arg)) {
2113 ifstack.Push (flags | TAKING);
2116 ifstack.Push (flags);
2120 if (ifstack == null || ifstack.Count == 0){
2121 Error_UnexpectedDirective ("no #if for this #endif");
2124 pop = (int) ifstack.Pop ();
2126 if ((pop & REGION) != 0)
2127 Report.Error (1038, Location, "#endregion directive expected");
2129 if (arg.Length != 0) {
2130 Error_EndLineExpected ();
2133 if (ifstack.Count == 0)
2136 int state = (int) ifstack.Peek ();
2137 return (state & TAKING) != 0;
2141 if (ifstack == null || ifstack.Count == 0){
2142 Error_UnexpectedDirective ("no #if for this #elif");
2145 int state = (int) ifstack.Pop ();
2147 if ((state & REGION) != 0) {
2148 Report.Error (1038, Location, "#endregion directive expected");
2152 if ((state & ELSE_SEEN) != 0){
2153 Error_UnexpectedDirective ("#elif not valid after #else");
2157 if ((state & TAKING) != 0) {
2162 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2163 ifstack.Push (state | TAKING);
2167 ifstack.Push (state);
2172 if (ifstack == null || ifstack.Count == 0){
2173 Error_UnexpectedDirective ("no #if for this #else");
2176 int state = (int) ifstack.Peek ();
2178 if ((state & REGION) != 0) {
2179 Report.Error (1038, Location, "#endregion directive expected");
2183 if ((state & ELSE_SEEN) != 0){
2184 Error_UnexpectedDirective ("#else within #else");
2190 if (arg.Length != 0) {
2191 Error_EndLineExpected ();
2196 if ((state & PARENT_TAKING) != 0) {
2197 ret = (state & TAKING) == 0;
2205 ifstack.Push (state | ELSE_SEEN);
2210 if (any_token_seen){
2211 Error_TokensSeen ();
2212 return caller_is_taking;
2214 PreProcessDefinition (true, arg, caller_is_taking);
2215 return caller_is_taking;
2218 if (any_token_seen){
2219 Error_TokensSeen ();
2220 return caller_is_taking;
2222 PreProcessDefinition (false, arg, caller_is_taking);
2223 return caller_is_taking;
2227 // These are only processed if we are in a `taking' block
2229 if (!caller_is_taking)
2234 Report.Error (1029, Location, "#error: '{0}'", arg);
2238 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2242 if (RootContext.Version == LanguageVersion.ISO_1) {
2243 Report.FeatureIsNotAvailable (Location, "#pragma");
2247 PreProcessPragma (arg);
2251 if (!PreProcessLine (arg))
2254 "The line number specified for #line directive is missing or invalid");
2255 return caller_is_taking;
2258 Report.Error (1024, Location, "Wrong preprocessor directive");
2263 private int consume_string (bool quoted)
2266 string_builder.Length = 0;
2268 while ((c = get_char ()) != -1){
2270 if (quoted && peek_char () == '"'){
2271 string_builder.Append ((char) c);
2275 val = string_builder.ToString ();
2276 return Token.LITERAL_STRING;
2282 Report.Error (1010, Location, "Newline in constant");
2287 c = escape (c, out surrogate);
2290 if (surrogate != 0) {
2291 string_builder.Append ((char) c);
2295 string_builder.Append ((char) c);
2298 Report.Error (1039, Location, "Unterminated string literal");
2302 private int consume_identifier (int s)
2304 int res = consume_identifier (s, false);
2306 if (doc_state == XmlCommentState.Allowed)
2307 doc_state = XmlCommentState.NotAllowed;
2312 private int consume_identifier (int c, bool quoted)
2318 c = escape (c, out surrogate);
2319 if (surrogate != 0) {
2320 id_builder [pos++] = (char) c;
2325 id_builder [pos++] = (char) c;
2326 Location loc = Location;
2328 while ((c = get_char ()) != -1) {
2330 if (is_identifier_part_character ((char) c)){
2331 if (pos == max_id_size){
2332 Report.Error (645, loc, "Identifier too long (limit is 512 chars)");
2336 id_builder [pos++] = (char) c;
2337 } else if (c == '\\') {
2339 c = escape (c, out surrogate);
2340 if (surrogate != 0) {
2341 if (is_identifier_part_character ((char) c))
2342 id_builder [pos++] = (char) c;
2353 // Optimization: avoids doing the keyword lookup
2354 // on uppercase letters
2356 if (id_builder [0] >= '_' && !quoted) {
2357 int keyword = GetKeyword (id_builder, pos);
2358 if (keyword != -1) {
2359 // TODO: No need to store location for keyword, required location cleanup
2366 // Keep identifiers in an array of hashtables to avoid needless
2369 CharArrayHashtable identifiers_group = identifiers [pos];
2370 if (identifiers_group != null) {
2371 val = identifiers_group [id_builder];
2373 val = new LocatedToken (loc, (string) val);
2375 AddEscapedIdentifier ((LocatedToken) val);
2376 return Token.IDENTIFIER;
2379 identifiers_group = new CharArrayHashtable (pos);
2380 identifiers [pos] = identifiers_group;
2383 char [] chars = new char [pos];
2384 Array.Copy (id_builder, chars, pos);
2386 val = new String (id_builder, 0, pos);
2387 identifiers_group.Add (chars, val);
2389 if (RootContext.Version == LanguageVersion.ISO_1) {
2390 for (int i = 1; i < chars.Length; i += 3) {
2391 if (chars [i] == '_' && (chars [i - 1] == '_' || chars [i + 1] == '_')) {
2392 Report.Error (1638, loc,
2393 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2398 val = new LocatedToken (loc, (string) val);
2400 AddEscapedIdentifier ((LocatedToken) val);
2401 return Token.IDENTIFIER;
2404 public int xtoken ()
2408 // Whether we have seen comments on the current line
2409 bool comments_seen = false;
2410 while ((c = get_char ()) != -1) {
2413 col = ((col + 8) / 8) * 8;
2421 case 0xFEFF: // Ignore BOM anywhere in the file
2424 /* This is required for compatibility with .NET
2426 if (peek_char () == 0xBB) {
2429 if (get_char () == 0xBF)
2436 if (peek_char () != '\n')
2441 any_token_seen |= tokens_seen;
2442 tokens_seen = false;
2443 comments_seen = false;
2448 return consume_identifier (c);
2452 return Token.OPEN_BRACE;
2455 return Token.CLOSE_BRACE;
2457 // To block doccomment inside attribute declaration.
2458 if (doc_state == XmlCommentState.Allowed)
2459 doc_state = XmlCommentState.NotAllowed;
2460 return Token.OPEN_BRACKET;
2462 return Token.CLOSE_BRACKET;
2466 // An expression versions of parens can appear in block context only
2468 if (parsing_block != 0 && !lambda_arguments_parsing) {
2471 // Optmize most common case where we know that parens
2474 switch (current_token) {
2475 case Token.IDENTIFIER:
2483 case Token.DELEGATE:
2484 case Token.OP_GENERICS_GT:
2485 return Token.OPEN_PARENS;
2488 // Optimize using peek
2489 int xx = peek_char ();
2496 return Token.OPEN_PARENS;
2499 lambda_arguments_parsing = true;
2501 d = TokenizeOpenParens ();
2503 lambda_arguments_parsing = false;
2507 return Token.OPEN_PARENS;
2509 return Token.CLOSE_PARENS;
2513 return Token.SEMICOLON;
2517 return TokenizePossibleNullableType ();
2519 if (parsing_generic_less_than++ > 0)
2520 return Token.OP_GENERICS_LT;
2522 return TokenizeLessThan ();
2532 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2533 parsing_generic_less_than--;
2534 return Token.OP_GENERICS_GT;
2543 return Token.OP_SHIFT_RIGHT_ASSIGN;
2545 return Token.OP_SHIFT_RIGHT;
2554 } else if (d == '=') {
2555 d = Token.OP_ADD_ASSIGN;
2566 } else if (d == '=')
2567 d = Token.OP_SUB_ASSIGN;
2577 if (peek_char () == '='){
2594 return Token.ASSIGN;
2600 return Token.OP_AND;
2604 return Token.OP_AND_ASSIGN;
2606 return Token.BITWISE_AND;
2616 return Token.OP_OR_ASSIGN;
2618 return Token.BITWISE_OR;
2621 if (peek_char () == '='){
2623 return Token.OP_MULT_ASSIGN;
2632 return Token.OP_DIV_ASSIGN;
2635 // Handle double-slash comments.
2638 if (RootContext.Documentation != null && peek_char () == '/') {
2640 // Don't allow ////.
2641 if ((d = peek_char ()) != '/') {
2642 update_comment_location ();
2643 if (doc_state == XmlCommentState.Allowed)
2644 handle_one_line_xml_comment ();
2645 else if (doc_state == XmlCommentState.NotAllowed)
2646 warn_incorrect_doc_comment ();
2649 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2651 any_token_seen |= tokens_seen;
2652 tokens_seen = false;
2653 comments_seen = false;
2655 } else if (d == '*'){
2657 bool docAppend = false;
2658 if (RootContext.Documentation != null && peek_char () == '*') {
2660 update_comment_location ();
2661 // But when it is /**/, just do nothing.
2662 if (peek_char () == '/') {
2666 if (doc_state == XmlCommentState.Allowed)
2668 else if (doc_state == XmlCommentState.NotAllowed)
2669 warn_incorrect_doc_comment ();
2672 int current_comment_start = 0;
2674 current_comment_start = xml_comment_buffer.Length;
2675 xml_comment_buffer.Append (Environment.NewLine);
2678 while ((d = get_char ()) != -1){
2679 if (d == '*' && peek_char () == '/'){
2681 comments_seen = true;
2685 xml_comment_buffer.Append ((char) d);
2688 any_token_seen |= tokens_seen;
2689 tokens_seen = false;
2691 // Reset 'comments_seen' just to be consistent.
2692 // It doesn't matter either way, here.
2694 comments_seen = false;
2698 Report.Error (1035, Location, "End-of-file found, '*/' expected");
2701 update_formatted_doc_comment (current_comment_start);
2707 if (peek_char () == '='){
2709 return Token.OP_MOD_ASSIGN;
2711 return Token.PERCENT;
2714 if (peek_char () == '='){
2716 return Token.OP_XOR_ASSIGN;
2718 return Token.CARRET;
2721 if (peek_char () == ':') {
2723 return Token.DOUBLE_COLON;
2727 case '0': case '1': case '2': case '3': case '4':
2728 case '5': case '6': case '7': case '8': case '9':
2730 return is_number (c);
2732 case '\n': // white space
2733 any_token_seen |= tokens_seen;
2734 tokens_seen = false;
2735 comments_seen = false;
2741 if (d >= '0' && d <= '9')
2742 return is_number (c);
2746 if (tokens_seen || comments_seen) {
2747 Eror_WrongPreprocessorLocation ();
2751 if (handle_preprocessing_directive (true))
2754 bool directive_expected = false;
2755 while ((c = get_char ()) != -1) {
2757 directive_expected = true;
2758 } else if (!directive_expected) {
2759 // TODO: Implement comment support for disabled code and uncomment this code
2761 // Eror_WrongPreprocessorLocation ();
2762 // return Token.ERROR;
2767 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2771 if (handle_preprocessing_directive (false))
2774 directive_expected = false;
2778 tokens_seen = false;
2785 return consume_string (false);
2788 return TokenizeBackslash ();
2794 return consume_string (true);
2797 if (is_identifier_start_character (c)){
2798 return consume_identifier (c, true);
2801 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2804 case EvalStatementParserCharacter:
2805 return Token.EVAL_STATEMENT_PARSER;
2806 case EvalCompilationUnitParserCharacter:
2807 return Token.EVAL_COMPILATION_UNIT_PARSER;
2808 case EvalUsingDeclarationsParserCharacter:
2809 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2812 if (is_identifier_start_character (c)) {
2814 return consume_identifier (c);
2817 error_details = ((char)c).ToString ();
2824 int TokenizeBackslash ()
2826 int c = get_char ();
2829 error_details = "Empty character literal";
2830 Report.Error (1011, Location, error_details);
2833 if (c == '\r' || c == '\n') {
2834 Report.Error (1010, Location, "Newline in constant");
2839 c = escape (c, out d);
2843 throw new NotImplementedException ();
2849 Report.Error (1012, Location, "Too many characters in character literal");
2851 // Try to recover, read until newline or next "'"
2852 while ((c = get_char ()) != -1) {
2853 if (c == '\n' || c == '\'')
2859 return Token.LITERAL_CHARACTER;
2862 int TokenizeLessThan ()
2865 if (handle_typeof) {
2867 if (parse_generic_dimension (out d)) {
2870 return Token.GENERIC_DIMENSION;
2875 // Save current position and parse next token.
2877 if (parse_less_than ()) {
2878 if (parsing_generic_declaration && token () != Token.DOT) {
2879 d = Token.OP_GENERICS_LT_DECL;
2881 d = Token.OP_GENERICS_LT;
2888 parsing_generic_less_than = 0;
2897 return Token.OP_SHIFT_LEFT_ASSIGN;
2899 return Token.OP_SHIFT_LEFT;
2910 // Handles one line xml comment
2912 private void handle_one_line_xml_comment ()
2915 while ((c = peek_char ()) == ' ')
2916 get_char (); // skip heading whitespaces.
2917 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2918 xml_comment_buffer.Append ((char) get_char ());
2920 if (c == '\r' || c == '\n')
2921 xml_comment_buffer.Append (Environment.NewLine);
2925 // Remove heading "*" in Javadoc-like xml documentation.
2927 private void update_formatted_doc_comment (int current_comment_start)
2929 int length = xml_comment_buffer.Length - current_comment_start;
2930 string [] lines = xml_comment_buffer.ToString (
2931 current_comment_start,
2932 length).Replace ("\r", "").Split ('\n');
2934 // The first line starts with /**, thus it is not target
2935 // for the format check.
2936 for (int i = 1; i < lines.Length; i++) {
2937 string s = lines [i];
2938 int idx = s.IndexOf ('*');
2941 if (i < lines.Length - 1)
2945 head = s.Substring (0, idx);
2946 foreach (char c in head)
2949 lines [i] = s.Substring (idx + 1);
2951 xml_comment_buffer.Remove (current_comment_start, length);
2952 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2956 // Updates current comment location.
2958 private void update_comment_location ()
2960 if (current_comment_location.IsNull) {
2961 // "-2" is for heading "//" or "/*"
2962 current_comment_location =
2963 new Location (ref_line, hidden ? -1 : col - 2);
2968 // Checks if there was incorrect doc comments and raise
2971 public void check_incorrect_doc_comment ()
2973 if (xml_comment_buffer.Length > 0)
2974 warn_incorrect_doc_comment ();
2978 // Raises a warning when tokenizer found incorrect doccomment
2981 private void warn_incorrect_doc_comment ()
2983 if (doc_state != XmlCommentState.Error) {
2984 doc_state = XmlCommentState.Error;
2985 // in csc, it is 'XML comment is not placed on
2986 // a valid language element'. But that does not
2988 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2993 // Consumes the saved xml comment lines (if any)
2994 // as for current target member or type.
2996 public string consume_doc_comment ()
2998 if (xml_comment_buffer.Length > 0) {
2999 string ret = xml_comment_buffer.ToString ();
3000 reset_doc_comment ();
3006 void reset_doc_comment ()
3008 xml_comment_buffer.Length = 0;
3009 current_comment_location = Location.Null;
3012 public void cleanup ()
3014 if (ifstack != null && ifstack.Count >= 1) {
3015 int state = (int) ifstack.Pop ();
3016 if ((state & REGION) != 0)
3017 Report.Error (1038, Location, "#endregion directive expected");
3019 Report.Error (1027, Location, "Expected `#endif' directive");
3025 // Indicates whether it accepts XML documentation or not.
3027 public enum XmlCommentState {
3028 // comment is allowed in this state.
3030 // comment is not allowed in this state.
3032 // once comments appeared when it is NotAllowed, then the
3033 // state is changed to it, until the state is changed to