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
32 public readonly int Token
;
33 public KeywordEntry Next
;
34 public readonly char[] Value
;
36 public KeywordEntry (string value, int token
)
38 this.Value
= value.ToCharArray ();
43 SeekableStreamReader reader
;
45 CompilationUnit file_name
;
52 bool handle_get_set
= false;
53 bool handle_remove_add
= false;
54 bool handle_where
= false;
55 bool handle_typeof
= false;
56 bool lambda_arguments_parsing
;
57 Location current_comment_location
= Location
.Null
;
58 ArrayList escaped_identifiers
;
59 int parsing_generic_less_than
;
62 // Used mainly for parser optimizations. Some expressions for instance
63 // can appear only in block (including initializer, base initializer)
66 public int parsing_block
;
67 internal bool query_parsing
;
70 // When parsing type only, useful for ambiguous nullable types
72 public int parsing_type
;
75 // Set when parsing generic declaration (type or method header)
77 public bool parsing_generic_declaration
;
80 // The value indicates that we have not reach any declaration or
83 public int parsing_declaration
;
86 // The special character to inject on streams to trigger the EXPRESSION_PARSE
87 // token to be returned. It just happens to be a Unicode character that
88 // would never be part of a program (can not be an identifier).
90 // This character is only tested just before the tokenizer is about to report
91 // an error; So on the regular operation mode, this addition will have no
92 // impact on the tokenizer's performance.
95 public const int EvalStatementParserCharacter
= 0x2190; // Unicode Left Arrow
96 public const int EvalCompilationUnitParserCharacter
= 0x2191; // Unicode Arrow
97 public const int EvalUsingDeclarationsParserCharacter
= 0x2192; // Unicode Arrow
100 // XML documentation buffer. The save point is used to divide
101 // comments on types and comments on members.
103 StringBuilder xml_comment_buffer
;
106 // See comment on XmlCommentState enumeration.
108 XmlCommentState xml_doc_state
= XmlCommentState
.Allowed
;
111 // Whether tokens have been seen on this line
113 bool tokens_seen
= false;
116 // Set to true once the GENERATE_COMPLETION token has bee
117 // returned. This helps produce one GENERATE_COMPLETION,
118 // as many COMPLETE_COMPLETION as necessary to complete the
119 // AST tree and one final EOF.
124 // Whether a token has been seen on the file
125 // This is needed because `define' is not allowed to be used
126 // after a token has been seen.
128 bool any_token_seen
= false;
130 static readonly char[] simple_whitespaces
= new char[] { ' ', '\t' }
;
132 public bool PropertyParsing
{
133 get { return handle_get_set; }
134 set { handle_get_set = value; }
137 public bool EventParsing
{
138 get { return handle_remove_add; }
139 set { handle_remove_add = value; }
142 public bool ConstraintsParsing
{
143 get { return handle_where; }
144 set { handle_where = value; }
147 public bool TypeOfParsing
{
148 get { return handle_typeof; }
149 set { handle_typeof = value; }
152 public XmlCommentState doc_state
{
153 get { return xml_doc_state; }
155 if (value == XmlCommentState
.Allowed
) {
156 check_incorrect_doc_comment ();
157 reset_doc_comment ();
159 xml_doc_state
= value;
164 // This is used to trigger completion generation on the parser
165 public bool CompleteOnEOF
;
167 void AddEscapedIdentifier (LocatedToken lt
)
169 if (escaped_identifiers
== null)
170 escaped_identifiers
= new ArrayList ();
172 escaped_identifiers
.Add (lt
);
175 public bool IsEscapedIdentifier (Location loc
)
177 if (escaped_identifiers
!= null) {
178 foreach (LocatedToken lt
in escaped_identifiers
)
179 if (lt
.Location
.Equals (loc
))
189 static KeywordEntry
[][] keywords
;
190 static Hashtable keyword_strings
;
191 static NumberStyles styles
;
192 static NumberFormatInfo csharp_format_info
;
195 // Values for the associated token returned
197 internal int putback_char
; // Used by repl only
203 const int TAKING
= 1;
204 const int ELSE_SEEN
= 4;
205 const int PARENT_TAKING
= 8;
206 const int REGION
= 16;
209 // pre-processor if stack state:
213 static System
.Text
.StringBuilder string_builder
;
215 const int max_id_size
= 512;
216 static char [] id_builder
= new char [max_id_size
];
218 static CharArrayHashtable
[] identifiers
= new CharArrayHashtable
[max_id_size
+ 1];
220 const int max_number_size
= 512;
221 static char [] number_builder
= new char [max_number_size
];
222 static int number_pos
;
225 // Details about the error encoutered by the tokenizer
227 string error_details
;
229 public string error
{
231 return error_details
;
242 // This is used when the tokenizer needs to save
243 // the current position as it needs to do some parsing
244 // on its own to deamiguate a token in behalf of the
247 Stack position_stack
= new Stack (2);
254 public int putback_char
;
255 public int previous_col
;
256 public Stack ifstack
;
257 public int parsing_generic_less_than
;
258 public int current_token
;
260 public Position (Tokenizer t
)
262 position
= t
.reader
.Position
;
264 ref_line
= t
.ref_line
;
267 putback_char
= t
.putback_char
;
268 previous_col
= t
.previous_col
;
269 if (t
.ifstack
!= null && t
.ifstack
.Count
!= 0)
270 ifstack
= (Stack
)t
.ifstack
.Clone ();
271 parsing_generic_less_than
= t
.parsing_generic_less_than
;
272 current_token
= t
.current_token
;
276 public void PushPosition ()
278 position_stack
.Push (new Position (this));
281 public void PopPosition ()
283 Position p
= (Position
) position_stack
.Pop ();
285 reader
.Position
= p
.position
;
286 ref_line
= p
.ref_line
;
290 putback_char
= p
.putback_char
;
291 previous_col
= p
.previous_col
;
293 parsing_generic_less_than
= p
.parsing_generic_less_than
;
294 current_token
= p
.current_token
;
297 // Do not reset the position, ignore it.
298 public void DiscardPosition ()
300 position_stack
.Pop ();
303 static void AddKeyword (string kw
, int token
)
305 keyword_strings
.Add (kw
, kw
);
307 int length
= kw
.Length
;
308 if (keywords
[length
] == null) {
309 keywords
[length
] = new KeywordEntry
['z' - '_' + 1];
312 int char_index
= kw
[0] - '_';
313 KeywordEntry kwe
= keywords
[length
] [char_index
];
315 keywords
[length
] [char_index
] = new KeywordEntry (kw
, token
);
319 while (kwe
.Next
!= null) {
323 kwe
.Next
= new KeywordEntry (kw
, token
);
326 static void InitTokens ()
328 keyword_strings
= new Hashtable ();
330 // 11 is the length of the longest keyword for now
331 keywords
= new KeywordEntry
[11] [];
333 AddKeyword ("__arglist", Token
.ARGLIST
);
334 AddKeyword ("abstract", Token
.ABSTRACT
);
335 AddKeyword ("as", Token
.AS
);
336 AddKeyword ("add", Token
.ADD
);
337 AddKeyword ("base", Token
.BASE
);
338 AddKeyword ("bool", Token
.BOOL
);
339 AddKeyword ("break", Token
.BREAK
);
340 AddKeyword ("byte", Token
.BYTE
);
341 AddKeyword ("case", Token
.CASE
);
342 AddKeyword ("catch", Token
.CATCH
);
343 AddKeyword ("char", Token
.CHAR
);
344 AddKeyword ("checked", Token
.CHECKED
);
345 AddKeyword ("class", Token
.CLASS
);
346 AddKeyword ("const", Token
.CONST
);
347 AddKeyword ("continue", Token
.CONTINUE
);
348 AddKeyword ("decimal", Token
.DECIMAL
);
349 AddKeyword ("default", Token
.DEFAULT
);
350 AddKeyword ("delegate", Token
.DELEGATE
);
351 AddKeyword ("do", Token
.DO
);
352 AddKeyword ("double", Token
.DOUBLE
);
353 AddKeyword ("else", Token
.ELSE
);
354 AddKeyword ("enum", Token
.ENUM
);
355 AddKeyword ("event", Token
.EVENT
);
356 AddKeyword ("explicit", Token
.EXPLICIT
);
357 AddKeyword ("extern", Token
.EXTERN
);
358 AddKeyword ("false", Token
.FALSE
);
359 AddKeyword ("finally", Token
.FINALLY
);
360 AddKeyword ("fixed", Token
.FIXED
);
361 AddKeyword ("float", Token
.FLOAT
);
362 AddKeyword ("for", Token
.FOR
);
363 AddKeyword ("foreach", Token
.FOREACH
);
364 AddKeyword ("goto", Token
.GOTO
);
365 AddKeyword ("get", Token
.GET
);
366 AddKeyword ("if", Token
.IF
);
367 AddKeyword ("implicit", Token
.IMPLICIT
);
368 AddKeyword ("in", Token
.IN
);
369 AddKeyword ("int", Token
.INT
);
370 AddKeyword ("interface", Token
.INTERFACE
);
371 AddKeyword ("internal", Token
.INTERNAL
);
372 AddKeyword ("is", Token
.IS
);
373 AddKeyword ("lock", Token
.LOCK
);
374 AddKeyword ("long", Token
.LONG
);
375 AddKeyword ("namespace", Token
.NAMESPACE
);
376 AddKeyword ("new", Token
.NEW
);
377 AddKeyword ("null", Token
.NULL
);
378 AddKeyword ("object", Token
.OBJECT
);
379 AddKeyword ("operator", Token
.OPERATOR
);
380 AddKeyword ("out", Token
.OUT
);
381 AddKeyword ("override", Token
.OVERRIDE
);
382 AddKeyword ("params", Token
.PARAMS
);
383 AddKeyword ("private", Token
.PRIVATE
);
384 AddKeyword ("protected", Token
.PROTECTED
);
385 AddKeyword ("public", Token
.PUBLIC
);
386 AddKeyword ("readonly", Token
.READONLY
);
387 AddKeyword ("ref", Token
.REF
);
388 AddKeyword ("remove", Token
.REMOVE
);
389 AddKeyword ("return", Token
.RETURN
);
390 AddKeyword ("sbyte", Token
.SBYTE
);
391 AddKeyword ("sealed", Token
.SEALED
);
392 AddKeyword ("set", Token
.SET
);
393 AddKeyword ("short", Token
.SHORT
);
394 AddKeyword ("sizeof", Token
.SIZEOF
);
395 AddKeyword ("stackalloc", Token
.STACKALLOC
);
396 AddKeyword ("static", Token
.STATIC
);
397 AddKeyword ("string", Token
.STRING
);
398 AddKeyword ("struct", Token
.STRUCT
);
399 AddKeyword ("switch", Token
.SWITCH
);
400 AddKeyword ("this", Token
.THIS
);
401 AddKeyword ("throw", Token
.THROW
);
402 AddKeyword ("true", Token
.TRUE
);
403 AddKeyword ("try", Token
.TRY
);
404 AddKeyword ("typeof", Token
.TYPEOF
);
405 AddKeyword ("uint", Token
.UINT
);
406 AddKeyword ("ulong", Token
.ULONG
);
407 AddKeyword ("unchecked", Token
.UNCHECKED
);
408 AddKeyword ("unsafe", Token
.UNSAFE
);
409 AddKeyword ("ushort", Token
.USHORT
);
410 AddKeyword ("using", Token
.USING
);
411 AddKeyword ("virtual", Token
.VIRTUAL
);
412 AddKeyword ("void", Token
.VOID
);
413 AddKeyword ("volatile", Token
.VOLATILE
);
414 AddKeyword ("while", Token
.WHILE
);
415 AddKeyword ("partial", Token
.PARTIAL
);
416 AddKeyword ("where", Token
.WHERE
);
419 AddKeyword ("from", Token
.FROM
);
420 AddKeyword ("join", Token
.JOIN
);
421 AddKeyword ("on", Token
.ON
);
422 AddKeyword ("equals", Token
.EQUALS
);
423 AddKeyword ("select", Token
.SELECT
);
424 AddKeyword ("group", Token
.GROUP
);
425 AddKeyword ("by", Token
.BY
);
426 AddKeyword ("let", Token
.LET
);
427 AddKeyword ("orderby", Token
.ORDERBY
);
428 AddKeyword ("ascending", Token
.ASCENDING
);
429 AddKeyword ("descending", Token
.DESCENDING
);
430 AddKeyword ("into", Token
.INTO
);
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 arrays grouped by their
449 // length and then by the first character
451 if (id_len
>= keywords
.Length
|| keywords
[id_len
] == null)
454 int first_index
= id
[0] - '_';
455 if (first_index
> 'z')
458 KeywordEntry kwe
= keywords
[id_len
] [first_index
];
465 for (int i
= 1; i
< id_len
; ++i
) {
466 if (id
[i
] != kwe
.Value
[i
]) {
472 } while (kwe
!= null && res
== 0);
486 if (!handle_remove_add
)
490 if (parsing_declaration
== 0)
491 res
= Token
.EXTERN_ALIAS
;
494 if (peek_token () == Token
.COLON
) {
496 res
= Token
.DEFAULT_COLON
;
500 if (!handle_where
&& !query_parsing
)
505 // A query expression is any expression that starts with `from identifier'
506 // followed by any token except ; , =
508 if (!query_parsing
) {
509 if (lambda_arguments_parsing
) {
515 // HACK: to disable generics micro-parser, because PushPosition does not
516 // store identifiers array
517 parsing_generic_less_than
= 1;
519 case Token
.IDENTIFIER
:
531 next_token
= xtoken ();
532 if (next_token
== Token
.SEMICOLON
|| next_token
== Token
.COMMA
|| next_token
== Token
.EQUALS
)
535 res
= Token
.FROM_FIRST
;
536 query_parsing
= true;
537 if (RootContext
.Version
<= LanguageVersion
.ISO_2
)
538 Report
.FeatureIsNotAvailable (Location
, "query expressions");
541 Expression
.Error_VoidInvalidInTheContext (Location
);
545 // HACK: A token is not a keyword so we need to restore identifiers buffer
546 // which has been overwritten before we grabbed the identifier
547 id_builder
[0] = 'f'; id_builder
[1] = 'r'; id_builder
[2] = 'o'; id_builder
[3] = 'm';
561 case Token
.ASCENDING
:
562 case Token
.DESCENDING
:
569 case Token
.NAMESPACE
:
570 // TODO: some explanation needed
571 check_incorrect_doc_comment ();
575 if (parsing_block
> 0) {
580 // Save current position and parse next token.
583 next_token
= token ();
584 bool ok
= (next_token
== Token
.CLASS
) ||
585 (next_token
== Token
.STRUCT
) ||
586 (next_token
== Token
.INTERFACE
) ||
587 (next_token
== Token
.VOID
);
592 if (next_token
== Token
.VOID
) {
593 if (RootContext
.Version
== LanguageVersion
.ISO_1
||
594 RootContext
.Version
== LanguageVersion
.ISO_2
)
595 Report
.FeatureIsNotAvailable (Location
, "partial methods");
596 } else if (RootContext
.Version
== LanguageVersion
.ISO_1
)
597 Report
.FeatureIsNotAvailable (Location
, "partial types");
602 if (next_token
< Token
.LAST_KEYWORD
) {
603 Report
.Error (267, Location
,
604 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
615 public Location Location
{
617 return new Location (ref_line
, hidden
? -1 : col
);
621 public Tokenizer (SeekableStreamReader input
, CompilationUnit file
)
623 this.ref_name
= file
;
624 this.file_name
= file
;
629 xml_comment_buffer
= new StringBuilder ();
632 // FIXME: This could be `Location.Push' but we have to
633 // find out why the MS compiler allows this
635 Mono
.CSharp
.Location
.Push (file
, file
);
638 static bool is_identifier_start_character (int c
)
640 return (c
>= 'a' && c
<= 'z') || (c
>= 'A' && c
<= 'Z') || c
== '_' || Char
.IsLetter ((char)c
);
643 static bool is_identifier_part_character (char c
)
645 if (c
>= 'a' && c
<= 'z')
648 if (c
>= 'A' && c
<= 'Z')
651 if (c
== '_' || (c
>= '0' && c
<= '9'))
657 return Char
.IsLetter (c
) || Char
.GetUnicodeCategory (c
) == UnicodeCategory
.ConnectorPunctuation
;
660 public static bool IsKeyword (string s
)
662 return keyword_strings
[s
] != null;
666 // Open parens micro parser. Detects both lambda and cast ambiguity.
669 int TokenizeOpenParens ()
674 int bracket_level
= 0;
675 bool is_type
= false;
676 bool can_be_type
= false;
679 ptoken
= current_token
;
682 switch (current_token
) {
683 case Token
.CLOSE_PARENS
:
687 // Expression inside parens is lambda, (int i) =>
689 if (current_token
== Token
.ARROW
) {
690 if (RootContext
.Version
<= LanguageVersion
.ISO_2
)
691 Report
.FeatureIsNotAvailable (Location
, "lambda expressions");
693 return Token
.OPEN_PARENS_LAMBDA
;
697 // Expression inside parens is single type, (int[])
700 return Token
.OPEN_PARENS_CAST
;
703 // Expression is possible cast, look at next token, (T)null
706 switch (current_token
) {
707 case Token
.OPEN_PARENS
:
710 case Token
.IDENTIFIER
:
711 case Token
.LITERAL_INTEGER
:
712 case Token
.LITERAL_FLOAT
:
713 case Token
.LITERAL_DOUBLE
:
714 case Token
.LITERAL_DECIMAL
:
715 case Token
.LITERAL_CHARACTER
:
716 case Token
.LITERAL_STRING
:
729 case Token
.UNCHECKED
:
734 // These can be part of a member access
748 return Token
.OPEN_PARENS_CAST
;
751 return Token
.OPEN_PARENS
;
754 case Token
.DOUBLE_COLON
:
755 if (ptoken
!= Token
.IDENTIFIER
&& ptoken
!= Token
.OP_GENERICS_GT
)
760 case Token
.IDENTIFIER
:
763 case Token
.OP_GENERICS_LT
:
765 case Token
.DOUBLE_COLON
:
767 if (bracket_level
== 0)
771 can_be_type
= is_type
= false;
791 if (bracket_level
== 0)
796 if (bracket_level
== 0) {
798 can_be_type
= is_type
= false;
802 case Token
.OP_GENERICS_LT
:
803 case Token
.OPEN_BRACKET
:
804 if (bracket_level
++ == 0)
808 case Token
.OP_GENERICS_GT
:
809 case Token
.CLOSE_BRACKET
:
813 case Token
.INTERR_NULLABLE
:
815 if (bracket_level
== 0)
821 can_be_type
= is_type
= false;
825 return Token
.OPEN_PARENS
;
830 public static bool IsValidIdentifier (string s
)
832 if (s
== null || s
.Length
== 0)
835 if (!is_identifier_start_character (s
[0]))
838 for (int i
= 1; i
< s
.Length
; i
++)
839 if (! is_identifier_part_character (s
[i
]))
845 bool parse_less_than ()
848 int the_token
= token ();
849 if (the_token
== Token
.OPEN_BRACKET
) {
851 the_token
= token ();
852 } while (the_token
!= Token
.CLOSE_BRACKET
);
853 the_token
= token ();
854 } else if (the_token
== Token
.IN
|| the_token
== Token
.OUT
) {
855 the_token
= token ();
858 case Token
.IDENTIFIER
:
876 case Token
.OP_GENERICS_GT
:
883 the_token
= token ();
885 if (the_token
== Token
.OP_GENERICS_GT
)
887 else if (the_token
== Token
.COMMA
|| the_token
== Token
.DOT
|| the_token
== Token
.DOUBLE_COLON
)
889 else if (the_token
== Token
.INTERR_NULLABLE
|| the_token
== Token
.STAR
)
891 else if (the_token
== Token
.OP_GENERICS_LT
) {
892 if (!parse_less_than ())
895 } else if (the_token
== Token
.OPEN_BRACKET
) {
897 the_token
= token ();
898 if (the_token
== Token
.CLOSE_BRACKET
)
900 else if (the_token
== Token
.COMMA
)
901 goto rank_specifiers
;
908 bool parse_generic_dimension (out int dimension
)
913 int the_token
= token ();
914 if (the_token
== Token
.OP_GENERICS_GT
)
916 else if (the_token
== Token
.COMMA
) {
924 public int peek_token ()
929 the_token
= token ();
936 // Tonizes `?' using custom disambiguous rules to return one
937 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
939 // Tricky expression look like:
941 // Foo ? a = x ? b : c;
943 int TokenizePossibleNullableType ()
945 if (parsing_block
== 0 || parsing_type
> 0)
946 return Token
.INTERR_NULLABLE
;
948 int d
= peek_char ();
951 return Token
.OP_COALESCING
;
954 switch (current_token
) {
955 case Token
.CLOSE_PARENS
:
959 case Token
.LITERAL_INTEGER
:
960 case Token
.LITERAL_STRING
:
965 if (d
== ',' || d
== ';' || d
== '>')
966 return Token
.INTERR_NULLABLE
;
967 if (d
== '*' || (d
>= '0' && d
<= '9'))
972 current_token
= Token
.NONE
;
975 case Token
.LITERAL_INTEGER
:
976 case Token
.LITERAL_STRING
:
977 case Token
.LITERAL_CHARACTER
:
978 case Token
.LITERAL_DECIMAL
:
979 case Token
.LITERAL_DOUBLE
:
980 case Token
.LITERAL_FLOAT
:
986 next_token
= Token
.INTERR
;
989 case Token
.SEMICOLON
:
991 case Token
.CLOSE_PARENS
:
992 case Token
.OPEN_BRACKET
:
993 case Token
.OP_GENERICS_GT
:
994 next_token
= Token
.INTERR_NULLABLE
;
1002 if (next_token
== -1) {
1003 switch (xtoken ()) {
1005 case Token
.SEMICOLON
:
1006 case Token
.OPEN_BRACE
:
1007 case Token
.CLOSE_PARENS
:
1009 next_token
= Token
.INTERR_NULLABLE
;
1013 next_token
= Token
.INTERR
;
1021 // All shorcuts failed, do it hard way
1023 while ((ntoken
= xtoken ()) != Token
.EOF
) {
1024 if (ntoken
== Token
.SEMICOLON
)
1027 if (ntoken
== Token
.COLON
) {
1028 if (++colons
== interrs
)
1033 if (ntoken
== Token
.INTERR
) {
1039 next_token
= colons
!= interrs
? Token
.INTERR_NULLABLE
: Token
.INTERR
;
1048 bool decimal_digits (int c
)
1051 bool seen_digits
= false;
1054 if (number_pos
== max_number_size
)
1055 Error_NumericConstantTooLong ();
1056 number_builder
[number_pos
++] = (char) c
;
1060 // We use peek_char2, because decimal_digits needs to do a
1061 // 2-character look-ahead (5.ToString for example).
1063 while ((d
= peek_char2 ()) != -1){
1064 if (d
>= '0' && d
<= '9'){
1065 if (number_pos
== max_number_size
)
1066 Error_NumericConstantTooLong ();
1067 number_builder
[number_pos
++] = (char) d
;
1077 static bool is_hex (int e
)
1079 return (e
>= '0' && e
<= '9') || (e
>= 'A' && e
<= 'F') || (e
>= 'a' && e
<= 'f');
1082 static int real_type_suffix (int c
)
1088 t
= Token
.LITERAL_FLOAT
;
1091 t
= Token
.LITERAL_DOUBLE
;
1094 t
= Token
.LITERAL_DECIMAL
;
1102 int integer_type_suffix (ulong ul
, int c
)
1104 bool is_unsigned
= false;
1105 bool is_long
= false;
1108 bool scanning
= true;
1121 // if we have not seen anything in between
1122 // report this error
1124 Report
.Warning (78, 4, Location
, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1127 // This goto statement causes the MS CLR 2.0 beta 1 csc to report an error, so
1128 // work around that.
1152 if (is_long
&& is_unsigned
){
1154 return Token
.LITERAL_INTEGER
;
1155 } else if (is_unsigned
){
1156 // uint if possible, or ulong else.
1158 if ((ul
& 0xffffffff00000000) == 0)
1162 } else if (is_long
){
1163 // long if possible, ulong otherwise
1164 if ((ul
& 0x8000000000000000) != 0)
1169 // int, uint, long or ulong in that order
1170 if ((ul
& 0xffffffff00000000) == 0){
1171 uint ui
= (uint) ul
;
1173 if ((ui
& 0x80000000) != 0)
1178 if ((ul
& 0x8000000000000000) != 0)
1184 return Token
.LITERAL_INTEGER
;
1188 // given `c' as the next char in the input decide whether
1189 // we need to convert to a special type, and then choose
1190 // the best representation for the integer
1192 int adjust_int (int c
)
1195 if (number_pos
> 9){
1196 ulong ul
= (uint) (number_builder
[0] - '0');
1198 for (int i
= 1; i
< number_pos
; i
++){
1199 ul
= checked ((ul
* 10) + ((uint)(number_builder
[i
] - '0')));
1201 return integer_type_suffix (ul
, c
);
1203 uint ui
= (uint) (number_builder
[0] - '0');
1205 for (int i
= 1; i
< number_pos
; i
++){
1206 ui
= checked ((ui
* 10) + ((uint)(number_builder
[i
] - '0')));
1208 return integer_type_suffix (ui
, c
);
1210 } catch (OverflowException
) {
1211 error_details
= "Integral constant is too large";
1212 Report
.Error (1021, Location
, error_details
);
1214 return Token
.LITERAL_INTEGER
;
1216 catch (FormatException
) {
1217 Report
.Error (1013, Location
, "Invalid number");
1219 return Token
.LITERAL_INTEGER
;
1223 int adjust_real (int t
)
1225 string s
= new String (number_builder
, 0, number_pos
);
1226 const string error_details
= "Floating-point constant is outside the range of type `{0}'";
1229 case Token
.LITERAL_DECIMAL
:
1231 val
= System
.Decimal
.Parse (s
, styles
, csharp_format_info
);
1232 } catch (OverflowException
) {
1234 Report
.Error (594, Location
, error_details
, "decimal");
1237 case Token
.LITERAL_FLOAT
:
1239 val
= float.Parse (s
, styles
, csharp_format_info
);
1240 } catch (OverflowException
) {
1242 Report
.Error (594, Location
, error_details
, "float");
1246 case Token
.LITERAL_DOUBLE
:
1248 t
= Token
.LITERAL_DOUBLE
;
1250 val
= System
.Double
.Parse (s
, styles
, csharp_format_info
);
1251 } catch (OverflowException
) {
1253 Report
.Error (594, Location
, error_details
, "double");
1266 while ((d
= peek_char ()) != -1){
1268 number_builder
[number_pos
++] = (char) d
;
1274 string s
= new String (number_builder
, 0, number_pos
);
1276 if (number_pos
<= 8)
1277 ul
= System
.UInt32
.Parse (s
, NumberStyles
.HexNumber
);
1279 ul
= System
.UInt64
.Parse (s
, NumberStyles
.HexNumber
);
1280 } catch (OverflowException
){
1281 error_details
= "Integral constant is too large";
1282 Report
.Error (1021, Location
, error_details
);
1284 return Token
.LITERAL_INTEGER
;
1286 catch (FormatException
) {
1287 Report
.Error (1013, Location
, "Invalid number");
1289 return Token
.LITERAL_INTEGER
;
1292 return integer_type_suffix (ul
, peek_char ());
1296 // Invoked if we know we have .digits or digits
1298 int is_number (int c
)
1300 bool is_real
= false;
1305 if (c
>= '0' && c
<= '9'){
1307 int peek
= peek_char ();
1309 if (peek
== 'x' || peek
== 'X')
1310 return handle_hex ();
1317 // We need to handle the case of
1318 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1321 if (decimal_digits ('.')){
1327 return adjust_int (-1);
1331 if (c
== 'e' || c
== 'E'){
1333 if (number_pos
== max_number_size
)
1334 Error_NumericConstantTooLong ();
1335 number_builder
[number_pos
++] = 'e';
1339 if (number_pos
== max_number_size
)
1340 Error_NumericConstantTooLong ();
1341 number_builder
[number_pos
++] = '+';
1343 } else if (c
== '-') {
1344 if (number_pos
== max_number_size
)
1345 Error_NumericConstantTooLong ();
1346 number_builder
[number_pos
++] = '-';
1349 if (number_pos
== max_number_size
)
1350 Error_NumericConstantTooLong ();
1351 number_builder
[number_pos
++] = '+';
1358 type
= real_type_suffix (c
);
1359 if (type
== Token
.NONE
&& !is_real
){
1361 return adjust_int (c
);
1365 if (type
== Token
.NONE
){
1370 return adjust_real (type
);
1372 Console
.WriteLine ("This should not be reached");
1373 throw new Exception ("Is Number should never reach this point");
1377 // Accepts exactly count (4 or 8) hex, no more no less
1379 int getHex (int count
, out int surrogate
, out bool error
)
1384 int top
= count
!= -1 ? count
: 4;
1389 for (i
= 0; i
< top
; i
++){
1392 if (c
>= '0' && c
<= '9')
1393 c
= (int) c
- (int) '0';
1394 else if (c
>= 'A' && c
<= 'F')
1395 c
= (int) c
- (int) 'A' + 10;
1396 else if (c
>= 'a' && c
<= 'f')
1397 c
= (int) c
- (int) 'a' + 10;
1403 total
= (total
* 16) + c
;
1405 int p
= peek_char ();
1408 if (!is_hex ((char)p
))
1414 if (total
> 0x0010FFFF) {
1419 if (total
>= 0x00010000) {
1420 surrogate
= ((total
- 0x00010000) % 0x0400 + 0xDC00);
1421 total
= ((total
- 0x00010000) / 0x0400 + 0xD800);
1428 int escape (int c
, out int surrogate
)
1464 v
= getHex (-1, out surrogate
, out error
);
1470 return EscapeUnicode (d
, out surrogate
);
1473 Report
.Error (1009, Location
, "Unrecognized escape sequence `\\{0}'", ((char)d
).ToString ());
1482 int EscapeUnicode (int ch
, out int surrogate
)
1486 ch
= getHex (8, out surrogate
, out error
);
1488 ch
= getHex (4, out surrogate
, out error
);
1492 Report
.Error (1009, Location
, "Unrecognized escape sequence");
1500 if (putback_char
!= -1) {
1513 void advance_line ()
1523 if (putback_char
== -1)
1524 putback_char
= reader
.Read ();
1525 return putback_char
;
1530 if (putback_char
!= -1)
1531 return putback_char
;
1532 return reader
.Peek ();
1535 void putback (int c
)
1537 if (putback_char
!= -1){
1538 Console
.WriteLine ("Col: " + col
);
1539 Console
.WriteLine ("Row: " + line
);
1540 Console
.WriteLine ("Name: " + ref_name
.Name
);
1541 Console
.WriteLine ("Current [{0}] putting back [{1}] ", putback_char
, c
);
1542 throw new Exception ("This should not happen putback on putback");
1544 if (c
== '\n' || col
== 0) {
1545 // It won't happen though.
1555 public bool advance ()
1557 return peek_char () != -1 || CompleteOnEOF
;
1560 public Object Value
{
1566 public Object
value ()
1573 current_token
= xtoken ();
1574 return current_token
;
1577 static StringBuilder static_cmd_arg
= new System
.Text
.StringBuilder ();
1579 void get_cmd_arg (out string cmd
, out string arg
)
1583 tokens_seen
= false;
1586 // skip over white space
1589 } while (c
== '\r' || c
== ' ' || c
== '\t');
1591 static_cmd_arg
.Length
= 0;
1592 while (c
!= -1 && is_identifier_part_character ((char)c
)) {
1593 static_cmd_arg
.Append ((char)c
);
1596 int peek
= peek_char ();
1597 if (peek
== 'U' || peek
== 'u') {
1599 c
= EscapeUnicode (c
, out surrogate
);
1600 if (surrogate
!= 0) {
1601 if (is_identifier_part_character ((char) c
))
1602 static_cmd_arg
.Append ((char) c
);
1609 cmd
= static_cmd_arg
.ToString ();
1611 // skip over white space
1612 while (c
== '\r' || c
== ' ' || c
== '\t')
1615 static_cmd_arg
.Length
= 0;
1616 int has_identifier_argument
= 0;
1618 while (c
!= -1 && c
!= '\n' && c
!= '\r') {
1619 if (c
== '\\' && has_identifier_argument
>= 0) {
1620 if (has_identifier_argument
!= 0 || (cmd
== "define" || cmd
== "if" || cmd
== "elif" || cmd
== "undef")) {
1621 has_identifier_argument
= 1;
1623 int peek
= peek_char ();
1624 if (peek
== 'U' || peek
== 'u') {
1626 c
= EscapeUnicode (c
, out surrogate
);
1627 if (surrogate
!= 0) {
1628 if (is_identifier_part_character ((char) c
))
1629 static_cmd_arg
.Append ((char) c
);
1634 has_identifier_argument
= -1;
1637 static_cmd_arg
.Append ((char) c
);
1641 if (static_cmd_arg
.Length
!= 0)
1642 arg
= static_cmd_arg
.ToString ();
1646 // Handles the #line directive
1648 bool PreProcessLine (string arg
)
1650 if (arg
.Length
== 0)
1653 if (arg
== "default"){
1655 ref_name
= file_name
;
1657 Location
.Push (file_name
, ref_name
);
1659 } else if (arg
== "hidden"){
1667 if ((pos
= arg
.IndexOf (' ')) != -1 && pos
!= 0){
1668 ref_line
= System
.Int32
.Parse (arg
.Substring (0, pos
));
1671 char [] quotes
= { '\"' }
;
1673 string name
= arg
.Substring (pos
). Trim (quotes
);
1674 ref_name
= Location
.LookupFile (file_name
, name
);
1675 file_name
.AddFile (ref_name
);
1677 Location
.Push (file_name
, ref_name
);
1679 ref_line
= System
.Int32
.Parse (arg
);
1690 // Handles #define and #undef
1692 void PreProcessDefinition (bool is_define
, string ident
, bool caller_is_taking
)
1694 if (ident
.Length
== 0 || ident
== "true" || ident
== "false"){
1695 Report
.Error (1001, Location
, "Missing identifier to pre-processor directive");
1699 if (ident
.IndexOfAny (simple_whitespaces
) != -1){
1700 Error_EndLineExpected ();
1704 if (!is_identifier_start_character (ident
[0]))
1705 Report
.Error (1001, Location
, "Identifier expected: {0}", ident
);
1707 foreach (char c
in ident
.Substring (1)){
1708 if (!is_identifier_part_character (c
)){
1709 Report
.Error (1001, Location
, "Identifier expected: {0}", ident
);
1714 if (!caller_is_taking
)
1721 if (RootContext
.IsConditionalDefined (ident
))
1724 file_name
.AddDefine (ident
);
1729 file_name
.AddUndefine (ident
);
1733 static byte read_hex (string arg
, int pos
, out bool error
)
1740 if ((c
>= '0') && (c
<= '9'))
1741 total
= (int) c
- (int) '0';
1742 else if ((c
>= 'A') && (c
<= 'F'))
1743 total
= (int) c
- (int) 'A' + 10;
1744 else if ((c
>= 'a') && (c
<= 'f'))
1745 total
= (int) c
- (int) 'a' + 10;
1754 if ((c
>= '0') && (c
<= '9'))
1755 total
+= (int) c
- (int) '0';
1756 else if ((c
>= 'A') && (c
<= 'F'))
1757 total
+= (int) c
- (int) 'A' + 10;
1758 else if ((c
>= 'a') && (c
<= 'f'))
1759 total
+= (int) c
- (int) 'a' + 10;
1765 return (byte) total
;
1769 /// Handles #pragma checksum
1771 bool PreProcessPragmaChecksum (string arg
)
1773 if ((arg
[0] != ' ') && (arg
[0] != '\t'))
1776 arg
= arg
.Trim (simple_whitespaces
);
1777 if ((arg
.Length
< 2) || (arg
[0] != '"'))
1780 StringBuilder file_sb
= new StringBuilder ();
1784 while ((ch
= arg
[pos
++]) != '"') {
1785 if (pos
>= arg
.Length
)
1789 if (pos
+1 >= arg
.Length
)
1794 file_sb
.Append (ch
);
1797 if ((pos
+2 >= arg
.Length
) || ((arg
[pos
] != ' ') && (arg
[pos
] != '\t')))
1800 arg
= arg
.Substring (pos
).Trim (simple_whitespaces
);
1801 if ((arg
.Length
< 42) || (arg
[0] != '"') || (arg
[1] != '{') ||
1802 (arg
[10] != '-') || (arg
[15] != '-') || (arg
[20] != '-') ||
1803 (arg
[25] != '-') || (arg
[38] != '}') || (arg
[39] != '"'))
1807 byte[] guid_bytes
= new byte [16];
1809 for (int i
= 0; i
< 4; i
++) {
1810 guid_bytes
[i
] = read_hex (arg
, 2+2*i
, out error
);
1814 for (int i
= 0; i
< 2; i
++) {
1815 guid_bytes
[i
+4] = read_hex (arg
, 11+2*i
, out error
);
1818 guid_bytes
[i
+6] = read_hex (arg
, 16+2*i
, out error
);
1821 guid_bytes
[i
+8] = read_hex (arg
, 21+2*i
, out error
);
1826 for (int i
= 0; i
< 6; i
++) {
1827 guid_bytes
[i
+10] = read_hex (arg
, 26+2*i
, out error
);
1832 arg
= arg
.Substring (40).Trim (simple_whitespaces
);
1833 if ((arg
.Length
< 34) || (arg
[0] != '"') || (arg
[33] != '"'))
1836 byte[] checksum_bytes
= new byte [16];
1837 for (int i
= 0; i
< 16; i
++) {
1838 checksum_bytes
[i
] = read_hex (arg
, 1+2*i
, out error
);
1843 arg
= arg
.Substring (34).Trim (simple_whitespaces
);
1847 SourceFile file
= Location
.LookupFile (file_name
, file_sb
.ToString ());
1848 file
.SetChecksum (guid_bytes
, checksum_bytes
);
1849 ref_name
.AutoGenerated
= true;
1854 /// Handles #pragma directive
1856 void PreProcessPragma (string arg
)
1858 const string warning
= "warning";
1859 const string w_disable
= "warning disable";
1860 const string w_restore
= "warning restore";
1861 const string checksum
= "checksum";
1863 if (arg
== w_disable
) {
1864 Report
.RegisterWarningRegion (Location
).WarningDisable (Location
.Row
);
1868 if (arg
== w_restore
) {
1869 Report
.RegisterWarningRegion (Location
).WarningEnable (Location
.Row
);
1873 if (arg
.StartsWith (w_disable
)) {
1874 int[] codes
= ParseNumbers (arg
.Substring (w_disable
.Length
));
1875 foreach (int code
in codes
) {
1877 Report
.RegisterWarningRegion (Location
).WarningDisable (Location
, code
);
1882 if (arg
.StartsWith (w_restore
)) {
1883 int[] codes
= ParseNumbers (arg
.Substring (w_restore
.Length
));
1884 Hashtable w_table
= Report
.warning_ignore_table
;
1885 foreach (int code
in codes
) {
1886 if (w_table
!= null && w_table
.Contains (code
))
1887 Report
.Warning (1635, 1, Location
, String
.Format ("Cannot restore warning `CS{0:0000}' because it was disabled globally", code
));
1888 Report
.RegisterWarningRegion (Location
).WarningEnable (Location
, code
);
1893 if (arg
.StartsWith (warning
)) {
1894 Report
.Warning (1634, 1, Location
, "Expected disable or restore");
1898 if (arg
.StartsWith (checksum
)) {
1899 if (!PreProcessPragmaChecksum (arg
.Substring (checksum
.Length
)))
1900 Warning_InvalidPragmaChecksum ();
1904 Report
.Warning (1633, 1, Location
, "Unrecognized #pragma directive");
1907 int[] ParseNumbers (string text
)
1909 string[] string_array
= text
.Split (',');
1910 int[] values
= new int [string_array
.Length
];
1912 foreach (string string_code
in string_array
) {
1914 values
[index
++] = int.Parse (string_code
, System
.Globalization
.CultureInfo
.InvariantCulture
);
1916 catch (FormatException
) {
1917 Report
.Warning (1692, 1, Location
, "Invalid number");
1923 bool eval_val (string s
)
1930 return file_name
.IsConditionalDefined (s
);
1933 bool pp_primary (ref string s
)
1942 s
= s
.Substring (1);
1943 bool val
= pp_expr (ref s
, false);
1944 if (s
.Length
> 0 && s
[0] == ')'){
1945 s
= s
.Substring (1);
1948 Error_InvalidDirective ();
1952 if (is_identifier_start_character (c
)){
1958 if (is_identifier_part_character (c
)){
1962 bool v
= eval_val (s
.Substring (0, j
));
1963 s
= s
.Substring (j
);
1966 bool vv
= eval_val (s
);
1971 Error_InvalidDirective ();
1975 bool pp_unary (ref string s
)
1982 if (len
> 1 && s
[1] == '='){
1983 Error_InvalidDirective ();
1986 s
= s
.Substring (1);
1987 return ! pp_primary (ref s
);
1989 return pp_primary (ref s
);
1991 Error_InvalidDirective ();
1996 bool pp_eq (ref string s
)
1998 bool va
= pp_unary (ref s
);
2004 if (len
> 2 && s
[1] == '='){
2005 s
= s
.Substring (2);
2006 return va
== pp_unary (ref s
);
2008 Error_InvalidDirective ();
2011 } else if (s
[0] == '!' && len
> 1 && s
[1] == '='){
2012 s
= s
.Substring (2);
2014 return va
!= pp_unary (ref s
);
2023 bool pp_and (ref string s
)
2025 bool va
= pp_eq (ref s
);
2031 if (len
> 2 && s
[1] == '&'){
2032 s
= s
.Substring (2);
2033 return (va
& pp_and (ref s
));
2035 Error_InvalidDirective ();
2044 // Evaluates an expression for `#if' or `#elif'
2046 bool pp_expr (ref string s
, bool isTerm
)
2048 bool va
= pp_and (ref s
);
2055 if (len
> 2 && s
[1] == '|'){
2056 s
= s
.Substring (2);
2057 return va
| pp_expr (ref s
, isTerm
);
2059 Error_InvalidDirective ();
2064 Error_EndLineExpected ();
2072 bool eval (string s
)
2074 bool v
= pp_expr (ref s
, true);
2083 void Error_NumericConstantTooLong ()
2085 Report
.Error (1021, Location
, "Numeric constant too long");
2088 void Error_InvalidDirective ()
2090 Report
.Error (1517, Location
, "Invalid preprocessor directive");
2093 void Error_UnexpectedDirective (string extra
)
2097 "Unexpected processor directive ({0})", extra
);
2100 void Error_TokensSeen ()
2102 Report
.Error (1032, Location
,
2103 "Cannot define or undefine preprocessor symbols after first token in file");
2106 void Eror_WrongPreprocessorLocation ()
2108 Report
.Error (1040, Location
,
2109 "Preprocessor directives must appear as the first non-whitespace character on a line");
2112 void Error_EndLineExpected ()
2114 Report
.Error (1025, Location
, "Single-line comment or end-of-line expected");
2117 void Warning_InvalidPragmaChecksum ()
2119 Report
.Warning (1695, 1, Location
,
2120 "Invalid #pragma checksum syntax; should be " +
2121 "#pragma checksum \"filename\" " +
2122 "\"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2125 // if true, then the code continues processing the code
2126 // if false, the code stays in a loop until another directive is
2128 // When caller_is_taking is false we ignore all directives except the ones
2129 // which can help us to identify where the #if block ends
2130 bool handle_preprocessing_directive (bool caller_is_taking
)
2133 bool region_directive
= false;
2135 get_cmd_arg (out cmd
, out arg
);
2137 // Eat any trailing whitespaces and single-line comments
2138 if (arg
.IndexOf ("//") != -1)
2139 arg
= arg
.Substring (0, arg
.IndexOf ("//"));
2140 arg
= arg
.Trim (simple_whitespaces
);
2143 // The first group of pre-processing instructions is always processed
2147 region_directive
= true;
2152 if (ifstack
== null || ifstack
.Count
== 0){
2153 Error_UnexpectedDirective ("no #region for this #endregion");
2156 int pop
= (int) ifstack
.Pop ();
2158 if ((pop
& REGION
) == 0)
2159 Report
.Error (1027, Location
, "Expected `#endif' directive");
2161 return caller_is_taking
;
2164 if (ifstack
== null)
2165 ifstack
= new Stack (2);
2167 int flags
= region_directive
? REGION
: 0;
2168 if (ifstack
.Count
== 0){
2169 flags
|= PARENT_TAKING
;
2171 int state
= (int) ifstack
.Peek ();
2172 if ((state
& TAKING
) != 0) {
2173 flags
|= PARENT_TAKING
;
2177 if (caller_is_taking
&& eval (arg
)) {
2178 ifstack
.Push (flags
| TAKING
);
2181 ifstack
.Push (flags
);
2185 if (ifstack
== null || ifstack
.Count
== 0){
2186 Error_UnexpectedDirective ("no #if for this #endif");
2189 pop
= (int) ifstack
.Pop ();
2191 if ((pop
& REGION
) != 0)
2192 Report
.Error (1038, Location
, "#endregion directive expected");
2194 if (arg
.Length
!= 0) {
2195 Error_EndLineExpected ();
2198 if (ifstack
.Count
== 0)
2201 int state
= (int) ifstack
.Peek ();
2202 return (state
& TAKING
) != 0;
2206 if (ifstack
== null || ifstack
.Count
== 0){
2207 Error_UnexpectedDirective ("no #if for this #elif");
2210 int state
= (int) ifstack
.Pop ();
2212 if ((state
& REGION
) != 0) {
2213 Report
.Error (1038, Location
, "#endregion directive expected");
2217 if ((state
& ELSE_SEEN
) != 0){
2218 Error_UnexpectedDirective ("#elif not valid after #else");
2222 if ((state
& TAKING
) != 0) {
2227 if (eval (arg
) && ((state
& PARENT_TAKING
) != 0)){
2228 ifstack
.Push (state
| TAKING
);
2232 ifstack
.Push (state
);
2237 if (ifstack
== null || ifstack
.Count
== 0){
2238 Error_UnexpectedDirective ("no #if for this #else");
2241 int state
= (int) ifstack
.Peek ();
2243 if ((state
& REGION
) != 0) {
2244 Report
.Error (1038, Location
, "#endregion directive expected");
2248 if ((state
& ELSE_SEEN
) != 0){
2249 Error_UnexpectedDirective ("#else within #else");
2255 if (arg
.Length
!= 0) {
2256 Error_EndLineExpected ();
2261 if ((state
& PARENT_TAKING
) != 0) {
2262 ret
= (state
& TAKING
) == 0;
2270 ifstack
.Push (state
| ELSE_SEEN
);
2275 if (any_token_seen
){
2276 Error_TokensSeen ();
2277 return caller_is_taking
;
2279 PreProcessDefinition (true, arg
, caller_is_taking
);
2280 return caller_is_taking
;
2283 if (any_token_seen
){
2284 Error_TokensSeen ();
2285 return caller_is_taking
;
2287 PreProcessDefinition (false, arg
, caller_is_taking
);
2288 return caller_is_taking
;
2292 // These are only processed if we are in a `taking' block
2294 if (!caller_is_taking
)
2299 Report
.Error (1029, Location
, "#error: '{0}'", arg
);
2303 Report
.Warning (1030, 1, Location
, "#warning: `{0}'", arg
);
2307 if (RootContext
.Version
== LanguageVersion
.ISO_1
) {
2308 Report
.FeatureIsNotAvailable (Location
, "#pragma");
2312 PreProcessPragma (arg
);
2316 if (!PreProcessLine (arg
))
2319 "The line number specified for #line directive is missing or invalid");
2320 return caller_is_taking
;
2323 Report
.Error (1024, Location
, "Wrong preprocessor directive");
2328 private int consume_string (bool quoted
)
2331 string_builder
.Length
= 0;
2333 while ((c
= get_char ()) != -1){
2335 if (quoted
&& peek_char () == '"'){
2336 string_builder
.Append ((char) c
);
2340 val
= string_builder
.ToString ();
2341 return Token
.LITERAL_STRING
;
2347 Report
.Error (1010, Location
, "Newline in constant");
2352 c
= escape (c
, out surrogate
);
2355 if (surrogate
!= 0) {
2356 string_builder
.Append ((char) c
);
2360 string_builder
.Append ((char) c
);
2363 Report
.Error (1039, Location
, "Unterminated string literal");
2367 private int consume_identifier (int s
)
2369 int res
= consume_identifier (s
, false);
2371 if (doc_state
== XmlCommentState
.Allowed
)
2372 doc_state
= XmlCommentState
.NotAllowed
;
2377 private int consume_identifier (int c
, bool quoted
)
2383 c
= escape (c
, out surrogate
);
2384 if (surrogate
!= 0) {
2385 id_builder
[pos
++] = (char) c
;
2390 id_builder
[pos
++] = (char) c
;
2391 Location loc
= Location
;
2393 while ((c
= get_char ()) != -1) {
2395 if (is_identifier_part_character ((char) c
)){
2396 if (pos
== max_id_size
){
2397 Report
.Error (645, loc
, "Identifier too long (limit is 512 chars)");
2401 id_builder
[pos
++] = (char) c
;
2402 } else if (c
== '\\') {
2404 c
= escape (c
, out surrogate
);
2405 if (surrogate
!= 0) {
2406 if (is_identifier_part_character ((char) c
))
2407 id_builder
[pos
++] = (char) c
;
2418 // Optimization: avoids doing the keyword lookup
2419 // on uppercase letters
2421 if (id_builder
[0] >= '_' && !quoted
) {
2422 int keyword
= GetKeyword (id_builder
, pos
);
2423 if (keyword
!= -1) {
2424 // TODO: No need to store location for keyword, required location cleanup
2431 // Keep identifiers in an array of hashtables to avoid needless
2434 CharArrayHashtable identifiers_group
= identifiers
[pos
];
2435 if (identifiers_group
!= null) {
2436 val
= identifiers_group
[id_builder
];
2438 val
= new LocatedToken (loc
, (string) val
);
2440 AddEscapedIdentifier ((LocatedToken
) val
);
2441 return Token
.IDENTIFIER
;
2444 identifiers_group
= new CharArrayHashtable (pos
);
2445 identifiers
[pos
] = identifiers_group
;
2448 char [] chars
= new char [pos
];
2449 Array
.Copy (id_builder
, chars
, pos
);
2451 val
= new String (id_builder
, 0, pos
);
2452 identifiers_group
.Add (chars
, val
);
2454 if (RootContext
.Version
== LanguageVersion
.ISO_1
) {
2455 for (int i
= 1; i
< chars
.Length
; i
+= 3) {
2456 if (chars
[i
] == '_' && (chars
[i
- 1] == '_' || chars
[i
+ 1] == '_')) {
2457 Report
.Error (1638, loc
,
2458 "`{0}': Any identifier with double underscores cannot be used when ISO language version mode is specified", val
.ToString ());
2463 val
= new LocatedToken (loc
, (string) val
);
2465 AddEscapedIdentifier ((LocatedToken
) val
);
2466 return Token
.IDENTIFIER
;
2469 public int xtoken ()
2473 // Whether we have seen comments on the current line
2474 bool comments_seen
= false;
2475 while ((c
= get_char ()) != -1) {
2478 col
= ((col
+ 8) / 8) * 8;
2486 case 0xFEFF: // Ignore BOM anywhere in the file
2489 /* This is required for compatibility with .NET
2491 if (peek_char () == 0xBB) {
2494 if (get_char () == 0xBF)
2501 if (peek_char () != '\n')
2506 any_token_seen
|= tokens_seen
;
2507 tokens_seen
= false;
2508 comments_seen
= false;
2513 return consume_identifier (c
);
2517 return Token
.OPEN_BRACE
;
2520 return Token
.CLOSE_BRACE
;
2522 // To block doccomment inside attribute declaration.
2523 if (doc_state
== XmlCommentState
.Allowed
)
2524 doc_state
= XmlCommentState
.NotAllowed
;
2525 return Token
.OPEN_BRACKET
;
2527 return Token
.CLOSE_BRACKET
;
2531 // An expression versions of parens can appear in block context only
2533 if (parsing_block
!= 0 && !lambda_arguments_parsing
) {
2536 // Optmize most common case where we know that parens
2539 switch (current_token
) {
2540 case Token
.IDENTIFIER
:
2548 case Token
.DELEGATE
:
2549 case Token
.OP_GENERICS_GT
:
2550 return Token
.OPEN_PARENS
;
2553 // Optimize using peek
2554 int xx
= peek_char ();
2561 return Token
.OPEN_PARENS
;
2564 lambda_arguments_parsing
= true;
2566 d
= TokenizeOpenParens ();
2568 lambda_arguments_parsing
= false;
2572 return Token
.OPEN_PARENS
;
2574 return Token
.CLOSE_PARENS
;
2578 return Token
.SEMICOLON
;
2582 return TokenizePossibleNullableType ();
2584 if (parsing_generic_less_than
++ > 0)
2585 return Token
.OP_GENERICS_LT
;
2587 return TokenizeLessThan ();
2597 if (parsing_generic_less_than
> 1 || (parsing_generic_less_than
== 1 && d
!= '>')) {
2598 parsing_generic_less_than
--;
2599 return Token
.OP_GENERICS_GT
;
2608 return Token
.OP_SHIFT_RIGHT_ASSIGN
;
2610 return Token
.OP_SHIFT_RIGHT
;
2619 } else if (d
== '=') {
2620 d
= Token
.OP_ADD_ASSIGN
;
2631 } else if (d
== '=')
2632 d
= Token
.OP_SUB_ASSIGN
;
2642 if (peek_char () == '='){
2659 return Token
.ASSIGN
;
2665 return Token
.OP_AND
;
2669 return Token
.OP_AND_ASSIGN
;
2671 return Token
.BITWISE_AND
;
2681 return Token
.OP_OR_ASSIGN
;
2683 return Token
.BITWISE_OR
;
2686 if (peek_char () == '='){
2688 return Token
.OP_MULT_ASSIGN
;
2697 return Token
.OP_DIV_ASSIGN
;
2700 // Handle double-slash comments.
2703 if (RootContext
.Documentation
!= null && peek_char () == '/') {
2705 // Don't allow ////.
2706 if ((d
= peek_char ()) != '/') {
2707 update_comment_location ();
2708 if (doc_state
== XmlCommentState
.Allowed
)
2709 handle_one_line_xml_comment ();
2710 else if (doc_state
== XmlCommentState
.NotAllowed
)
2711 warn_incorrect_doc_comment ();
2714 while ((d
= get_char ()) != -1 && (d
!= '\n') && d
!= '\r');
2716 any_token_seen
|= tokens_seen
;
2717 tokens_seen
= false;
2718 comments_seen
= false;
2720 } else if (d
== '*'){
2722 bool docAppend
= false;
2723 if (RootContext
.Documentation
!= null && peek_char () == '*') {
2725 update_comment_location ();
2726 // But when it is /**/, just do nothing.
2727 if (peek_char () == '/') {
2731 if (doc_state
== XmlCommentState
.Allowed
)
2733 else if (doc_state
== XmlCommentState
.NotAllowed
)
2734 warn_incorrect_doc_comment ();
2737 int current_comment_start
= 0;
2739 current_comment_start
= xml_comment_buffer
.Length
;
2740 xml_comment_buffer
.Append (Environment
.NewLine
);
2743 while ((d
= get_char ()) != -1){
2744 if (d
== '*' && peek_char () == '/'){
2746 comments_seen
= true;
2750 xml_comment_buffer
.Append ((char) d
);
2753 any_token_seen
|= tokens_seen
;
2754 tokens_seen
= false;
2756 // Reset 'comments_seen' just to be consistent.
2757 // It doesn't matter either way, here.
2759 comments_seen
= false;
2763 Report
.Error (1035, Location
, "End-of-file found, '*/' expected");
2766 update_formatted_doc_comment (current_comment_start
);
2772 if (peek_char () == '='){
2774 return Token
.OP_MOD_ASSIGN
;
2776 return Token
.PERCENT
;
2779 if (peek_char () == '='){
2781 return Token
.OP_XOR_ASSIGN
;
2783 return Token
.CARRET
;
2786 if (peek_char () == ':') {
2788 return Token
.DOUBLE_COLON
;
2792 case '0': case '1': case '2': case '3': case '4':
2793 case '5': case '6': case '7': case '8': case '9':
2795 return is_number (c
);
2797 case '\n': // white space
2798 any_token_seen
|= tokens_seen
;
2799 tokens_seen
= false;
2800 comments_seen
= false;
2806 if (d
>= '0' && d
<= '9')
2807 return is_number (c
);
2811 if (tokens_seen
|| comments_seen
) {
2812 Eror_WrongPreprocessorLocation ();
2816 if (handle_preprocessing_directive (true))
2819 bool directive_expected
= false;
2820 while ((c
= get_char ()) != -1) {
2822 directive_expected
= true;
2823 } else if (!directive_expected
) {
2824 // TODO: Implement comment support for disabled code and uncomment this code
2826 // Eror_WrongPreprocessorLocation ();
2827 // return Token.ERROR;
2832 if (c
== ' ' || c
== '\t' || c
== '\r' || c
== '\n' || c
== '\f' || c
== '\v' )
2836 if (handle_preprocessing_directive (false))
2839 directive_expected
= false;
2843 tokens_seen
= false;
2850 return consume_string (false);
2853 return TokenizeBackslash ();
2859 return consume_string (true);
2862 if (is_identifier_start_character (c
)){
2863 return consume_identifier (c
, true);
2866 Report
.Error (1646, Location
, "Keyword, identifier, or string expected after verbatim specifier: @");
2869 case EvalStatementParserCharacter
:
2870 return Token
.EVAL_STATEMENT_PARSER
;
2871 case EvalCompilationUnitParserCharacter
:
2872 return Token
.EVAL_COMPILATION_UNIT_PARSER
;
2873 case EvalUsingDeclarationsParserCharacter
:
2874 return Token
.EVAL_USING_DECLARATIONS_UNIT_PARSER
;
2877 if (is_identifier_start_character (c
)) {
2879 return consume_identifier (c
);
2882 error_details
= ((char)c
).ToString ();
2888 return Token
.COMPLETE_COMPLETION
;
2891 return Token
.GENERATE_COMPLETION
;
2898 int TokenizeBackslash ()
2900 int c
= get_char ();
2903 error_details
= "Empty character literal";
2904 Report
.Error (1011, Location
, error_details
);
2907 if (c
== '\r' || c
== '\n') {
2908 Report
.Error (1010, Location
, "Newline in constant");
2913 c
= escape (c
, out d
);
2917 throw new NotImplementedException ();
2923 Report
.Error (1012, Location
, "Too many characters in character literal");
2925 // Try to recover, read until newline or next "'"
2926 while ((c
= get_char ()) != -1) {
2927 if (c
== '\n' || c
== '\'')
2933 return Token
.LITERAL_CHARACTER
;
2936 int TokenizeLessThan ()
2939 if (handle_typeof
) {
2941 if (parse_generic_dimension (out d
)) {
2944 return Token
.GENERIC_DIMENSION
;
2949 // Save current position and parse next token.
2951 if (parse_less_than ()) {
2952 if (parsing_generic_declaration
&& token () != Token
.DOT
) {
2953 d
= Token
.OP_GENERICS_LT_DECL
;
2955 d
= Token
.OP_GENERICS_LT
;
2962 parsing_generic_less_than
= 0;
2971 return Token
.OP_SHIFT_LEFT_ASSIGN
;
2973 return Token
.OP_SHIFT_LEFT
;
2984 // Handles one line xml comment
2986 private void handle_one_line_xml_comment ()
2989 while ((c
= peek_char ()) == ' ')
2990 get_char (); // skip heading whitespaces.
2991 while ((c
= peek_char ()) != -1 && c
!= '\n' && c
!= '\r') {
2992 xml_comment_buffer
.Append ((char) get_char ());
2994 if (c
== '\r' || c
== '\n')
2995 xml_comment_buffer
.Append (Environment
.NewLine
);
2999 // Remove heading "*" in Javadoc-like xml documentation.
3001 private void update_formatted_doc_comment (int current_comment_start
)
3003 int length
= xml_comment_buffer
.Length
- current_comment_start
;
3004 string [] lines
= xml_comment_buffer
.ToString (
3005 current_comment_start
,
3006 length
).Replace ("\r", "").Split ('\n');
3008 // The first line starts with /**, thus it is not target
3009 // for the format check.
3010 for (int i
= 1; i
< lines
.Length
; i
++) {
3011 string s
= lines
[i
];
3012 int idx
= s
.IndexOf ('*');
3015 if (i
< lines
.Length
- 1)
3019 head
= s
.Substring (0, idx
);
3020 foreach (char c
in head
)
3023 lines
[i
] = s
.Substring (idx
+ 1);
3025 xml_comment_buffer
.Remove (current_comment_start
, length
);
3026 xml_comment_buffer
.Insert (current_comment_start
, String
.Join (Environment
.NewLine
, lines
));
3030 // Updates current comment location.
3032 private void update_comment_location ()
3034 if (current_comment_location
.IsNull
) {
3035 // "-2" is for heading "//" or "/*"
3036 current_comment_location
=
3037 new Location (ref_line
, hidden
? -1 : col
- 2);
3042 // Checks if there was incorrect doc comments and raise
3045 public void check_incorrect_doc_comment ()
3047 if (xml_comment_buffer
.Length
> 0)
3048 warn_incorrect_doc_comment ();
3052 // Raises a warning when tokenizer found incorrect doccomment
3055 private void warn_incorrect_doc_comment ()
3057 if (doc_state
!= XmlCommentState
.Error
) {
3058 doc_state
= XmlCommentState
.Error
;
3059 // in csc, it is 'XML comment is not placed on
3060 // a valid language element'. But that does not
3062 Report
.Warning (1587, 2, Location
, "XML comment is not placed on a valid language element");
3067 // Consumes the saved xml comment lines (if any)
3068 // as for current target member or type.
3070 public string consume_doc_comment ()
3072 if (xml_comment_buffer
.Length
> 0) {
3073 string ret
= xml_comment_buffer
.ToString ();
3074 reset_doc_comment ();
3080 void reset_doc_comment ()
3082 xml_comment_buffer
.Length
= 0;
3083 current_comment_location
= Location
.Null
;
3086 public void cleanup ()
3088 if (ifstack
!= null && ifstack
.Count
>= 1) {
3089 int state
= (int) ifstack
.Pop ();
3090 if ((state
& REGION
) != 0)
3091 Report
.Error (1038, Location
, "#endregion directive expected");
3093 Report
.Error (1027, Location
, "Expected `#endif' directive");
3099 // Indicates whether it accepts XML documentation or not.
3101 public enum XmlCommentState
{
3102 // comment is allowed in this state.
3104 // comment is not allowed in this state.
3106 // once comments appeared when it is NotAllowed, then the
3107 // state is changed to it, until the state is changed to