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_assembly = false;
42 bool handle_where = false;
43 bool handle_typeof = false;
44 bool lambda_arguments_parsing;
45 Location current_location;
46 Location current_comment_location = Location.Null;
47 ArrayList escaped_identifiers = new ArrayList ();
50 // Used mainly for parser optimizations. Some expressions for instance
51 // can appear only in block (including initializer, base initializer)
54 public int parsing_block;
55 internal int query_parsing;
58 // The special character to inject on streams to trigger the EXPRESSION_PARSE
59 // token to be returned. It just happens to be a Unicode character that
60 // would never be part of a program (can not be an identifier).
62 // This character is only tested just before the tokenizer is about to report
63 // an error; So on the regular operation mode, this addition will have no
64 // impact on the tokenizer's performance.
67 public const int EvalStatementParserCharacter = 0x2190; // Unicode Left Arrow
68 public const int EvalCompilationUnitParserCharacter = 0x2191; // Unicode Arrow
69 public const int EvalUsingDeclarationsParserCharacter = 0x2192; // Unicode Arrow
72 // XML documentation buffer. The save point is used to divide
73 // comments on types and comments on members.
75 StringBuilder xml_comment_buffer;
78 // See comment on XmlCommentState enumeration.
80 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
83 // Whether tokens have been seen on this line
85 bool tokens_seen = false;
88 // Whether a token has been seen on the file
89 // This is needed because `define' is not allowed to be used
90 // after a token has been seen.
92 bool any_token_seen = false;
94 static Hashtable token_values;
95 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
97 private static Hashtable TokenValueName
100 if (token_values == null)
101 token_values = GetTokenValueNameHash ();
107 private static Hashtable GetTokenValueNameHash ()
109 Type t = typeof (Token);
110 FieldInfo [] fields = t.GetFields ();
111 Hashtable hash = new Hashtable ();
112 foreach (FieldInfo field in fields) {
113 if (field.IsLiteral && field.IsStatic && field.FieldType == typeof (int))
114 hash.Add (field.GetValue (null), field.Name);
120 // Returns a verbose representation of the current location
122 public string location {
126 if (current_token == Token.ERROR)
127 det = "detail: " + error_details;
131 // return "Line: "+line+" Col: "+col + "\n" +
132 // "VirtLine: "+ref_line +
133 // " Token: "+current_token + " " + det;
134 string current_token_name = TokenValueName [current_token] as string;
135 if (current_token_name == null)
136 current_token_name = current_token.ToString ();
138 return String.Format ("{0} ({1},{2}), Token: {3} {4}", ref_name.Name,
146 public bool PropertyParsing {
147 get { return handle_get_set; }
148 set { handle_get_set = value; }
151 public bool AssemblyTargetParsing {
152 get { return handle_assembly; }
153 set { handle_assembly = value; }
156 public bool EventParsing {
157 get { return handle_remove_add; }
158 set { handle_remove_add = value; }
161 public bool ConstraintsParsing {
162 get { return handle_where; }
163 set { handle_where = value; }
166 public bool TypeOfParsing {
167 get { return handle_typeof; }
168 set { handle_typeof = value; }
171 public XmlCommentState doc_state {
172 get { return xml_doc_state; }
174 if (value == XmlCommentState.Allowed) {
175 check_incorrect_doc_comment ();
176 reset_doc_comment ();
178 xml_doc_state = value;
182 public bool IsEscapedIdentifier (Location loc)
184 foreach (LocatedToken lt in escaped_identifiers)
185 if (lt.Location.Equals (loc))
193 static CharArrayHashtable[] keywords;
194 static Hashtable keyword_strings;
195 static NumberStyles styles;
196 static NumberFormatInfo csharp_format_info;
199 // Values for the associated token returned
201 internal int putback_char; // Used by repl only
207 const int TAKING = 1;
208 const int ELSE_SEEN = 4;
209 const int PARENT_TAKING = 8;
210 const int REGION = 16;
213 // pre-processor if stack state:
217 static System.Text.StringBuilder string_builder;
219 const int max_id_size = 512;
220 static char [] id_builder = new char [max_id_size];
222 static CharArrayHashtable [] identifiers = new CharArrayHashtable [max_id_size + 1];
224 const int max_number_size = 512;
225 static char [] number_builder = new char [max_number_size];
226 static int number_pos;
229 // Details about the error encoutered by the tokenizer
231 string error_details;
233 public string error {
235 return error_details;
252 // This is used when the tokenizer needs to save
253 // the current position as it needs to do some parsing
254 // on its own to deamiguate a token in behalf of the
257 Stack position_stack = new Stack (2);
264 public int putback_char;
265 public int previous_col;
266 public Stack ifstack;
267 public int parsing_generic_less_than;
268 public int current_token;
270 public Position (Tokenizer t)
272 position = t.reader.Position;
274 ref_line = t.ref_line;
277 putback_char = t.putback_char;
278 previous_col = t.previous_col;
279 if (t.ifstack != null && t.ifstack.Count != 0)
280 ifstack = (Stack)t.ifstack.Clone ();
281 parsing_generic_less_than = t.parsing_generic_less_than;
282 current_token = t.current_token;
286 public void PushPosition ()
288 position_stack.Push (new Position (this));
291 public void PopPosition ()
293 Position p = (Position) position_stack.Pop ();
295 reader.Position = p.position;
296 ref_line = p.ref_line;
300 putback_char = p.putback_char;
301 previous_col = p.previous_col;
303 parsing_generic_less_than = p.parsing_generic_less_than;
304 current_token = p.current_token;
307 // Do not reset the position, ignore it.
308 public void DiscardPosition ()
310 position_stack.Pop ();
313 static void AddKeyword (string kw, int token)
315 keyword_strings.Add (kw, kw);
316 if (keywords [kw.Length] == null) {
317 keywords [kw.Length] = new CharArrayHashtable (kw.Length);
319 keywords [kw.Length] [kw.ToCharArray ()] = token;
322 static void InitTokens ()
324 keyword_strings = new Hashtable ();
325 keywords = new CharArrayHashtable [64];
327 AddKeyword ("__arglist", Token.ARGLIST);
328 AddKeyword ("abstract", Token.ABSTRACT);
329 AddKeyword ("as", Token.AS);
330 AddKeyword ("add", Token.ADD);
331 AddKeyword ("assembly", Token.ASSEMBLY);
332 AddKeyword ("base", Token.BASE);
333 AddKeyword ("bool", Token.BOOL);
334 AddKeyword ("break", Token.BREAK);
335 AddKeyword ("byte", Token.BYTE);
336 AddKeyword ("case", Token.CASE);
337 AddKeyword ("catch", Token.CATCH);
338 AddKeyword ("char", Token.CHAR);
339 AddKeyword ("checked", Token.CHECKED);
340 AddKeyword ("class", Token.CLASS);
341 AddKeyword ("const", Token.CONST);
342 AddKeyword ("continue", Token.CONTINUE);
343 AddKeyword ("decimal", Token.DECIMAL);
344 AddKeyword ("default", Token.DEFAULT);
345 AddKeyword ("delegate", Token.DELEGATE);
346 AddKeyword ("do", Token.DO);
347 AddKeyword ("double", Token.DOUBLE);
348 AddKeyword ("else", Token.ELSE);
349 AddKeyword ("enum", Token.ENUM);
350 AddKeyword ("event", Token.EVENT);
351 AddKeyword ("explicit", Token.EXPLICIT);
352 AddKeyword ("extern", Token.EXTERN);
353 AddKeyword ("false", Token.FALSE);
354 AddKeyword ("finally", Token.FINALLY);
355 AddKeyword ("fixed", Token.FIXED);
356 AddKeyword ("float", Token.FLOAT);
357 AddKeyword ("for", Token.FOR);
358 AddKeyword ("foreach", Token.FOREACH);
359 AddKeyword ("goto", Token.GOTO);
360 AddKeyword ("get", Token.GET);
361 AddKeyword ("if", Token.IF);
362 AddKeyword ("implicit", Token.IMPLICIT);
363 AddKeyword ("in", Token.IN);
364 AddKeyword ("int", Token.INT);
365 AddKeyword ("interface", Token.INTERFACE);
366 AddKeyword ("internal", Token.INTERNAL);
367 AddKeyword ("is", Token.IS);
368 AddKeyword ("lock", Token.LOCK);
369 AddKeyword ("long", Token.LONG);
370 AddKeyword ("namespace", Token.NAMESPACE);
371 AddKeyword ("new", Token.NEW);
372 AddKeyword ("null", Token.NULL);
373 AddKeyword ("object", Token.OBJECT);
374 AddKeyword ("operator", Token.OPERATOR);
375 AddKeyword ("out", Token.OUT);
376 AddKeyword ("override", Token.OVERRIDE);
377 AddKeyword ("params", Token.PARAMS);
378 AddKeyword ("private", Token.PRIVATE);
379 AddKeyword ("protected", Token.PROTECTED);
380 AddKeyword ("public", Token.PUBLIC);
381 AddKeyword ("readonly", Token.READONLY);
382 AddKeyword ("ref", Token.REF);
383 AddKeyword ("remove", Token.REMOVE);
384 AddKeyword ("return", Token.RETURN);
385 AddKeyword ("sbyte", Token.SBYTE);
386 AddKeyword ("sealed", Token.SEALED);
387 AddKeyword ("set", Token.SET);
388 AddKeyword ("short", Token.SHORT);
389 AddKeyword ("sizeof", Token.SIZEOF);
390 AddKeyword ("stackalloc", Token.STACKALLOC);
391 AddKeyword ("static", Token.STATIC);
392 AddKeyword ("string", Token.STRING);
393 AddKeyword ("struct", Token.STRUCT);
394 AddKeyword ("switch", Token.SWITCH);
395 AddKeyword ("this", Token.THIS);
396 AddKeyword ("throw", Token.THROW);
397 AddKeyword ("true", Token.TRUE);
398 AddKeyword ("try", Token.TRY);
399 AddKeyword ("typeof", Token.TYPEOF);
400 AddKeyword ("uint", Token.UINT);
401 AddKeyword ("ulong", Token.ULONG);
402 AddKeyword ("unchecked", Token.UNCHECKED);
403 AddKeyword ("unsafe", Token.UNSAFE);
404 AddKeyword ("ushort", Token.USHORT);
405 AddKeyword ("using", Token.USING);
406 AddKeyword ("virtual", Token.VIRTUAL);
407 AddKeyword ("void", Token.VOID);
408 AddKeyword ("volatile", Token.VOLATILE);
409 AddKeyword ("while", Token.WHILE);
410 AddKeyword ("partial", Token.PARTIAL);
411 AddKeyword ("where", Token.WHERE);
414 AddKeyword ("from", Token.FROM);
415 AddKeyword ("join", Token.JOIN);
416 AddKeyword ("on", Token.ON);
417 AddKeyword ("equals", Token.EQUALS);
418 AddKeyword ("select", Token.SELECT);
419 AddKeyword ("group", Token.GROUP);
420 AddKeyword ("by", Token.BY);
421 AddKeyword ("let", Token.LET);
422 AddKeyword ("orderby", Token.ORDERBY);
423 AddKeyword ("ascending", Token.ASCENDING);
424 AddKeyword ("descending", Token.DESCENDING);
425 AddKeyword ("into", Token.INTO);
436 public static void Reset ()
439 csharp_format_info = NumberFormatInfo.InvariantInfo;
440 styles = NumberStyles.Float;
442 string_builder = new System.Text.StringBuilder ();
445 int GetKeyword (char[] id, int id_len)
448 * Keywords are stored in an array of hashtables grouped by their
452 if ((id_len >= keywords.Length) || (keywords [id_len] == null))
454 object o = keywords [id_len] [id];
461 if (!handle_get_set && (res == Token.GET || res == Token.SET))
463 if (!handle_remove_add && (res == Token.REMOVE || res == Token.ADD))
465 if (!handle_assembly && res == Token.ASSEMBLY)
469 // A query expression is any expression that starts with `from identifier'
470 // followed by any token except ; , =
472 if (query_parsing == 0) {
473 if (res == Token.FROM && !lambda_arguments_parsing) {
475 // HACK: to disable generics micro-parser, because PushPosition does not
476 // store identifiers array
477 parsing_generic_less_than = 1;
479 case Token.IDENTIFIER:
491 int next_token = xtoken ();
492 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
496 if (RootContext.Version <= LanguageVersion.ISO_2)
497 Report.FeatureIsNotAvailable (Location, "query expressions");
500 Expression.Error_VoidInvalidInTheContext (Location);
504 // HACK: A token is not a keyword so we need to restore identifiers buffer
505 // which has been overwritten before we grabbed the identifier
506 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
513 if (res > Token.QUERY_FIRST_TOKEN && res < Token.QUERY_LAST_TOKEN)
517 if (res == Token.WHERE && !handle_where && query_parsing == 0)
523 public Location Location {
524 get { return current_location; }
527 public Tokenizer (SeekableStreamReader input, CompilationUnit file)
529 this.ref_name = file;
530 this.file_name = file;
535 xml_comment_buffer = new StringBuilder ();
538 // FIXME: This could be `Location.Push' but we have to
539 // find out why the MS compiler allows this
541 Mono.CSharp.Location.Push (file, file);
544 static bool is_identifier_start_character (char c)
546 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter (c);
549 static bool is_identifier_part_character (char c)
551 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') ||
552 Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
555 public static bool IsKeyword (string s)
557 return keyword_strings [s] != null;
561 // Tests whether '(' is beggining of lambda parameters
563 bool IsLambdaOpenParens ()
566 while ((ntoken = xtoken ()) != Token.EOF) {
568 case Token.CLOSE_PARENS:
569 return xtoken () == Token.ARROW;
572 case Token.SEMICOLON:
573 case Token.OPEN_BRACE:
574 case Token.OPEN_PARENS:
575 case Token.LITERAL_STRING:
576 case Token.LITERAL_INTEGER:
577 case Token.LITERAL_FLOAT:
578 case Token.LITERAL_DOUBLE:
579 case Token.LITERAL_DECIMAL:
580 case Token.LITERAL_CHARACTER:
586 case Token.OP_SHIFT_LEFT:
587 case Token.OP_SHIFT_RIGHT:
594 case Token.BITWISE_AND:
595 case Token.BITWISE_OR:
607 Error_TokenExpected (",' or `)");
611 public static bool IsValidIdentifier (string s)
613 if (s == null || s.Length == 0)
616 if (!is_identifier_start_character (s [0]))
619 for (int i = 1; i < s.Length; i ++)
620 if (! is_identifier_part_character (s [i]))
626 bool parse_less_than ()
629 int the_token = token ();
630 if (the_token == Token.OPEN_BRACKET) {
632 the_token = token ();
633 } while (the_token != Token.CLOSE_BRACKET);
634 the_token = token ();
637 case Token.IDENTIFIER:
656 case Token.OP_GENERICS_GT:
663 the_token = token ();
665 if (the_token == Token.OP_GENERICS_GT)
667 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
669 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
671 else if (the_token == Token.OP_GENERICS_LT) {
672 if (!parse_less_than ())
675 } else if (the_token == Token.OPEN_BRACKET) {
677 the_token = token ();
678 if (the_token == Token.CLOSE_BRACKET)
680 else if (the_token == Token.COMMA)
681 goto rank_specifiers;
688 bool parse_generic_dimension (out int dimension)
693 int the_token = token ();
694 if (the_token == Token.OP_GENERICS_GT)
696 else if (the_token == Token.COMMA) {
704 public int peek_token ()
709 the_token = token ();
715 int parsing_generic_less_than = 0;
717 int is_punct (char c, ref bool doread)
727 return Token.OPEN_BRACE;
730 return Token.CLOSE_BRACE;
732 // To block doccomment inside attribute declaration.
733 if (doc_state == XmlCommentState.Allowed)
734 doc_state = XmlCommentState.NotAllowed;
735 return Token.OPEN_BRACKET;
737 return Token.CLOSE_BRACKET;
740 // A lambda expression can appear in block context only
742 if (parsing_block != 0 && !lambda_arguments_parsing) {
743 lambda_arguments_parsing = true;
745 bool lambda_start = IsLambdaOpenParens ();
747 lambda_arguments_parsing = false;
749 if (RootContext.Version <= LanguageVersion.ISO_2)
750 Report.FeatureIsNotAvailable (Location, "lambda expressions");
752 return Token.OPEN_PARENS_LAMBDA;
755 return Token.OPEN_PARENS;
757 if (deambiguate_close_parens == 0)
758 return Token.CLOSE_PARENS;
760 --deambiguate_close_parens;
764 int new_token = xtoken ();
768 if (new_token == Token.OPEN_PARENS)
769 return Token.CLOSE_PARENS_OPEN_PARENS;
770 else if (new_token == Token.MINUS)
771 return Token.CLOSE_PARENS_MINUS;
772 else if (IsCastToken (new_token))
773 return Token.CLOSE_PARENS_CAST;
775 return Token.CLOSE_PARENS_NO_CAST;
782 return Token.SEMICOLON;
787 return TokenizePossibleNullableType ();
791 if (parsing_generic_less_than++ > 0)
792 return Token.OP_GENERICS_LT;
797 if (parse_generic_dimension (out dimension)) {
800 return Token.GENERIC_DIMENSION;
805 // Save current position and parse next token.
807 bool is_generic_lt = parse_less_than ();
811 return Token.OP_GENERICS_LT;
813 parsing_generic_less_than = 0;
822 return Token.OP_SHIFT_LEFT_ASSIGN;
824 return Token.OP_SHIFT_LEFT;
825 } else if (d == '='){
830 } else if (c == '>') {
838 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
839 parsing_generic_less_than--;
840 return Token.OP_GENERICS_GT;
849 return Token.OP_SHIFT_RIGHT_ASSIGN;
851 return Token.OP_SHIFT_RIGHT;
865 t = Token.OP_ADD_ASSIGN;
879 t = Token.OP_SUB_ASSIGN;
917 } else if (d == '='){
919 return Token.OP_AND_ASSIGN;
922 return Token.BITWISE_AND;
929 } else if (d == '='){
931 return Token.OP_OR_ASSIGN;
933 return Token.BITWISE_OR;
939 return Token.OP_MULT_ASSIGN;
948 return Token.OP_DIV_ASSIGN;
956 return Token.OP_MOD_ASSIGN;
958 return Token.PERCENT;
964 return Token.OP_XOR_ASSIGN;
972 return Token.DOUBLE_COLON;
982 // Tonizes `?' using custom disambiguous rules to return one
983 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
985 // Tricky expression look like:
987 // Foo ? a = x ? b : c;
989 int TokenizePossibleNullableType ()
991 if (parsing_block == 0)
992 return Token.INTERR_NULLABLE;
994 int d = peek_char ();
997 return Token.OP_COALESCING;
1000 switch (current_token) {
1001 case Token.CLOSE_PARENS:
1005 case Token.LITERAL_INTEGER:
1006 case Token.LITERAL_STRING:
1007 return Token.INTERR;
1011 if (d == ',' || d == ';' || d == '>')
1012 return Token.INTERR_NULLABLE;
1013 if (d == '*' || (d >= '0' && d <= '9'))
1014 return Token.INTERR;
1019 switch (xtoken ()) {
1020 case Token.LITERAL_INTEGER:
1021 case Token.LITERAL_STRING:
1022 case Token.LITERAL_CHARACTER:
1023 case Token.LITERAL_DECIMAL:
1024 case Token.LITERAL_DOUBLE:
1025 case Token.LITERAL_FLOAT:
1030 next_token = Token.INTERR;
1033 case Token.SEMICOLON:
1035 case Token.CLOSE_PARENS:
1036 case Token.OPEN_BRACKET:
1037 case Token.OP_GENERICS_GT:
1038 next_token = Token.INTERR_NULLABLE;
1046 if (next_token == -1) {
1047 switch (xtoken ()) {
1049 case Token.SEMICOLON:
1050 case Token.OPEN_BRACE:
1051 case Token.CLOSE_PARENS:
1053 next_token = Token.INTERR_NULLABLE;
1057 next_token = Token.INTERR;
1065 // All shorcuts failed, do it hard way
1067 while ((ntoken = xtoken ()) != Token.EOF) {
1068 if (ntoken == Token.SEMICOLON)
1071 if (ntoken == Token.COLON) {
1072 if (++colons == interrs)
1077 if (ntoken == Token.INTERR) {
1083 next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1092 int deambiguate_close_parens = 0;
1094 public void Deambiguate_CloseParens (object expression)
1098 // When any binary operation, a conditional is used we are sure it is not a cast
1101 if (expression is Binary || expression is Conditional)
1104 deambiguate_close_parens++;
1107 bool decimal_digits (int c)
1110 bool seen_digits = false;
1113 if (number_pos == max_number_size)
1114 Error_NumericConstantTooLong ();
1115 number_builder [number_pos++] = (char) c;
1119 // We use peek_char2, because decimal_digits needs to do a
1120 // 2-character look-ahead (5.ToString for example).
1122 while ((d = peek_char2 ()) != -1){
1123 if (d >= '0' && d <= '9'){
1124 if (number_pos == max_number_size)
1125 Error_NumericConstantTooLong ();
1126 number_builder [number_pos++] = (char) d;
1136 static bool is_hex (int e)
1138 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1141 static int real_type_suffix (int c)
1147 t = Token.LITERAL_FLOAT;
1150 t = Token.LITERAL_DOUBLE;
1153 t= Token.LITERAL_DECIMAL;
1161 int integer_type_suffix (ulong ul, int c)
1163 bool is_unsigned = false;
1164 bool is_long = false;
1167 bool scanning = true;
1180 // if we have not seen anything in between
1181 // report this error
1183 Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1186 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1187 // work around that.
1211 if (is_long && is_unsigned){
1213 return Token.LITERAL_INTEGER;
1214 } else if (is_unsigned){
1215 // uint if possible, or ulong else.
1217 if ((ul & 0xffffffff00000000) == 0)
1221 } else if (is_long){
1222 // long if possible, ulong otherwise
1223 if ((ul & 0x8000000000000000) != 0)
1228 // int, uint, long or ulong in that order
1229 if ((ul & 0xffffffff00000000) == 0){
1230 uint ui = (uint) ul;
1232 if ((ui & 0x80000000) != 0)
1237 if ((ul & 0x8000000000000000) != 0)
1243 return Token.LITERAL_INTEGER;
1247 // given `c' as the next char in the input decide whether
1248 // we need to convert to a special type, and then choose
1249 // the best representation for the integer
1251 int adjust_int (int c)
1254 if (number_pos > 9){
1255 ulong ul = (uint) (number_builder [0] - '0');
1257 for (int i = 1; i < number_pos; i++){
1258 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1260 return integer_type_suffix (ul, c);
1262 uint ui = (uint) (number_builder [0] - '0');
1264 for (int i = 1; i < number_pos; i++){
1265 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1267 return integer_type_suffix (ui, c);
1269 } catch (OverflowException) {
1270 error_details = "Integral constant is too large";
1271 Report.Error (1021, Location, error_details);
1273 return Token.LITERAL_INTEGER;
1275 catch (FormatException) {
1276 Report.Error (1013, Location, "Invalid number");
1278 return Token.LITERAL_INTEGER;
1282 int adjust_real (int t)
1284 string s = new String (number_builder, 0, number_pos);
1285 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1288 case Token.LITERAL_DECIMAL:
1290 val = System.Decimal.Parse (s, styles, csharp_format_info);
1291 } catch (OverflowException) {
1293 Report.Error (594, Location, error_details, "decimal");
1296 case Token.LITERAL_FLOAT:
1298 val = float.Parse (s, styles, csharp_format_info);
1299 } catch (OverflowException) {
1301 Report.Error (594, Location, error_details, "float");
1305 case Token.LITERAL_DOUBLE:
1307 t = Token.LITERAL_DOUBLE;
1309 val = System.Double.Parse (s, styles, csharp_format_info);
1310 } catch (OverflowException) {
1312 Report.Error (594, Location, error_details, "double");
1325 while ((d = peek_char ()) != -1){
1327 number_builder [number_pos++] = (char) d;
1333 string s = new String (number_builder, 0, number_pos);
1335 if (number_pos <= 8)
1336 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1338 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1339 } catch (OverflowException){
1340 error_details = "Integral constant is too large";
1341 Report.Error (1021, Location, error_details);
1343 return Token.LITERAL_INTEGER;
1345 catch (FormatException) {
1346 Report.Error (1013, Location, "Invalid number");
1348 return Token.LITERAL_INTEGER;
1351 return integer_type_suffix (ul, peek_char ());
1355 // Invoked if we know we have .digits or digits
1357 int is_number (int c)
1359 bool is_real = false;
1364 if (c >= '0' && c <= '9'){
1366 int peek = peek_char ();
1368 if (peek == 'x' || peek == 'X')
1369 return handle_hex ();
1376 // We need to handle the case of
1377 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1380 if (decimal_digits ('.')){
1386 return adjust_int (-1);
1390 if (c == 'e' || c == 'E'){
1392 if (number_pos == max_number_size)
1393 Error_NumericConstantTooLong ();
1394 number_builder [number_pos++] = 'e';
1398 if (number_pos == max_number_size)
1399 Error_NumericConstantTooLong ();
1400 number_builder [number_pos++] = '+';
1402 } else if (c == '-') {
1403 if (number_pos == max_number_size)
1404 Error_NumericConstantTooLong ();
1405 number_builder [number_pos++] = '-';
1408 if (number_pos == max_number_size)
1409 Error_NumericConstantTooLong ();
1410 number_builder [number_pos++] = '+';
1417 type = real_type_suffix (c);
1418 if (type == Token.NONE && !is_real){
1420 return adjust_int (c);
1424 if (type == Token.NONE){
1429 return adjust_real (type);
1431 Console.WriteLine ("This should not be reached");
1432 throw new Exception ("Is Number should never reach this point");
1436 // Accepts exactly count (4 or 8) hex, no more no less
1438 int getHex (int count, out int surrogate, out bool error)
1443 int top = count != -1 ? count : 4;
1448 for (i = 0; i < top; i++){
1451 if (c >= '0' && c <= '9')
1452 c = (int) c - (int) '0';
1453 else if (c >= 'A' && c <= 'F')
1454 c = (int) c - (int) 'A' + 10;
1455 else if (c >= 'a' && c <= 'f')
1456 c = (int) c - (int) 'a' + 10;
1462 total = (total * 16) + c;
1464 int p = peek_char ();
1467 if (!is_hex ((char)p))
1473 if (total > 0x0010FFFF) {
1478 if (total >= 0x00010000) {
1479 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1480 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1487 int escape (int c, out int surrogate)
1523 v = getHex (-1, out surrogate, out error);
1529 return EscapeUnicode (d, out surrogate);
1532 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1541 int EscapeUnicode (int ch, out int surrogate)
1545 ch = getHex (8, out surrogate, out error);
1547 ch = getHex (4, out surrogate, out error);
1551 Report.Error (1009, Location, "Unrecognized escape sequence");
1559 if (putback_char != -1) {
1572 void advance_line ()
1582 if (putback_char != -1)
1583 return putback_char;
1584 putback_char = reader.Read ();
1585 return putback_char;
1590 if (putback_char != -1)
1591 return putback_char;
1592 return reader.Peek ();
1595 void putback (int c)
1597 if (putback_char != -1){
1598 Console.WriteLine ("Col: " + col);
1599 Console.WriteLine ("Row: " + line);
1600 Console.WriteLine ("Name: " + ref_name.Name);
1601 Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
1602 throw new Exception ("This should not happen putback on putback");
1604 if (c == '\n' || col == 0) {
1605 // It won't happen though.
1615 public bool advance ()
1617 return peek_char () != -1;
1620 public Object Value {
1626 public Object value ()
1631 static bool IsCastToken (int token)
1636 case Token.IDENTIFIER:
1637 case Token.LITERAL_INTEGER:
1638 case Token.LITERAL_FLOAT:
1639 case Token.LITERAL_DOUBLE:
1640 case Token.LITERAL_DECIMAL:
1641 case Token.LITERAL_CHARACTER:
1642 case Token.LITERAL_STRING:
1645 case Token.DELEGATE:
1655 case Token.UNCHECKED:
1660 // These can be part of a member access
1682 current_token = xtoken ();
1684 if (current_token != Token.DEFAULT)
1685 return current_token;
1690 current_token = Token.ERROR;
1691 else if (c == Token.OPEN_PARENS)
1692 current_token = Token.DEFAULT_OPEN_PARENS;
1693 else if (c == Token.COLON)
1694 current_token = Token.DEFAULT_COLON;
1698 return current_token;
1701 static StringBuilder static_cmd_arg = new System.Text.StringBuilder ();
1703 void get_cmd_arg (out string cmd, out string arg)
1707 tokens_seen = false;
1710 // skip over white space
1713 } while (c == '\r' || c == ' ' || c == '\t');
1715 static_cmd_arg.Length = 0;
1716 while (c != -1 && is_identifier_part_character ((char)c)) {
1717 static_cmd_arg.Append ((char)c);
1720 int peek = peek_char ();
1721 if (peek == 'U' || peek == 'u') {
1723 c = EscapeUnicode (c, out surrogate);
1724 if (surrogate != 0) {
1725 if (is_identifier_part_character ((char) c))
1726 static_cmd_arg.Append ((char) c);
1733 cmd = static_cmd_arg.ToString ();
1735 // skip over white space
1736 while (c == '\r' || c == ' ' || c == '\t')
1739 static_cmd_arg.Length = 0;
1740 while (c != -1 && c != '\n' && c != '\r') {
1742 int peek = peek_char ();
1743 if (peek == 'U' || peek == 'u') {
1745 c = EscapeUnicode (c, out surrogate);
1746 if (surrogate != 0) {
1747 if (is_identifier_part_character ((char) c))
1748 static_cmd_arg.Append ((char) c);
1753 static_cmd_arg.Append ((char) c);
1757 if (static_cmd_arg.Length != 0)
1758 arg = static_cmd_arg.ToString ();
1762 // Handles the #line directive
1764 bool PreProcessLine (string arg)
1766 if (arg.Length == 0)
1769 if (arg == "default"){
1771 ref_name = file_name;
1773 Location.Push (file_name, ref_name);
1775 } else if (arg == "hidden"){
1783 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1784 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1787 char [] quotes = { '\"' };
1789 string name = arg.Substring (pos). Trim (quotes);
1790 ref_name = Location.LookupFile (file_name, name);
1791 file_name.AddFile (ref_name);
1793 Location.Push (file_name, ref_name);
1795 ref_line = System.Int32.Parse (arg);
1806 // Handles #define and #undef
1808 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1810 if (ident.Length == 0 || ident == "true" || ident == "false"){
1811 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1815 if (ident.IndexOfAny (simple_whitespaces) != -1){
1816 Error_EndLineExpected ();
1820 if (!is_identifier_start_character (ident [0]))
1821 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1823 foreach (char c in ident.Substring (1)){
1824 if (!is_identifier_part_character (c)){
1825 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1830 if (!caller_is_taking)
1837 if (RootContext.IsConditionalDefined (ident))
1840 file_name.AddDefine (ident);
1845 file_name.AddUndefine (ident);
1849 static byte read_hex (string arg, int pos, out bool error)
1856 if ((c >= '0') && (c <= '9'))
1857 total = (int) c - (int) '0';
1858 else if ((c >= 'A') && (c <= 'F'))
1859 total = (int) c - (int) 'A' + 10;
1860 else if ((c >= 'a') && (c <= 'f'))
1861 total = (int) c - (int) 'a' + 10;
1870 if ((c >= '0') && (c <= '9'))
1871 total += (int) c - (int) '0';
1872 else if ((c >= 'A') && (c <= 'F'))
1873 total += (int) c - (int) 'A' + 10;
1874 else if ((c >= 'a') && (c <= 'f'))
1875 total += (int) c - (int) 'a' + 10;
1881 return (byte) total;
1885 /// Handles #pragma checksum
1887 bool PreProcessPragmaChecksum (string arg)
1889 if ((arg [0] != ' ') && (arg [0] != '\t'))
1892 arg = arg.Trim (simple_whitespaces);
1893 if ((arg.Length < 2) || (arg [0] != '"'))
1896 StringBuilder file_sb = new StringBuilder ();
1900 while ((ch = arg [pos++]) != '"') {
1901 if (pos >= arg.Length)
1905 if (pos+1 >= arg.Length)
1910 file_sb.Append (ch);
1913 if ((pos+2 >= arg.Length) || ((arg [pos] != ' ') && (arg [pos] != '\t')))
1916 arg = arg.Substring (pos).Trim (simple_whitespaces);
1917 if ((arg.Length < 42) || (arg [0] != '"') || (arg [1] != '{') ||
1918 (arg [10] != '-') || (arg [15] != '-') || (arg [20] != '-') ||
1919 (arg [25] != '-') || (arg [38] != '}') || (arg [39] != '"'))
1923 byte[] guid_bytes = new byte [16];
1925 for (int i = 0; i < 4; i++) {
1926 guid_bytes [i] = read_hex (arg, 2+2*i, out error);
1930 for (int i = 0; i < 2; i++) {
1931 guid_bytes [i+4] = read_hex (arg, 11+2*i, out error);
1934 guid_bytes [i+6] = read_hex (arg, 16+2*i, out error);
1937 guid_bytes [i+8] = read_hex (arg, 21+2*i, out error);
1942 for (int i = 0; i < 6; i++) {
1943 guid_bytes [i+10] = read_hex (arg, 26+2*i, out error);
1948 arg = arg.Substring (40).Trim (simple_whitespaces);
1949 if ((arg.Length < 34) || (arg [0] != '"') || (arg [33] != '"'))
1952 byte[] checksum_bytes = new byte [16];
1953 for (int i = 0; i < 16; i++) {
1954 checksum_bytes [i] = read_hex (arg, 1+2*i, out error);
1959 arg = arg.Substring (34).Trim (simple_whitespaces);
1963 SourceFile file = Location.LookupFile (file_name, file_sb.ToString ());
1964 file.SetChecksum (guid_bytes, checksum_bytes);
1965 ref_name.AutoGenerated = true;
1970 /// Handles #pragma directive
1972 void PreProcessPragma (string arg)
1974 const string warning = "warning";
1975 const string w_disable = "warning disable";
1976 const string w_restore = "warning restore";
1977 const string checksum = "checksum";
1979 if (arg == w_disable) {
1980 Report.RegisterWarningRegion (Location).WarningDisable (Location.Row);
1984 if (arg == w_restore) {
1985 Report.RegisterWarningRegion (Location).WarningEnable (Location.Row);
1989 if (arg.StartsWith (w_disable)) {
1990 int[] codes = ParseNumbers (arg.Substring (w_disable.Length));
1991 foreach (int code in codes) {
1993 Report.RegisterWarningRegion (Location).WarningDisable (Location, code);
1998 if (arg.StartsWith (w_restore)) {
1999 int[] codes = ParseNumbers (arg.Substring (w_restore.Length));
2000 Hashtable w_table = Report.warning_ignore_table;
2001 foreach (int code in codes) {
2002 if (w_table != null && w_table.Contains (code))
2003 Report.Warning (1635, 1, Location, String.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code));
2004 Report.RegisterWarningRegion (Location).WarningEnable (Location, code);
2009 if (arg.StartsWith (warning)) {
2010 Report.Warning (1634, 1, Location, "Expected disable or restore");
2014 if (arg.StartsWith (checksum)) {
2015 if (!PreProcessPragmaChecksum (arg.Substring (checksum.Length)))
2016 Warning_InvalidPragmaChecksum ();
2020 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2023 int[] ParseNumbers (string text)
2025 string[] string_array = text.Split (',');
2026 int[] values = new int [string_array.Length];
2028 foreach (string string_code in string_array) {
2030 values[index++] = int.Parse (string_code, System.Globalization.CultureInfo.InvariantCulture);
2032 catch (FormatException) {
2033 Report.Warning (1692, 1, Location, "Invalid number");
2039 bool eval_val (string s)
2046 return file_name.IsConditionalDefined (s);
2049 bool pp_primary (ref string s)
2058 s = s.Substring (1);
2059 bool val = pp_expr (ref s, false);
2060 if (s.Length > 0 && s [0] == ')'){
2061 s = s.Substring (1);
2064 Error_InvalidDirective ();
2068 if (is_identifier_start_character (c)){
2074 if (is_identifier_part_character (c)){
2078 bool v = eval_val (s.Substring (0, j));
2079 s = s.Substring (j);
2082 bool vv = eval_val (s);
2087 Error_InvalidDirective ();
2091 bool pp_unary (ref string s)
2098 if (len > 1 && s [1] == '='){
2099 Error_InvalidDirective ();
2102 s = s.Substring (1);
2103 return ! pp_primary (ref s);
2105 return pp_primary (ref s);
2107 Error_InvalidDirective ();
2112 bool pp_eq (ref string s)
2114 bool va = pp_unary (ref s);
2120 if (len > 2 && s [1] == '='){
2121 s = s.Substring (2);
2122 return va == pp_unary (ref s);
2124 Error_InvalidDirective ();
2127 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2128 s = s.Substring (2);
2130 return va != pp_unary (ref s);
2139 bool pp_and (ref string s)
2141 bool va = pp_eq (ref s);
2147 if (len > 2 && s [1] == '&'){
2148 s = s.Substring (2);
2149 return (va & pp_and (ref s));
2151 Error_InvalidDirective ();
2160 // Evaluates an expression for `#if' or `#elif'
2162 bool pp_expr (ref string s, bool isTerm)
2164 bool va = pp_and (ref s);
2171 if (len > 2 && s [1] == '|'){
2172 s = s.Substring (2);
2173 return va | pp_expr (ref s, isTerm);
2175 Error_InvalidDirective ();
2180 Error_EndLineExpected ();
2188 bool eval (string s)
2190 bool v = pp_expr (ref s, true);
2199 void Error_NumericConstantTooLong ()
2201 Report.Error (1021, Location, "Numeric constant too long");
2204 void Error_InvalidDirective ()
2206 Report.Error (1517, Location, "Invalid preprocessor directive");
2209 void Error_UnexpectedDirective (string extra)
2213 "Unexpected processor directive ({0})", extra);
2216 void Error_TokenExpected (string token)
2218 Report.Error (1026, Location, "Expected `{0}'", token);
2221 void Error_TokensSeen ()
2223 Report.Error (1032, Location,
2224 "Cannot define or undefine preprocessor symbols after first token in file");
2227 void Eror_WrongPreprocessorLocation ()
2229 Report.Error (1040, Location,
2230 "Preprocessor directives must appear as the first non-whitespace character on a line");
2233 void Error_EndLineExpected ()
2235 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2238 void Warning_InvalidPragmaChecksum ()
2240 Report.Warning (1695, 1, Location,
2241 "Invalid #pragma checksum syntax; should be " +
2242 "#pragma checksum \"filename\" " +
2243 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2246 // if true, then the code continues processing the code
2247 // if false, the code stays in a loop until another directive is
2249 // When caller_is_taking is false we ignore all directives except the ones
2250 // which can help us to identify where the #if block ends
2251 bool handle_preprocessing_directive (bool caller_is_taking)
2254 bool region_directive = false;
2256 get_cmd_arg (out cmd, out arg);
2258 // Eat any trailing whitespaces and single-line comments
2259 if (arg.IndexOf ("//") != -1)
2260 arg = arg.Substring (0, arg.IndexOf ("//"));
2261 arg = arg.Trim (simple_whitespaces);
2264 // The first group of pre-processing instructions is always processed
2268 region_directive = true;
2273 if (ifstack == null || ifstack.Count == 0){
2274 Error_UnexpectedDirective ("no #region for this #endregion");
2277 int pop = (int) ifstack.Pop ();
2279 if ((pop & REGION) == 0)
2280 Report.Error (1027, Location, "Expected `#endif' directive");
2282 return caller_is_taking;
2285 if (ifstack == null)
2286 ifstack = new Stack (2);
2288 int flags = region_directive ? REGION : 0;
2289 if (ifstack.Count == 0){
2290 flags |= PARENT_TAKING;
2292 int state = (int) ifstack.Peek ();
2293 if ((state & TAKING) != 0) {
2294 flags |= PARENT_TAKING;
2298 if (caller_is_taking && eval (arg)) {
2299 ifstack.Push (flags | TAKING);
2302 ifstack.Push (flags);
2306 if (ifstack == null || ifstack.Count == 0){
2307 Error_UnexpectedDirective ("no #if for this #endif");
2310 pop = (int) ifstack.Pop ();
2312 if ((pop & REGION) != 0)
2313 Report.Error (1038, Location, "#endregion directive expected");
2315 if (arg.Length != 0) {
2316 Error_EndLineExpected ();
2319 if (ifstack.Count == 0)
2322 int state = (int) ifstack.Peek ();
2323 return (state & TAKING) != 0;
2327 if (ifstack == null || ifstack.Count == 0){
2328 Error_UnexpectedDirective ("no #if for this #elif");
2331 int state = (int) ifstack.Pop ();
2333 if ((state & REGION) != 0) {
2334 Report.Error (1038, Location, "#endregion directive expected");
2338 if ((state & ELSE_SEEN) != 0){
2339 Error_UnexpectedDirective ("#elif not valid after #else");
2343 if ((state & TAKING) != 0) {
2348 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2349 ifstack.Push (state | TAKING);
2353 ifstack.Push (state);
2358 if (ifstack == null || ifstack.Count == 0){
2359 Error_UnexpectedDirective ("no #if for this #else");
2362 int state = (int) ifstack.Peek ();
2364 if ((state & REGION) != 0) {
2365 Report.Error (1038, Location, "#endregion directive expected");
2369 if ((state & ELSE_SEEN) != 0){
2370 Error_UnexpectedDirective ("#else within #else");
2376 if (arg.Length != 0) {
2377 Error_EndLineExpected ();
2382 if ((state & PARENT_TAKING) != 0) {
2383 ret = (state & TAKING) == 0;
2391 ifstack.Push (state | ELSE_SEEN);
2396 if (any_token_seen){
2397 Error_TokensSeen ();
2398 return caller_is_taking;
2400 PreProcessDefinition (true, arg, caller_is_taking);
2401 return caller_is_taking;
2404 if (any_token_seen){
2405 Error_TokensSeen ();
2406 return caller_is_taking;
2408 PreProcessDefinition (false, arg, caller_is_taking);
2409 return caller_is_taking;
2413 // These are only processed if we are in a `taking' block
2415 if (!caller_is_taking)
2420 Report.Error (1029, Location, "#error: '{0}'", arg);
2424 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2428 if (RootContext.Version == LanguageVersion.ISO_1) {
2429 Report.FeatureIsNotAvailable (Location, "#pragma");
2433 PreProcessPragma (arg);
2437 if (!PreProcessLine (arg))
2440 "The line number specified for #line directive is missing or invalid");
2441 return caller_is_taking;
2444 Report.Error (1024, Location, "Wrong preprocessor directive");
2449 private int consume_string (bool quoted)
2452 string_builder.Length = 0;
2455 // No need to parse full string when parsing lambda arguments
2457 if (lambda_arguments_parsing)
2458 return Token.LITERAL_STRING;
2460 while ((c = get_char ()) != -1){
2462 if (quoted && peek_char () == '"'){
2463 string_builder.Append ((char) c);
2467 val = string_builder.ToString ();
2468 return Token.LITERAL_STRING;
2474 Report.Error (1010, Location, "Newline in constant");
2479 c = escape (c, out surrogate);
2482 if (surrogate != 0) {
2483 string_builder.Append ((char) c);
2487 string_builder.Append ((char) c);
2490 Report.Error (1039, Location, "Unterminated string literal");
2494 private int consume_identifier (int s)
2496 int res = consume_identifier (s, false);
2498 if (doc_state == XmlCommentState.Allowed)
2499 doc_state = XmlCommentState.NotAllowed;
2502 case Token.NAMESPACE:
2503 check_incorrect_doc_comment ();
2507 if (res == Token.PARTIAL) {
2508 if (parsing_block > 0) {
2509 val = new LocatedToken (Location, "partial");
2510 return Token.IDENTIFIER;
2513 // Save current position and parse next token.
2516 int next_token = token ();
2517 bool ok = (next_token == Token.CLASS) ||
2518 (next_token == Token.STRUCT) ||
2519 (next_token == Token.INTERFACE) ||
2520 (next_token == Token.VOID);
2525 if (next_token == Token.VOID) {
2526 if (RootContext.Version == LanguageVersion.ISO_1 ||
2527 RootContext.Version == LanguageVersion.ISO_2)
2528 Report.FeatureIsNotAvailable (Location, "partial methods");
2529 } else if (RootContext.Version == LanguageVersion.ISO_1)
2530 Report.FeatureIsNotAvailable (Location, "partial types");
2535 if (next_token < Token.LAST_KEYWORD) {
2536 Report.Error (267, Location,
2537 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
2541 val = new LocatedToken (Location, "partial");
2542 return Token.IDENTIFIER;
2548 private int consume_identifier (int c, bool quoted)
2554 c = escape (c, out surrogate);
2555 if (surrogate != 0) {
2556 id_builder [pos++] = (char) c;
2561 id_builder [pos++] = (char) c;
2562 current_location = new Location (ref_line, hidden ? -1 : Col);
2564 while ((c = get_char ()) != -1) {
2566 if (is_identifier_part_character ((char) c)){
2567 if (pos == max_id_size){
2568 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2572 id_builder [pos++] = (char) c;
2573 // putback_char = -1;
2574 } else if (c == '\\') {
2576 c = escape (c, out surrogate);
2577 if (surrogate != 0) {
2578 if (is_identifier_part_character ((char) c))
2579 id_builder [pos++] = (char) c;
2584 // putback_char = c;
2591 // Optimization: avoids doing the keyword lookup
2592 // on uppercase letters
2594 if (id_builder [0] >= '_' && !quoted) {
2595 int keyword = GetKeyword (id_builder, pos);
2596 if (keyword != -1) {
2603 // Keep identifiers in an array of hashtables to avoid needless
2607 if (identifiers [pos] != null) {
2608 val = identifiers [pos][id_builder];
2610 val = new LocatedToken (Location, (string) val);
2612 escaped_identifiers.Add (val);
2613 return Token.IDENTIFIER;
2617 identifiers [pos] = new CharArrayHashtable (pos);
2619 val = new String (id_builder, 0, pos);
2620 if (RootContext.Version == LanguageVersion.ISO_1) {
2621 for (int i = 1; i < id_builder.Length; i += 3) {
2622 if (id_builder [i] == '_' && (id_builder [i - 1] == '_' || id_builder [i + 1] == '_')) {
2623 Report.Error (1638, Location,
2624 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val.ToString ());
2630 char [] chars = new char [pos];
2631 Array.Copy (id_builder, chars, pos);
2633 identifiers [pos] [chars] = val;
2635 val = new LocatedToken (Location, (string) val);
2637 escaped_identifiers.Add (val);
2638 return Token.IDENTIFIER;
2641 public int xtoken ()
2644 bool doread = false;
2647 // Whether we have seen comments on the current line
2648 bool comments_seen = false;
2650 for (;(c = get_char ()) != -1;) {
2652 col = ((col + 8) / 8) * 8;
2656 if (c == ' ' || c == '\f' || c == '\v' || c == 0xa0 || c == 0)
2660 if (peek_char () != '\n')
2665 any_token_seen |= tokens_seen;
2666 tokens_seen = false;
2667 comments_seen = false;
2671 // Handle double-slash comments.
2673 int d = peek_char ();
2677 if (RootContext.Documentation != null && peek_char () == '/') {
2679 // Don't allow ////.
2680 if ((d = peek_char ()) != '/') {
2681 update_comment_location ();
2682 if (doc_state == XmlCommentState.Allowed)
2683 handle_one_line_xml_comment ();
2684 else if (doc_state == XmlCommentState.NotAllowed)
2685 warn_incorrect_doc_comment ();
2688 while ((d = get_char ()) != -1 && (d != '\n') && d != '\r');
2690 any_token_seen |= tokens_seen;
2691 tokens_seen = false;
2692 comments_seen = false;
2694 } else if (d == '*'){
2696 bool docAppend = false;
2697 if (RootContext.Documentation != null && peek_char () == '*') {
2699 update_comment_location ();
2700 // But when it is /**/, just do nothing.
2701 if (peek_char () == '/') {
2705 if (doc_state == XmlCommentState.Allowed)
2707 else if (doc_state == XmlCommentState.NotAllowed)
2708 warn_incorrect_doc_comment ();
2711 int current_comment_start = 0;
2713 current_comment_start = xml_comment_buffer.Length;
2714 xml_comment_buffer.Append (Environment.NewLine);
2717 Location start_location = Location;
2719 while ((d = get_char ()) != -1){
2720 if (d == '*' && peek_char () == '/'){
2722 comments_seen = true;
2726 xml_comment_buffer.Append ((char) d);
2729 any_token_seen |= tokens_seen;
2730 tokens_seen = false;
2732 // Reset 'comments_seen' just to be consistent.
2733 // It doesn't matter either way, here.
2735 comments_seen = false;
2739 Report.Error (1035, start_location, "End-of-file found, '*/' expected");
2742 update_formatted_doc_comment (current_comment_start);
2745 goto is_punct_label;
2749 if (c == '\\' || is_identifier_start_character ((char)c)){
2751 return consume_identifier (c);
2755 current_location = new Location (ref_line, hidden ? -1 : Col);
2756 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR){
2766 any_token_seen |= tokens_seen;
2767 tokens_seen = false;
2768 comments_seen = false;
2772 if (c >= '0' && c <= '9'){
2774 return is_number (c);
2779 int peek = peek_char ();
2780 if (peek >= '0' && peek <= '9')
2781 return is_number (c);
2786 if (tokens_seen || comments_seen) {
2787 Eror_WrongPreprocessorLocation ();
2791 if (handle_preprocessing_directive (true))
2794 bool directive_expected = false;
2795 while ((c = get_char ()) != -1) {
2797 directive_expected = true;
2798 } else if (!directive_expected) {
2799 // TODO: Implement comment support for disabled code and uncomment this code
2801 // Eror_WrongPreprocessorLocation ();
2802 // return Token.ERROR;
2807 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v' )
2811 if (handle_preprocessing_directive (false))
2814 directive_expected = false;
2818 tokens_seen = false;
2826 return consume_string (false);
2832 error_details = "Empty character literal";
2833 Report.Error (1011, Location, error_details);
2836 if (c == '\r' || c == '\n') {
2837 Report.Error (1010, Location, "Newline in constant");
2842 c = escape (c, out surrogate);
2846 throw new NotImplementedException ();
2852 error_details = "Too many characters in character literal";
2853 Report.Error (1012, Location, error_details);
2855 // Try to recover, read until newline or next "'"
2856 while ((c = get_char ()) != -1){
2865 return Token.LITERAL_CHARACTER;
2872 return consume_string (true);
2873 } else if (is_identifier_start_character ((char) c)){
2874 return consume_identifier (c, true);
2876 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
2880 if (c == EvalStatementParserCharacter)
2881 return Token.EVAL_STATEMENT_PARSER;
2882 if (c == EvalCompilationUnitParserCharacter)
2883 return Token.EVAL_COMPILATION_UNIT_PARSER;
2884 if (c == EvalUsingDeclarationsParserCharacter)
2885 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
2887 error_details = ((char)c).ToString ();
2896 // Handles one line xml comment
2898 private void handle_one_line_xml_comment ()
2901 while ((c = peek_char ()) == ' ')
2902 get_char (); // skip heading whitespaces.
2903 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
2904 xml_comment_buffer.Append ((char) get_char ());
2906 if (c == '\r' || c == '\n')
2907 xml_comment_buffer.Append (Environment.NewLine);
2911 // Remove heading "*" in Javadoc-like xml documentation.
2913 private void update_formatted_doc_comment (int current_comment_start)
2915 int length = xml_comment_buffer.Length - current_comment_start;
2916 string [] lines = xml_comment_buffer.ToString (
2917 current_comment_start,
2918 length).Replace ("\r", "").Split ('\n');
2920 // The first line starts with /**, thus it is not target
2921 // for the format check.
2922 for (int i = 1; i < lines.Length; i++) {
2923 string s = lines [i];
2924 int idx = s.IndexOf ('*');
2927 if (i < lines.Length - 1)
2931 head = s.Substring (0, idx);
2932 foreach (char c in head)
2935 lines [i] = s.Substring (idx + 1);
2937 xml_comment_buffer.Remove (current_comment_start, length);
2938 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
2942 // Updates current comment location.
2944 private void update_comment_location ()
2946 if (current_comment_location.IsNull) {
2947 // "-2" is for heading "//" or "/*"
2948 current_comment_location =
2949 new Location (ref_line, hidden ? -1 : col - 2);
2954 // Checks if there was incorrect doc comments and raise
2957 public void check_incorrect_doc_comment ()
2959 if (xml_comment_buffer.Length > 0)
2960 warn_incorrect_doc_comment ();
2964 // Raises a warning when tokenizer found incorrect doccomment
2967 private void warn_incorrect_doc_comment ()
2969 if (doc_state != XmlCommentState.Error) {
2970 doc_state = XmlCommentState.Error;
2971 // in csc, it is 'XML comment is not placed on
2972 // a valid language element'. But that does not
2974 Report.Warning (1587, 2, Location, "XML comment is not placed on a valid language element");
2979 // Consumes the saved xml comment lines (if any)
2980 // as for current target member or type.
2982 public string consume_doc_comment ()
2984 if (xml_comment_buffer.Length > 0) {
2985 string ret = xml_comment_buffer.ToString ();
2986 reset_doc_comment ();
2992 void reset_doc_comment ()
2994 xml_comment_buffer.Length = 0;
2995 current_comment_location = Location.Null;
2998 public void cleanup ()
3000 if (ifstack != null && ifstack.Count >= 1) {
3001 current_location = new Location (ref_line, hidden ? -1 : Col);
3002 int state = (int) ifstack.Pop ();
3003 if ((state & REGION) != 0)
3004 Report.Error (1038, Location, "#endregion directive expected");
3006 Report.Error (1027, Location, "Expected `#endif' directive");
3012 // Indicates whether it accepts XML documentation or not.
3014 public enum XmlCommentState {
3015 // comment is allowed in this state.
3017 // comment is not allowed in this state.
3019 // once comments appeared when it is NotAllowed, then the
3020 // state is changed to it, until the state is changed to