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 // Set when parsing generic declaration (type or method header)
59 public bool parsing_generic_declaration;
62 // The value indicates that we have not reach any declaration or
65 public int parsing_declaration;
68 // The special character to inject on streams to trigger the EXPRESSION_PARSE
69 // token to be returned. It just happens to be a Unicode character that
70 // would never be part of a program (can not be an identifier).
72 // This character is only tested just before the tokenizer is about to report
73 // an error; So on the regular operation mode, this addition will have no
74 // impact on the tokenizer's performance.
77 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
78 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
79 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
82 // XML documentation buffer. The save point is used to divide
83 // comments on types and comments on members.
85 StringBuilder xml_comment_buffer;
88 // See comment on XmlCommentState enumeration.
90 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
93 // Whether tokens have been seen on this line
95 bool tokens_seen = false;
98 // Whether a token has been seen on the file
99 // This is needed because `define' is not allowed to be used
100 // after a token has been seen.
102 bool any_token_seen = false;
104 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
106 public bool PropertyParsing {
107 get { return handle_get_set; }
108 set { handle_get_set = value; }
111 public bool EventParsing {
112 get { return handle_remove_add; }
113 set { handle_remove_add = value; }
116 public bool ConstraintsParsing {
117 get { return handle_where; }
118 set { handle_where = value; }
121 public bool TypeOfParsing {
122 get { return handle_typeof; }
123 set { handle_typeof = value; }
126 public XmlCommentState doc_state {
127 get { return xml_doc_state; }
129 if (value == XmlCommentState.Allowed) {
130 check_incorrect_doc_comment ();
131 reset_doc_comment ();
133 xml_doc_state = value;
137 void AddEscapedIdentifier (LocatedToken lt)
139 if (escaped_identifiers == null)
140 escaped_identifiers = new ArrayList ();
142 escaped_identifiers.Add (lt);
145 public bool IsEscapedIdentifier (Location loc)
147 if (escaped_identifiers != null) {
148 foreach (LocatedToken lt in escaped_identifiers)
149 if (lt.Location.Equals (loc))
159 static CharArrayHashtable[] keywords;
160 static Hashtable keyword_strings;
161 static NumberStyles styles;
162 static NumberFormatInfo csharp_format_info;
165 // Values for the associated token returned
167 internal int putback_char; // Used by repl only
173 const int TAKING = 1;
174 const int ELSE_SEEN = 4;
175 const int PARENT_TAKING = 8;
176 const int REGION = 16;
179 // pre-processor if stack state:
183 static System.Text.StringBuilder string_builder;
185 const int max_id_size = 512;
186 static char [] id_builder = new char [max_id_size];
188 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
190 const int max_number_size = 512;
191 static char [] number_builder = new char [max_number_size];
192 static int number_pos;
195 // Details about the error encoutered by the tokenizer
197 string error_details;
199 public string error {
201 return error_details;
212 // This is used when the tokenizer needs to save
213 // the current position as it needs to do some parsing
214 // on its own to deamiguate a token in behalf of the
217 Stack position_stack = new Stack (2);
224 public int putback_char;
225 public int previous_col;
226 public Stack ifstack;
227 public int parsing_generic_less_than;
228 public int current_token;
230 public Position (Tokenizer t)
232 position = t.reader.Position;
234 ref_line = t.ref_line;
237 putback_char = t.putback_char;
238 previous_col = t.previous_col;
239 if (t.ifstack != null && t.ifstack.Count != 0)
240 ifstack = (Stack)t.ifstack.Clone ();
241 parsing_generic_less_than = t.parsing_generic_less_than;
242 current_token = t.current_token;
246 public void PushPosition ()
248 position_stack.Push (new Position (this));
251 public void PopPosition ()
253 Position p = (Position) position_stack.Pop ();
255 reader.Position = p.position;
256 ref_line = p.ref_line;
260 putback_char = p.putback_char;
261 previous_col = p.previous_col;
263 parsing_generic_less_than = p.parsing_generic_less_than;
264 current_token = p.current_token;
267 // Do not reset the position, ignore it.
268 public void DiscardPosition ()
270 position_stack.Pop ();
273 static void AddKeyword (string kw, int token)
275 keyword_strings.Add (kw, kw);
276 if (keywords [kw.Length] == null) {
277 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
279 keywords [kw.Length] [kw.ToCharArray ()] = token;
282 static void InitTokens ()
284 keyword_strings = new Hashtable ();
285 keywords = new CharArrayHashtable [64];
287 AddKeyword ("__arglist", Token.ARGLIST);
288 AddKeyword ("abstract", Token.ABSTRACT);
289 AddKeyword ("as", Token.AS);
290 AddKeyword ("add", Token.ADD);
291 AddKeyword ("base", Token.BASE);
292 AddKeyword ("bool", Token.BOOL);
293 AddKeyword ("break", Token.BREAK);
294 AddKeyword ("byte", Token.BYTE);
295 AddKeyword ("case", Token.CASE);
296 AddKeyword ("catch", Token.CATCH);
297 AddKeyword ("char", Token.CHAR);
298 AddKeyword ("checked", Token.CHECKED);
299 AddKeyword ("class", Token.CLASS);
300 AddKeyword ("const", Token.CONST);
301 AddKeyword ("continue", Token.CONTINUE);
302 AddKeyword ("decimal", Token.DECIMAL);
303 AddKeyword ("default", Token.DEFAULT);
304 AddKeyword ("delegate", Token.DELEGATE);
305 AddKeyword ("do", Token.DO);
306 AddKeyword ("double", Token.DOUBLE);
307 AddKeyword ("else", Token.ELSE);
308 AddKeyword ("enum", Token.ENUM);
309 AddKeyword ("event", Token.EVENT);
310 AddKeyword ("explicit", Token.EXPLICIT);
311 AddKeyword ("extern", Token.EXTERN);
312 AddKeyword ("false", Token.FALSE);
313 AddKeyword ("finally", Token.FINALLY);
314 AddKeyword ("fixed", Token.FIXED);
315 AddKeyword ("float", Token.FLOAT);
316 AddKeyword ("for", Token.FOR);
317 AddKeyword ("foreach", Token.FOREACH);
318 AddKeyword ("goto", Token.GOTO);
319 AddKeyword ("get", Token.GET);
320 AddKeyword ("if", Token.IF);
321 AddKeyword ("implicit", Token.IMPLICIT);
322 AddKeyword ("in", Token.IN);
323 AddKeyword ("int", Token.INT);
324 AddKeyword ("interface", Token.INTERFACE);
325 AddKeyword ("internal", Token.INTERNAL);
326 AddKeyword ("is", Token.IS);
327 AddKeyword ("lock", Token.LOCK);
328 AddKeyword ("long", Token.LONG);
329 AddKeyword ("namespace", Token.NAMESPACE);
330 AddKeyword ("new", Token.NEW);
331 AddKeyword ("null", Token.NULL);
332 AddKeyword ("object", Token.OBJECT);
333 AddKeyword ("operator", Token.OPERATOR);
334 AddKeyword ("out", Token.OUT);
335 AddKeyword ("override", Token.OVERRIDE);
336 AddKeyword ("params", Token.PARAMS);
337 AddKeyword ("private", Token.PRIVATE);
338 AddKeyword ("protected", Token.PROTECTED);
339 AddKeyword ("public", Token.PUBLIC);
340 AddKeyword ("readonly", Token.READONLY);
341 AddKeyword ("ref", Token.REF);
342 AddKeyword ("remove", Token.REMOVE);
343 AddKeyword ("return", Token.RETURN);
344 AddKeyword ("sbyte", Token.SBYTE);
345 AddKeyword ("sealed", Token.SEALED);
346 AddKeyword ("set", Token.SET);
347 AddKeyword ("short", Token.SHORT);
348 AddKeyword ("sizeof", Token.SIZEOF);
349 AddKeyword ("stackalloc", Token.STACKALLOC);
350 AddKeyword ("static", Token.STATIC);
351 AddKeyword ("string", Token.STRING);
352 AddKeyword ("struct", Token.STRUCT);
353 AddKeyword ("switch", Token.SWITCH);
354 AddKeyword ("this", Token.THIS);
355 AddKeyword ("throw", Token.THROW);
356 AddKeyword ("true", Token.TRUE);
357 AddKeyword ("try", Token.TRY);
358 AddKeyword ("typeof", Token.TYPEOF);
359 AddKeyword ("uint", Token.UINT);
360 AddKeyword ("ulong", Token.ULONG);
361 AddKeyword ("unchecked", Token.UNCHECKED);
362 AddKeyword ("unsafe", Token.UNSAFE);
363 AddKeyword ("ushort", Token.USHORT);
364 AddKeyword ("using", Token.USING);
365 AddKeyword ("virtual", Token.VIRTUAL);
366 AddKeyword ("void", Token.VOID);
367 AddKeyword ("volatile", Token.VOLATILE);
368 AddKeyword ("while", Token.WHILE);
369 AddKeyword ("partial", Token.PARTIAL);
370 AddKeyword ("where", Token.WHERE);
373 AddKeyword ("from", Token.FROM);
374 AddKeyword ("join", Token.JOIN);
375 AddKeyword ("on", Token.ON);
376 AddKeyword ("equals", Token.EQUALS);
377 AddKeyword ("select", Token.SELECT);
378 AddKeyword ("group", Token.GROUP);
379 AddKeyword ("by", Token.BY);
380 AddKeyword ("let", Token.LET);
381 AddKeyword ("orderby", Token.ORDERBY);
382 AddKeyword ("ascending", Token.ASCENDING);
383 AddKeyword ("descending", Token.DESCENDING);
384 AddKeyword ("into", Token.INTO);
395 public static void Reset ()
398 csharp_format_info = NumberFormatInfo.InvariantInfo;
399 styles = NumberStyles.Float;
401 string_builder = new System.Text.StringBuilder ();
404 int GetKeyword (char[] id, int id_len)
407 * Keywords are stored in an array of hashtables grouped by their
411 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
413 object o = keywords [id_len] [id];
428 if (!handle_remove_add)
432 if (parsing_declaration == 0)
433 res = Token.EXTERN_ALIAS;
436 if (peek_token () == Token.COLON) {
438 res = Token.DEFAULT_COLON;
442 if (!handle_where && query_parsing == 0)
447 // A query expression is any expression that starts with `from identifier'
448 // followed by any token except ; , =
450 if (query_parsing == 0) {
451 if (lambda_arguments_parsing) {
457 // HACK: to disable generics micro-parser, because PushPosition does not
458 // store identifiers array
459 parsing_generic_less_than = 1;
461 case Token.IDENTIFIER:
473 next_token = xtoken ();
474 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
478 if (RootContext.Version <= LanguageVersion.ISO_2)
479 Report.FeatureIsNotAvailable (Location, "query expressions");
482 Expression.Error_VoidInvalidInTheContext (Location);
486 // HACK: A token is not a keyword so we need to restore identifiers buffer
487 // which has been overwritten before we grabbed the identifier
488 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
502 case Token.ASCENDING:
503 case Token.DESCENDING:
505 if (query_parsing == 0)
510 case Token.NAMESPACE:
511 // TODO: some explanation needed
512 check_incorrect_doc_comment ();
516 if (parsing_block > 0) {
521 // Save current position and parse next token.
524 next_token = token ();
525 bool ok = (next_token == Token.CLASS) ||
526 (next_token == Token.STRUCT) ||
527 (next_token == Token.INTERFACE) ||
528 (next_token == Token.VOID);
533 if (next_token == Token.VOID) {
534 if (RootContext.Version == LanguageVersion.ISO_1 ||
535 RootContext.Version == LanguageVersion.ISO_2)
536 Report.FeatureIsNotAvailable (Location, "partial methods");
537 } else if (RootContext.Version == LanguageVersion.ISO_1)
538 Report.FeatureIsNotAvailable (Location, "partial types");
543 if (next_token < Token.LAST_KEYWORD) {
544 Report.Error (267, Location,
545 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
556 public Location Location {
558 return new Location (ref_line, hidden ? -1 : col);
562 public Tokenizer (SeekableStreamReader input, CompilationUnit file)
564 this.ref_name = file;
565 this.file_name = file;
570 xml_comment_buffer = new StringBuilder ();
573 // FIXME: This could be `Location.Push' but we have to
574 // find out why the MS compiler allows this
576 Mono.CSharp.Location.Push (file, file);
579 static bool is_identifier_start_character (int c)
581 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
584 static bool is_identifier_part_character (char c)
586 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') ||
587 Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
590 public static bool IsKeyword (string s)
592 return keyword_strings [s] != null;
596 // Open parens micro parser. Detects both lambda and cast ambiguity.
599 int TokenizeOpenParens ()
604 int bracket_level = 0;
605 bool is_type = false;
606 bool can_be_type = false;
609 ptoken = current_token;
612 switch (current_token) {
613 case Token.CLOSE_PARENS:
617 // Expression inside parens is lambda, (int i) =>
619 if (current_token == Token.ARROW) {
620 if (RootContext.Version <= LanguageVersion.ISO_2)
621 Report.FeatureIsNotAvailable (Location, "lambda expressions");
623 return Token.OPEN_PARENS_LAMBDA;
627 // Expression inside parens is single type, (int[])
630 return Token.OPEN_PARENS_CAST;
633 // Expression is possible cast, look at next token, (T)null
636 switch (current_token) {
637 case Token.OPEN_PARENS:
640 case Token.IDENTIFIER:
641 case Token.LITERAL_INTEGER:
642 case Token.LITERAL_FLOAT:
643 case Token.LITERAL_DOUBLE:
644 case Token.LITERAL_DECIMAL:
645 case Token.LITERAL_CHARACTER:
646 case Token.LITERAL_STRING:
659 case Token.UNCHECKED:
664 // These can be part of a member access
678 return Token.OPEN_PARENS_CAST;
681 return Token.OPEN_PARENS;
684 case Token.DOUBLE_COLON:
685 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
690 case Token.IDENTIFIER:
693 case Token.OP_GENERICS_LT:
695 case Token.DOUBLE_COLON:
697 if (bracket_level == 0)
701 can_be_type = is_type = false;
721 if (bracket_level == 0)
726 if (bracket_level == 0) {
728 can_be_type = is_type = false;
732 case Token.OP_GENERICS_LT:
733 case Token.OPEN_BRACKET:
734 if (bracket_level++ == 0)
738 case Token.OP_GENERICS_GT:
739 case Token.CLOSE_BRACKET:
743 case Token.INTERR_NULLABLE:
745 if (bracket_level == 0)
751 can_be_type = is_type = false;
755 return Token.OPEN_PARENS;
760 public static bool IsValidIdentifier (string s)
762 if (s == null || s.Length == 0)
765 if (!is_identifier_start_character (s [0]))
768 for (int i = 1; i < s.Length; i ++)
769 if (! is_identifier_part_character (s [i]))
775 bool parse_less_than ()
778 int the_token = token ();
779 if (the_token == Token.OPEN_BRACKET) {
781 the_token = token ();
782 } while (the_token != Token.CLOSE_BRACKET);
783 the_token = token ();
786 case Token.IDENTIFIER:
805 case Token.OP_GENERICS_GT:
812 the_token = token ();
814 if (the_token == Token.OP_GENERICS_GT)
816 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
818 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
820 else if (the_token == Token.OP_GENERICS_LT) {
821 if (!parse_less_than ())
824 } else if (the_token == Token.OPEN_BRACKET) {
826 the_token = token ();
827 if (the_token == Token.CLOSE_BRACKET)
829 else if (the_token == Token.COMMA)
830 goto rank_specifiers;
837 bool parse_generic_dimension (out int dimension)
842 int the_token = token ();
843 if (the_token == Token.OP_GENERICS_GT)
845 else if (the_token == Token.COMMA) {
853 public int peek_token ()
858 the_token = token ();
865 // Tonizes `?' using custom disambiguous rules to return one
866 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
868 // Tricky expression look like:
870 // Foo ? a = x ? b : c;
872 int TokenizePossibleNullableType ()
874 if (parsing_block == 0)
875 return Token.INTERR_NULLABLE;
877 int d = peek_char ();
880 return Token.OP_COALESCING;
883 switch (current_token) {
884 case Token.CLOSE_PARENS:
888 case Token.LITERAL_INTEGER:
889 case Token.LITERAL_STRING:
894 if (d == ',' || d == ';' || d == '>')
895 return Token.INTERR_NULLABLE;
896 if (d == '*' || (d >= '0' && d <= '9'))
903 case Token.LITERAL_INTEGER:
904 case Token.LITERAL_STRING:
905 case Token.LITERAL_CHARACTER:
906 case Token.LITERAL_DECIMAL:
907 case Token.LITERAL_DOUBLE:
908 case Token.LITERAL_FLOAT:
913 next_token = Token.INTERR;
916 case Token.SEMICOLON:
918 case Token.CLOSE_PARENS:
919 case Token.OPEN_BRACKET:
920 case Token.OP_GENERICS_GT:
921 next_token = Token.INTERR_NULLABLE;
929 if (next_token == -1) {
932 case Token.SEMICOLON:
933 case Token.OPEN_BRACE:
934 case Token.CLOSE_PARENS:
936 next_token = Token.INTERR_NULLABLE;
940 next_token = Token.INTERR;
948 // All shorcuts failed, do it hard way
950 while ((ntoken = xtoken ()) != Token.EOF) {
951 if (ntoken == Token.SEMICOLON)
954 if (ntoken == Token.COLON) {
955 if (++colons == interrs)
960 if (ntoken == Token.INTERR) {
966 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
975 bool decimal_digits (int c)
978 bool seen_digits = false;
981 if (number_pos == max_number_size)
982 Error_NumericConstantTooLong ();
983 number_builder [number_pos++] = (char) c;
987 // We use peek_char2, because decimal_digits needs to do a
988 // 2-character look-ahead (5.ToString for example).
990 while ((d = peek_char2 ()) != -1){
991 if (d >= '0' && d <= '9'){
992 if (number_pos == max_number_size)
993 Error_NumericConstantTooLong ();
994 number_builder [number_pos++] = (char) d;
1004 static bool is_hex (int e)
1006 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1009 static int real_type_suffix (int c)
1015 t = Token.LITERAL_FLOAT;
1018 t = Token.LITERAL_DOUBLE;
1021 t= Token.LITERAL_DECIMAL;
1029 int integer_type_suffix (ulong ul, int c)
1031 bool is_unsigned = false;
1032 bool is_long = false;
1035 bool scanning = true;
1048 // if we have not seen anything in between
1049 // report this error
1051 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1054 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1055 // work around that.
1079 if (is_long && is_unsigned){
1081 return Token.LITERAL_INTEGER;
1082 } else if (is_unsigned){
1083 // uint if possible, or ulong else.
1085 if ((ul & 0xffffffff00000000) == 0)
1089 } else if (is_long){
1090 // long if possible, ulong otherwise
1091 if ((ul & 0x8000000000000000) != 0)
1096 // int, uint, long or ulong in that order
1097 if ((ul & 0xffffffff00000000) == 0){
1098 uint ui = (uint) ul;
1100 if ((ui & 0x80000000) != 0)
1105 if ((ul & 0x8000000000000000) != 0)
1111 return Token.LITERAL_INTEGER;
1115 // given `c' as the next char in the input decide whether
1116 // we need to convert to a special type, and then choose
1117 // the best representation for the integer
1119 int adjust_int (int c)
1122 if (number_pos > 9){
1123 ulong ul = (uint) (number_builder [0] - '0');
1125 for (int i = 1; i < number_pos; i++){
1126 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1128 return integer_type_suffix (ul, c);
1130 uint ui = (uint) (number_builder [0] - '0');
1132 for (int i = 1; i < number_pos; i++){
1133 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1135 return integer_type_suffix (ui, c);
1137 } catch (OverflowException) {
1138 error_details = "Integral constant is too large";
1139 Report.Error (1021, Location, error_details);
1141 return Token.LITERAL_INTEGER;
1143 catch (FormatException) {
1144 Report.Error (1013, Location, "Invalid number");
1146 return Token.LITERAL_INTEGER;
1150 int adjust_real (int t)
1152 string s = new String (number_builder, 0, number_pos);
1153 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1156 case Token.LITERAL_DECIMAL:
1158 val = System.Decimal.Parse (s, styles, csharp_format_info);
1159 } catch (OverflowException) {
1161 Report.Error (594, Location, error_details, "decimal");
1164 case Token.LITERAL_FLOAT:
1166 val = float.Parse (s, styles, csharp_format_info);
1167 } catch (OverflowException) {
1169 Report.Error (594, Location, error_details, "float");
1173 case Token.LITERAL_DOUBLE:
1175 t = Token.LITERAL_DOUBLE;
1177 val = System.Double.Parse (s, styles, csharp_format_info);
1178 } catch (OverflowException) {
1180 Report.Error (594, Location, error_details, "double");
1193 while ((d = peek_char ()) != -1){
1195 number_builder [number_pos++] = (char) d;
1201 string s = new String (number_builder, 0, number_pos);
1203 if (number_pos <= 8)
1204 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1206 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1207 } catch (OverflowException){
1208 error_details = "Integral constant is too large";
1209 Report.Error (1021, Location, error_details);
1211 return Token.LITERAL_INTEGER;
1213 catch (FormatException) {
1214 Report.Error (1013, Location, "Invalid number");
1216 return Token.LITERAL_INTEGER;
1219 return integer_type_suffix (ul, peek_char ());
1223 // Invoked if we know we have .digits or digits
1225 int is_number (int c)
1227 bool is_real = false;
1232 if (c >= '0' && c <= '9'){
1234 int peek = peek_char ();
1236 if (peek == 'x' || peek == 'X')
1237 return handle_hex ();
1244 // We need to handle the case of
1245 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1248 if (decimal_digits ('.')){
1254 return adjust_int (-1);
1258 if (c == 'e' || c == 'E'){
1260 if (number_pos == max_number_size)
1261 Error_NumericConstantTooLong ();
1262 number_builder [number_pos++] = 'e';
1266 if (number_pos == max_number_size)
1267 Error_NumericConstantTooLong ();
1268 number_builder [number_pos++] = '+';
1270 } else if (c == '-') {
1271 if (number_pos == max_number_size)
1272 Error_NumericConstantTooLong ();
1273 number_builder [number_pos++] = '-';
1276 if (number_pos == max_number_size)
1277 Error_NumericConstantTooLong ();
1278 number_builder [number_pos++] = '+';
1285 type = real_type_suffix (c);
1286 if (type == Token.NONE && !is_real){
1288 return adjust_int (c);
1292 if (type == Token.NONE){
1297 return adjust_real (type);
1299 Console.WriteLine ("This should not be reached");
1300 throw new Exception ("Is Number should never reach this point");
1304 // Accepts exactly count (4 or 8) hex, no more no less
1306 int getHex (int count, out int surrogate, out bool error)
1311 int top = count != -1 ? count : 4;
1316 for (i = 0; i < top; i++){
1319 if (c >= '0' && c <= '9')
1320 c = (int) c - (int) '0';
1321 else if (c >= 'A' && c <= 'F')
1322 c = (int) c - (int) 'A' + 10;
1323 else if (c >= 'a' && c <= 'f')
1324 c = (int) c - (int) 'a' + 10;
1330 total = (total * 16) + c;
1332 int p = peek_char ();
1335 if (!is_hex ((char)p))
1341 if (total > 0x0010FFFF) {
1346 if (total >= 0x00010000) {
1347 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1348 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1355 int escape (int c, out int surrogate)
1391 v = getHex (-1, out surrogate, out error);
1397 return EscapeUnicode (d, out surrogate);
1400 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1409 int EscapeUnicode (int ch, out int surrogate)
1413 ch = getHex (8, out surrogate, out error);
1415 ch = getHex (4, out surrogate, out error);
1419 Report.Error (1009, Location, "Unrecognized escape sequence");
1427 if (putback_char != -1) {
1440 void advance_line ()
1450 if (putback_char == -1)
1451 putback_char = reader.Read ();
1452 return putback_char;
1457 if (putback_char != -1)
1458 return putback_char;
1459 return reader.Peek ();
1462 void putback (int c)
1464 if (putback_char != -1){
1465 Console.WriteLine ("Col: " + col);
1466 Console.WriteLine ("Row: " + line);
1467 Console.WriteLine ("Name: " + ref_name.Name);
1468 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1469 throw new Exception ("This should not happen putback on putback");
1471 if (c == '\n' || col == 0) {
1472 // It won't happen though.
1482 public bool advance ()
1484 return peek_char () != -1;
1487 public Object Value {
1493 public Object value ()
1500 current_token = xtoken ();
1501 return current_token;
1504 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1506 void get_cmd_arg (out string cmd, out string arg)
1510 tokens_seen = false;
1513 // skip over white space
1516 } while (c == '\r' || c == ' ' || c == '\t');
1518 static_cmd_arg.Length = 0;
1519 while (c != -1 && is_identifier_part_character ((char)c)) {
1520 static_cmd_arg.Append ((char)c);
1523 int peek = peek_char ();
1524 if (peek == 'U' || peek == 'u') {
1526 c = EscapeUnicode (c, out surrogate);
1527 if (surrogate != 0) {
1528 if (is_identifier_part_character ((char) c))
1529 static_cmd_arg.Append ((char) c);
1536 cmd = static_cmd_arg.ToString ();
1538 // skip over white space
1539 while (c == '\r' || c == ' ' || c == '\t')
1542 static_cmd_arg.Length = 0;
1543 int has_identifier_argument = 0;
1545 while (c != -1 && c != '\n' && c != '\r') {
1546 if (c == '\\' && has_identifier_argument >= 0) {
1547 if (has_identifier_argument != 0 || (cmd == "define" || cmd == "if" || cmd == "elif" || cmd == "undef")) {
1548 has_identifier_argument = 1;
1550 int peek = peek_char ();
1551 if (peek == 'U' || peek == 'u') {
1553 c = EscapeUnicode (c, out surrogate);
1554 if (surrogate != 0) {
1555 if (is_identifier_part_character ((char) c))
1556 static_cmd_arg.Append ((char) c);
1561 has_identifier_argument = -1;
1564 static_cmd_arg.Append ((char) c);
1568 if (static_cmd_arg.Length != 0)
1569 arg = static_cmd_arg.ToString ();
1573 // Handles the #line directive
1575 bool PreProcessLine (string arg)
1577 if (arg.Length == 0)
1580 if (arg == "default"){
1582 ref_name = file_name;
1584 Location.Push (file_name, ref_name);
1586 } else if (arg == "hidden"){
1594 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1595 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1598 char [] quotes = { '\"' };
1600 string name = arg.Substring (pos). Trim (quotes);
1601 ref_name = Location.LookupFile (file_name, name);
1602 file_name.AddFile (ref_name);
1604 Location.Push (file_name, ref_name);
1606 ref_line = System.Int32.Parse (arg);
1617 // Handles #define and #undef
1619 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1621 if (ident.Length == 0 || ident == "true" || ident == "false"){
1622 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1626 if (ident.IndexOfAny (simple_whitespaces) != -1){
1627 Error_EndLineExpected ();
1631 if (!is_identifier_start_character (ident [0]))
1632 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1634 foreach (char c in ident.Substring (1)){
1635 if (!is_identifier_part_character (c)){
1636 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1641 if (!caller_is_taking)
1648 if (RootContext.IsConditionalDefined (ident))
1651 file_name.AddDefine (ident);
1656 file_name.AddUndefine (ident);
1660 static byte read_hex (string arg, int pos, out bool error)
1667 if ((c >= '0') && (c <= '9'))
1668 total = (int) c - (int) '0';
1669 else if ((c >= 'A') && (c <= 'F'))
1670 total = (int) c - (int) 'A' + 10;
1671 else if ((c >= 'a') && (c <= 'f'))
1672 total = (int) c - (int) 'a' + 10;
1681 if ((c >= '0') && (c <= '9'))
1682 total += (int) c - (int) '0';
1683 else if ((c >= 'A') && (c <= 'F'))
1684 total += (int) c - (int) 'A' + 10;
1685 else if ((c >= 'a') && (c <= 'f'))
1686 total += (int) c - (int) 'a' + 10;
1692 return (byte) total;
1696 /// Handles #pragma checksum
1698 bool PreProcessPragmaChecksum (string arg)
1700 if ((arg [0] != ' ') && (arg [0] != '\t'))
1703 arg = arg.Trim (simple_whitespaces);
1704 if ((arg.Length < 2) || (arg [0] != '"'))
1707 StringBuilder file_sb = new StringBuilder ();
1711 while ((ch = arg [pos++]) != '"') {
1712 if (pos >= arg.Length)
1716 if (pos+1 >= arg.Length)
1721 file_sb.Append (ch);
1724 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1727 arg = arg.Substring (pos).Trim (simple_whitespaces);
1728 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1729 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1730 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1734 byte[] guid_bytes = new byte [16];
1736 for (int i = 0; i < 4; i++) {
1737 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1741 for (int i = 0; i < 2; i++) {
1742 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1745 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1748 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1753 for (int i = 0; i < 6; i++) {
1754 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1759 arg = arg.Substring (40).Trim (simple_whitespaces);
1760 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1763 byte[] checksum_bytes = new byte [16];
1764 for (int i = 0; i < 16; i++) {
1765 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1770 arg = arg.Substring (34).Trim (simple_whitespaces);
1774 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1775 file.SetChecksum (guid_bytes, checksum_bytes);
1776 ref_name.AutoGenerated = true;
1781 /// Handles #pragma directive
1783 void PreProcessPragma (string arg)
1785 const string warning = "warning";
1786 const string w_disable = "warning disable";
1787 const string w_restore = "warning restore";
1788 const string checksum = "checksum";
1790 if (arg == w_disable) {
1791 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1795 if (arg == w_restore) {
1796 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1800 if (arg.StartsWith (w_disable)) {
1801 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1802 foreach (int code in codes) {
1804 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1809 if (arg.StartsWith (w_restore)) {
1810 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
1811 Hashtable w_table = Report.warning_ignore_table;
1812 foreach (int code in codes) {
1813 if (w_table != null && w_table.Contains (code))
1814 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
1815 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
1820 if (arg.StartsWith (warning)) {
1821 Report.Warning (1634, 1, Location, "Expected disable or restore");
1825 if (arg.StartsWith (checksum)) {
1826 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
1827 Warning_InvalidPragmaChecksum ();
1831 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
1834 int[] ParseNumbers (string text)
1836 string[] string_array = text.Split (',');
1837 int[] values = new int [string_array.Length];
1839 foreach (string string_code in string_array) {
1841 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
1843 catch (FormatException) {
1844 Report.Warning (1692, 1, Location, "Invalid number");
1850 bool eval_val (string s)
1857 return file_name.IsConditionalDefined (s);
1860 bool pp_primary (ref string s)
1869 s = s.Substring (1);
1870 bool val = pp_expr (ref s, false);
1871 if (s.Length > 0 && s [0] == ')'){
1872 s = s.Substring (1);
1875 Error_InvalidDirective ();
1879 if (is_identifier_start_character (c)){
1885 if (is_identifier_part_character (c)){
1889 bool v = eval_val (s.Substring (0, j));
1890 s = s.Substring (j);
1893 bool vv = eval_val (s);
1898 Error_InvalidDirective ();
1902 bool pp_unary (ref string s)
1909 if (len > 1 && s [1] == '='){
1910 Error_InvalidDirective ();
1913 s = s.Substring (1);
1914 return ! pp_primary (ref s);
1916 return pp_primary (ref s);
1918 Error_InvalidDirective ();
1923 bool pp_eq (ref string s)
1925 bool va = pp_unary (ref s);
1931 if (len > 2 && s [1] == '='){
1932 s = s.Substring (2);
1933 return va == pp_unary (ref s);
1935 Error_InvalidDirective ();
1938 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1939 s = s.Substring (2);
1941 return va != pp_unary (ref s);
1950 bool pp_and (ref string s)
1952 bool va = pp_eq (ref s);
1958 if (len > 2 && s [1] == '&'){
1959 s = s.Substring (2);
1960 return (va & pp_and (ref s));
1962 Error_InvalidDirective ();
1971 // Evaluates an expression for `#if' or `#elif'
1973 bool pp_expr (ref string s, bool isTerm)
1975 bool va = pp_and (ref s);
1982 if (len > 2 && s [1] == '|'){
1983 s = s.Substring (2);
1984 return va | pp_expr (ref s, isTerm);
1986 Error_InvalidDirective ();
1991 Error_EndLineExpected ();
1999 bool eval (string s)
2001 bool v = pp_expr (ref s, true);
2010 void Error_NumericConstantTooLong ()
2012 Report.Error (1021, Location, "Numeric constant too long");
2015 void Error_InvalidDirective ()
2017 Report.Error (1517, Location, "Invalid preprocessor directive");
2020 void Error_UnexpectedDirective (string extra)
2024 "Unexpected processor directive ({0})", extra);
2027 void Error_TokensSeen ()
2029 Report.Error (1032, Location,
2030 "Cannot define or undefine preprocessor symbols after first token in file");
2033 void Eror_WrongPreprocessorLocation ()
2035 Report.Error (1040, Location,
2036 "Preprocessor directives must appear as the first non-whitespace character on a line");
2039 void Error_EndLineExpected ()
2041 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2044 void Warning_InvalidPragmaChecksum ()
2046 Report.Warning (1695, 1, Location,
2047 "Invalid #pragma checksum syntax; should be " +
2048 "#pragma checksum \"filename\" " +
2049 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2052 // if true, then the code continues processing the code
2053 // if false, the code stays in a loop until another directive is
2055 // When caller_is_taking is false we ignore all directives except the ones
2056 // which can help us to identify where the #if block ends
2057 bool handle_preprocessing_directive (bool caller_is_taking)
2060 bool region_directive = false;
2062 get_cmd_arg (out cmd, out arg);
2064 // Eat any trailing whitespaces and single-line comments
2065 if (arg.IndexOf ("//") != -1)
2066 arg = arg.Substring (0, arg.IndexOf ("//"));
2067 arg = arg.Trim (simple_whitespaces);
2070 // The first group of pre-processing instructions is always processed
2074 region_directive = true;
2079 if (ifstack == null || ifstack.Count == 0){
2080 Error_UnexpectedDirective ("no #region for this #endregion");
2083 int pop = (int) ifstack.Pop ();
2085 if ((pop & REGION) == 0)
2086 Report.Error (1027, Location, "Expected `#endif' directive");
2088 return caller_is_taking;
2091 if (ifstack == null)
2092 ifstack = new Stack (2);
2094 int flags = region_directive ? REGION : 0;
2095 if (ifstack.Count == 0){
2096 flags |= PARENT_TAKING;
2098 int state = (int) ifstack.Peek ();
2099 if ((state & TAKING) != 0) {
2100 flags |= PARENT_TAKING;
2104 if (caller_is_taking && eval (arg)) {
2105 ifstack.Push (flags | TAKING);
2108 ifstack.Push (flags);
2112 if (ifstack == null || ifstack.Count == 0){
2113 Error_UnexpectedDirective ("no #if for this #endif");
2116 pop = (int) ifstack.Pop ();
2118 if ((pop & REGION) != 0)
2119 Report.Error (1038, Location, "#endregion directive expected");
2121 if (arg.Length != 0) {
2122 Error_EndLineExpected ();
2125 if (ifstack.Count == 0)
2128 int state = (int) ifstack.Peek ();
2129 return (state & TAKING) != 0;
2133 if (ifstack == null || ifstack.Count == 0){
2134 Error_UnexpectedDirective ("no #if for this #elif");
2137 int state = (int) ifstack.Pop ();
2139 if ((state & REGION) != 0) {
2140 Report.Error (1038, Location, "#endregion directive expected");
2144 if ((state & ELSE_SEEN) != 0){
2145 Error_UnexpectedDirective ("#elif not valid after #else");
2149 if ((state & TAKING) != 0) {
2154 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2155 ifstack.Push (state | TAKING);
2159 ifstack.Push (state);
2164 if (ifstack == null || ifstack.Count == 0){
2165 Error_UnexpectedDirective ("no #if for this #else");
2168 int state = (int) ifstack.Peek ();
2170 if ((state & REGION) != 0) {
2171 Report.Error (1038, Location, "#endregion directive expected");
2175 if ((state & ELSE_SEEN) != 0){
2176 Error_UnexpectedDirective ("#else within #else");
2182 if (arg.Length != 0) {
2183 Error_EndLineExpected ();
2188 if ((state & PARENT_TAKING) != 0) {
2189 ret = (state & TAKING) == 0;
2197 ifstack.Push (state | ELSE_SEEN);
2202 if (any_token_seen){
2203 Error_TokensSeen ();
2204 return caller_is_taking;
2206 PreProcessDefinition (true, arg, caller_is_taking);
2207 return caller_is_taking;
2210 if (any_token_seen){
2211 Error_TokensSeen ();
2212 return caller_is_taking;
2214 PreProcessDefinition (false, arg, caller_is_taking);
2215 return caller_is_taking;
2219 // These are only processed if we are in a `taking' block
2221 if (!caller_is_taking)
2226 Report.Error (1029, Location, "#error: '{0}'", arg);
2230 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2234 if (RootContext.Version == LanguageVersion.ISO_1) {
2235 Report.FeatureIsNotAvailable (Location, "#pragma");
2239 PreProcessPragma (arg);
2243 if (!PreProcessLine (arg))
2246 "The line number specified for #line directive is missing or invalid");
2247 return caller_is_taking;
2250 Report.Error (1024, Location, "Wrong preprocessor directive");
2255 private int consume_string (bool quoted)
2258 string_builder.Length = 0;
2261 // No need to parse full string when parsing lambda arguments
2263 if (lambda_arguments_parsing)
2264 return Token.LITERAL_STRING;
2266 while ((c = get_char ()) != -1){
2268 if (quoted && peek_char () == '"'){
2269 string_builder.Append ((char) c);
2273 val = string_builder.ToString ();
2274 return Token.LITERAL_STRING;
2280 Report.Error (1010, Location, "Newline in constant");
2285 c = escape (c, out surrogate);
2288 if (surrogate != 0) {
2289 string_builder.Append ((char) c);
2293 string_builder.Append ((char) c);
2296 Report.Error (1039, Location, "Unterminated string literal");
2300 private int consume_identifier (int s)
2302 int res = consume_identifier (s, false);
2304 if (doc_state == XmlCommentState.Allowed)
2305 doc_state = XmlCommentState.NotAllowed;
2310 private int consume_identifier (int c, bool quoted)
2316 c = escape (c, out surrogate);
2317 if (surrogate != 0) {
2318 id_builder [pos++] = (char) c;
2323 id_builder [pos++] = (char) c;
2324 Location loc = Location;
2326 while ((c = get_char ()) != -1) {
2328 if (is_identifier_part_character ((char) c)){
2329 if (pos == max_id_size){
2330 Report.Error (645, loc, "Identifier too long (limit is 512 chars)");
2334 id_builder [pos++] = (char) c;
2335 } else if (c == '\\') {
2337 c = escape (c, out surrogate);
2338 if (surrogate != 0) {
2339 if (is_identifier_part_character ((char) c))
2340 id_builder [pos++] = (char) c;
2351 // Optimization: avoids doing the keyword lookup
2352 // on uppercase letters
2354 if (id_builder [0] >= '_' && !quoted) {
2355 int keyword = GetKeyword (id_builder, pos);
2356 if (keyword != -1) {
2357 // TODO: No need to store location for keyword, required location cleanup
2364 // Keep identifiers in an array of hashtables to avoid needless
2367 CharArrayHashtable identifiers_group = identifiers [pos];
2368 if (identifiers_group != null) {
2369 val = identifiers_group [id_builder];
2371 val = new LocatedToken (loc, (string) val);
2373 AddEscapedIdentifier ((LocatedToken) val);
2374 return Token.IDENTIFIER;
2377 identifiers_group = new CharArrayHashtable (pos);
2378 identifiers [pos] = identifiers_group;
2381 char [] chars = new char [pos];
2382 Array.Copy (id_builder, chars, pos);
2384 val = new String (id_builder, 0, pos);
2385 identifiers_group.Add (chars, val);
2387 if (RootContext.Version == LanguageVersion.ISO_1) {
2388 for (int i = 1; i < chars.Length; i += 3) {
2389 if (chars [i] == '_' && (chars [i - 1] == '_' || chars [i + 1] == '_')) {
2390 Report.Error (1638, loc,
2391 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2396 val = new LocatedToken (loc, (string) val);
2398 AddEscapedIdentifier ((LocatedToken) val);
2399 return Token.IDENTIFIER;
2402 public int xtoken ()
2406 // Whether we have seen comments on the current line
2407 bool comments_seen = false;
2408 while ((c = get_char ()) != -1) {
2411 col = ((col + 8) / 8) * 8;
2422 if (peek_char () != '\n')
2427 any_token_seen |= tokens_seen;
2428 tokens_seen = false;
2429 comments_seen = false;
2434 return consume_identifier (c);
2438 return Token.OPEN_BRACE;
2441 return Token.CLOSE_BRACE;
2443 // To block doccomment inside attribute declaration.
2444 if (doc_state == XmlCommentState.Allowed)
2445 doc_state = XmlCommentState.NotAllowed;
2446 return Token.OPEN_BRACKET;
2448 return Token.CLOSE_BRACKET;
2452 // An expression versions of parens can appear in block context only
2454 if (parsing_block != 0 && !lambda_arguments_parsing) {
2457 // Optmize most common case where we know that parens
2460 switch (current_token) {
2461 case Token.IDENTIFIER:
2469 case Token.DELEGATE:
2470 case Token.OP_GENERICS_GT:
2471 return Token.OPEN_PARENS;
2474 lambda_arguments_parsing = true;
2476 d = TokenizeOpenParens ();
2478 lambda_arguments_parsing = false;
2482 return Token.OPEN_PARENS;
2484 return Token.CLOSE_PARENS;
2488 return Token.SEMICOLON;
2492 return TokenizePossibleNullableType ();
2494 if (parsing_generic_less_than++ > 0)
2495 return Token.OP_GENERICS_LT;
2497 return TokenizeLessThan ();
2507 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2508 parsing_generic_less_than--;
2509 return Token.OP_GENERICS_GT;
2518 return Token.OP_SHIFT_RIGHT_ASSIGN;
2520 return Token.OP_SHIFT_RIGHT;
2529 } else if (d == '=') {
2530 d = Token.OP_ADD_ASSIGN;
2541 } else if (d == '=')
2542 d = Token.OP_SUB_ASSIGN;
2552 if (peek_char () == '='){
2569 return Token.ASSIGN;
2575 return Token.OP_AND;
2579 return Token.OP_AND_ASSIGN;
2581 return Token.BITWISE_AND;
2591 return Token.OP_OR_ASSIGN;
2593 return Token.BITWISE_OR;
2596 if (peek_char () == '='){
2598 return Token.OP_MULT_ASSIGN;
2607 return Token.OP_DIV_ASSIGN;
2610 // Handle double-slash comments.
2613 if (RootContext.Documentation != null && peek_char () == '/') {
2615 // Don't allow ////.
2616 if ((d = peek_char ()) != '/') {
2617 update_comment_location ();
2618 if (doc_state == XmlCommentState.Allowed)
2619 handle_one_line_xml_comment ();
2620 else if (doc_state == XmlCommentState.NotAllowed)
2621 warn_incorrect_doc_comment ();
2624 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2626 any_token_seen |= tokens_seen;
2627 tokens_seen = false;
2628 comments_seen = false;
2630 } else if (d == '*'){
2632 bool docAppend = false;
2633 if (RootContext.Documentation != null && peek_char () == '*') {
2635 update_comment_location ();
2636 // But when it is /**/, just do nothing.
2637 if (peek_char () == '/') {
2641 if (doc_state == XmlCommentState.Allowed)
2643 else if (doc_state == XmlCommentState.NotAllowed)
2644 warn_incorrect_doc_comment ();
2647 int current_comment_start = 0;
2649 current_comment_start = xml_comment_buffer.Length;
2650 xml_comment_buffer.Append (Environment.NewLine);
2653 while ((d = get_char ()) != -1){
2654 if (d == '*' && peek_char () == '/'){
2656 comments_seen = true;
2660 xml_comment_buffer.Append ((char) d);
2663 any_token_seen |= tokens_seen;
2664 tokens_seen = false;
2666 // Reset 'comments_seen' just to be consistent.
2667 // It doesn't matter either way, here.
2669 comments_seen = false;
2673 Report.Error (1035, Location, "End-of-file found, '*/' expected");
2676 update_formatted_doc_comment (current_comment_start);
2682 if (peek_char () == '='){
2684 return Token.OP_MOD_ASSIGN;
2686 return Token.PERCENT;
2689 if (peek_char () == '='){
2691 return Token.OP_XOR_ASSIGN;
2693 return Token.CARRET;
2696 if (peek_char () == ':') {
2698 return Token.DOUBLE_COLON;
2702 case '0': case '1': case '2': case '3': case '4':
2703 case '5': case '6': case '7': case '8': case '9':
2705 return is_number (c);
2707 case '\n': // white space
2708 any_token_seen |= tokens_seen;
2709 tokens_seen = false;
2710 comments_seen = false;
2716 if (d >= '0' && d <= '9')
2717 return is_number (c);
2721 if (tokens_seen || comments_seen) {
2722 Eror_WrongPreprocessorLocation ();
2726 if (handle_preprocessing_directive (true))
2729 bool directive_expected = false;
2730 while ((c = get_char ()) != -1) {
2732 directive_expected = true;
2733 } else if (!directive_expected) {
2734 // TODO: Implement comment support for disabled code and uncomment this code
2736 // Eror_WrongPreprocessorLocation ();
2737 // return Token.ERROR;
2742 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2746 if (handle_preprocessing_directive (false))
2749 directive_expected = false;
2753 tokens_seen = false;
2760 return consume_string (false);
2763 return TokenizeBackslash ();
2769 return consume_string (true);
2772 if (is_identifier_start_character (c)){
2773 return consume_identifier (c, true);
2776 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2779 case EvalStatementParserCharacter:
2780 return Token.EVAL_STATEMENT_PARSER;
2781 case EvalCompilationUnitParserCharacter:
2782 return Token.EVAL_COMPILATION_UNIT_PARSER;
2783 case EvalUsingDeclarationsParserCharacter:
2784 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2787 if (is_identifier_start_character (c)) {
2789 return consume_identifier (c);
2792 error_details = ((char)c).ToString ();
2799 int TokenizeBackslash ()
2801 int c = get_char ();
2804 error_details = "Empty character literal";
2805 Report.Error (1011, Location, error_details);
2808 if (c == '\r' || c == '\n') {
2809 Report.Error (1010, Location, "Newline in constant");
2814 c = escape (c, out d);
2818 throw new NotImplementedException ();
2824 Report.Error (1012, Location, "Too many characters in character literal");
2826 // Try to recover, read until newline or next "'"
2827 while ((c = get_char ()) != -1) {
2828 if (c == '\n' || c == '\'')
2834 return Token.LITERAL_CHARACTER;
2837 int TokenizeLessThan ()
2840 if (handle_typeof) {
2842 if (parse_generic_dimension (out d)) {
2845 return Token.GENERIC_DIMENSION;
2850 // Save current position and parse next token.
2852 if (parse_less_than ()) {
2853 if (parsing_generic_declaration && token () != Token.DOT) {
2854 d = Token.OP_GENERICS_LT_DECL;
2856 d = Token.OP_GENERICS_LT;
2863 parsing_generic_less_than = 0;
2872 return Token.OP_SHIFT_LEFT_ASSIGN;
2874 return Token.OP_SHIFT_LEFT;
2885 // Handles one line xml comment
2887 private void handle_one_line_xml_comment ()
2890 while ((c = peek_char ()) == ' ')
2891 get_char (); // skip heading whitespaces.
2892 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2893 xml_comment_buffer.Append ((char) get_char ());
2895 if (c == '\r' || c == '\n')
2896 xml_comment_buffer.Append (Environment.NewLine);
2900 // Remove heading "*" in Javadoc-like xml documentation.
2902 private void update_formatted_doc_comment (int current_comment_start)
2904 int length = xml_comment_buffer.Length - current_comment_start;
2905 string [] lines = xml_comment_buffer.ToString (
2906 current_comment_start,
2907 length).Replace ("\r", "").Split ('\n');
2909 // The first line starts with /**, thus it is not target
2910 // for the format check.
2911 for (int i = 1; i < lines.Length; i++) {
2912 string s = lines [i];
2913 int idx = s.IndexOf ('*');
2916 if (i < lines.Length - 1)
2920 head = s.Substring (0, idx);
2921 foreach (char c in head)
2924 lines [i] = s.Substring (idx + 1);
2926 xml_comment_buffer.Remove (current_comment_start, length);
2927 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2931 // Updates current comment location.
2933 private void update_comment_location ()
2935 if (current_comment_location.IsNull) {
2936 // "-2" is for heading "//" or "/*"
2937 current_comment_location =
2938 new Location (ref_line, hidden ? -1 : col - 2);
2943 // Checks if there was incorrect doc comments and raise
2946 public void check_incorrect_doc_comment ()
2948 if (xml_comment_buffer.Length > 0)
2949 warn_incorrect_doc_comment ();
2953 // Raises a warning when tokenizer found incorrect doccomment
2956 private void warn_incorrect_doc_comment ()
2958 if (doc_state != XmlCommentState.Error) {
2959 doc_state = XmlCommentState.Error;
2960 // in csc, it is 'XML comment is not placed on
2961 // a valid language element'. But that does not
2963 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2968 // Consumes the saved xml comment lines (if any)
2969 // as for current target member or type.
2971 public string consume_doc_comment ()
2973 if (xml_comment_buffer.Length > 0) {
2974 string ret = xml_comment_buffer.ToString ();
2975 reset_doc_comment ();
2981 void reset_doc_comment ()
2983 xml_comment_buffer.Length = 0;
2984 current_comment_location = Location.Null;
2987 public void cleanup ()
2989 if (ifstack != null && ifstack.Count >= 1) {
2990 int state = (int) ifstack.Pop ();
2991 if ((state & REGION) != 0)
2992 Report.Error (1038, Location, "#endregion directive expected");
2994 Report.Error (1027, Location, "Expected `#endif' directive");
3000 // Indicates whether it accepts XML documentation or not.
3002 public enum XmlCommentState {
3003 // comment is allowed in this state.
3005 // comment is not allowed in this state.
3007 // once comments appeared when it is NotAllowed, then the
3008 // state is changed to it, until the state is changed to