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 int 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 == 0)
452 // A query expression is any expression that starts with `from identifier'
453 // followed by any token except ; , =
455 if (query_parsing == 0) {
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)
483 if (RootContext.Version <= LanguageVersion.ISO_2)
484 Report.FeatureIsNotAvailable (Location, "query expressions");
487 Expression.Error_VoidInvalidInTheContext (Location);
491 // HACK: A token is not a keyword so we need to restore identifiers buffer
492 // which has been overwritten before we grabbed the identifier
493 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
507 case Token.ASCENDING:
508 case Token.DESCENDING:
510 if (query_parsing == 0)
515 case Token.NAMESPACE:
516 // TODO: some explanation needed
517 check_incorrect_doc_comment ();
521 if (parsing_block > 0) {
526 // Save current position and parse next token.
529 next_token = token ();
530 bool ok = (next_token == Token.CLASS) ||
531 (next_token == Token.STRUCT) ||
532 (next_token == Token.INTERFACE) ||
533 (next_token == Token.VOID);
538 if (next_token == Token.VOID) {
539 if (RootContext.Version == LanguageVersion.ISO_1 ||
540 RootContext.Version == LanguageVersion.ISO_2)
541 Report.FeatureIsNotAvailable (Location, "partial methods");
542 } else if (RootContext.Version == LanguageVersion.ISO_1)
543 Report.FeatureIsNotAvailable (Location, "partial types");
548 if (next_token < Token.LAST_KEYWORD) {
549 Report.Error (267, Location,
550 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
561 public Location Location {
563 return new Location (ref_line, hidden ? -1 : col);
567 public Tokenizer (SeekableStreamReader input, CompilationUnit file)
569 this.ref_name = file;
570 this.file_name = file;
575 xml_comment_buffer = new StringBuilder ();
578 // FIXME: This could be `Location.Push' but we have to
579 // find out why the MS compiler allows this
581 Mono.CSharp.Location.Push (file, file);
584 static bool is_identifier_start_character (int c)
586 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
589 static bool is_identifier_part_character (char c)
591 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') ||
592 Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
595 public static bool IsKeyword (string s)
597 return keyword_strings [s] != null;
601 // Open parens micro parser. Detects both lambda and cast ambiguity.
604 int TokenizeOpenParens ()
609 int bracket_level = 0;
610 bool is_type = false;
611 bool can_be_type = false;
614 ptoken = current_token;
617 switch (current_token) {
618 case Token.CLOSE_PARENS:
622 // Expression inside parens is lambda, (int i) =>
624 if (current_token == Token.ARROW) {
625 if (RootContext.Version <= LanguageVersion.ISO_2)
626 Report.FeatureIsNotAvailable (Location, "lambda expressions");
628 return Token.OPEN_PARENS_LAMBDA;
632 // Expression inside parens is single type, (int[])
635 return Token.OPEN_PARENS_CAST;
638 // Expression is possible cast, look at next token, (T)null
641 switch (current_token) {
642 case Token.OPEN_PARENS:
645 case Token.IDENTIFIER:
646 case Token.LITERAL_INTEGER:
647 case Token.LITERAL_FLOAT:
648 case Token.LITERAL_DOUBLE:
649 case Token.LITERAL_DECIMAL:
650 case Token.LITERAL_CHARACTER:
651 case Token.LITERAL_STRING:
664 case Token.UNCHECKED:
669 // These can be part of a member access
683 return Token.OPEN_PARENS_CAST;
686 return Token.OPEN_PARENS;
689 case Token.DOUBLE_COLON:
690 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
695 case Token.IDENTIFIER:
698 case Token.OP_GENERICS_LT:
700 case Token.DOUBLE_COLON:
702 if (bracket_level == 0)
706 can_be_type = is_type = false;
726 if (bracket_level == 0)
731 if (bracket_level == 0) {
733 can_be_type = is_type = false;
737 case Token.OP_GENERICS_LT:
738 case Token.OPEN_BRACKET:
739 if (bracket_level++ == 0)
743 case Token.OP_GENERICS_GT:
744 case Token.CLOSE_BRACKET:
748 case Token.INTERR_NULLABLE:
750 if (bracket_level == 0)
756 can_be_type = is_type = false;
760 return Token.OPEN_PARENS;
765 public static bool IsValidIdentifier (string s)
767 if (s == null || s.Length == 0)
770 if (!is_identifier_start_character (s [0]))
773 for (int i = 1; i < s.Length; i ++)
774 if (! is_identifier_part_character (s [i]))
780 bool parse_less_than ()
783 int the_token = token ();
784 if (the_token == Token.OPEN_BRACKET) {
786 the_token = token ();
787 } while (the_token != Token.CLOSE_BRACKET);
788 the_token = token ();
791 case Token.IDENTIFIER:
810 case Token.OP_GENERICS_GT:
817 the_token = token ();
819 if (the_token == Token.OP_GENERICS_GT)
821 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
823 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
825 else if (the_token == Token.OP_GENERICS_LT) {
826 if (!parse_less_than ())
829 } else if (the_token == Token.OPEN_BRACKET) {
831 the_token = token ();
832 if (the_token == Token.CLOSE_BRACKET)
834 else if (the_token == Token.COMMA)
835 goto rank_specifiers;
842 bool parse_generic_dimension (out int dimension)
847 int the_token = token ();
848 if (the_token == Token.OP_GENERICS_GT)
850 else if (the_token == Token.COMMA) {
858 public int peek_token ()
863 the_token = token ();
870 // Tonizes `?' using custom disambiguous rules to return one
871 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
873 // Tricky expression look like:
875 // Foo ? a = x ? b : c;
877 int TokenizePossibleNullableType ()
879 if (parsing_block == 0 || parsing_type > 0)
880 return Token.INTERR_NULLABLE;
882 int d = peek_char ();
885 return Token.OP_COALESCING;
888 switch (current_token) {
889 case Token.CLOSE_PARENS:
893 case Token.LITERAL_INTEGER:
894 case Token.LITERAL_STRING:
899 if (d == ',' || d == ';' || d == '>')
900 return Token.INTERR_NULLABLE;
901 if (d == '*' || (d >= '0' && d <= '9'))
906 current_token = Token.NONE;
909 case Token.LITERAL_INTEGER:
910 case Token.LITERAL_STRING:
911 case Token.LITERAL_CHARACTER:
912 case Token.LITERAL_DECIMAL:
913 case Token.LITERAL_DOUBLE:
914 case Token.LITERAL_FLOAT:
920 next_token = Token.INTERR;
923 case Token.SEMICOLON:
925 case Token.CLOSE_PARENS:
926 case Token.OPEN_BRACKET:
927 case Token.OP_GENERICS_GT:
928 next_token = Token.INTERR_NULLABLE;
936 if (next_token == -1) {
939 case Token.SEMICOLON:
940 case Token.OPEN_BRACE:
941 case Token.CLOSE_PARENS:
943 next_token = Token.INTERR_NULLABLE;
947 next_token = Token.INTERR;
955 // All shorcuts failed, do it hard way
957 while ((ntoken = xtoken ()) != Token.EOF) {
958 if (ntoken == Token.SEMICOLON)
961 if (ntoken == Token.COLON) {
962 if (++colons == interrs)
967 if (ntoken == Token.INTERR) {
973 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
982 bool decimal_digits (int c)
985 bool seen_digits = false;
988 if (number_pos == max_number_size)
989 Error_NumericConstantTooLong ();
990 number_builder [number_pos++] = (char) c;
994 // We use peek_char2, because decimal_digits needs to do a
995 // 2-character look-ahead (5.ToString for example).
997 while ((d = peek_char2 ()) != -1){
998 if (d >= '0' && d <= '9'){
999 if (number_pos == max_number_size)
1000 Error_NumericConstantTooLong ();
1001 number_builder [number_pos++] = (char) d;
1011 static bool is_hex (int e)
1013 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1016 static int real_type_suffix (int c)
1022 t = Token.LITERAL_FLOAT;
1025 t = Token.LITERAL_DOUBLE;
1028 t= Token.LITERAL_DECIMAL;
1036 int integer_type_suffix (ulong ul, int c)
1038 bool is_unsigned = false;
1039 bool is_long = false;
1042 bool scanning = true;
1055 // if we have not seen anything in between
1056 // report this error
1058 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1061 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1062 // work around that.
1086 if (is_long && is_unsigned){
1088 return Token.LITERAL_INTEGER;
1089 } else if (is_unsigned){
1090 // uint if possible, or ulong else.
1092 if ((ul & 0xffffffff00000000) == 0)
1096 } else if (is_long){
1097 // long if possible, ulong otherwise
1098 if ((ul & 0x8000000000000000) != 0)
1103 // int, uint, long or ulong in that order
1104 if ((ul & 0xffffffff00000000) == 0){
1105 uint ui = (uint) ul;
1107 if ((ui & 0x80000000) != 0)
1112 if ((ul & 0x8000000000000000) != 0)
1118 return Token.LITERAL_INTEGER;
1122 // given `c' as the next char in the input decide whether
1123 // we need to convert to a special type, and then choose
1124 // the best representation for the integer
1126 int adjust_int (int c)
1129 if (number_pos > 9){
1130 ulong ul = (uint) (number_builder [0] - '0');
1132 for (int i = 1; i < number_pos; i++){
1133 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1135 return integer_type_suffix (ul, c);
1137 uint ui = (uint) (number_builder [0] - '0');
1139 for (int i = 1; i < number_pos; i++){
1140 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1142 return integer_type_suffix (ui, c);
1144 } catch (OverflowException) {
1145 error_details = "Integral constant is too large";
1146 Report.Error (1021, Location, error_details);
1148 return Token.LITERAL_INTEGER;
1150 catch (FormatException) {
1151 Report.Error (1013, Location, "Invalid number");
1153 return Token.LITERAL_INTEGER;
1157 int adjust_real (int t)
1159 string s = new String (number_builder, 0, number_pos);
1160 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1163 case Token.LITERAL_DECIMAL:
1165 val = System.Decimal.Parse (s, styles, csharp_format_info);
1166 } catch (OverflowException) {
1168 Report.Error (594, Location, error_details, "decimal");
1171 case Token.LITERAL_FLOAT:
1173 val = float.Parse (s, styles, csharp_format_info);
1174 } catch (OverflowException) {
1176 Report.Error (594, Location, error_details, "float");
1180 case Token.LITERAL_DOUBLE:
1182 t = Token.LITERAL_DOUBLE;
1184 val = System.Double.Parse (s, styles, csharp_format_info);
1185 } catch (OverflowException) {
1187 Report.Error (594, Location, error_details, "double");
1200 while ((d = peek_char ()) != -1){
1202 number_builder [number_pos++] = (char) d;
1208 string s = new String (number_builder, 0, number_pos);
1210 if (number_pos <= 8)
1211 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1213 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1214 } catch (OverflowException){
1215 error_details = "Integral constant is too large";
1216 Report.Error (1021, Location, error_details);
1218 return Token.LITERAL_INTEGER;
1220 catch (FormatException) {
1221 Report.Error (1013, Location, "Invalid number");
1223 return Token.LITERAL_INTEGER;
1226 return integer_type_suffix (ul, peek_char ());
1230 // Invoked if we know we have .digits or digits
1232 int is_number (int c)
1234 bool is_real = false;
1239 if (c >= '0' && c <= '9'){
1241 int peek = peek_char ();
1243 if (peek == 'x' || peek == 'X')
1244 return handle_hex ();
1251 // We need to handle the case of
1252 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1255 if (decimal_digits ('.')){
1261 return adjust_int (-1);
1265 if (c == 'e' || c == 'E'){
1267 if (number_pos == max_number_size)
1268 Error_NumericConstantTooLong ();
1269 number_builder [number_pos++] = 'e';
1273 if (number_pos == max_number_size)
1274 Error_NumericConstantTooLong ();
1275 number_builder [number_pos++] = '+';
1277 } else if (c == '-') {
1278 if (number_pos == max_number_size)
1279 Error_NumericConstantTooLong ();
1280 number_builder [number_pos++] = '-';
1283 if (number_pos == max_number_size)
1284 Error_NumericConstantTooLong ();
1285 number_builder [number_pos++] = '+';
1292 type = real_type_suffix (c);
1293 if (type == Token.NONE && !is_real){
1295 return adjust_int (c);
1299 if (type == Token.NONE){
1304 return adjust_real (type);
1306 Console.WriteLine ("This should not be reached");
1307 throw new Exception ("Is Number should never reach this point");
1311 // Accepts exactly count (4 or 8) hex, no more no less
1313 int getHex (int count, out int surrogate, out bool error)
1318 int top = count != -1 ? count : 4;
1323 for (i = 0; i < top; i++){
1326 if (c >= '0' && c <= '9')
1327 c = (int) c - (int) '0';
1328 else if (c >= 'A' && c <= 'F')
1329 c = (int) c - (int) 'A' + 10;
1330 else if (c >= 'a' && c <= 'f')
1331 c = (int) c - (int) 'a' + 10;
1337 total = (total * 16) + c;
1339 int p = peek_char ();
1342 if (!is_hex ((char)p))
1348 if (total > 0x0010FFFF) {
1353 if (total >= 0x00010000) {
1354 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1355 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1362 int escape (int c, out int surrogate)
1398 v = getHex (-1, out surrogate, out error);
1404 return EscapeUnicode (d, out surrogate);
1407 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1416 int EscapeUnicode (int ch, out int surrogate)
1420 ch = getHex (8, out surrogate, out error);
1422 ch = getHex (4, out surrogate, out error);
1426 Report.Error (1009, Location, "Unrecognized escape sequence");
1434 if (putback_char != -1) {
1447 void advance_line ()
1457 if (putback_char == -1)
1458 putback_char = reader.Read ();
1459 return putback_char;
1464 if (putback_char != -1)
1465 return putback_char;
1466 return reader.Peek ();
1469 void putback (int c)
1471 if (putback_char != -1){
1472 Console.WriteLine ("Col: " + col);
1473 Console.WriteLine ("Row: " + line);
1474 Console.WriteLine ("Name: " + ref_name.Name);
1475 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1476 throw new Exception ("This should not happen putback on putback");
1478 if (c == '\n' || col == 0) {
1479 // It won't happen though.
1489 public bool advance ()
1491 return peek_char () != -1;
1494 public Object Value {
1500 public Object value ()
1507 current_token = xtoken ();
1508 return current_token;
1511 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1513 void get_cmd_arg (out string cmd, out string arg)
1517 tokens_seen = false;
1520 // skip over white space
1523 } while (c == '\r' || c == ' ' || c == '\t');
1525 static_cmd_arg.Length = 0;
1526 while (c != -1 && is_identifier_part_character ((char)c)) {
1527 static_cmd_arg.Append ((char)c);
1530 int peek = peek_char ();
1531 if (peek == 'U' || peek == 'u') {
1533 c = EscapeUnicode (c, out surrogate);
1534 if (surrogate != 0) {
1535 if (is_identifier_part_character ((char) c))
1536 static_cmd_arg.Append ((char) c);
1543 cmd = static_cmd_arg.ToString ();
1545 // skip over white space
1546 while (c == '\r' || c == ' ' || c == '\t')
1549 static_cmd_arg.Length = 0;
1550 int has_identifier_argument = 0;
1552 while (c != -1 && c != '\n' && c != '\r') {
1553 if (c == '\\' && has_identifier_argument >= 0) {
1554 if (has_identifier_argument != 0 || (cmd == "define" || cmd == "if" || cmd == "elif" || cmd == "undef")) {
1555 has_identifier_argument = 1;
1557 int peek = peek_char ();
1558 if (peek == 'U' || peek == 'u') {
1560 c = EscapeUnicode (c, out surrogate);
1561 if (surrogate != 0) {
1562 if (is_identifier_part_character ((char) c))
1563 static_cmd_arg.Append ((char) c);
1568 has_identifier_argument = -1;
1571 static_cmd_arg.Append ((char) c);
1575 if (static_cmd_arg.Length != 0)
1576 arg = static_cmd_arg.ToString ();
1580 // Handles the #line directive
1582 bool PreProcessLine (string arg)
1584 if (arg.Length == 0)
1587 if (arg == "default"){
1589 ref_name = file_name;
1591 Location.Push (file_name, ref_name);
1593 } else if (arg == "hidden"){
1601 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1602 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1605 char [] quotes = { '\"' };
1607 string name = arg.Substring (pos). Trim (quotes);
1608 ref_name = Location.LookupFile (file_name, name);
1609 file_name.AddFile (ref_name);
1611 Location.Push (file_name, ref_name);
1613 ref_line = System.Int32.Parse (arg);
1624 // Handles #define and #undef
1626 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1628 if (ident.Length == 0 || ident == "true" || ident == "false"){
1629 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1633 if (ident.IndexOfAny (simple_whitespaces) != -1){
1634 Error_EndLineExpected ();
1638 if (!is_identifier_start_character (ident [0]))
1639 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1641 foreach (char c in ident.Substring (1)){
1642 if (!is_identifier_part_character (c)){
1643 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1648 if (!caller_is_taking)
1655 if (RootContext.IsConditionalDefined (ident))
1658 file_name.AddDefine (ident);
1663 file_name.AddUndefine (ident);
1667 static byte read_hex (string arg, int pos, out bool error)
1674 if ((c >= '0') && (c <= '9'))
1675 total = (int) c - (int) '0';
1676 else if ((c >= 'A') && (c <= 'F'))
1677 total = (int) c - (int) 'A' + 10;
1678 else if ((c >= 'a') && (c <= 'f'))
1679 total = (int) c - (int) 'a' + 10;
1688 if ((c >= '0') && (c <= '9'))
1689 total += (int) c - (int) '0';
1690 else if ((c >= 'A') && (c <= 'F'))
1691 total += (int) c - (int) 'A' + 10;
1692 else if ((c >= 'a') && (c <= 'f'))
1693 total += (int) c - (int) 'a' + 10;
1699 return (byte) total;
1703 /// Handles #pragma checksum
1705 bool PreProcessPragmaChecksum (string arg)
1707 if ((arg [0] != ' ') && (arg [0] != '\t'))
1710 arg = arg.Trim (simple_whitespaces);
1711 if ((arg.Length < 2) || (arg [0] != '"'))
1714 StringBuilder file_sb = new StringBuilder ();
1718 while ((ch = arg [pos++]) != '"') {
1719 if (pos >= arg.Length)
1723 if (pos+1 >= arg.Length)
1728 file_sb.Append (ch);
1731 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1734 arg = arg.Substring (pos).Trim (simple_whitespaces);
1735 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1736 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1737 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1741 byte[] guid_bytes = new byte [16];
1743 for (int i = 0; i < 4; i++) {
1744 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1748 for (int i = 0; i < 2; i++) {
1749 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1752 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1755 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1760 for (int i = 0; i < 6; i++) {
1761 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1766 arg = arg.Substring (40).Trim (simple_whitespaces);
1767 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1770 byte[] checksum_bytes = new byte [16];
1771 for (int i = 0; i < 16; i++) {
1772 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1777 arg = arg.Substring (34).Trim (simple_whitespaces);
1781 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1782 file.SetChecksum (guid_bytes, checksum_bytes);
1783 ref_name.AutoGenerated = true;
1788 /// Handles #pragma directive
1790 void PreProcessPragma (string arg)
1792 const string warning = "warning";
1793 const string w_disable = "warning disable";
1794 const string w_restore = "warning restore";
1795 const string checksum = "checksum";
1797 if (arg == w_disable) {
1798 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1802 if (arg == w_restore) {
1803 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1807 if (arg.StartsWith (w_disable)) {
1808 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1809 foreach (int code in codes) {
1811 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1816 if (arg.StartsWith (w_restore)) {
1817 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1818 Hashtable w_table = Report.warning_ignore_table;
1819 foreach (int code in codes) {
1820 if (w_table != null && w_table.Contains (code))
1821 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1822 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1827 if (arg.StartsWith (warning)) {
1828 Report.Warning (1634, 1, Location, "Expected disable or restore");
1832 if (arg.StartsWith (checksum)) {
1833 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1834 Warning_InvalidPragmaChecksum ();
1838 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1841 int[] ParseNumbers (string text)
1843 string[] string_array = text.Split (',');
1844 int[] values = new int [string_array.Length];
1846 foreach (string string_code in string_array) {
1848 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1850 catch (FormatException) {
1851 Report.Warning (1692, 1, Location, "Invalid number");
1857 bool eval_val (string s)
1864 return file_name.IsConditionalDefined (s);
1867 bool pp_primary (ref string s)
1876 s = s.Substring (1);
1877 bool val = pp_expr (ref s, false);
1878 if (s.Length > 0 && s [0] == ')'){
1879 s = s.Substring (1);
1882 Error_InvalidDirective ();
1886 if (is_identifier_start_character (c)){
1892 if (is_identifier_part_character (c)){
1896 bool v = eval_val (s.Substring (0, j));
1897 s = s.Substring (j);
1900 bool vv = eval_val (s);
1905 Error_InvalidDirective ();
1909 bool pp_unary (ref string s)
1916 if (len > 1 && s [1] == '='){
1917 Error_InvalidDirective ();
1920 s = s.Substring (1);
1921 return ! pp_primary (ref s);
1923 return pp_primary (ref s);
1925 Error_InvalidDirective ();
1930 bool pp_eq (ref string s)
1932 bool va = pp_unary (ref s);
1938 if (len > 2 && s [1] == '='){
1939 s = s.Substring (2);
1940 return va == pp_unary (ref s);
1942 Error_InvalidDirective ();
1945 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1946 s = s.Substring (2);
1948 return va != pp_unary (ref s);
1957 bool pp_and (ref string s)
1959 bool va = pp_eq (ref s);
1965 if (len > 2 && s [1] == '&'){
1966 s = s.Substring (2);
1967 return (va & pp_and (ref s));
1969 Error_InvalidDirective ();
1978 // Evaluates an expression for `#if' or `#elif'
1980 bool pp_expr (ref string s, bool isTerm)
1982 bool va = pp_and (ref s);
1989 if (len > 2 && s [1] == '|'){
1990 s = s.Substring (2);
1991 return va | pp_expr (ref s, isTerm);
1993 Error_InvalidDirective ();
1998 Error_EndLineExpected ();
2006 bool eval (string s)
2008 bool v = pp_expr (ref s, true);
2017 void Error_NumericConstantTooLong ()
2019 Report.Error (1021, Location, "Numeric constant too long");
2022 void Error_InvalidDirective ()
2024 Report.Error (1517, Location, "Invalid preprocessor directive");
2027 void Error_UnexpectedDirective (string extra)
2031 "Unexpected processor directive ({0})", extra);
2034 void Error_TokensSeen ()
2036 Report.Error (1032, Location,
2037 "Cannot define or undefine preprocessor symbols after first token in file");
2040 void Eror_WrongPreprocessorLocation ()
2042 Report.Error (1040, Location,
2043 "Preprocessor directives must appear as the first non-whitespace character on a line");
2046 void Error_EndLineExpected ()
2048 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2051 void Warning_InvalidPragmaChecksum ()
2053 Report.Warning (1695, 1, Location,
2054 "Invalid #pragma checksum syntax; should be " +
2055 "#pragma checksum \"filename\" " +
2056 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2059 // if true, then the code continues processing the code
2060 // if false, the code stays in a loop until another directive is
2062 // When caller_is_taking is false we ignore all directives except the ones
2063 // which can help us to identify where the #if block ends
2064 bool handle_preprocessing_directive (bool caller_is_taking)
2067 bool region_directive = false;
2069 get_cmd_arg (out cmd, out arg);
2071 // Eat any trailing whitespaces and single-line comments
2072 if (arg.IndexOf ("//") != -1)
2073 arg = arg.Substring (0, arg.IndexOf ("//"));
2074 arg = arg.Trim (simple_whitespaces);
2077 // The first group of pre-processing instructions is always processed
2081 region_directive = true;
2086 if (ifstack == null || ifstack.Count == 0){
2087 Error_UnexpectedDirective ("no #region for this #endregion");
2090 int pop = (int) ifstack.Pop ();
2092 if ((pop & REGION) == 0)
2093 Report.Error (1027, Location, "Expected `#endif' directive");
2095 return caller_is_taking;
2098 if (ifstack == null)
2099 ifstack = new Stack (2);
2101 int flags = region_directive ? REGION : 0;
2102 if (ifstack.Count == 0){
2103 flags |= PARENT_TAKING;
2105 int state = (int) ifstack.Peek ();
2106 if ((state & TAKING) != 0) {
2107 flags |= PARENT_TAKING;
2111 if (caller_is_taking && eval (arg)) {
2112 ifstack.Push (flags | TAKING);
2115 ifstack.Push (flags);
2119 if (ifstack == null || ifstack.Count == 0){
2120 Error_UnexpectedDirective ("no #if for this #endif");
2123 pop = (int) ifstack.Pop ();
2125 if ((pop & REGION) != 0)
2126 Report.Error (1038, Location, "#endregion directive expected");
2128 if (arg.Length != 0) {
2129 Error_EndLineExpected ();
2132 if (ifstack.Count == 0)
2135 int state = (int) ifstack.Peek ();
2136 return (state & TAKING) != 0;
2140 if (ifstack == null || ifstack.Count == 0){
2141 Error_UnexpectedDirective ("no #if for this #elif");
2144 int state = (int) ifstack.Pop ();
2146 if ((state & REGION) != 0) {
2147 Report.Error (1038, Location, "#endregion directive expected");
2151 if ((state & ELSE_SEEN) != 0){
2152 Error_UnexpectedDirective ("#elif not valid after #else");
2156 if ((state & TAKING) != 0) {
2161 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2162 ifstack.Push (state | TAKING);
2166 ifstack.Push (state);
2171 if (ifstack == null || ifstack.Count == 0){
2172 Error_UnexpectedDirective ("no #if for this #else");
2175 int state = (int) ifstack.Peek ();
2177 if ((state & REGION) != 0) {
2178 Report.Error (1038, Location, "#endregion directive expected");
2182 if ((state & ELSE_SEEN) != 0){
2183 Error_UnexpectedDirective ("#else within #else");
2189 if (arg.Length != 0) {
2190 Error_EndLineExpected ();
2195 if ((state & PARENT_TAKING) != 0) {
2196 ret = (state & TAKING) == 0;
2204 ifstack.Push (state | ELSE_SEEN);
2209 if (any_token_seen){
2210 Error_TokensSeen ();
2211 return caller_is_taking;
2213 PreProcessDefinition (true, arg, caller_is_taking);
2214 return caller_is_taking;
2217 if (any_token_seen){
2218 Error_TokensSeen ();
2219 return caller_is_taking;
2221 PreProcessDefinition (false, arg, caller_is_taking);
2222 return caller_is_taking;
2226 // These are only processed if we are in a `taking' block
2228 if (!caller_is_taking)
2233 Report.Error (1029, Location, "#error: '{0}'", arg);
2237 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2241 if (RootContext.Version == LanguageVersion.ISO_1) {
2242 Report.FeatureIsNotAvailable (Location, "#pragma");
2246 PreProcessPragma (arg);
2250 if (!PreProcessLine (arg))
2253 "The line number specified for #line directive is missing or invalid");
2254 return caller_is_taking;
2257 Report.Error (1024, Location, "Wrong preprocessor directive");
2262 private int consume_string (bool quoted)
2265 string_builder.Length = 0;
2267 while ((c = get_char ()) != -1){
2269 if (quoted && peek_char () == '"'){
2270 string_builder.Append ((char) c);
2274 val = string_builder.ToString ();
2275 return Token.LITERAL_STRING;
2281 Report.Error (1010, Location, "Newline in constant");
2286 c = escape (c, out surrogate);
2289 if (surrogate != 0) {
2290 string_builder.Append ((char) c);
2294 string_builder.Append ((char) c);
2297 Report.Error (1039, Location, "Unterminated string literal");
2301 private int consume_identifier (int s)
2303 int res = consume_identifier (s, false);
2305 if (doc_state == XmlCommentState.Allowed)
2306 doc_state = XmlCommentState.NotAllowed;
2311 private int consume_identifier (int c, bool quoted)
2317 c = escape (c, out surrogate);
2318 if (surrogate != 0) {
2319 id_builder [pos++] = (char) c;
2324 id_builder [pos++] = (char) c;
2325 Location loc = Location;
2327 while ((c = get_char ()) != -1) {
2329 if (is_identifier_part_character ((char) c)){
2330 if (pos == max_id_size){
2331 Report.Error (645, loc, "Identifier too long (limit is 512 chars)");
2335 id_builder [pos++] = (char) c;
2336 } else if (c == '\\') {
2338 c = escape (c, out surrogate);
2339 if (surrogate != 0) {
2340 if (is_identifier_part_character ((char) c))
2341 id_builder [pos++] = (char) c;
2352 // Optimization: avoids doing the keyword lookup
2353 // on uppercase letters
2355 if (id_builder [0] >= '_' && !quoted) {
2356 int keyword = GetKeyword (id_builder, pos);
2357 if (keyword != -1) {
2358 // TODO: No need to store location for keyword, required location cleanup
2365 // Keep identifiers in an array of hashtables to avoid needless
2368 CharArrayHashtable identifiers_group = identifiers [pos];
2369 if (identifiers_group != null) {
2370 val = identifiers_group [id_builder];
2372 val = new LocatedToken (loc, (string) val);
2374 AddEscapedIdentifier ((LocatedToken) val);
2375 return Token.IDENTIFIER;
2378 identifiers_group = new CharArrayHashtable (pos);
2379 identifiers [pos] = identifiers_group;
2382 char [] chars = new char [pos];
2383 Array.Copy (id_builder, chars, pos);
2385 val = new String (id_builder, 0, pos);
2386 identifiers_group.Add (chars, val);
2388 if (RootContext.Version == LanguageVersion.ISO_1) {
2389 for (int i = 1; i < chars.Length; i += 3) {
2390 if (chars [i] == '_' && (chars [i - 1] == '_' || chars [i + 1] == '_')) {
2391 Report.Error (1638, loc,
2392 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2397 val = new LocatedToken (loc, (string) val);
2399 AddEscapedIdentifier ((LocatedToken) val);
2400 return Token.IDENTIFIER;
2403 public int xtoken ()
2407 // Whether we have seen comments on the current line
2408 bool comments_seen = false;
2409 while ((c = get_char ()) != -1) {
2412 col = ((col + 8) / 8) * 8;
2420 case 0xFEFF: // Ignore BOM anywhere in the file
2423 /* This is required for compatibility with .NET
2425 if (peek_char () == 0xBB) {
2428 if (get_char () == 0xBF)
2435 if (peek_char () != '\n')
2440 any_token_seen |= tokens_seen;
2441 tokens_seen = false;
2442 comments_seen = false;
2447 return consume_identifier (c);
2451 return Token.OPEN_BRACE;
2454 return Token.CLOSE_BRACE;
2456 // To block doccomment inside attribute declaration.
2457 if (doc_state == XmlCommentState.Allowed)
2458 doc_state = XmlCommentState.NotAllowed;
2459 return Token.OPEN_BRACKET;
2461 return Token.CLOSE_BRACKET;
2465 // An expression versions of parens can appear in block context only
2467 if (parsing_block != 0 && !lambda_arguments_parsing) {
2470 // Optmize most common case where we know that parens
2473 switch (current_token) {
2474 case Token.IDENTIFIER:
2482 case Token.DELEGATE:
2483 case Token.OP_GENERICS_GT:
2484 return Token.OPEN_PARENS;
2487 lambda_arguments_parsing = true;
2489 d = TokenizeOpenParens ();
2491 lambda_arguments_parsing = false;
2495 return Token.OPEN_PARENS;
2497 return Token.CLOSE_PARENS;
2501 return Token.SEMICOLON;
2505 return TokenizePossibleNullableType ();
2507 if (parsing_generic_less_than++ > 0)
2508 return Token.OP_GENERICS_LT;
2510 return TokenizeLessThan ();
2520 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2521 parsing_generic_less_than--;
2522 return Token.OP_GENERICS_GT;
2531 return Token.OP_SHIFT_RIGHT_ASSIGN;
2533 return Token.OP_SHIFT_RIGHT;
2542 } else if (d == '=') {
2543 d = Token.OP_ADD_ASSIGN;
2554 } else if (d == '=')
2555 d = Token.OP_SUB_ASSIGN;
2565 if (peek_char () == '='){
2582 return Token.ASSIGN;
2588 return Token.OP_AND;
2592 return Token.OP_AND_ASSIGN;
2594 return Token.BITWISE_AND;
2604 return Token.OP_OR_ASSIGN;
2606 return Token.BITWISE_OR;
2609 if (peek_char () == '='){
2611 return Token.OP_MULT_ASSIGN;
2620 return Token.OP_DIV_ASSIGN;
2623 // Handle double-slash comments.
2626 if (RootContext.Documentation != null && peek_char () == '/') {
2628 // Don't allow ////.
2629 if ((d = peek_char ()) != '/') {
2630 update_comment_location ();
2631 if (doc_state == XmlCommentState.Allowed)
2632 handle_one_line_xml_comment ();
2633 else if (doc_state == XmlCommentState.NotAllowed)
2634 warn_incorrect_doc_comment ();
2637 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2639 any_token_seen |= tokens_seen;
2640 tokens_seen = false;
2641 comments_seen = false;
2643 } else if (d == '*'){
2645 bool docAppend = false;
2646 if (RootContext.Documentation != null && peek_char () == '*') {
2648 update_comment_location ();
2649 // But when it is /**/, just do nothing.
2650 if (peek_char () == '/') {
2654 if (doc_state == XmlCommentState.Allowed)
2656 else if (doc_state == XmlCommentState.NotAllowed)
2657 warn_incorrect_doc_comment ();
2660 int current_comment_start = 0;
2662 current_comment_start = xml_comment_buffer.Length;
2663 xml_comment_buffer.Append (Environment.NewLine);
2666 while ((d = get_char ()) != -1){
2667 if (d == '*' && peek_char () == '/'){
2669 comments_seen = true;
2673 xml_comment_buffer.Append ((char) d);
2676 any_token_seen |= tokens_seen;
2677 tokens_seen = false;
2679 // Reset 'comments_seen' just to be consistent.
2680 // It doesn't matter either way, here.
2682 comments_seen = false;
2686 Report.Error (1035, Location, "End-of-file found, '*/' expected");
2689 update_formatted_doc_comment (current_comment_start);
2695 if (peek_char () == '='){
2697 return Token.OP_MOD_ASSIGN;
2699 return Token.PERCENT;
2702 if (peek_char () == '='){
2704 return Token.OP_XOR_ASSIGN;
2706 return Token.CARRET;
2709 if (peek_char () == ':') {
2711 return Token.DOUBLE_COLON;
2715 case '0': case '1': case '2': case '3': case '4':
2716 case '5': case '6': case '7': case '8': case '9':
2718 return is_number (c);
2720 case '\n': // white space
2721 any_token_seen |= tokens_seen;
2722 tokens_seen = false;
2723 comments_seen = false;
2729 if (d >= '0' && d <= '9')
2730 return is_number (c);
2734 if (tokens_seen || comments_seen) {
2735 Eror_WrongPreprocessorLocation ();
2739 if (handle_preprocessing_directive (true))
2742 bool directive_expected = false;
2743 while ((c = get_char ()) != -1) {
2745 directive_expected = true;
2746 } else if (!directive_expected) {
2747 // TODO: Implement comment support for disabled code and uncomment this code
2749 // Eror_WrongPreprocessorLocation ();
2750 // return Token.ERROR;
2755 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2759 if (handle_preprocessing_directive (false))
2762 directive_expected = false;
2766 tokens_seen = false;
2773 return consume_string (false);
2776 return TokenizeBackslash ();
2782 return consume_string (true);
2785 if (is_identifier_start_character (c)){
2786 return consume_identifier (c, true);
2789 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2792 case EvalStatementParserCharacter:
2793 return Token.EVAL_STATEMENT_PARSER;
2794 case EvalCompilationUnitParserCharacter:
2795 return Token.EVAL_COMPILATION_UNIT_PARSER;
2796 case EvalUsingDeclarationsParserCharacter:
2797 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2800 if (is_identifier_start_character (c)) {
2802 return consume_identifier (c);
2805 error_details = ((char)c).ToString ();
2812 int TokenizeBackslash ()
2814 int c = get_char ();
2817 error_details = "Empty character literal";
2818 Report.Error (1011, Location, error_details);
2821 if (c == '\r' || c == '\n') {
2822 Report.Error (1010, Location, "Newline in constant");
2827 c = escape (c, out d);
2831 throw new NotImplementedException ();
2837 Report.Error (1012, Location, "Too many characters in character literal");
2839 // Try to recover, read until newline or next "'"
2840 while ((c = get_char ()) != -1) {
2841 if (c == '\n' || c == '\'')
2847 return Token.LITERAL_CHARACTER;
2850 int TokenizeLessThan ()
2853 if (handle_typeof) {
2855 if (parse_generic_dimension (out d)) {
2858 return Token.GENERIC_DIMENSION;
2863 // Save current position and parse next token.
2865 if (parse_less_than ()) {
2866 if (parsing_generic_declaration && token () != Token.DOT) {
2867 d = Token.OP_GENERICS_LT_DECL;
2869 d = Token.OP_GENERICS_LT;
2876 parsing_generic_less_than = 0;
2885 return Token.OP_SHIFT_LEFT_ASSIGN;
2887 return Token.OP_SHIFT_LEFT;
2898 // Handles one line xml comment
2900 private void handle_one_line_xml_comment ()
2903 while ((c = peek_char ()) == ' ')
2904 get_char (); // skip heading whitespaces.
2905 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2906 xml_comment_buffer.Append ((char) get_char ());
2908 if (c == '\r' || c == '\n')
2909 xml_comment_buffer.Append (Environment.NewLine);
2913 // Remove heading "*" in Javadoc-like xml documentation.
2915 private void update_formatted_doc_comment (int current_comment_start)
2917 int length = xml_comment_buffer.Length - current_comment_start;
2918 string [] lines = xml_comment_buffer.ToString (
2919 current_comment_start,
2920 length).Replace ("\r", "").Split ('\n');
2922 // The first line starts with /**, thus it is not target
2923 // for the format check.
2924 for (int i = 1; i < lines.Length; i++) {
2925 string s = lines [i];
2926 int idx = s.IndexOf ('*');
2929 if (i < lines.Length - 1)
2933 head = s.Substring (0, idx);
2934 foreach (char c in head)
2937 lines [i] = s.Substring (idx + 1);
2939 xml_comment_buffer.Remove (current_comment_start, length);
2940 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2944 // Updates current comment location.
2946 private void update_comment_location ()
2948 if (current_comment_location.IsNull) {
2949 // "-2" is for heading "//" or "/*"
2950 current_comment_location =
2951 new Location (ref_line, hidden ? -1 : col - 2);
2956 // Checks if there was incorrect doc comments and raise
2959 public void check_incorrect_doc_comment ()
2961 if (xml_comment_buffer.Length > 0)
2962 warn_incorrect_doc_comment ();
2966 // Raises a warning when tokenizer found incorrect doccomment
2969 private void warn_incorrect_doc_comment ()
2971 if (doc_state != XmlCommentState.Error) {
2972 doc_state = XmlCommentState.Error;
2973 // in csc, it is 'XML comment is not placed on
2974 // a valid language element'. But that does not
2976 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2981 // Consumes the saved xml comment lines (if any)
2982 // as for current target member or type.
2984 public string consume_doc_comment ()
2986 if (xml_comment_buffer.Length > 0) {
2987 string ret = xml_comment_buffer.ToString ();
2988 reset_doc_comment ();
2994 void reset_doc_comment ()
2996 xml_comment_buffer.Length = 0;
2997 current_comment_location = Location.Null;
3000 public void cleanup ()
3002 if (ifstack != null && ifstack.Count >= 1) {
3003 int state = (int) ifstack.Pop ();
3004 if ((state & REGION) != 0)
3005 Report.Error (1038, Location, "#endregion directive expected");
3007 Report.Error (1027, Location, "Expected `#endif' directive");
3013 // Indicates whether it accepts XML documentation or not.
3015 public enum XmlCommentState {
3016 // comment is allowed in this state.
3018 // comment is not allowed in this state.
3020 // once comments appeared when it is NotAllowed, then the
3021 // state is changed to it, until the state is changed to