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@gmail.com)
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
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
17 using System.Collections.Generic;
18 using System.Globalization;
19 using System.Diagnostics;
20 using System.Collections;
25 // This class has to be used by parser only, it reuses token
26 // details once a file is parsed
28 public class LocatedToken
30 public int row, column;
32 public SourceFile file;
34 public LocatedToken ()
38 public LocatedToken (string value, Location loc)
41 file = loc.SourceFile;
46 public override string ToString ()
48 return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
51 public Location Location
53 get { return new Location (file, row, column); }
63 /// Tokenizer for C# source code.
65 public class Tokenizer : yyParser.yyInput
69 public readonly T Token;
70 public KeywordEntry<T> Next;
71 public readonly char[] Value;
73 public KeywordEntry (string value, T token)
75 this.Value = value.ToCharArray ();
80 sealed class IdentifiersComparer : IEqualityComparer<char[]>
84 public IdentifiersComparer (int length)
89 public bool Equals (char[] x, char[] y)
91 for (int i = 0; i < length; ++i)
98 public int GetHashCode (char[] obj)
101 for (int i = 0; i < length; ++i)
102 h = (h << 5) - h + obj [i];
108 public class LocatedTokenBuffer
110 readonly LocatedToken[] buffer;
113 public LocatedTokenBuffer ()
115 buffer = new LocatedToken[0];
118 public LocatedTokenBuffer (LocatedToken[] buffer)
120 this.buffer = buffer ?? new LocatedToken[0];
123 public LocatedToken Create (SourceFile file, int row, int column)
125 return Create (null, file, row, column);
128 public LocatedToken Create (string value, SourceFile file, int row, int column)
131 // TODO: I am not very happy about the logic but it's the best
132 // what I could come up with for now.
133 // Ideally we should be using just tiny buffer (256 elements) which
134 // is enough to hold all details for currect stack and recycle elements
135 // poped from the stack but there is a trick needed to recycle
139 if (pos >= buffer.Length) {
140 entry = new LocatedToken ();
144 entry = new LocatedToken ();
153 entry.column = column;
158 // Used for token not required by expression evaluator
160 [Conditional ("FULL_AST")]
161 public void CreateOptional (SourceFile file, int row, int col, ref object token)
163 token = Create (file, row, col);
167 public enum PreprocessorDirective
173 If = 3 | RequiresArgument,
175 Elif = 5 | RequiresArgument,
177 Define = 7 | RequiresArgument,
178 Undef = 8 | RequiresArgument,
181 Pragma = 11 | CustomArgumentsParsing,
182 Line = 12 | CustomArgumentsParsing,
184 CustomArgumentsParsing = 1 << 10,
185 RequiresArgument = 1 << 11
188 readonly SeekableStreamReader reader;
189 readonly CompilationSourceFile source_file;
190 readonly CompilerContext context;
191 readonly Report Report;
194 SourceFile current_source;
195 Location hidden_block_start;
201 readonly int tab_size;
202 bool handle_get_set = false;
203 bool handle_remove_add = false;
205 bool lambda_arguments_parsing;
206 List<Location> escaped_identifiers;
207 int parsing_generic_less_than;
208 readonly bool doc_processing;
209 readonly LocatedTokenBuffer ltb;
212 // Used mainly for parser optimizations. Some expressions for instance
213 // can appear only in block (including initializer, base initializer)
216 public int parsing_block;
217 internal bool query_parsing;
220 // When parsing type only, useful for ambiguous nullable types
222 public int parsing_type;
225 // Set when parsing generic declaration (type or method header)
227 public bool parsing_generic_declaration;
228 public bool parsing_generic_declaration_doc;
231 // The value indicates that we have not reach any declaration or
234 public int parsing_declaration;
236 public bool parsing_attribute_section;
238 public bool parsing_modifiers;
241 // The special characters to inject on streams to run the unit parser
242 // in the special expression mode. Using private characters from
243 // Plane Sixteen (U+100000 to U+10FFFD)
245 // This character is only tested just before the tokenizer is about to report
246 // an error; So on the regular operation mode, this addition will have no
247 // impact on the tokenizer's performance.
250 public const int EvalStatementParserCharacter = 0x100000;
251 public const int EvalCompilationUnitParserCharacter = 0x100001;
252 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
253 public const int DocumentationXref = 0x100003;
255 const int UnicodeLS = 0x2028;
256 const int UnicodePS = 0x2029;
259 // XML documentation buffer. The save point is used to divide
260 // comments on types and comments on members.
262 StringBuilder xml_comment_buffer;
265 // See comment on XmlCommentState enumeration.
267 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
270 // Whether tokens have been seen on this line
272 bool tokens_seen = false;
275 // Set to true once the GENERATE_COMPLETION token has bee
276 // returned. This helps produce one GENERATE_COMPLETION,
277 // as many COMPLETE_COMPLETION as necessary to complete the
278 // AST tree and one final EOF.
283 // Whether a token has been seen on the file
284 // This is needed because `define' is not allowed to be used
285 // after a token has been seen.
292 static readonly KeywordEntry<int>[][] keywords;
293 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
294 static readonly HashSet<string> keyword_strings;
295 static readonly NumberStyles styles;
296 static readonly NumberFormatInfo csharp_format_info;
299 static readonly char[] pragma_warning = "warning".ToCharArray ();
300 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
301 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
302 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
303 static readonly char[] line_hidden = "hidden".ToCharArray ();
304 static readonly char[] line_default = "default".ToCharArray ();
306 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
308 public bool PropertyParsing {
309 get { return handle_get_set; }
310 set { handle_get_set = value; }
313 public bool EventParsing {
314 get { return handle_remove_add; }
315 set { handle_remove_add = value; }
318 public bool ConstraintsParsing {
319 get { return handle_where; }
320 set { handle_where = value; }
323 public XmlCommentState doc_state {
324 get { return xml_doc_state; }
326 if (value == XmlCommentState.Allowed) {
327 check_incorrect_doc_comment ();
328 reset_doc_comment ();
330 xml_doc_state = value;
335 // This is used to trigger completion generation on the parser
336 public bool CompleteOnEOF;
338 void AddEscapedIdentifier (Location loc)
340 if (escaped_identifiers == null)
341 escaped_identifiers = new List<Location> ();
343 escaped_identifiers.Add (loc);
346 public bool IsEscapedIdentifier (ATypeNameExpression name)
348 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
352 // Values for the associated token returned
354 internal int putback_char; // Used by repl only
360 const int TAKING = 1;
361 const int ELSE_SEEN = 4;
362 const int PARENT_TAKING = 8;
363 const int REGION = 16;
366 // pre-processor if stack state:
370 public const int MaxIdentifierLength = 512;
371 public const int MaxNumberLength = 512;
373 readonly char[] id_builder;
374 readonly Dictionary<char[], string>[] identifiers;
375 readonly char[] number_builder;
378 char[] value_builder = new char[64];
387 // This is used when the tokenizer needs to save
388 // the current position as it needs to do some parsing
389 // on its own to deamiguate a token in behalf of the
392 Stack<Position> position_stack = new Stack<Position> (2);
399 public Location hidden;
400 public int putback_char;
401 public int previous_col;
402 public Stack<int> ifstack;
403 public int parsing_generic_less_than;
404 public int current_token;
407 public Position (Tokenizer t)
409 position = t.reader.Position;
411 ref_line = t.ref_line;
413 hidden = t.hidden_block_start;
414 putback_char = t.putback_char;
415 previous_col = t.previous_col;
416 if (t.ifstack != null && t.ifstack.Count != 0) {
417 // There is no simple way to clone Stack<T> all
418 // methods reverse the order
419 var clone = t.ifstack.ToArray ();
420 Array.Reverse (clone);
421 ifstack = new Stack<int> (clone);
423 parsing_generic_less_than = t.parsing_generic_less_than;
424 current_token = t.current_token;
429 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session, Report report)
431 this.source_file = file;
432 this.context = file.Compiler;
433 this.current_source = file.SourceFile;
434 this.identifiers = session.Identifiers;
435 this.id_builder = session.IDBuilder;
436 this.number_builder = session.NumberBuilder;
437 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
438 this.Report = report;
444 xml_comment_buffer = new StringBuilder ();
445 doc_processing = context.Settings.DocumentationFile != null;
447 tab_size = context.Settings.TabSize;
450 public void PushPosition ()
452 position_stack.Push (new Position (this));
455 public void PopPosition ()
457 Position p = position_stack.Pop ();
459 reader.Position = p.position;
460 ref_line = p.ref_line;
463 hidden_block_start = p.hidden;
464 putback_char = p.putback_char;
465 previous_col = p.previous_col;
467 parsing_generic_less_than = p.parsing_generic_less_than;
468 current_token = p.current_token;
472 // Do not reset the position, ignore it.
473 public void DiscardPosition ()
475 position_stack.Pop ();
478 static void AddKeyword (string kw, int token)
480 keyword_strings.Add (kw);
482 AddKeyword (keywords, kw, token);
485 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
487 AddKeyword (keywords_preprocessor, kw, directive);
490 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
492 int length = kw.Length;
493 if (keywords[length] == null) {
494 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
497 int char_index = kw[0] - '_';
498 var kwe = keywords[length][char_index];
500 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
504 while (kwe.Next != null) {
508 kwe.Next = new KeywordEntry<T> (kw, token);
516 keyword_strings = new HashSet<string> ();
518 // 11 is the length of the longest keyword for now
519 keywords = new KeywordEntry<int>[11][];
521 AddKeyword ("__arglist", Token.ARGLIST);
522 AddKeyword ("__makeref", Token.MAKEREF);
523 AddKeyword ("__reftype", Token.REFTYPE);
524 AddKeyword ("__refvalue", Token.REFVALUE);
525 AddKeyword ("abstract", Token.ABSTRACT);
526 AddKeyword ("as", Token.AS);
527 AddKeyword ("add", Token.ADD);
528 AddKeyword ("base", Token.BASE);
529 AddKeyword ("bool", Token.BOOL);
530 AddKeyword ("break", Token.BREAK);
531 AddKeyword ("byte", Token.BYTE);
532 AddKeyword ("case", Token.CASE);
533 AddKeyword ("catch", Token.CATCH);
534 AddKeyword ("char", Token.CHAR);
535 AddKeyword ("checked", Token.CHECKED);
536 AddKeyword ("class", Token.CLASS);
537 AddKeyword ("const", Token.CONST);
538 AddKeyword ("continue", Token.CONTINUE);
539 AddKeyword ("decimal", Token.DECIMAL);
540 AddKeyword ("default", Token.DEFAULT);
541 AddKeyword ("delegate", Token.DELEGATE);
542 AddKeyword ("do", Token.DO);
543 AddKeyword ("double", Token.DOUBLE);
544 AddKeyword ("else", Token.ELSE);
545 AddKeyword ("enum", Token.ENUM);
546 AddKeyword ("event", Token.EVENT);
547 AddKeyword ("explicit", Token.EXPLICIT);
548 AddKeyword ("extern", Token.EXTERN);
549 AddKeyword ("false", Token.FALSE);
550 AddKeyword ("finally", Token.FINALLY);
551 AddKeyword ("fixed", Token.FIXED);
552 AddKeyword ("float", Token.FLOAT);
553 AddKeyword ("for", Token.FOR);
554 AddKeyword ("foreach", Token.FOREACH);
555 AddKeyword ("goto", Token.GOTO);
556 AddKeyword ("get", Token.GET);
557 AddKeyword ("if", Token.IF);
558 AddKeyword ("implicit", Token.IMPLICIT);
559 AddKeyword ("in", Token.IN);
560 AddKeyword ("int", Token.INT);
561 AddKeyword ("interface", Token.INTERFACE);
562 AddKeyword ("internal", Token.INTERNAL);
563 AddKeyword ("is", Token.IS);
564 AddKeyword ("lock", Token.LOCK);
565 AddKeyword ("long", Token.LONG);
566 AddKeyword ("namespace", Token.NAMESPACE);
567 AddKeyword ("new", Token.NEW);
568 AddKeyword ("null", Token.NULL);
569 AddKeyword ("object", Token.OBJECT);
570 AddKeyword ("operator", Token.OPERATOR);
571 AddKeyword ("out", Token.OUT);
572 AddKeyword ("override", Token.OVERRIDE);
573 AddKeyword ("params", Token.PARAMS);
574 AddKeyword ("private", Token.PRIVATE);
575 AddKeyword ("protected", Token.PROTECTED);
576 AddKeyword ("public", Token.PUBLIC);
577 AddKeyword ("readonly", Token.READONLY);
578 AddKeyword ("ref", Token.REF);
579 AddKeyword ("remove", Token.REMOVE);
580 AddKeyword ("return", Token.RETURN);
581 AddKeyword ("sbyte", Token.SBYTE);
582 AddKeyword ("sealed", Token.SEALED);
583 AddKeyword ("set", Token.SET);
584 AddKeyword ("short", Token.SHORT);
585 AddKeyword ("sizeof", Token.SIZEOF);
586 AddKeyword ("stackalloc", Token.STACKALLOC);
587 AddKeyword ("static", Token.STATIC);
588 AddKeyword ("string", Token.STRING);
589 AddKeyword ("struct", Token.STRUCT);
590 AddKeyword ("switch", Token.SWITCH);
591 AddKeyword ("this", Token.THIS);
592 AddKeyword ("throw", Token.THROW);
593 AddKeyword ("true", Token.TRUE);
594 AddKeyword ("try", Token.TRY);
595 AddKeyword ("typeof", Token.TYPEOF);
596 AddKeyword ("uint", Token.UINT);
597 AddKeyword ("ulong", Token.ULONG);
598 AddKeyword ("unchecked", Token.UNCHECKED);
599 AddKeyword ("unsafe", Token.UNSAFE);
600 AddKeyword ("ushort", Token.USHORT);
601 AddKeyword ("using", Token.USING);
602 AddKeyword ("virtual", Token.VIRTUAL);
603 AddKeyword ("void", Token.VOID);
604 AddKeyword ("volatile", Token.VOLATILE);
605 AddKeyword ("while", Token.WHILE);
606 AddKeyword ("partial", Token.PARTIAL);
607 AddKeyword ("where", Token.WHERE);
610 AddKeyword ("from", Token.FROM);
611 AddKeyword ("join", Token.JOIN);
612 AddKeyword ("on", Token.ON);
613 AddKeyword ("equals", Token.EQUALS);
614 AddKeyword ("select", Token.SELECT);
615 AddKeyword ("group", Token.GROUP);
616 AddKeyword ("by", Token.BY);
617 AddKeyword ("let", Token.LET);
618 AddKeyword ("orderby", Token.ORDERBY);
619 AddKeyword ("ascending", Token.ASCENDING);
620 AddKeyword ("descending", Token.DESCENDING);
621 AddKeyword ("into", Token.INTO);
623 // Contextual async keywords
624 AddKeyword ("async", Token.ASYNC);
625 AddKeyword ("await", Token.AWAIT);
627 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
629 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
630 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
631 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
632 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
633 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
634 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
635 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
636 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
637 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
638 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
639 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
640 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
642 csharp_format_info = NumberFormatInfo.InvariantInfo;
643 styles = NumberStyles.Float;
646 int GetKeyword (char[] id, int id_len)
649 // Keywords are stored in an array of arrays grouped by their
650 // length and then by the first character
652 if (id_len >= keywords.Length || keywords [id_len] == null)
655 int first_index = id [0] - '_';
656 if (first_index > 'z' - '_')
659 var kwe = keywords [id_len] [first_index];
666 for (int i = 1; i < id_len; ++i) {
667 if (id [i] != kwe.Value [i]) {
673 } while (res == 0 && kwe != null);
687 if (!handle_remove_add)
691 if (parsing_declaration == 0)
692 res = Token.EXTERN_ALIAS;
695 if (peek_token () == Token.COLON) {
697 res = Token.DEFAULT_COLON;
701 if (!(handle_where && current_token != Token.COLON) && !query_parsing)
706 // A query expression is any expression that starts with `from identifier'
707 // followed by any token except ; , =
709 if (!query_parsing) {
710 if (lambda_arguments_parsing || parsing_block == 0) {
716 // HACK: to disable generics micro-parser, because PushPosition does not
717 // store identifiers array
718 parsing_generic_less_than = 1;
720 case Token.IDENTIFIER:
733 next_token = xtoken ();
734 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
737 res = Token.FROM_FIRST;
738 query_parsing = true;
739 if (context.Settings.Version <= LanguageVersion.ISO_2)
740 Report.FeatureIsNotAvailable (context, Location, "query expressions");
743 Expression.Error_VoidInvalidInTheContext (Location, Report);
747 // HACK: A token is not a keyword so we need to restore identifiers buffer
748 // which has been overwritten before we grabbed the identifier
749 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
763 case Token.ASCENDING:
764 case Token.DESCENDING:
771 case Token.NAMESPACE:
772 // TODO: some explanation needed
773 check_incorrect_doc_comment ();
774 parsing_modifiers = false;
778 if (parsing_block > 0) {
783 // Save current position and parse next token.
786 next_token = token ();
787 bool ok = (next_token == Token.CLASS) ||
788 (next_token == Token.STRUCT) ||
789 (next_token == Token.INTERFACE) ||
790 (next_token == Token.VOID);
795 if (next_token == Token.VOID) {
796 if (context.Settings.Version <= LanguageVersion.ISO_2)
797 Report.FeatureIsNotAvailable (context, Location, "partial methods");
798 } else if (context.Settings.Version == LanguageVersion.ISO_1)
799 Report.FeatureIsNotAvailable (context, Location, "partial types");
804 if (next_token < Token.LAST_KEYWORD) {
805 Report.Error (267, Location,
806 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
810 // HACK: A token is not a keyword so we need to restore identifiers buffer
811 // which has been overwritten before we grabbed the identifier
823 if (parsing_modifiers) {
825 // Skip attributes section or constructor called async
827 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
832 } else if (parsing_block > 0) {
833 switch (peek_token ()) {
835 case Token.OPEN_PARENS_LAMBDA:
838 case Token.IDENTIFIER:
841 if (xtoken () != Token.ARROW) {
849 // peek_token could overwrite id_buffer
850 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
858 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
859 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
865 if (parsing_block == 0)
875 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
878 // Keywords are stored in an array of arrays grouped by their
879 // length and then by the first character
881 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
882 return PreprocessorDirective.Invalid;
884 int first_index = id[0] - '_';
885 if (first_index > 'z' - '_')
886 return PreprocessorDirective.Invalid;
888 var kwe = keywords_preprocessor[id_len][first_index];
890 return PreprocessorDirective.Invalid;
892 PreprocessorDirective res = PreprocessorDirective.Invalid;
895 for (int i = 1; i < id_len; ++i) {
896 if (id[i] != kwe.Value[i]) {
902 } while (res == PreprocessorDirective.Invalid && kwe != null);
907 public Location Location {
909 return new Location (current_source, ref_line, col);
913 static bool is_identifier_start_character (int c)
915 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
918 static bool is_identifier_part_character (char c)
920 if (c >= 'a' && c <= 'z')
923 if (c >= 'A' && c <= 'Z')
926 if (c == '_' || (c >= '0' && c <= '9'))
932 return is_identifier_part_character_slow_part (c);
935 static bool is_identifier_part_character_slow_part (char c)
937 if (Char.IsLetter (c))
940 switch (Char.GetUnicodeCategory (c)) {
941 case UnicodeCategory.ConnectorPunctuation:
943 // combining-character: A Unicode character of classes Mn or Mc
944 case UnicodeCategory.NonSpacingMark:
945 case UnicodeCategory.SpacingCombiningMark:
947 // decimal-digit-character: A Unicode character of the class Nd
948 case UnicodeCategory.DecimalDigitNumber:
955 public static bool IsKeyword (string s)
957 return keyword_strings.Contains (s);
961 // Open parens micro parser. Detects both lambda and cast ambiguity.
963 int TokenizeOpenParens ()
968 int bracket_level = 0;
969 bool is_type = false;
970 bool can_be_type = false;
973 ptoken = current_token;
976 switch (current_token) {
977 case Token.CLOSE_PARENS:
981 // Expression inside parens is lambda, (int i) =>
983 if (current_token == Token.ARROW)
984 return Token.OPEN_PARENS_LAMBDA;
987 // Expression inside parens is single type, (int[])
990 if (current_token == Token.SEMICOLON)
991 return Token.OPEN_PARENS;
993 return Token.OPEN_PARENS_CAST;
997 // Expression is possible cast, look at next token, (T)null
1000 switch (current_token) {
1001 case Token.OPEN_PARENS:
1004 case Token.IDENTIFIER:
1008 case Token.DELEGATE:
1018 case Token.UNCHECKED:
1024 // These can be part of a member access
1039 return Token.OPEN_PARENS_CAST;
1042 return Token.OPEN_PARENS;
1045 case Token.DOUBLE_COLON:
1046 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1051 case Token.IDENTIFIER:
1055 if (bracket_level == 0) {
1061 case Token.OP_GENERICS_LT:
1063 case Token.DOUBLE_COLON:
1065 if (bracket_level == 0)
1069 can_be_type = is_type = false;
1089 if (bracket_level == 0)
1094 if (bracket_level == 0) {
1095 bracket_level = 100;
1096 can_be_type = is_type = false;
1100 case Token.OP_GENERICS_LT:
1101 case Token.OPEN_BRACKET:
1102 if (bracket_level++ == 0)
1106 case Token.OP_GENERICS_GT:
1107 case Token.CLOSE_BRACKET:
1111 case Token.INTERR_NULLABLE:
1113 if (bracket_level == 0)
1119 can_be_type = is_type = false;
1123 return Token.OPEN_PARENS;
1128 public static bool IsValidIdentifier (string s)
1130 if (s == null || s.Length == 0)
1133 if (!is_identifier_start_character (s [0]))
1136 for (int i = 1; i < s.Length; i ++)
1137 if (! is_identifier_part_character (s [i]))
1143 bool parse_less_than (ref int genericDimension)
1146 int the_token = token ();
1147 if (the_token == Token.OPEN_BRACKET) {
1149 the_token = token ();
1150 if (the_token == Token.EOF)
1153 if (the_token == Token.CLOSE_BRACKET)
1156 the_token = token ();
1157 } else if (the_token == Token.IN || the_token == Token.OUT) {
1158 the_token = token ();
1160 switch (the_token) {
1161 case Token.IDENTIFIER:
1179 case Token.OP_GENERICS_GT:
1180 genericDimension = 1;
1188 the_token = token ();
1189 } while (the_token == Token.COMMA);
1191 if (the_token == Token.OP_GENERICS_GT) {
1201 the_token = token ();
1203 if (the_token == Token.OP_GENERICS_GT)
1205 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1207 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1209 else if (the_token == Token.OP_GENERICS_LT) {
1210 if (!parse_less_than (ref genericDimension))
1213 } else if (the_token == Token.OPEN_BRACKET) {
1215 the_token = token ();
1216 if (the_token == Token.CLOSE_BRACKET)
1218 else if (the_token == Token.COMMA)
1219 goto rank_specifiers;
1226 public int peek_token ()
1231 the_token = token ();
1238 // Tonizes `?' using custom disambiguous rules to return one
1239 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1241 // Tricky expression looks like:
1243 // Foo ? a = x ? b : c;
1245 int TokenizePossibleNullableType ()
1247 if (parsing_block == 0 || parsing_type > 0)
1248 return Token.INTERR_NULLABLE;
1250 int d = peek_char ();
1253 return Token.OP_COALESCING;
1257 return Token.INTERR_OPERATOR;
1261 if (d == ',' || d == ';' || d == '>')
1262 return Token.INTERR_NULLABLE;
1263 if (d == '*' || (d >= '0' && d <= '9'))
1264 return Token.INTERR;
1268 current_token = Token.NONE;
1277 case Token.OPEN_BRACKET_EXPR:
1278 next_token = Token.INTERR_OPERATOR;
1286 next_token = Token.INTERR;
1289 case Token.SEMICOLON:
1291 case Token.CLOSE_PARENS:
1292 case Token.OPEN_BRACKET:
1293 case Token.OP_GENERICS_GT:
1295 case Token.OP_COALESCING:
1297 next_token = Token.INTERR_NULLABLE;
1300 case Token.OPEN_PARENS:
1301 case Token.OPEN_PARENS_CAST:
1302 case Token.OPEN_PARENS_LAMBDA:
1307 case Token.OP_GENERICS_LT:
1308 case Token.OP_GENERICS_LT_DECL:
1309 case Token.GENERIC_DIMENSION:
1319 if (next_token == -1) {
1320 switch (xtoken ()) {
1322 case Token.SEMICOLON:
1323 case Token.OPEN_BRACE:
1325 next_token = Token.INTERR_NULLABLE;
1329 next_token = Token.INTERR;
1332 case Token.OPEN_PARENS:
1333 case Token.OPEN_PARENS_CAST:
1334 case Token.OPEN_PARENS_LAMBDA:
1338 case Token.OPEN_BRACKET:
1339 case Token.OPEN_BRACKET_EXPR:
1343 case Token.CLOSE_PARENS:
1347 case Token.OP_GENERICS_LT:
1348 case Token.OP_GENERICS_LT_DECL:
1349 case Token.GENERIC_DIMENSION:
1359 // All shorcuts failed, do it hard way
1361 while ((ntoken = xtoken ()) != Token.EOF) {
1363 case Token.OPEN_BRACE:
1366 case Token.OPEN_PARENS:
1367 case Token.OPEN_PARENS_CAST:
1368 case Token.OPEN_PARENS_LAMBDA:
1371 case Token.CLOSE_BRACE:
1374 case Token.OP_GENERICS_LT:
1375 case Token.OP_GENERICS_LT_DECL:
1376 case Token.GENERIC_DIMENSION:
1379 case Token.OPEN_BRACKET:
1380 case Token.OPEN_BRACKET_EXPR:
1383 case Token.CLOSE_BRACKET:
1386 case Token.CLOSE_PARENS:
1393 return Token.INTERR_NULLABLE;
1395 case Token.OP_GENERICS_GT:
1402 return Token.INTERR_NULLABLE;
1408 if (ntoken == Token.SEMICOLON)
1414 if (ntoken == Token.COMMA) {
1415 if (generics != 0 || brackets != 0)
1419 return Token.INTERR_NULLABLE;
1422 if (ntoken == Token.COLON) {
1423 if (++colons == interrs)
1428 if (ntoken == Token.INTERR) {
1434 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1443 bool decimal_digits (int c)
1446 bool seen_digits = false;
1449 if (number_pos == MaxNumberLength)
1450 Error_NumericConstantTooLong ();
1451 number_builder [number_pos++] = (char) c;
1455 // We use peek_char2, because decimal_digits needs to do a
1456 // 2-character look-ahead (5.ToString for example).
1458 while ((d = peek_char2 ()) != -1){
1459 if (d >= '0' && d <= '9'){
1460 if (number_pos == MaxNumberLength)
1461 Error_NumericConstantTooLong ();
1462 number_builder [number_pos++] = (char) d;
1472 static bool is_hex (int e)
1474 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1477 static TypeCode real_type_suffix (int c)
1481 return TypeCode.Single;
1483 return TypeCode.Double;
1485 return TypeCode.Decimal;
1487 return TypeCode.Empty;
1491 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1493 bool is_unsigned = false;
1494 bool is_long = false;
1497 bool scanning = true;
1510 // if we have not seen anything in between
1511 // report this error
1513 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1533 if (is_long && is_unsigned){
1534 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1538 // uint if possible, or ulong else.
1540 if ((ul & 0xffffffff00000000) == 0)
1541 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1543 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1544 } else if (is_long){
1545 // long if possible, ulong otherwise
1546 if ((ul & 0x8000000000000000) != 0)
1547 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1549 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1551 // int, uint, long or ulong in that order
1552 if ((ul & 0xffffffff00000000) == 0){
1553 uint ui = (uint) ul;
1555 if ((ui & 0x80000000) != 0)
1556 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1558 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1560 if ((ul & 0x8000000000000000) != 0)
1561 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1563 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1569 // given `c' as the next char in the input decide whether
1570 // we need to convert to a special type, and then choose
1571 // the best representation for the integer
1573 ILiteralConstant adjust_int (int c, Location loc)
1576 if (number_pos > 9){
1577 ulong ul = (uint) (number_builder [0] - '0');
1579 for (int i = 1; i < number_pos; i++){
1580 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1583 return integer_type_suffix (ul, c, loc);
1585 uint ui = (uint) (number_builder [0] - '0');
1587 for (int i = 1; i < number_pos; i++){
1588 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1591 return integer_type_suffix (ui, c, loc);
1593 } catch (OverflowException) {
1594 Error_NumericConstantTooLong ();
1595 return new IntLiteral (context.BuiltinTypes, 0, loc);
1597 catch (FormatException) {
1598 Report.Error (1013, Location, "Invalid number");
1599 return new IntLiteral (context.BuiltinTypes, 0, loc);
1603 ILiteralConstant adjust_real (TypeCode t, Location loc)
1605 string s = new string (number_builder, 0, number_pos);
1606 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1609 case TypeCode.Decimal:
1611 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1612 } catch (OverflowException) {
1613 Report.Error (594, Location, error_details, "decimal");
1614 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1616 case TypeCode.Single:
1618 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1619 } catch (OverflowException) {
1620 Report.Error (594, Location, error_details, "float");
1621 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1625 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1626 } catch (OverflowException) {
1627 Report.Error (594, loc, error_details, "double");
1628 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1633 ILiteralConstant handle_hex (Location loc)
1639 while ((d = peek_char ()) != -1){
1641 number_builder [number_pos++] = (char) d;
1647 string s = new String (number_builder, 0, number_pos);
1650 if (number_pos <= 8)
1651 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1653 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1655 return integer_type_suffix (ul, peek_char (), loc);
1656 } catch (OverflowException){
1657 Error_NumericConstantTooLong ();
1658 return new IntLiteral (context.BuiltinTypes, 0, loc);
1660 catch (FormatException) {
1661 Report.Error (1013, Location, "Invalid number");
1662 return new IntLiteral (context.BuiltinTypes, 0, loc);
1667 // Invoked if we know we have .digits or digits
1669 int is_number (int c, bool dotLead)
1671 ILiteralConstant res;
1674 int read_start = reader.Position - 1;
1677 // Caller did peek_char
1687 int peek = peek_char ();
1689 if (peek == 'x' || peek == 'X') {
1690 val = res = handle_hex (loc);
1692 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1695 return Token.LITERAL;
1703 // We need to handle the case of
1704 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1706 bool is_real = false;
1711 if (decimal_digits ('.')){
1717 val = res = adjust_int (-1, loc);
1720 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1722 return Token.LITERAL;
1726 if (c == 'e' || c == 'E'){
1729 if (number_pos == MaxNumberLength)
1730 Error_NumericConstantTooLong ();
1731 number_builder [number_pos++] = (char) c;
1735 if (number_pos == MaxNumberLength)
1736 Error_NumericConstantTooLong ();
1737 number_builder [number_pos++] = '+';
1739 } else if (c == '-') {
1740 if (number_pos == MaxNumberLength)
1741 Error_NumericConstantTooLong ();
1742 number_builder [number_pos++] = '-';
1745 if (number_pos == MaxNumberLength)
1746 Error_NumericConstantTooLong ();
1747 number_builder [number_pos++] = '+';
1754 var type = real_type_suffix (c);
1755 if (type == TypeCode.Empty && !is_real) {
1756 res = adjust_int (c, loc);
1760 if (type != TypeCode.Empty) {
1764 res = adjust_real (type, loc);
1770 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1771 if (chars[chars.Length - 1] == '\r')
1772 Array.Resize (ref chars, chars.Length - 1);
1773 res.ParsedValue = chars;
1776 return Token.LITERAL;
1780 // Accepts exactly count (4 or 8) hex, no more no less
1782 int getHex (int count, out int surrogate, out bool error)
1787 int top = count != -1 ? count : 4;
1792 for (i = 0; i < top; i++){
1795 if (c >= '0' && c <= '9')
1796 c = (int) c - (int) '0';
1797 else if (c >= 'A' && c <= 'F')
1798 c = (int) c - (int) 'A' + 10;
1799 else if (c >= 'a' && c <= 'f')
1800 c = (int) c - (int) 'a' + 10;
1806 total = (total * 16) + c;
1808 int p = peek_char ();
1811 if (!is_hex ((char)p))
1817 if (total > 0x0010FFFF) {
1822 if (total >= 0x00010000) {
1823 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1824 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1831 int escape (int c, out int surrogate)
1867 v = getHex (-1, out surrogate, out error);
1873 return EscapeUnicode (d, out surrogate);
1876 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1885 int EscapeUnicode (int ch, out int surrogate)
1889 ch = getHex (8, out surrogate, out error);
1891 ch = getHex (4, out surrogate, out error);
1895 Report.Error (1009, Location, "Unrecognized escape sequence");
1903 if (putback_char != -1) {
1912 if (peek_char () == '\n') {
1918 } else if (x == '\n') {
1923 } else if (x >= UnicodeLS && x <= UnicodePS) {
1932 void advance_line ()
1942 if (putback_char == -1)
1943 putback_char = reader.Read ();
1944 return putback_char;
1949 if (putback_char != -1)
1950 return putback_char;
1951 return reader.Peek ();
1954 public void putback (int c)
1956 if (putback_char != -1) {
1957 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
1960 if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
1961 // It won't happen though.
1971 public bool advance ()
1973 return peek_char () != -1 || CompleteOnEOF;
1976 public Object Value {
1982 public Object value ()
1989 current_token = xtoken ();
1990 return current_token;
1993 int TokenizePreprocessorKeyword (out int c)
1995 // skip over white space
1998 } while (c == ' ' || c == '\t');
2002 while (c != -1 && c >= 'a' && c <= 'z') {
2003 id_builder[pos++] = (char) c;
2006 int peek = peek_char ();
2007 if (peek == 'U' || peek == 'u') {
2009 c = EscapeUnicode (c, out surrogate);
2010 if (surrogate != 0) {
2011 if (is_identifier_part_character ((char) c)) {
2012 id_builder[pos++] = (char) c;
2023 PreprocessorDirective get_cmd_arg (out string arg)
2027 tokens_seen = false;
2030 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2032 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2035 // skip over white space
2036 while (c == ' ' || c == '\t')
2039 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2042 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2043 if (c == '\\' && has_identifier_argument >= 0) {
2044 if (has_identifier_argument != 0) {
2045 has_identifier_argument = 1;
2047 int peek = peek_char ();
2048 if (peek == 'U' || peek == 'u') {
2050 c = EscapeUnicode (c, out surrogate);
2051 if (surrogate != 0) {
2052 if (is_identifier_part_character ((char) c)) {
2053 if (pos == value_builder.Length)
2054 Array.Resize (ref value_builder, pos * 2);
2056 value_builder[pos++] = (char) c;
2062 has_identifier_argument = -1;
2064 } else if (c == '/' && peek_char () == '/') {
2066 // Eat single-line comments
2073 if (pos == value_builder.Length)
2074 Array.Resize (ref value_builder, pos * 2);
2076 value_builder[pos++] = (char) c;
2081 if (pos > MaxIdentifierLength)
2082 arg = new string (value_builder, 0, pos);
2084 arg = InternIdentifier (value_builder, pos);
2086 // Eat any trailing whitespaces
2087 arg = arg.Trim (simple_whitespaces);
2094 // Handles the #line directive
2096 bool PreProcessLine ()
2098 Location loc = Location;
2102 int length = TokenizePreprocessorKeyword (out c);
2103 if (length == line_default.Length) {
2104 if (!IsTokenIdentifierEqual (line_default))
2107 current_source = source_file.SourceFile;
2108 if (!hidden_block_start.IsNull) {
2109 current_source.RegisterHiddenScope (hidden_block_start, loc);
2110 hidden_block_start = Location.Null;
2117 if (length == line_hidden.Length) {
2118 if (!IsTokenIdentifierEqual (line_hidden))
2121 if (hidden_block_start.IsNull)
2122 hidden_block_start = loc;
2127 if (length != 0 || c < '0' || c > '9') {
2129 // Eat any remaining characters to continue parsing on next line
2135 int new_line = TokenizeNumber (c);
2138 // Eat any remaining characters to continue parsing on next line
2141 return new_line != 0;
2146 // skip over white space
2149 } while (c == ' ' || c == '\t');
2150 } else if (c == '"') {
2154 if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2156 // Eat any remaining characters to continue parsing on next line
2160 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2164 string new_file_name = null;
2166 new_file_name = TokenizeFileName (ref c);
2168 // skip over white space
2169 while (c == ' ' || c == '\t') {
2174 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2176 } else if (c == '/') {
2177 ReadSingleLineComment ();
2180 // Eat any remaining characters to continue parsing on next line
2184 Error_EndLineExpected ();
2188 if (new_file_name != null) {
2189 current_source = context.LookupFile (source_file, new_file_name);
2190 source_file.AddIncludeFile (current_source);
2193 if (!hidden_block_start.IsNull) {
2194 current_source.RegisterHiddenScope (hidden_block_start, loc);
2195 hidden_block_start = Location.Null;
2198 ref_line = new_line;
2203 // Handles #define and #undef
2205 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2207 if (ident.Length == 0 || ident == "true" || ident == "false"){
2208 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2212 if (ident.IndexOfAny (simple_whitespaces) != -1){
2213 Error_EndLineExpected ();
2217 if (!is_identifier_start_character (ident [0]))
2218 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2220 foreach (char c in ident.Substring (1)){
2221 if (!is_identifier_part_character (c)){
2222 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2227 if (!caller_is_taking)
2234 if (context.Settings.IsConditionalSymbolDefined (ident))
2237 source_file.AddDefine (ident);
2242 source_file.AddUndefine (ident);
2246 byte read_hex (out bool error)
2249 int c = get_char ();
2251 if ((c >= '0') && (c <= '9'))
2252 total = (int) c - (int) '0';
2253 else if ((c >= 'A') && (c <= 'F'))
2254 total = (int) c - (int) 'A' + 10;
2255 else if ((c >= 'a') && (c <= 'f'))
2256 total = (int) c - (int) 'a' + 10;
2265 if ((c >= '0') && (c <= '9'))
2266 total += (int) c - (int) '0';
2267 else if ((c >= 'A') && (c <= 'F'))
2268 total += (int) c - (int) 'A' + 10;
2269 else if ((c >= 'a') && (c <= 'f'))
2270 total += (int) c - (int) 'a' + 10;
2277 return (byte) total;
2281 // Parses #pragma checksum
2283 bool ParsePragmaChecksum ()
2286 // The syntax is ` "foo.txt" "{guid}" "hash"'
2288 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2290 int c = get_char ();
2295 string file_name = TokenizeFileName (ref c);
2297 // TODO: Any white-spaces count
2301 SourceFile file = context.LookupFile (source_file, file_name);
2303 if (get_char () != '"' || get_char () != '{')
2307 byte[] guid_bytes = new byte [16];
2310 for (; i < 4; i++) {
2311 guid_bytes [i] = read_hex (out error);
2316 if (get_char () != '-')
2319 for (; i < 10; i++) {
2320 guid_bytes [i] = read_hex (out error);
2324 guid_bytes [i++] = read_hex (out error);
2328 if (get_char () != '-')
2332 for (; i < 16; i++) {
2333 guid_bytes [i] = read_hex (out error);
2338 if (get_char () != '}' || get_char () != '"')
2341 // TODO: Any white-spaces count
2346 if (get_char () != '"')
2349 // Any length of checksum
2350 List<byte> checksum_bytes = new List<byte> (16);
2352 var checksum_location = Location;
2354 while (c != '"' && c != -1) {
2355 checksum_bytes.Add (read_hex (out error));
2363 ReadSingleLineComment ();
2364 } else if (get_char () != '"') {
2368 if (context.Settings.GenerateDebugInfo) {
2369 var chsum = checksum_bytes.ToArray ();
2371 if (file.HasChecksum) {
2372 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2373 // TODO: Report.SymbolRelatedToPreviousError
2374 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2378 file.SetChecksum (guid_bytes, chsum);
2379 current_source.AutoGenerated = true;
2385 bool IsTokenIdentifierEqual (char[] identifier)
2387 for (int i = 0; i < identifier.Length; ++i) {
2388 if (identifier[i] != id_builder[i])
2395 int TokenizeNumber (int value)
2399 decimal_digits (value);
2400 uint ui = (uint) (number_builder[0] - '0');
2403 for (int i = 1; i < number_pos; i++) {
2404 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2408 } catch (OverflowException) {
2409 Error_NumericConstantTooLong ();
2414 string TokenizeFileName (ref int c)
2416 var string_builder = new StringBuilder ();
2417 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2424 string_builder.Append ((char) c);
2427 if (string_builder.Length == 0) {
2428 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2432 return string_builder.ToString ();
2435 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2438 if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2441 if (c >= '0' && c <= '9') {
2443 number = TokenizeNumber (c);
2447 if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2448 return ReadPragmaWarningComment (c);
2452 // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2456 id_builder [pos++] = (char)c;
2457 while (c < MaxIdentifierLength) {
2459 id_builder [pos] = (char)c;
2461 if (c >= '0' && c <= '9') {
2462 if (pos == 6 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2463 // Recognize CSXXXX as C# XXXX warning
2466 for (int i = 0; i < 4; ++i) {
2467 var ch = id_builder [i + 2];
2468 if (ch < '0' || ch > '9') {
2473 number += (ch - '0') * pow;
2477 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2490 // skip over white space
2491 while (c == ' ' || c == '\t')
2498 // skip over white space
2499 while (c == ' ' || c == '\t')
2505 return ReadPragmaWarningComment (c);
2508 int ReadPragmaWarningComment (int c)
2511 ReadSingleLineComment ();
2513 Report.Warning (1692, 1, Location, "Invalid number");
2515 // Read everything till the end of the line or file
2522 void ReadToEndOfLine ()
2527 } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2530 void ReadSingleLineComment ()
2532 if (peek_char () != '/')
2533 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2535 // Read everything till the end of the line or file
2540 /// Handles #pragma directive
2542 void ParsePragmaDirective ()
2545 int length = TokenizePreprocessorKeyword (out c);
2546 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2547 length = TokenizePreprocessorKeyword (out c);
2550 // #pragma warning disable
2551 // #pragma warning restore
2553 if (length == pragma_warning_disable.Length) {
2554 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2555 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2556 // skip over white space
2557 while (c == ' ' || c == '\t')
2562 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2564 ReadSingleLineComment ();
2567 // Disable/Restore all warnings
2570 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2572 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2576 // Disable/Restore a warning or group of warnings
2580 bool identifier = false;
2581 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2584 // no-op, custom warnings cannot occur in mcs
2585 } else if (disable) {
2586 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2588 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2591 } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2598 Report.Warning (1634, 1, Location, "Expected disable or restore");
2600 // Eat any remaining characters on the line
2609 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2610 if (c != ' ' || !ParsePragmaChecksum ()) {
2611 Report.Warning (1695, 1, Location,
2612 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2618 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2621 bool eval_val (string s)
2628 return source_file.IsConditionalDefined (s);
2631 bool pp_primary (ref string s)
2640 s = s.Substring (1);
2641 bool val = pp_expr (ref s, false);
2642 if (s.Length > 0 && s [0] == ')'){
2643 s = s.Substring (1);
2646 Error_InvalidDirective ();
2650 if (is_identifier_start_character (c)){
2656 if (is_identifier_part_character (c)){
2660 bool v = eval_val (s.Substring (0, j));
2661 s = s.Substring (j);
2664 bool vv = eval_val (s);
2669 Error_InvalidDirective ();
2673 bool pp_unary (ref string s)
2680 if (len > 1 && s [1] == '='){
2681 Error_InvalidDirective ();
2684 s = s.Substring (1);
2685 return ! pp_primary (ref s);
2687 return pp_primary (ref s);
2689 Error_InvalidDirective ();
2694 bool pp_eq (ref string s)
2696 bool va = pp_unary (ref s);
2702 if (len > 2 && s [1] == '='){
2703 s = s.Substring (2);
2704 return va == pp_unary (ref s);
2706 Error_InvalidDirective ();
2709 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2710 s = s.Substring (2);
2712 return va != pp_unary (ref s);
2721 bool pp_and (ref string s)
2723 bool va = pp_eq (ref s);
2729 if (len > 2 && s [1] == '&'){
2730 s = s.Substring (2);
2731 return (va & pp_and (ref s));
2733 Error_InvalidDirective ();
2742 // Evaluates an expression for `#if' or `#elif'
2744 bool pp_expr (ref string s, bool isTerm)
2746 bool va = pp_and (ref s);
2753 if (len > 2 && s [1] == '|'){
2754 s = s.Substring (2);
2755 return va | pp_expr (ref s, isTerm);
2757 Error_InvalidDirective ();
2762 Error_EndLineExpected ();
2770 bool eval (string s)
2772 bool v = pp_expr (ref s, true);
2781 void Error_NumericConstantTooLong ()
2783 Report.Error (1021, Location, "Integral constant is too large");
2786 void Error_InvalidDirective ()
2788 Report.Error (1517, Location, "Invalid preprocessor directive");
2791 void Error_UnexpectedDirective (string extra)
2795 "Unexpected processor directive ({0})", extra);
2798 void Error_TokensSeen ()
2800 Report.Error (1032, Location,
2801 "Cannot define or undefine preprocessor symbols after first token in file");
2804 void Eror_WrongPreprocessorLocation ()
2806 Report.Error (1040, Location,
2807 "Preprocessor directives must appear as the first non-whitespace character on a line");
2810 void Error_EndLineExpected ()
2812 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2816 // Raises a warning when tokenizer found documentation comment
2817 // on unexpected place
2819 void WarningMisplacedComment (Location loc)
2821 if (doc_state != XmlCommentState.Error) {
2822 doc_state = XmlCommentState.Error;
2823 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2828 // if true, then the code continues processing the code
2829 // if false, the code stays in a loop until another directive is
2831 // When caller_is_taking is false we ignore all directives except the ones
2832 // which can help us to identify where the #if block ends
2833 bool ParsePreprocessingDirective (bool caller_is_taking)
2836 bool region_directive = false;
2838 var directive = get_cmd_arg (out arg);
2841 // The first group of pre-processing instructions is always processed
2843 switch (directive) {
2844 case PreprocessorDirective.Region:
2845 region_directive = true;
2847 goto case PreprocessorDirective.If;
2849 case PreprocessorDirective.Endregion:
2850 if (ifstack == null || ifstack.Count == 0){
2851 Error_UnexpectedDirective ("no #region for this #endregion");
2854 int pop = ifstack.Pop ();
2856 if ((pop & REGION) == 0)
2857 Report.Error (1027, Location, "Expected `#endif' directive");
2859 return caller_is_taking;
2861 case PreprocessorDirective.If:
2862 if (ifstack == null)
2863 ifstack = new Stack<int> (2);
2865 int flags = region_directive ? REGION : 0;
2866 if (ifstack.Count == 0){
2867 flags |= PARENT_TAKING;
2869 int state = ifstack.Peek ();
2870 if ((state & TAKING) != 0) {
2871 flags |= PARENT_TAKING;
2875 if (eval (arg) && caller_is_taking) {
2876 ifstack.Push (flags | TAKING);
2879 ifstack.Push (flags);
2882 case PreprocessorDirective.Endif:
2883 if (ifstack == null || ifstack.Count == 0){
2884 Error_UnexpectedDirective ("no #if for this #endif");
2887 pop = ifstack.Pop ();
2889 if ((pop & REGION) != 0)
2890 Report.Error (1038, Location, "#endregion directive expected");
2892 if (arg.Length != 0) {
2893 Error_EndLineExpected ();
2896 if (ifstack.Count == 0)
2899 int state = ifstack.Peek ();
2900 return (state & TAKING) != 0;
2903 case PreprocessorDirective.Elif:
2904 if (ifstack == null || ifstack.Count == 0){
2905 Error_UnexpectedDirective ("no #if for this #elif");
2908 int state = ifstack.Pop ();
2910 if ((state & REGION) != 0) {
2911 Report.Error (1038, Location, "#endregion directive expected");
2915 if ((state & ELSE_SEEN) != 0){
2916 Error_UnexpectedDirective ("#elif not valid after #else");
2920 if ((state & TAKING) != 0) {
2925 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2926 ifstack.Push (state | TAKING);
2930 ifstack.Push (state);
2934 case PreprocessorDirective.Else:
2935 if (ifstack == null || ifstack.Count == 0){
2936 Error_UnexpectedDirective ("no #if for this #else");
2939 int state = ifstack.Peek ();
2941 if ((state & REGION) != 0) {
2942 Report.Error (1038, Location, "#endregion directive expected");
2946 if ((state & ELSE_SEEN) != 0){
2947 Error_UnexpectedDirective ("#else within #else");
2953 if (arg.Length != 0) {
2954 Error_EndLineExpected ();
2959 if ((state & PARENT_TAKING) != 0) {
2960 ret = (state & TAKING) == 0;
2968 ifstack.Push (state | ELSE_SEEN);
2972 case PreprocessorDirective.Define:
2973 if (any_token_seen){
2974 if (caller_is_taking)
2975 Error_TokensSeen ();
2976 return caller_is_taking;
2978 PreProcessDefinition (true, arg, caller_is_taking);
2979 return caller_is_taking;
2981 case PreprocessorDirective.Undef:
2982 if (any_token_seen){
2983 if (caller_is_taking)
2984 Error_TokensSeen ();
2985 return caller_is_taking;
2987 PreProcessDefinition (false, arg, caller_is_taking);
2988 return caller_is_taking;
2990 case PreprocessorDirective.Invalid:
2991 Report.Error (1024, Location, "Wrong preprocessor directive");
2996 // These are only processed if we are in a `taking' block
2998 if (!caller_is_taking)
3002 case PreprocessorDirective.Error:
3003 Report.Error (1029, Location, "#error: '{0}'", arg);
3006 case PreprocessorDirective.Warning:
3007 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3010 case PreprocessorDirective.Pragma:
3011 if (context.Settings.Version == LanguageVersion.ISO_1) {
3012 Report.FeatureIsNotAvailable (context, Location, "#pragma");
3015 ParsePragmaDirective ();
3018 case PreprocessorDirective.Line:
3019 Location loc = Location;
3020 if (!PreProcessLine ())
3021 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3023 return caller_is_taking;
3026 throw new NotImplementedException (directive.ToString ());
3029 private int consume_string (bool quoted)
3033 Location start_location = Location;
3035 start_location = start_location - 1;
3038 int reader_pos = reader.Position;
3042 // Cannot use get_char because of \r in quoted strings
3043 if (putback_char != -1) {
3053 if (quoted && peek_char () == '"') {
3054 if (pos == value_builder.Length)
3055 Array.Resize (ref value_builder, pos * 2);
3057 value_builder[pos++] = (char) c;
3066 s = InternIdentifier (value_builder, pos);
3068 s = new string (value_builder, 0, pos);
3070 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
3073 res.ParsedValue = quoted ?
3074 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3075 reader.ReadChars (reader_pos - 1, reader.Position);
3078 return Token.LITERAL;
3081 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3083 Report.Error (1010, Location, "Newline in constant");
3087 // Don't add \r to string literal
3088 if (pos > 1 && value_builder [pos - 1] == '\r')
3091 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3092 return Token.LITERAL;
3096 } else if (c == '\\' && !quoted) {
3099 c = escape (c, out surrogate);
3102 if (surrogate != 0) {
3103 if (pos == value_builder.Length)
3104 Array.Resize (ref value_builder, pos * 2);
3106 value_builder[pos++] = (char) c;
3109 } else if (c == -1) {
3110 Report.Error (1039, Location, "Unterminated string literal");
3116 if (pos == value_builder.Length)
3117 Array.Resize (ref value_builder, pos * 2);
3119 value_builder[pos++] = (char) c;
3123 private int consume_identifier (int s)
3125 int res = consume_identifier (s, false);
3127 if (doc_state == XmlCommentState.Allowed)
3128 doc_state = XmlCommentState.NotAllowed;
3133 int consume_identifier (int c, bool quoted)
3136 // This method is very performance sensitive. It accounts
3137 // for approximately 25% of all parser time
3147 c = escape (c, out surrogate);
3148 if (surrogate != 0) {
3149 id_builder [pos++] = (char) c;
3154 id_builder [pos++] = (char) c;
3160 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3161 id_builder [pos++] = (char) c;
3168 c = escape (c, out surrogate);
3169 if (is_identifier_part_character ((char) c))
3170 id_builder[pos++] = (char) c;
3172 if (surrogate != 0) {
3178 } else if (is_identifier_part_character_slow_part ((char) c)) {
3179 id_builder [pos++] = (char) c;
3186 } catch (IndexOutOfRangeException) {
3187 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3195 // Optimization: avoids doing the keyword lookup
3196 // on uppercase letters
3198 if (id_builder [0] >= '_' && !quoted) {
3199 int keyword = GetKeyword (id_builder, pos);
3200 if (keyword != -1) {
3201 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3206 string s = InternIdentifier (id_builder, pos);
3207 val = ltb.Create (s, current_source, ref_line, column);
3208 if (quoted && parsing_attribute_section)
3209 AddEscapedIdentifier (((LocatedToken) val).Location);
3211 return Token.IDENTIFIER;
3214 string InternIdentifier (char[] charBuffer, int length)
3217 // Keep identifiers in an array of hashtables to avoid needless
3220 var identifiers_group = identifiers[length];
3222 if (identifiers_group != null) {
3223 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3227 // TODO: this should be number of files dependant
3228 // corlib compilation peaks at 1000 and System.Core at 150
3229 int capacity = length > 20 ? 10 : 100;
3230 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3231 identifiers[length] = identifiers_group;
3234 char[] chars = new char[length];
3235 Array.Copy (charBuffer, chars, length);
3237 s = new string (charBuffer, 0, length);
3238 identifiers_group.Add (chars, s);
3242 public int xtoken ()
3246 // Whether we have seen comments on the current line
3247 bool comments_seen = false;
3248 while ((c = get_char ()) != -1) {
3251 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3259 case 0xFEFF: // Ignore BOM anywhere in the file
3262 /* This is required for compatibility with .NET
3264 if (peek_char () == 0xBB) {
3267 if (get_char () == 0xBF)
3275 return consume_identifier (c);
3278 val = ltb.Create (current_source, ref_line, col);
3279 return Token.OPEN_BRACE;
3281 val = ltb.Create (current_source, ref_line, col);
3282 return Token.CLOSE_BRACE;
3284 // To block doccomment inside attribute declaration.
3285 if (doc_state == XmlCommentState.Allowed)
3286 doc_state = XmlCommentState.NotAllowed;
3288 val = ltb.Create (current_source, ref_line, col);
3290 if (parsing_block == 0 || lambda_arguments_parsing)
3291 return Token.OPEN_BRACKET;
3293 int next = peek_char ();
3297 return Token.OPEN_BRACKET;
3307 next = peek_token ();
3308 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3309 return Token.OPEN_BRACKET;
3311 return Token.OPEN_BRACKET_EXPR;
3313 return Token.OPEN_BRACKET_EXPR;
3316 ltb.CreateOptional (current_source, ref_line, col, ref val);
3317 return Token.CLOSE_BRACKET;
3319 val = ltb.Create (current_source, ref_line, col);
3321 // An expression versions of parens can appear in block context only
3323 if (parsing_block != 0 && !lambda_arguments_parsing) {
3326 // Optmize most common case where we know that parens
3329 switch (current_token) {
3330 case Token.IDENTIFIER:
3339 case Token.DELEGATE:
3340 case Token.OP_GENERICS_GT:
3341 return Token.OPEN_PARENS;
3344 // Optimize using peek
3345 int xx = peek_char ();
3352 return Token.OPEN_PARENS;
3355 lambda_arguments_parsing = true;
3357 d = TokenizeOpenParens ();
3359 lambda_arguments_parsing = false;
3363 return Token.OPEN_PARENS;
3365 ltb.CreateOptional (current_source, ref_line, col, ref val);
3366 return Token.CLOSE_PARENS;
3368 ltb.CreateOptional (current_source, ref_line, col, ref val);
3371 ltb.CreateOptional (current_source, ref_line, col, ref val);
3372 return Token.SEMICOLON;
3374 val = ltb.Create (current_source, ref_line, col);
3377 val = ltb.Create (current_source, ref_line, col);
3378 return TokenizePossibleNullableType ();
3380 val = ltb.Create (current_source, ref_line, col);
3381 if (parsing_generic_less_than++ > 0)
3382 return Token.OP_GENERICS_LT;
3384 return TokenizeLessThan ();
3387 val = ltb.Create (current_source, ref_line, col);
3395 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3396 parsing_generic_less_than--;
3397 return Token.OP_GENERICS_GT;
3406 return Token.OP_SHIFT_RIGHT_ASSIGN;
3408 return Token.OP_SHIFT_RIGHT;
3414 val = ltb.Create (current_source, ref_line, col);
3418 } else if (d == '=') {
3419 d = Token.OP_ADD_ASSIGN;
3427 val = ltb.Create (current_source, ref_line, col);
3431 } else if (d == '=')
3432 d = Token.OP_SUB_ASSIGN;
3442 val = ltb.Create (current_source, ref_line, col);
3443 if (peek_char () == '='){
3450 val = ltb.Create (current_source, ref_line, col);
3461 return Token.ASSIGN;
3464 val = ltb.Create (current_source, ref_line, col);
3468 return Token.OP_AND;
3472 return Token.OP_AND_ASSIGN;
3474 return Token.BITWISE_AND;
3477 val = ltb.Create (current_source, ref_line, col);
3485 return Token.OP_OR_ASSIGN;
3487 return Token.BITWISE_OR;
3490 val = ltb.Create (current_source, ref_line, col);
3491 if (peek_char () == '='){
3493 return Token.OP_MULT_ASSIGN;
3500 val = ltb.Create (current_source, ref_line, col);
3502 return Token.OP_DIV_ASSIGN;
3505 // Handle double-slash comments.
3508 if (doc_processing) {
3509 if (peek_char () == '/') {
3511 // Don't allow ////.
3512 if ((d = peek_char ()) != '/') {
3513 if (doc_state == XmlCommentState.Allowed)
3514 handle_one_line_xml_comment ();
3515 else if (doc_state == XmlCommentState.NotAllowed)
3516 WarningMisplacedComment (Location - 3);
3519 if (xml_comment_buffer.Length > 0)
3520 doc_state = XmlCommentState.NotAllowed;
3526 any_token_seen |= tokens_seen;
3527 tokens_seen = false;
3528 comments_seen = false;
3530 } else if (d == '*'){
3532 bool docAppend = false;
3533 if (doc_processing && peek_char () == '*') {
3535 // But when it is /**/, just do nothing.
3536 if (peek_char () == '/') {
3540 if (doc_state == XmlCommentState.Allowed)
3542 else if (doc_state == XmlCommentState.NotAllowed) {
3543 WarningMisplacedComment (Location - 2);
3547 int current_comment_start = 0;
3549 current_comment_start = xml_comment_buffer.Length;
3550 xml_comment_buffer.Append (Environment.NewLine);
3553 while ((d = get_char ()) != -1){
3554 if (d == '*' && peek_char () == '/'){
3556 comments_seen = true;
3560 xml_comment_buffer.Append ((char) d);
3562 if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3563 any_token_seen |= tokens_seen;
3564 tokens_seen = false;
3566 // Reset 'comments_seen' just to be consistent.
3567 // It doesn't matter either way, here.
3569 comments_seen = false;
3573 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3576 update_formatted_doc_comment (current_comment_start);
3579 val = ltb.Create (current_source, ref_line, col);
3583 val = ltb.Create (current_source, ref_line, col);
3584 if (peek_char () == '='){
3586 return Token.OP_MOD_ASSIGN;
3588 return Token.PERCENT;
3591 val = ltb.Create (current_source, ref_line, col);
3592 if (peek_char () == '='){
3594 return Token.OP_XOR_ASSIGN;
3596 return Token.CARRET;
3599 val = ltb.Create (current_source, ref_line, col);
3600 if (peek_char () == ':') {
3602 return Token.DOUBLE_COLON;
3606 case '0': case '1': case '2': case '3': case '4':
3607 case '5': case '6': case '7': case '8': case '9':
3609 return is_number (c, false);
3611 case '\n': // white space
3614 any_token_seen |= tokens_seen;
3615 tokens_seen = false;
3616 comments_seen = false;
3622 if (d >= '0' && d <= '9')
3623 return is_number (c, true);
3625 ltb.CreateOptional (current_source, ref_line, col, ref val);
3629 if (tokens_seen || comments_seen) {
3630 Eror_WrongPreprocessorLocation ();
3634 if (ParsePreprocessingDirective (true))
3637 bool directive_expected = false;
3638 while ((c = get_char ()) != -1) {
3640 directive_expected = true;
3641 } else if (!directive_expected) {
3642 // TODO: Implement comment support for disabled code and uncomment this code
3644 // Eror_WrongPreprocessorLocation ();
3645 // return Token.ERROR;
3650 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3654 if (ParsePreprocessingDirective (false))
3657 directive_expected = false;
3661 tokens_seen = false;
3668 return consume_string (false);
3671 return TokenizeBackslash ();
3677 return consume_string (true);
3680 if (is_identifier_start_character (c)){
3681 return consume_identifier (c, true);
3684 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3687 case EvalStatementParserCharacter:
3688 return Token.EVAL_STATEMENT_PARSER;
3689 case EvalCompilationUnitParserCharacter:
3690 return Token.EVAL_COMPILATION_UNIT_PARSER;
3691 case EvalUsingDeclarationsParserCharacter:
3692 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3693 case DocumentationXref:
3694 return Token.DOC_SEE;
3697 if (is_identifier_start_character (c)) {
3699 return consume_identifier (c);
3702 if (char.IsWhiteSpace ((char) c))
3705 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3710 return Token.COMPLETE_COMPLETION;
3713 return Token.GENERATE_COMPLETION;
3720 int TokenizeBackslash ()
3723 int read_start = reader.Position;
3725 Location start_location = Location;
3726 int c = get_char ();
3729 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3730 Report.Error (1011, start_location, "Empty character literal");
3731 return Token.LITERAL;
3734 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3735 Report.Error (1010, start_location, "Newline in constant");
3740 c = escape (c, out d);
3744 throw new NotImplementedException ();
3746 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3751 Report.Error (1012, start_location, "Too many characters in character literal");
3753 // Try to recover, read until newline or next "'"
3754 while ((c = get_char ()) != -1) {
3755 if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3761 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3764 return Token.LITERAL;
3767 int TokenizeLessThan ()
3771 // Save current position and parse next token.
3773 int generic_dimension = 0;
3774 if (parse_less_than (ref generic_dimension)) {
3775 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3776 d = Token.OP_GENERICS_LT_DECL;
3778 if (generic_dimension > 0) {
3779 val = generic_dimension;
3781 return Token.GENERIC_DIMENSION;
3784 d = Token.OP_GENERICS_LT;
3791 parsing_generic_less_than = 0;
3800 return Token.OP_SHIFT_LEFT_ASSIGN;
3802 return Token.OP_SHIFT_LEFT;
3813 // Handles one line xml comment
3815 private void handle_one_line_xml_comment ()
3818 while ((c = peek_char ()) == ' ')
3819 get_char (); // skip heading whitespaces.
3820 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3821 xml_comment_buffer.Append ((char) get_char ());
3823 if (c == '\r' || c == '\n')
3824 xml_comment_buffer.Append (Environment.NewLine);
3828 // Remove heading "*" in Javadoc-like xml documentation.
3830 private void update_formatted_doc_comment (int current_comment_start)
3832 int length = xml_comment_buffer.Length - current_comment_start;
3833 string [] lines = xml_comment_buffer.ToString (
3834 current_comment_start,
3835 length).Replace ("\r", "").Split ('\n');
3837 // The first line starts with /**, thus it is not target
3838 // for the format check.
3839 for (int i = 1; i < lines.Length; i++) {
3840 string s = lines [i];
3841 int idx = s.IndexOf ('*');
3844 if (i < lines.Length - 1)
3848 head = s.Substring (0, idx);
3849 foreach (char c in head)
3852 lines [i] = s.Substring (idx + 1);
3854 xml_comment_buffer.Remove (current_comment_start, length);
3855 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3859 // Checks if there was incorrect doc comments and raise
3862 public void check_incorrect_doc_comment ()
3864 if (xml_comment_buffer.Length > 0)
3865 WarningMisplacedComment (Location);
3869 // Consumes the saved xml comment lines (if any)
3870 // as for current target member or type.
3872 public string consume_doc_comment ()
3874 if (xml_comment_buffer.Length > 0) {
3875 string ret = xml_comment_buffer.ToString ();
3876 reset_doc_comment ();
3882 void reset_doc_comment ()
3884 xml_comment_buffer.Length = 0;
3887 public void cleanup ()
3889 if (ifstack != null && ifstack.Count >= 1) {
3890 int state = ifstack.Pop ();
3891 if ((state & REGION) != 0)
3892 Report.Error (1038, Location, "#endregion directive expected");
3894 Report.Error (1027, Location, "Expected `#endif' directive");
3900 // Indicates whether it accepts XML documentation or not.
3902 public enum XmlCommentState {
3903 // comment is allowed in this state.
3905 // comment is not allowed in this state.
3907 // once comments appeared when it is NotAllowed, then the
3908 // state is changed to it, until the state is changed to