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;
18 using System.Collections.Generic;
20 using System.Globalization;
21 using System.Reflection;
26 /// Tokenizer for C# source code.
29 public class Tokenizer : yyParser.yyInput
33 public readonly int Token;
34 public KeywordEntry Next;
35 public readonly char[] Value;
37 public KeywordEntry (string value, int token)
39 this.Value = value.ToCharArray ();
44 sealed class IdentifiersComparer : IEqualityComparer<char[]>
48 public IdentifiersComparer (int length)
53 public bool Equals (char[] x, char[] y)
55 for (int i = 0; i < length; ++i)
62 public int GetHashCode (char[] obj)
65 for (int i = 0; i < length; ++i)
66 h = (h << 5) - h + obj [i];
72 SeekableStreamReader reader;
74 CompilationUnit file_name;
75 CompilerContext context;
82 bool handle_get_set = false;
83 bool handle_remove_add = false;
84 bool handle_where = false;
85 bool handle_typeof = false;
86 bool lambda_arguments_parsing;
87 Location current_comment_location = Location.Null;
88 ArrayList escaped_identifiers;
89 int parsing_generic_less_than;
92 // Used mainly for parser optimizations. Some expressions for instance
93 // can appear only in block (including initializer, base initializer)
96 public int parsing_block;
97 internal bool query_parsing;
100 // When parsing type only, useful for ambiguous nullable types
102 public int parsing_type;
105 // Set when parsing generic declaration (type or method header)
107 public bool parsing_generic_declaration;
110 // The value indicates that we have not reach any declaration or
113 public int parsing_declaration;
116 // The special character to inject on streams to trigger the EXPRESSION_PARSE
117 // token to be returned. It just happens to be a Unicode character that
118 // would never be part of a program (can not be an identifier).
120 // This character is only tested just before the tokenizer is about to report
121 // an error; So on the regular operation mode, this addition will have no
122 // impact on the tokenizer's performance.
125 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
126 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
127 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
130 // XML documentation buffer. The save point is used to divide
131 // comments on types and comments on members.
133 StringBuilder xml_comment_buffer;
136 // See comment on XmlCommentState enumeration.
138 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
141 // Whether tokens have been seen on this line
143 bool tokens_seen = false;
146 // Set to true once the GENERATE_COMPLETION token has bee
147 // returned. This helps produce one GENERATE_COMPLETION,
148 // as many COMPLETE_COMPLETION as necessary to complete the
149 // AST tree and one final EOF.
154 // Whether a token has been seen on the file
155 // This is needed because `define' is not allowed to be used
156 // after a token has been seen.
158 bool any_token_seen = false;
160 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
162 public bool PropertyParsing {
163 get { return handle_get_set; }
164 set { handle_get_set = value; }
167 public bool EventParsing {
168 get { return handle_remove_add; }
169 set { handle_remove_add = value; }
172 public bool ConstraintsParsing {
173 get { return handle_where; }
174 set { handle_where = value; }
177 public bool TypeOfParsing {
178 get { return handle_typeof; }
179 set { handle_typeof = value; }
182 public XmlCommentState doc_state {
183 get { return xml_doc_state; }
185 if (value == XmlCommentState.Allowed) {
186 check_incorrect_doc_comment ();
187 reset_doc_comment ();
189 xml_doc_state = value;
194 // This is used to trigger completion generation on the parser
195 public bool CompleteOnEOF;
197 void AddEscapedIdentifier (LocatedToken lt)
199 if (escaped_identifiers == null)
200 escaped_identifiers = new ArrayList ();
202 escaped_identifiers.Add (lt);
205 public bool IsEscapedIdentifier (Location loc)
207 if (escaped_identifiers != null) {
208 foreach (LocatedToken lt in escaped_identifiers)
209 if (lt.Location.Equals (loc))
219 static KeywordEntry[][] keywords;
220 static Dictionary<string, object> keyword_strings; // TODO: HashSet
221 static NumberStyles styles;
222 static NumberFormatInfo csharp_format_info;
225 // Values for the associated token returned
227 internal int putback_char; // Used by repl only
233 const int TAKING = 1;
234 const int ELSE_SEEN = 4;
235 const int PARENT_TAKING = 8;
236 const int REGION = 16;
239 // pre-processor if stack state:
243 static System.Text.StringBuilder string_builder;
245 const int max_id_size = 512;
246 static char [] id_builder = new char [max_id_size];
248 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
250 const int max_number_size = 512;
251 static char [] number_builder = new char [max_number_size];
252 static int number_pos;
254 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
257 // Details about the error encoutered by the tokenizer
259 string error_details;
261 public string error {
263 return error_details;
274 // This is used when the tokenizer needs to save
275 // the current position as it needs to do some parsing
276 // on its own to deamiguate a token in behalf of the
279 Stack position_stack = new Stack (2);
286 public int putback_char;
287 public int previous_col;
288 public Stack ifstack;
289 public int parsing_generic_less_than;
290 public int current_token;
292 public Position (Tokenizer t)
294 position = t.reader.Position;
296 ref_line = t.ref_line;
299 putback_char = t.putback_char;
300 previous_col = t.previous_col;
301 if (t.ifstack != null && t.ifstack.Count != 0)
302 ifstack = (Stack)t.ifstack.Clone ();
303 parsing_generic_less_than = t.parsing_generic_less_than;
304 current_token = t.current_token;
308 public void PushPosition ()
310 position_stack.Push (new Position (this));
313 public void PopPosition ()
315 Position p = (Position) position_stack.Pop ();
317 reader.Position = p.position;
318 ref_line = p.ref_line;
322 putback_char = p.putback_char;
323 previous_col = p.previous_col;
325 parsing_generic_less_than = p.parsing_generic_less_than;
326 current_token = p.current_token;
329 // Do not reset the position, ignore it.
330 public void DiscardPosition ()
332 position_stack.Pop ();
335 static void AddKeyword (string kw, int token)
337 keyword_strings.Add (kw, null);
339 int length = kw.Length;
340 if (keywords [length] == null) {
341 keywords [length] = new KeywordEntry ['z' - '_' + 1];
344 int char_index = kw [0] - '_';
345 KeywordEntry kwe = keywords [length] [char_index];
347 keywords [length] [char_index] = new KeywordEntry (kw, token);
351 while (kwe.Next != null) {
355 kwe.Next = new KeywordEntry (kw, token);
358 static void InitTokens ()
360 keyword_strings = new Dictionary<string, object> ();
362 // 11 is the length of the longest keyword for now
363 keywords = new KeywordEntry [11] [];
365 AddKeyword ("__arglist", Token.ARGLIST);
366 AddKeyword ("abstract", Token.ABSTRACT);
367 AddKeyword ("as", Token.AS);
368 AddKeyword ("add", Token.ADD);
369 AddKeyword ("base", Token.BASE);
370 AddKeyword ("bool", Token.BOOL);
371 AddKeyword ("break", Token.BREAK);
372 AddKeyword ("byte", Token.BYTE);
373 AddKeyword ("case", Token.CASE);
374 AddKeyword ("catch", Token.CATCH);
375 AddKeyword ("char", Token.CHAR);
376 AddKeyword ("checked", Token.CHECKED);
377 AddKeyword ("class", Token.CLASS);
378 AddKeyword ("const", Token.CONST);
379 AddKeyword ("continue", Token.CONTINUE);
380 AddKeyword ("decimal", Token.DECIMAL);
381 AddKeyword ("default", Token.DEFAULT);
382 AddKeyword ("delegate", Token.DELEGATE);
383 AddKeyword ("do", Token.DO);
384 AddKeyword ("double", Token.DOUBLE);
385 AddKeyword ("else", Token.ELSE);
386 AddKeyword ("enum", Token.ENUM);
387 AddKeyword ("event", Token.EVENT);
388 AddKeyword ("explicit", Token.EXPLICIT);
389 AddKeyword ("extern", Token.EXTERN);
390 AddKeyword ("false", Token.FALSE);
391 AddKeyword ("finally", Token.FINALLY);
392 AddKeyword ("fixed", Token.FIXED);
393 AddKeyword ("float", Token.FLOAT);
394 AddKeyword ("for", Token.FOR);
395 AddKeyword ("foreach", Token.FOREACH);
396 AddKeyword ("goto", Token.GOTO);
397 AddKeyword ("get", Token.GET);
398 AddKeyword ("if", Token.IF);
399 AddKeyword ("implicit", Token.IMPLICIT);
400 AddKeyword ("in", Token.IN);
401 AddKeyword ("int", Token.INT);
402 AddKeyword ("interface", Token.INTERFACE);
403 AddKeyword ("internal", Token.INTERNAL);
404 AddKeyword ("is", Token.IS);
405 AddKeyword ("lock", Token.LOCK);
406 AddKeyword ("long", Token.LONG);
407 AddKeyword ("namespace", Token.NAMESPACE);
408 AddKeyword ("new", Token.NEW);
409 AddKeyword ("null", Token.NULL);
410 AddKeyword ("object", Token.OBJECT);
411 AddKeyword ("operator", Token.OPERATOR);
412 AddKeyword ("out", Token.OUT);
413 AddKeyword ("override", Token.OVERRIDE);
414 AddKeyword ("params", Token.PARAMS);
415 AddKeyword ("private", Token.PRIVATE);
416 AddKeyword ("protected", Token.PROTECTED);
417 AddKeyword ("public", Token.PUBLIC);
418 AddKeyword ("readonly", Token.READONLY);
419 AddKeyword ("ref", Token.REF);
420 AddKeyword ("remove", Token.REMOVE);
421 AddKeyword ("return", Token.RETURN);
422 AddKeyword ("sbyte", Token.SBYTE);
423 AddKeyword ("sealed", Token.SEALED);
424 AddKeyword ("set", Token.SET);
425 AddKeyword ("short", Token.SHORT);
426 AddKeyword ("sizeof", Token.SIZEOF);
427 AddKeyword ("stackalloc", Token.STACKALLOC);
428 AddKeyword ("static", Token.STATIC);
429 AddKeyword ("string", Token.STRING);
430 AddKeyword ("struct", Token.STRUCT);
431 AddKeyword ("switch", Token.SWITCH);
432 AddKeyword ("this", Token.THIS);
433 AddKeyword ("throw", Token.THROW);
434 AddKeyword ("true", Token.TRUE);
435 AddKeyword ("try", Token.TRY);
436 AddKeyword ("typeof", Token.TYPEOF);
437 AddKeyword ("uint", Token.UINT);
438 AddKeyword ("ulong", Token.ULONG);
439 AddKeyword ("unchecked", Token.UNCHECKED);
440 AddKeyword ("unsafe", Token.UNSAFE);
441 AddKeyword ("ushort", Token.USHORT);
442 AddKeyword ("using", Token.USING);
443 AddKeyword ("virtual", Token.VIRTUAL);
444 AddKeyword ("void", Token.VOID);
445 AddKeyword ("volatile", Token.VOLATILE);
446 AddKeyword ("while", Token.WHILE);
447 AddKeyword ("partial", Token.PARTIAL);
448 AddKeyword ("where", Token.WHERE);
451 AddKeyword ("from", Token.FROM);
452 AddKeyword ("join", Token.JOIN);
453 AddKeyword ("on", Token.ON);
454 AddKeyword ("equals", Token.EQUALS);
455 AddKeyword ("select", Token.SELECT);
456 AddKeyword ("group", Token.GROUP);
457 AddKeyword ("by", Token.BY);
458 AddKeyword ("let", Token.LET);
459 AddKeyword ("orderby", Token.ORDERBY);
460 AddKeyword ("ascending", Token.ASCENDING);
461 AddKeyword ("descending", Token.DESCENDING);
462 AddKeyword ("into", Token.INTO);
471 csharp_format_info = NumberFormatInfo.InvariantInfo;
472 styles = NumberStyles.Float;
474 string_builder = new System.Text.StringBuilder ();
477 int GetKeyword (char[] id, int id_len)
480 // Keywords are stored in an array of arrays grouped by their
481 // length and then by the first character
483 if (id_len >= keywords.Length || keywords [id_len] == null)
486 int first_index = id [0] - '_';
487 if (first_index > 'z')
490 KeywordEntry kwe = keywords [id_len] [first_index];
497 for (int i = 1; i < id_len; ++i) {
498 if (id [i] != kwe.Value [i]) {
504 } while (kwe != null && res == 0);
518 if (!handle_remove_add)
522 if (parsing_declaration == 0)
523 res = Token.EXTERN_ALIAS;
526 if (peek_token () == Token.COLON) {
528 res = Token.DEFAULT_COLON;
532 if (!handle_where && !query_parsing)
537 // A query expression is any expression that starts with `from identifier'
538 // followed by any token except ; , =
540 if (!query_parsing) {
541 if (lambda_arguments_parsing) {
547 // HACK: to disable generics micro-parser, because PushPosition does not
548 // store identifiers array
549 parsing_generic_less_than = 1;
551 case Token.IDENTIFIER:
563 next_token = xtoken ();
564 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
567 res = Token.FROM_FIRST;
568 query_parsing = true;
569 if (RootContext.Version <= LanguageVersion.ISO_2)
570 Report.FeatureIsNotAvailable (Location, "query expressions");
573 Expression.Error_VoidInvalidInTheContext (Location, Report);
577 // HACK: A token is not a keyword so we need to restore identifiers buffer
578 // which has been overwritten before we grabbed the identifier
579 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
593 case Token.ASCENDING:
594 case Token.DESCENDING:
601 case Token.NAMESPACE:
602 // TODO: some explanation needed
603 check_incorrect_doc_comment ();
607 if (parsing_block > 0) {
612 // Save current position and parse next token.
615 next_token = token ();
616 bool ok = (next_token == Token.CLASS) ||
617 (next_token == Token.STRUCT) ||
618 (next_token == Token.INTERFACE) ||
619 (next_token == Token.VOID);
624 if (next_token == Token.VOID) {
625 if (RootContext.Version == LanguageVersion.ISO_1 ||
626 RootContext.Version == LanguageVersion.ISO_2)
627 Report.FeatureIsNotAvailable (Location, "partial methods");
628 } else if (RootContext.Version == LanguageVersion.ISO_1)
629 Report.FeatureIsNotAvailable (Location, "partial types");
634 if (next_token < Token.LAST_KEYWORD) {
635 Report.Error (267, Location,
636 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
647 public Location Location {
649 return new Location (ref_line, hidden ? -1 : col);
653 public Tokenizer (SeekableStreamReader input, CompilationUnit file, CompilerContext ctx)
655 this.ref_name = file;
656 this.file_name = file;
662 xml_comment_buffer = new StringBuilder ();
665 // FIXME: This could be `Location.Push' but we have to
666 // find out why the MS compiler allows this
668 Mono.CSharp.Location.Push (file, file);
671 static bool is_identifier_start_character (int c)
673 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
676 static bool is_identifier_part_character (char c)
678 if (c >= 'a' && c <= 'z')
681 if (c >= 'A' && c <= 'Z')
684 if (c == '_' || (c >= '0' && c <= '9'))
690 return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
693 public static bool IsKeyword (string s)
695 return keyword_strings.ContainsKey (s);
699 // Open parens micro parser. Detects both lambda and cast ambiguity.
702 int TokenizeOpenParens ()
707 int bracket_level = 0;
708 bool is_type = false;
709 bool can_be_type = false;
712 ptoken = current_token;
715 switch (current_token) {
716 case Token.CLOSE_PARENS:
720 // Expression inside parens is lambda, (int i) =>
722 if (current_token == Token.ARROW) {
723 if (RootContext.Version <= LanguageVersion.ISO_2)
724 Report.FeatureIsNotAvailable (Location, "lambda expressions");
726 return Token.OPEN_PARENS_LAMBDA;
730 // Expression inside parens is single type, (int[])
733 return Token.OPEN_PARENS_CAST;
736 // Expression is possible cast, look at next token, (T)null
739 switch (current_token) {
740 case Token.OPEN_PARENS:
743 case Token.IDENTIFIER:
744 case Token.LITERAL_INTEGER:
745 case Token.LITERAL_FLOAT:
746 case Token.LITERAL_DOUBLE:
747 case Token.LITERAL_DECIMAL:
748 case Token.LITERAL_CHARACTER:
749 case Token.LITERAL_STRING:
762 case Token.UNCHECKED:
767 // These can be part of a member access
781 return Token.OPEN_PARENS_CAST;
784 return Token.OPEN_PARENS;
787 case Token.DOUBLE_COLON:
788 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
793 case Token.IDENTIFIER:
796 case Token.OP_GENERICS_LT:
798 case Token.DOUBLE_COLON:
800 if (bracket_level == 0)
804 can_be_type = is_type = false;
824 if (bracket_level == 0)
829 if (bracket_level == 0) {
831 can_be_type = is_type = false;
835 case Token.OP_GENERICS_LT:
836 case Token.OPEN_BRACKET:
837 if (bracket_level++ == 0)
841 case Token.OP_GENERICS_GT:
842 case Token.CLOSE_BRACKET:
846 case Token.INTERR_NULLABLE:
848 if (bracket_level == 0)
854 can_be_type = is_type = false;
858 return Token.OPEN_PARENS;
863 public static bool IsValidIdentifier (string s)
865 if (s == null || s.Length == 0)
868 if (!is_identifier_start_character (s [0]))
871 for (int i = 1; i < s.Length; i ++)
872 if (! is_identifier_part_character (s [i]))
878 bool parse_less_than ()
881 int the_token = token ();
882 if (the_token == Token.OPEN_BRACKET) {
884 the_token = token ();
885 } while (the_token != Token.CLOSE_BRACKET);
886 the_token = token ();
887 } else if (the_token == Token.IN || the_token == Token.OUT) {
888 the_token = token ();
891 case Token.IDENTIFIER:
909 case Token.OP_GENERICS_GT:
916 the_token = token ();
918 if (the_token == Token.OP_GENERICS_GT)
920 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
922 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
924 else if (the_token == Token.OP_GENERICS_LT) {
925 if (!parse_less_than ())
928 } else if (the_token == Token.OPEN_BRACKET) {
930 the_token = token ();
931 if (the_token == Token.CLOSE_BRACKET)
933 else if (the_token == Token.COMMA)
934 goto rank_specifiers;
941 bool parse_generic_dimension (out int dimension)
946 int the_token = token ();
947 if (the_token == Token.OP_GENERICS_GT)
949 else if (the_token == Token.COMMA) {
957 public int peek_token ()
962 the_token = token ();
969 // Tonizes `?' using custom disambiguous rules to return one
970 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
972 // Tricky expression look like:
974 // Foo ? a = x ? b : c;
976 int TokenizePossibleNullableType ()
978 if (parsing_block == 0 || parsing_type > 0)
979 return Token.INTERR_NULLABLE;
981 int d = peek_char ();
984 return Token.OP_COALESCING;
987 switch (current_token) {
988 case Token.CLOSE_PARENS:
992 case Token.LITERAL_INTEGER:
993 case Token.LITERAL_STRING:
998 if (d == ',' || d == ';' || d == '>')
999 return Token.INTERR_NULLABLE;
1000 if (d == '*' || (d >= '0' && d <= '9'))
1001 return Token.INTERR;
1005 current_token = Token.NONE;
1007 switch (xtoken ()) {
1008 case Token.LITERAL_INTEGER:
1009 case Token.LITERAL_STRING:
1010 case Token.LITERAL_CHARACTER:
1011 case Token.LITERAL_DECIMAL:
1012 case Token.LITERAL_DOUBLE:
1013 case Token.LITERAL_FLOAT:
1019 next_token = Token.INTERR;
1022 case Token.SEMICOLON:
1024 case Token.CLOSE_PARENS:
1025 case Token.OPEN_BRACKET:
1026 case Token.OP_GENERICS_GT:
1027 next_token = Token.INTERR_NULLABLE;
1035 if (next_token == -1) {
1036 switch (xtoken ()) {
1038 case Token.SEMICOLON:
1039 case Token.OPEN_BRACE:
1040 case Token.CLOSE_PARENS:
1042 next_token = Token.INTERR_NULLABLE;
1046 next_token = Token.INTERR;
1054 // All shorcuts failed, do it hard way
1056 while ((ntoken = xtoken ()) != Token.EOF) {
1057 if (ntoken == Token.SEMICOLON)
1060 if (ntoken == Token.COLON) {
1061 if (++colons == interrs)
1066 if (ntoken == Token.INTERR) {
1072 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1081 bool decimal_digits (int c)
1084 bool seen_digits = false;
1087 if (number_pos == max_number_size)
1088 Error_NumericConstantTooLong ();
1089 number_builder [number_pos++] = (char) c;
1093 // We use peek_char2, because decimal_digits needs to do a
1094 // 2-character look-ahead (5.ToString for example).
1096 while ((d = peek_char2 ()) != -1){
1097 if (d >= '0' && d <= '9'){
1098 if (number_pos == max_number_size)
1099 Error_NumericConstantTooLong ();
1100 number_builder [number_pos++] = (char) d;
1110 static bool is_hex (int e)
1112 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1115 static int real_type_suffix (int c)
1121 t = Token.LITERAL_FLOAT;
1124 t = Token.LITERAL_DOUBLE;
1127 t= Token.LITERAL_DECIMAL;
1135 int integer_type_suffix (ulong ul, int c)
1137 bool is_unsigned = false;
1138 bool is_long = false;
1141 bool scanning = true;
1154 // if we have not seen anything in between
1155 // report this error
1157 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1177 if (is_long && is_unsigned){
1179 return Token.LITERAL_INTEGER;
1180 } else if (is_unsigned){
1181 // uint if possible, or ulong else.
1183 if ((ul & 0xffffffff00000000) == 0)
1187 } else if (is_long){
1188 // long if possible, ulong otherwise
1189 if ((ul & 0x8000000000000000) != 0)
1194 // int, uint, long or ulong in that order
1195 if ((ul & 0xffffffff00000000) == 0){
1196 uint ui = (uint) ul;
1198 if ((ui & 0x80000000) != 0)
1203 if ((ul & 0x8000000000000000) != 0)
1209 return Token.LITERAL_INTEGER;
1213 // given `c' as the next char in the input decide whether
1214 // we need to convert to a special type, and then choose
1215 // the best representation for the integer
1217 int adjust_int (int c)
1220 if (number_pos > 9){
1221 ulong ul = (uint) (number_builder [0] - '0');
1223 for (int i = 1; i < number_pos; i++){
1224 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1226 return integer_type_suffix (ul, c);
1228 uint ui = (uint) (number_builder [0] - '0');
1230 for (int i = 1; i < number_pos; i++){
1231 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1233 return integer_type_suffix (ui, c);
1235 } catch (OverflowException) {
1236 error_details = "Integral constant is too large";
1237 Report.Error (1021, Location, error_details);
1239 return Token.LITERAL_INTEGER;
1241 catch (FormatException) {
1242 Report.Error (1013, Location, "Invalid number");
1244 return Token.LITERAL_INTEGER;
1248 int adjust_real (int t)
1250 string s = new String (number_builder, 0, number_pos);
1251 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1254 case Token.LITERAL_DECIMAL:
1256 val = System.Decimal.Parse (s, styles, csharp_format_info);
1257 } catch (OverflowException) {
1259 Report.Error (594, Location, error_details, "decimal");
1262 case Token.LITERAL_FLOAT:
1264 val = float.Parse (s, styles, csharp_format_info);
1265 } catch (OverflowException) {
1267 Report.Error (594, Location, error_details, "float");
1271 case Token.LITERAL_DOUBLE:
1273 t = Token.LITERAL_DOUBLE;
1275 val = System.Double.Parse (s, styles, csharp_format_info);
1276 } catch (OverflowException) {
1278 Report.Error (594, Location, error_details, "double");
1291 while ((d = peek_char ()) != -1){
1293 number_builder [number_pos++] = (char) d;
1299 string s = new String (number_builder, 0, number_pos);
1301 if (number_pos <= 8)
1302 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1304 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1305 } catch (OverflowException){
1306 error_details = "Integral constant is too large";
1307 Report.Error (1021, Location, error_details);
1309 return Token.LITERAL_INTEGER;
1311 catch (FormatException) {
1312 Report.Error (1013, Location, "Invalid number");
1314 return Token.LITERAL_INTEGER;
1317 return integer_type_suffix (ul, peek_char ());
1321 // Invoked if we know we have .digits or digits
1323 int is_number (int c)
1325 bool is_real = false;
1330 if (c >= '0' && c <= '9'){
1332 int peek = peek_char ();
1334 if (peek == 'x' || peek == 'X')
1335 return handle_hex ();
1342 // We need to handle the case of
1343 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1346 if (decimal_digits ('.')){
1352 return adjust_int (-1);
1356 if (c == 'e' || c == 'E'){
1358 if (number_pos == max_number_size)
1359 Error_NumericConstantTooLong ();
1360 number_builder [number_pos++] = 'e';
1364 if (number_pos == max_number_size)
1365 Error_NumericConstantTooLong ();
1366 number_builder [number_pos++] = '+';
1368 } else if (c == '-') {
1369 if (number_pos == max_number_size)
1370 Error_NumericConstantTooLong ();
1371 number_builder [number_pos++] = '-';
1374 if (number_pos == max_number_size)
1375 Error_NumericConstantTooLong ();
1376 number_builder [number_pos++] = '+';
1383 type = real_type_suffix (c);
1384 if (type == Token.NONE && !is_real){
1386 return adjust_int (c);
1390 if (type == Token.NONE){
1395 return adjust_real (type);
1397 Console.WriteLine ("This should not be reached");
1398 throw new Exception ("Is Number should never reach this point");
1402 // Accepts exactly count (4 or 8) hex, no more no less
1404 int getHex (int count, out int surrogate, out bool error)
1409 int top = count != -1 ? count : 4;
1414 for (i = 0; i < top; i++){
1417 if (c >= '0' && c <= '9')
1418 c = (int) c - (int) '0';
1419 else if (c >= 'A' && c <= 'F')
1420 c = (int) c - (int) 'A' + 10;
1421 else if (c >= 'a' && c <= 'f')
1422 c = (int) c - (int) 'a' + 10;
1428 total = (total * 16) + c;
1430 int p = peek_char ();
1433 if (!is_hex ((char)p))
1439 if (total > 0x0010FFFF) {
1444 if (total >= 0x00010000) {
1445 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1446 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1453 int escape (int c, out int surrogate)
1489 v = getHex (-1, out surrogate, out error);
1495 return EscapeUnicode (d, out surrogate);
1498 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1507 int EscapeUnicode (int ch, out int surrogate)
1511 ch = getHex (8, out surrogate, out error);
1513 ch = getHex (4, out surrogate, out error);
1517 Report.Error (1009, Location, "Unrecognized escape sequence");
1525 if (putback_char != -1) {
1538 void advance_line ()
1548 if (putback_char == -1)
1549 putback_char = reader.Read ();
1550 return putback_char;
1555 if (putback_char != -1)
1556 return putback_char;
1557 return reader.Peek ();
1560 void putback (int c)
1562 if (putback_char != -1){
1563 Console.WriteLine ("Col: " + col);
1564 Console.WriteLine ("Row: " + line);
1565 Console.WriteLine ("Name: " + ref_name.Name);
1566 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1567 throw new Exception ("This should not happen putback on putback");
1569 if (c == '\n' || col == 0) {
1570 // It won't happen though.
1580 public bool advance ()
1582 return peek_char () != -1 || CompleteOnEOF;
1585 public Object Value {
1591 public Object value ()
1598 current_token = xtoken ();
1599 return current_token;
1602 void get_cmd_arg (out string cmd, out string arg)
1606 tokens_seen = false;
1609 // skip over white space
1612 } while (c == '\r' || c == ' ' || c == '\t');
1614 static_cmd_arg.Length = 0;
1615 while (c != -1 && is_identifier_part_character ((char)c)) {
1616 static_cmd_arg.Append ((char)c);
1619 int peek = peek_char ();
1620 if (peek == 'U' || peek == 'u') {
1622 c = EscapeUnicode (c, out surrogate);
1623 if (surrogate != 0) {
1624 if (is_identifier_part_character ((char) c))
1625 static_cmd_arg.Append ((char) c);
1632 cmd = static_cmd_arg.ToString ();
1634 // skip over white space
1635 while (c == '\r' || c == ' ' || c == '\t')
1638 static_cmd_arg.Length = 0;
1639 int has_identifier_argument = 0;
1641 while (c != -1 && c != '\n' && c != '\r') {
1642 if (c == '\\' && has_identifier_argument >= 0) {
1643 if (has_identifier_argument != 0 || (cmd == "define" || cmd == "if" || cmd == "elif" || cmd == "undef")) {
1644 has_identifier_argument = 1;
1646 int peek = peek_char ();
1647 if (peek == 'U' || peek == 'u') {
1649 c = EscapeUnicode (c, out surrogate);
1650 if (surrogate != 0) {
1651 if (is_identifier_part_character ((char) c))
1652 static_cmd_arg.Append ((char) c);
1657 has_identifier_argument = -1;
1660 static_cmd_arg.Append ((char) c);
1664 if (static_cmd_arg.Length != 0)
1665 arg = static_cmd_arg.ToString ();
1669 // Handles the #line directive
1671 bool PreProcessLine (string arg)
1673 if (arg.Length == 0)
1676 if (arg == "default"){
1678 ref_name = file_name;
1680 Location.Push (file_name, ref_name);
1682 } else if (arg == "hidden"){
1690 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1691 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1694 char [] quotes = { '\"' };
1696 string name = arg.Substring (pos). Trim (quotes);
1697 ref_name = Location.LookupFile (file_name, name);
1698 file_name.AddFile (ref_name);
1700 Location.Push (file_name, ref_name);
1702 ref_line = System.Int32.Parse (arg);
1713 // Handles #define and #undef
1715 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1717 if (ident.Length == 0 || ident == "true" || ident == "false"){
1718 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1722 if (ident.IndexOfAny (simple_whitespaces) != -1){
1723 Error_EndLineExpected ();
1727 if (!is_identifier_start_character (ident [0]))
1728 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1730 foreach (char c in ident.Substring (1)){
1731 if (!is_identifier_part_character (c)){
1732 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1737 if (!caller_is_taking)
1744 if (RootContext.IsConditionalDefined (ident))
1747 file_name.AddDefine (ident);
1752 file_name.AddUndefine (ident);
1756 static byte read_hex (string arg, int pos, out bool error)
1763 if ((c >= '0') && (c <= '9'))
1764 total = (int) c - (int) '0';
1765 else if ((c >= 'A') && (c <= 'F'))
1766 total = (int) c - (int) 'A' + 10;
1767 else if ((c >= 'a') && (c <= 'f'))
1768 total = (int) c - (int) 'a' + 10;
1777 if ((c >= '0') && (c <= '9'))
1778 total += (int) c - (int) '0';
1779 else if ((c >= 'A') && (c <= 'F'))
1780 total += (int) c - (int) 'A' + 10;
1781 else if ((c >= 'a') && (c <= 'f'))
1782 total += (int) c - (int) 'a' + 10;
1788 return (byte) total;
1792 /// Handles #pragma checksum
1794 bool PreProcessPragmaChecksum (string arg)
1796 if ((arg [0] != ' ') && (arg [0] != '\t'))
1799 arg = arg.Trim (simple_whitespaces);
1800 if ((arg.Length < 2) || (arg [0] != '"'))
1803 StringBuilder file_sb = new StringBuilder ();
1807 while ((ch = arg [pos++]) != '"') {
1808 if (pos >= arg.Length)
1812 if (pos+1 >= arg.Length)
1817 file_sb.Append (ch);
1820 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1823 arg = arg.Substring (pos).Trim (simple_whitespaces);
1824 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1825 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1826 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1830 byte[] guid_bytes = new byte [16];
1832 for (int i = 0; i < 4; i++) {
1833 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1837 for (int i = 0; i < 2; i++) {
1838 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1841 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1844 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1849 for (int i = 0; i < 6; i++) {
1850 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1855 arg = arg.Substring (40).Trim (simple_whitespaces);
1856 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1859 byte[] checksum_bytes = new byte [16];
1860 for (int i = 0; i < 16; i++) {
1861 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1866 arg = arg.Substring (34).Trim (simple_whitespaces);
1870 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1871 file.SetChecksum (guid_bytes, checksum_bytes);
1872 ref_name.AutoGenerated = true;
1877 /// Handles #pragma directive
1879 void PreProcessPragma (string arg)
1881 const string warning = "warning";
1882 const string w_disable = "warning disable";
1883 const string w_restore = "warning restore";
1884 const string checksum = "checksum";
1886 if (arg == w_disable) {
1887 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1891 if (arg == w_restore) {
1892 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1896 if (arg.StartsWith (w_disable)) {
1897 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1898 foreach (int code in codes) {
1900 Report.RegisterWarningRegion (Location).WarningDisable (Location, code, Report);
1905 if (arg.StartsWith (w_restore)) {
1906 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1907 Hashtable w_table = Report.warning_ignore_table;
1908 foreach (int code in codes) {
1909 if (w_table != null && w_table.Contains (code))
1910 Report.Warning (1635, 1, Location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1911 Report.RegisterWarningRegion (Location).WarningEnable (Location, code, Report);
1916 if (arg.StartsWith (warning)) {
1917 Report.Warning (1634, 1, Location, "Expected disable or restore");
1921 if (arg.StartsWith (checksum)) {
1922 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1923 Warning_InvalidPragmaChecksum ();
1927 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1930 int[] ParseNumbers (string text)
1932 string[] string_array = text.Split (',');
1933 int[] values = new int [string_array.Length];
1935 foreach (string string_code in string_array) {
1937 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1939 catch (FormatException) {
1940 Report.Warning (1692, 1, Location, "Invalid number");
1946 bool eval_val (string s)
1953 return file_name.IsConditionalDefined (s);
1956 bool pp_primary (ref string s)
1965 s = s.Substring (1);
1966 bool val = pp_expr (ref s, false);
1967 if (s.Length > 0 && s [0] == ')'){
1968 s = s.Substring (1);
1971 Error_InvalidDirective ();
1975 if (is_identifier_start_character (c)){
1981 if (is_identifier_part_character (c)){
1985 bool v = eval_val (s.Substring (0, j));
1986 s = s.Substring (j);
1989 bool vv = eval_val (s);
1994 Error_InvalidDirective ();
1998 bool pp_unary (ref string s)
2005 if (len > 1 && s [1] == '='){
2006 Error_InvalidDirective ();
2009 s = s.Substring (1);
2010 return ! pp_primary (ref s);
2012 return pp_primary (ref s);
2014 Error_InvalidDirective ();
2019 bool pp_eq (ref string s)
2021 bool va = pp_unary (ref s);
2027 if (len > 2 && s [1] == '='){
2028 s = s.Substring (2);
2029 return va == pp_unary (ref s);
2031 Error_InvalidDirective ();
2034 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2035 s = s.Substring (2);
2037 return va != pp_unary (ref s);
2046 bool pp_and (ref string s)
2048 bool va = pp_eq (ref s);
2054 if (len > 2 && s [1] == '&'){
2055 s = s.Substring (2);
2056 return (va & pp_and (ref s));
2058 Error_InvalidDirective ();
2067 // Evaluates an expression for `#if' or `#elif'
2069 bool pp_expr (ref string s, bool isTerm)
2071 bool va = pp_and (ref s);
2078 if (len > 2 && s [1] == '|'){
2079 s = s.Substring (2);
2080 return va | pp_expr (ref s, isTerm);
2082 Error_InvalidDirective ();
2087 Error_EndLineExpected ();
2095 bool eval (string s)
2097 bool v = pp_expr (ref s, true);
2106 void Error_NumericConstantTooLong ()
2108 Report.Error (1021, Location, "Numeric constant too long");
2111 void Error_InvalidDirective ()
2113 Report.Error (1517, Location, "Invalid preprocessor directive");
2116 void Error_UnexpectedDirective (string extra)
2120 "Unexpected processor directive ({0})", extra);
2123 void Error_TokensSeen ()
2125 Report.Error (1032, Location,
2126 "Cannot define or undefine preprocessor symbols after first token in file");
2129 void Eror_WrongPreprocessorLocation ()
2131 Report.Error (1040, Location,
2132 "Preprocessor directives must appear as the first non-whitespace character on a line");
2135 void Error_EndLineExpected ()
2137 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2140 void Warning_InvalidPragmaChecksum ()
2142 Report.Warning (1695, 1, Location,
2143 "Invalid #pragma checksum syntax; should be " +
2144 "#pragma checksum \"filename\" " +
2145 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2148 // if true, then the code continues processing the code
2149 // if false, the code stays in a loop until another directive is
2151 // When caller_is_taking is false we ignore all directives except the ones
2152 // which can help us to identify where the #if block ends
2153 bool handle_preprocessing_directive (bool caller_is_taking)
2156 bool region_directive = false;
2158 get_cmd_arg (out cmd, out arg);
2160 // Eat any trailing whitespaces and single-line comments
2161 if (arg.IndexOf ("//") != -1)
2162 arg = arg.Substring (0, arg.IndexOf ("//"));
2163 arg = arg.Trim (simple_whitespaces);
2166 // The first group of pre-processing instructions is always processed
2170 region_directive = true;
2175 if (ifstack == null || ifstack.Count == 0){
2176 Error_UnexpectedDirective ("no #region for this #endregion");
2179 int pop = (int) ifstack.Pop ();
2181 if ((pop & REGION) == 0)
2182 Report.Error (1027, Location, "Expected `#endif' directive");
2184 return caller_is_taking;
2187 if (ifstack == null)
2188 ifstack = new Stack (2);
2190 int flags = region_directive ? REGION : 0;
2191 if (ifstack.Count == 0){
2192 flags |= PARENT_TAKING;
2194 int state = (int) ifstack.Peek ();
2195 if ((state & TAKING) != 0) {
2196 flags |= PARENT_TAKING;
2200 if (caller_is_taking && eval (arg)) {
2201 ifstack.Push (flags | TAKING);
2204 ifstack.Push (flags);
2208 if (ifstack == null || ifstack.Count == 0){
2209 Error_UnexpectedDirective ("no #if for this #endif");
2212 pop = (int) ifstack.Pop ();
2214 if ((pop & REGION) != 0)
2215 Report.Error (1038, Location, "#endregion directive expected");
2217 if (arg.Length != 0) {
2218 Error_EndLineExpected ();
2221 if (ifstack.Count == 0)
2224 int state = (int) ifstack.Peek ();
2225 return (state & TAKING) != 0;
2229 if (ifstack == null || ifstack.Count == 0){
2230 Error_UnexpectedDirective ("no #if for this #elif");
2233 int state = (int) ifstack.Pop ();
2235 if ((state & REGION) != 0) {
2236 Report.Error (1038, Location, "#endregion directive expected");
2240 if ((state & ELSE_SEEN) != 0){
2241 Error_UnexpectedDirective ("#elif not valid after #else");
2245 if ((state & TAKING) != 0) {
2250 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2251 ifstack.Push (state | TAKING);
2255 ifstack.Push (state);
2260 if (ifstack == null || ifstack.Count == 0){
2261 Error_UnexpectedDirective ("no #if for this #else");
2264 int state = (int) ifstack.Peek ();
2266 if ((state & REGION) != 0) {
2267 Report.Error (1038, Location, "#endregion directive expected");
2271 if ((state & ELSE_SEEN) != 0){
2272 Error_UnexpectedDirective ("#else within #else");
2278 if (arg.Length != 0) {
2279 Error_EndLineExpected ();
2284 if ((state & PARENT_TAKING) != 0) {
2285 ret = (state & TAKING) == 0;
2293 ifstack.Push (state | ELSE_SEEN);
2298 if (any_token_seen){
2299 Error_TokensSeen ();
2300 return caller_is_taking;
2302 PreProcessDefinition (true, arg, caller_is_taking);
2303 return caller_is_taking;
2306 if (any_token_seen){
2307 Error_TokensSeen ();
2308 return caller_is_taking;
2310 PreProcessDefinition (false, arg, caller_is_taking);
2311 return caller_is_taking;
2315 // These are only processed if we are in a `taking' block
2317 if (!caller_is_taking)
2322 Report.Error (1029, Location, "#error: '{0}'", arg);
2326 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2330 if (RootContext.Version == LanguageVersion.ISO_1) {
2331 Report.FeatureIsNotAvailable (Location, "#pragma");
2335 PreProcessPragma (arg);
2339 if (!PreProcessLine (arg))
2342 "The line number specified for #line directive is missing or invalid");
2343 return caller_is_taking;
2346 Report.Error (1024, Location, "Wrong preprocessor directive");
2351 private int consume_string (bool quoted)
2354 string_builder.Length = 0;
2356 while ((c = get_char ()) != -1){
2358 if (quoted && peek_char () == '"'){
2359 string_builder.Append ((char) c);
2363 val = string_builder.ToString ();
2364 return Token.LITERAL_STRING;
2370 Report.Error (1010, Location, "Newline in constant");
2375 c = escape (c, out surrogate);
2378 if (surrogate != 0) {
2379 string_builder.Append ((char) c);
2383 string_builder.Append ((char) c);
2386 Report.Error (1039, Location, "Unterminated string literal");
2390 private int consume_identifier (int s)
2392 int res = consume_identifier (s, false);
2394 if (doc_state == XmlCommentState.Allowed)
2395 doc_state = XmlCommentState.NotAllowed;
2400 private int consume_identifier (int c, bool quoted)
2406 c = escape (c, out surrogate);
2407 if (surrogate != 0) {
2408 id_builder [pos++] = (char) c;
2413 id_builder [pos++] = (char) c;
2414 Location loc = Location;
2416 while ((c = get_char ()) != -1) {
2418 if (is_identifier_part_character ((char) c)){
2419 if (pos == max_id_size){
2420 Report.Error (645, loc, "Identifier too long (limit is 512 chars)");
2424 id_builder [pos++] = (char) c;
2425 } else if (c == '\\') {
2427 c = escape (c, out surrogate);
2428 if (surrogate != 0) {
2429 if (is_identifier_part_character ((char) c))
2430 id_builder [pos++] = (char) c;
2441 // Optimization: avoids doing the keyword lookup
2442 // on uppercase letters
2444 if (id_builder [0] >= '_' && !quoted) {
2445 int keyword = GetKeyword (id_builder, pos);
2446 if (keyword != -1) {
2447 // TODO: No need to store location for keyword, required location cleanup
2454 // Keep identifiers in an array of hashtables to avoid needless
2457 var identifiers_group = identifiers [pos];
2459 if (identifiers_group != null) {
2460 if (identifiers_group.TryGetValue (id_builder, out s)) {
2461 val = new LocatedToken (loc, s);
2463 AddEscapedIdentifier ((LocatedToken) val);
2464 return Token.IDENTIFIER;
2467 // TODO: this should be number of files dependant
2468 // corlib compilation peaks at 1000 and System.Core at 150
2469 int capacity = pos > 20 ? 10 : 100;
2470 identifiers_group = new Dictionary<char[],string> (capacity, new IdentifiersComparer (pos));
2471 identifiers [pos] = identifiers_group;
2474 char [] chars = new char [pos];
2475 Array.Copy (id_builder, chars, pos);
2477 s = new string (id_builder, 0, pos);
2478 identifiers_group.Add (chars, s);
2480 val = new LocatedToken (loc, s);
2482 AddEscapedIdentifier ((LocatedToken) val);
2483 return Token.IDENTIFIER;
2486 public int xtoken ()
2490 // Whether we have seen comments on the current line
2491 bool comments_seen = false;
2492 while ((c = get_char ()) != -1) {
2495 col = ((col + 8) / 8) * 8;
2503 case 0xFEFF: // Ignore BOM anywhere in the file
2506 /* This is required for compatibility with .NET
2508 if (peek_char () == 0xBB) {
2511 if (get_char () == 0xBF)
2518 if (peek_char () != '\n')
2523 any_token_seen |= tokens_seen;
2524 tokens_seen = false;
2525 comments_seen = false;
2530 return consume_identifier (c);
2534 return Token.OPEN_BRACE;
2537 return Token.CLOSE_BRACE;
2539 // To block doccomment inside attribute declaration.
2540 if (doc_state == XmlCommentState.Allowed)
2541 doc_state = XmlCommentState.NotAllowed;
2542 return Token.OPEN_BRACKET;
2544 return Token.CLOSE_BRACKET;
2548 // An expression versions of parens can appear in block context only
2550 if (parsing_block != 0 && !lambda_arguments_parsing) {
2553 // Optmize most common case where we know that parens
2556 switch (current_token) {
2557 case Token.IDENTIFIER:
2565 case Token.DELEGATE:
2566 case Token.OP_GENERICS_GT:
2567 return Token.OPEN_PARENS;
2570 // Optimize using peek
2571 int xx = peek_char ();
2578 return Token.OPEN_PARENS;
2581 lambda_arguments_parsing = true;
2583 d = TokenizeOpenParens ();
2585 lambda_arguments_parsing = false;
2589 return Token.OPEN_PARENS;
2591 return Token.CLOSE_PARENS;
2595 return Token.SEMICOLON;
2599 return TokenizePossibleNullableType ();
2601 if (parsing_generic_less_than++ > 0)
2602 return Token.OP_GENERICS_LT;
2604 return TokenizeLessThan ();
2614 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2615 parsing_generic_less_than--;
2616 return Token.OP_GENERICS_GT;
2625 return Token.OP_SHIFT_RIGHT_ASSIGN;
2627 return Token.OP_SHIFT_RIGHT;
2636 } else if (d == '=') {
2637 d = Token.OP_ADD_ASSIGN;
2648 } else if (d == '=')
2649 d = Token.OP_SUB_ASSIGN;
2659 if (peek_char () == '='){
2676 return Token.ASSIGN;
2682 return Token.OP_AND;
2686 return Token.OP_AND_ASSIGN;
2688 return Token.BITWISE_AND;
2698 return Token.OP_OR_ASSIGN;
2700 return Token.BITWISE_OR;
2703 if (peek_char () == '='){
2705 return Token.OP_MULT_ASSIGN;
2714 return Token.OP_DIV_ASSIGN;
2717 // Handle double-slash comments.
2720 if (RootContext.Documentation != null && peek_char () == '/') {
2722 // Don't allow ////.
2723 if ((d = peek_char ()) != '/') {
2724 update_comment_location ();
2725 if (doc_state == XmlCommentState.Allowed)
2726 handle_one_line_xml_comment ();
2727 else if (doc_state == XmlCommentState.NotAllowed)
2728 warn_incorrect_doc_comment ();
2731 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2733 any_token_seen |= tokens_seen;
2734 tokens_seen = false;
2735 comments_seen = false;
2737 } else if (d == '*'){
2739 bool docAppend = false;
2740 if (RootContext.Documentation != null && peek_char () == '*') {
2742 update_comment_location ();
2743 // But when it is /**/, just do nothing.
2744 if (peek_char () == '/') {
2748 if (doc_state == XmlCommentState.Allowed)
2750 else if (doc_state == XmlCommentState.NotAllowed)
2751 warn_incorrect_doc_comment ();
2754 int current_comment_start = 0;
2756 current_comment_start = xml_comment_buffer.Length;
2757 xml_comment_buffer.Append (Environment.NewLine);
2760 while ((d = get_char ()) != -1){
2761 if (d == '*' && peek_char () == '/'){
2763 comments_seen = true;
2767 xml_comment_buffer.Append ((char) d);
2770 any_token_seen |= tokens_seen;
2771 tokens_seen = false;
2773 // Reset 'comments_seen' just to be consistent.
2774 // It doesn't matter either way, here.
2776 comments_seen = false;
2780 Report.Error (1035, Location, "End-of-file found, '*/' expected");
2783 update_formatted_doc_comment (current_comment_start);
2789 if (peek_char () == '='){
2791 return Token.OP_MOD_ASSIGN;
2793 return Token.PERCENT;
2796 if (peek_char () == '='){
2798 return Token.OP_XOR_ASSIGN;
2800 return Token.CARRET;
2803 if (peek_char () == ':') {
2805 return Token.DOUBLE_COLON;
2809 case '0': case '1': case '2': case '3': case '4':
2810 case '5': case '6': case '7': case '8': case '9':
2812 return is_number (c);
2814 case '\n': // white space
2815 any_token_seen |= tokens_seen;
2816 tokens_seen = false;
2817 comments_seen = false;
2823 if (d >= '0' && d <= '9')
2824 return is_number (c);
2828 if (tokens_seen || comments_seen) {
2829 Eror_WrongPreprocessorLocation ();
2833 if (handle_preprocessing_directive (true))
2836 bool directive_expected = false;
2837 while ((c = get_char ()) != -1) {
2839 directive_expected = true;
2840 } else if (!directive_expected) {
2841 // TODO: Implement comment support for disabled code and uncomment this code
2843 // Eror_WrongPreprocessorLocation ();
2844 // return Token.ERROR;
2849 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2853 if (handle_preprocessing_directive (false))
2856 directive_expected = false;
2860 tokens_seen = false;
2867 return consume_string (false);
2870 return TokenizeBackslash ();
2876 return consume_string (true);
2879 if (is_identifier_start_character (c)){
2880 return consume_identifier (c, true);
2883 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2886 case EvalStatementParserCharacter:
2887 return Token.EVAL_STATEMENT_PARSER;
2888 case EvalCompilationUnitParserCharacter:
2889 return Token.EVAL_COMPILATION_UNIT_PARSER;
2890 case EvalUsingDeclarationsParserCharacter:
2891 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2894 if (is_identifier_start_character (c)) {
2896 return consume_identifier (c);
2899 error_details = ((char)c).ToString ();
2905 return Token.COMPLETE_COMPLETION;
2908 return Token.GENERATE_COMPLETION;
2915 int TokenizeBackslash ()
2917 int c = get_char ();
2920 error_details = "Empty character literal";
2921 Report.Error (1011, Location, error_details);
2924 if (c == '\r' || c == '\n') {
2925 Report.Error (1010, Location, "Newline in constant");
2930 c = escape (c, out d);
2934 throw new NotImplementedException ();
2940 Report.Error (1012, Location, "Too many characters in character literal");
2942 // Try to recover, read until newline or next "'"
2943 while ((c = get_char ()) != -1) {
2944 if (c == '\n' || c == '\'')
2950 return Token.LITERAL_CHARACTER;
2953 int TokenizeLessThan ()
2956 if (handle_typeof) {
2958 if (parse_generic_dimension (out d)) {
2961 return Token.GENERIC_DIMENSION;
2966 // Save current position and parse next token.
2968 if (parse_less_than ()) {
2969 if (parsing_generic_declaration && token () != Token.DOT) {
2970 d = Token.OP_GENERICS_LT_DECL;
2972 d = Token.OP_GENERICS_LT;
2979 parsing_generic_less_than = 0;
2988 return Token.OP_SHIFT_LEFT_ASSIGN;
2990 return Token.OP_SHIFT_LEFT;
3001 // Handles one line xml comment
3003 private void handle_one_line_xml_comment ()
3006 while ((c = peek_char ()) == ' ')
3007 get_char (); // skip heading whitespaces.
3008 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3009 xml_comment_buffer.Append ((char) get_char ());
3011 if (c == '\r' || c == '\n')
3012 xml_comment_buffer.Append (Environment.NewLine);
3016 // Remove heading "*" in Javadoc-like xml documentation.
3018 private void update_formatted_doc_comment (int current_comment_start)
3020 int length = xml_comment_buffer.Length - current_comment_start;
3021 string [] lines = xml_comment_buffer.ToString (
3022 current_comment_start,
3023 length).Replace ("\r", "").Split ('\n');
3025 // The first line starts with /**, thus it is not target
3026 // for the format check.
3027 for (int i = 1; i < lines.Length; i++) {
3028 string s = lines [i];
3029 int idx = s.IndexOf ('*');
3032 if (i < lines.Length - 1)
3036 head = s.Substring (0, idx);
3037 foreach (char c in head)
3040 lines [i] = s.Substring (idx + 1);
3042 xml_comment_buffer.Remove (current_comment_start, length);
3043 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3047 // Updates current comment location.
3049 private void update_comment_location ()
3051 if (current_comment_location.IsNull) {
3052 // "-2" is for heading "//" or "/*"
3053 current_comment_location =
3054 new Location (ref_line, hidden ? -1 : col - 2);
3059 // Checks if there was incorrect doc comments and raise
3062 public void check_incorrect_doc_comment ()
3064 if (xml_comment_buffer.Length > 0)
3065 warn_incorrect_doc_comment ();
3069 // Raises a warning when tokenizer found incorrect doccomment
3072 private void warn_incorrect_doc_comment ()
3074 if (doc_state != XmlCommentState.Error) {
3075 doc_state = XmlCommentState.Error;
3076 // in csc, it is 'XML comment is not placed on
3077 // a valid language element'. But that does not
3079 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
3084 // Consumes the saved xml comment lines (if any)
3085 // as for current target member or type.
3087 public string consume_doc_comment ()
3089 if (xml_comment_buffer.Length > 0) {
3090 string ret = xml_comment_buffer.ToString ();
3091 reset_doc_comment ();
3098 get { return context.Report; }
3101 void reset_doc_comment ()
3103 xml_comment_buffer.Length = 0;
3104 current_comment_location = Location.Null;
3107 public void cleanup ()
3109 if (ifstack != null && ifstack.Count >= 1) {
3110 int state = (int) ifstack.Pop ();
3111 if ((state & REGION) != 0)
3112 Report.Error (1038, Location, "#endregion directive expected");
3114 Report.Error (1027, Location, "Expected `#endif' directive");
3120 // Indicates whether it accepts XML documentation or not.
3122 public enum XmlCommentState {
3123 // comment is allowed in this state.
3125 // comment is not allowed in this state.
3127 // once comments appeared when it is NotAllowed, then the
3128 // state is changed to it, until the state is changed to