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 handle_typeof = false;
206 bool lambda_arguments_parsing;
207 List<Location> escaped_identifiers;
208 int parsing_generic_less_than;
209 readonly bool doc_processing;
210 readonly LocatedTokenBuffer ltb;
213 // Used mainly for parser optimizations. Some expressions for instance
214 // can appear only in block (including initializer, base initializer)
217 public int parsing_block;
218 internal bool query_parsing;
221 // When parsing type only, useful for ambiguous nullable types
223 public int parsing_type;
226 // Set when parsing generic declaration (type or method header)
228 public bool parsing_generic_declaration;
229 public bool parsing_generic_declaration_doc;
232 // The value indicates that we have not reach any declaration or
235 public int parsing_declaration;
237 public bool parsing_attribute_section;
239 public bool parsing_modifiers;
242 // The special characters to inject on streams to run the unit parser
243 // in the special expression mode. Using private characters from
244 // Plane Sixteen (U+100000 to U+10FFFD)
246 // This character is only tested just before the tokenizer is about to report
247 // an error; So on the regular operation mode, this addition will have no
248 // impact on the tokenizer's performance.
251 public const int EvalStatementParserCharacter = 0x100000;
252 public const int EvalCompilationUnitParserCharacter = 0x100001;
253 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
254 public const int DocumentationXref = 0x100003;
256 const int UnicodeLS = 0x2028;
257 const int UnicodePS = 0x2029;
260 // XML documentation buffer. The save point is used to divide
261 // comments on types and comments on members.
263 StringBuilder xml_comment_buffer;
266 // See comment on XmlCommentState enumeration.
268 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
271 // Whether tokens have been seen on this line
273 bool tokens_seen = false;
276 // Set to true once the GENERATE_COMPLETION token has bee
277 // returned. This helps produce one GENERATE_COMPLETION,
278 // as many COMPLETE_COMPLETION as necessary to complete the
279 // AST tree and one final EOF.
284 // Whether a token has been seen on the file
285 // This is needed because `define' is not allowed to be used
286 // after a token has been seen.
293 static readonly KeywordEntry<int>[][] keywords;
294 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
295 static readonly HashSet<string> keyword_strings;
296 static readonly NumberStyles styles;
297 static readonly NumberFormatInfo csharp_format_info;
300 static readonly char[] pragma_warning = "warning".ToCharArray ();
301 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
302 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
303 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
304 static readonly char[] line_hidden = "hidden".ToCharArray ();
305 static readonly char[] line_default = "default".ToCharArray ();
307 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
309 public bool PropertyParsing {
310 get { return handle_get_set; }
311 set { handle_get_set = value; }
314 public bool EventParsing {
315 get { return handle_remove_add; }
316 set { handle_remove_add = value; }
319 public bool ConstraintsParsing {
320 get { return handle_where; }
321 set { handle_where = value; }
324 public bool TypeOfParsing {
325 get { return handle_typeof; }
326 set { handle_typeof = value; }
329 public XmlCommentState doc_state {
330 get { return xml_doc_state; }
332 if (value == XmlCommentState.Allowed) {
333 check_incorrect_doc_comment ();
334 reset_doc_comment ();
336 xml_doc_state = value;
341 // This is used to trigger completion generation on the parser
342 public bool CompleteOnEOF;
344 void AddEscapedIdentifier (Location loc)
346 if (escaped_identifiers == null)
347 escaped_identifiers = new List<Location> ();
349 escaped_identifiers.Add (loc);
352 public bool IsEscapedIdentifier (ATypeNameExpression name)
354 return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
358 // Values for the associated token returned
360 internal int putback_char; // Used by repl only
366 const int TAKING = 1;
367 const int ELSE_SEEN = 4;
368 const int PARENT_TAKING = 8;
369 const int REGION = 16;
372 // pre-processor if stack state:
376 public const int MaxIdentifierLength = 512;
377 public const int MaxNumberLength = 512;
379 readonly char[] id_builder;
380 readonly Dictionary<char[], string>[] identifiers;
381 readonly char[] number_builder;
384 char[] value_builder = new char[64];
393 // This is used when the tokenizer needs to save
394 // the current position as it needs to do some parsing
395 // on its own to deamiguate a token in behalf of the
398 Stack<Position> position_stack = new Stack<Position> (2);
405 public Location hidden;
406 public int putback_char;
407 public int previous_col;
408 public Stack<int> ifstack;
409 public int parsing_generic_less_than;
410 public int current_token;
413 public Position (Tokenizer t)
415 position = t.reader.Position;
417 ref_line = t.ref_line;
419 hidden = t.hidden_block_start;
420 putback_char = t.putback_char;
421 previous_col = t.previous_col;
422 if (t.ifstack != null && t.ifstack.Count != 0) {
423 // There is no simple way to clone Stack<T> all
424 // methods reverse the order
425 var clone = t.ifstack.ToArray ();
426 Array.Reverse (clone);
427 ifstack = new Stack<int> (clone);
429 parsing_generic_less_than = t.parsing_generic_less_than;
430 current_token = t.current_token;
435 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session, Report report)
437 this.source_file = file;
438 this.context = file.Compiler;
439 this.current_source = file.SourceFile;
440 this.identifiers = session.Identifiers;
441 this.id_builder = session.IDBuilder;
442 this.number_builder = session.NumberBuilder;
443 this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
444 this.Report = report;
450 xml_comment_buffer = new StringBuilder ();
451 doc_processing = context.Settings.DocumentationFile != null;
453 tab_size = context.Settings.TabSize;
456 public void PushPosition ()
458 position_stack.Push (new Position (this));
461 public void PopPosition ()
463 Position p = position_stack.Pop ();
465 reader.Position = p.position;
466 ref_line = p.ref_line;
469 hidden_block_start = p.hidden;
470 putback_char = p.putback_char;
471 previous_col = p.previous_col;
473 parsing_generic_less_than = p.parsing_generic_less_than;
474 current_token = p.current_token;
478 // Do not reset the position, ignore it.
479 public void DiscardPosition ()
481 position_stack.Pop ();
484 static void AddKeyword (string kw, int token)
486 keyword_strings.Add (kw);
488 AddKeyword (keywords, kw, token);
491 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
493 AddKeyword (keywords_preprocessor, kw, directive);
496 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
498 int length = kw.Length;
499 if (keywords[length] == null) {
500 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
503 int char_index = kw[0] - '_';
504 var kwe = keywords[length][char_index];
506 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
510 while (kwe.Next != null) {
514 kwe.Next = new KeywordEntry<T> (kw, token);
522 keyword_strings = new HashSet<string> ();
524 // 11 is the length of the longest keyword for now
525 keywords = new KeywordEntry<int>[11][];
527 AddKeyword ("__arglist", Token.ARGLIST);
528 AddKeyword ("__makeref", Token.MAKEREF);
529 AddKeyword ("__reftype", Token.REFTYPE);
530 AddKeyword ("__refvalue", Token.REFVALUE);
531 AddKeyword ("abstract", Token.ABSTRACT);
532 AddKeyword ("as", Token.AS);
533 AddKeyword ("add", Token.ADD);
534 AddKeyword ("base", Token.BASE);
535 AddKeyword ("bool", Token.BOOL);
536 AddKeyword ("break", Token.BREAK);
537 AddKeyword ("byte", Token.BYTE);
538 AddKeyword ("case", Token.CASE);
539 AddKeyword ("catch", Token.CATCH);
540 AddKeyword ("char", Token.CHAR);
541 AddKeyword ("checked", Token.CHECKED);
542 AddKeyword ("class", Token.CLASS);
543 AddKeyword ("const", Token.CONST);
544 AddKeyword ("continue", Token.CONTINUE);
545 AddKeyword ("decimal", Token.DECIMAL);
546 AddKeyword ("default", Token.DEFAULT);
547 AddKeyword ("delegate", Token.DELEGATE);
548 AddKeyword ("do", Token.DO);
549 AddKeyword ("double", Token.DOUBLE);
550 AddKeyword ("else", Token.ELSE);
551 AddKeyword ("enum", Token.ENUM);
552 AddKeyword ("event", Token.EVENT);
553 AddKeyword ("explicit", Token.EXPLICIT);
554 AddKeyword ("extern", Token.EXTERN);
555 AddKeyword ("false", Token.FALSE);
556 AddKeyword ("finally", Token.FINALLY);
557 AddKeyword ("fixed", Token.FIXED);
558 AddKeyword ("float", Token.FLOAT);
559 AddKeyword ("for", Token.FOR);
560 AddKeyword ("foreach", Token.FOREACH);
561 AddKeyword ("goto", Token.GOTO);
562 AddKeyword ("get", Token.GET);
563 AddKeyword ("if", Token.IF);
564 AddKeyword ("implicit", Token.IMPLICIT);
565 AddKeyword ("in", Token.IN);
566 AddKeyword ("int", Token.INT);
567 AddKeyword ("interface", Token.INTERFACE);
568 AddKeyword ("internal", Token.INTERNAL);
569 AddKeyword ("is", Token.IS);
570 AddKeyword ("lock", Token.LOCK);
571 AddKeyword ("long", Token.LONG);
572 AddKeyword ("namespace", Token.NAMESPACE);
573 AddKeyword ("new", Token.NEW);
574 AddKeyword ("null", Token.NULL);
575 AddKeyword ("object", Token.OBJECT);
576 AddKeyword ("operator", Token.OPERATOR);
577 AddKeyword ("out", Token.OUT);
578 AddKeyword ("override", Token.OVERRIDE);
579 AddKeyword ("params", Token.PARAMS);
580 AddKeyword ("private", Token.PRIVATE);
581 AddKeyword ("protected", Token.PROTECTED);
582 AddKeyword ("public", Token.PUBLIC);
583 AddKeyword ("readonly", Token.READONLY);
584 AddKeyword ("ref", Token.REF);
585 AddKeyword ("remove", Token.REMOVE);
586 AddKeyword ("return", Token.RETURN);
587 AddKeyword ("sbyte", Token.SBYTE);
588 AddKeyword ("sealed", Token.SEALED);
589 AddKeyword ("set", Token.SET);
590 AddKeyword ("short", Token.SHORT);
591 AddKeyword ("sizeof", Token.SIZEOF);
592 AddKeyword ("stackalloc", Token.STACKALLOC);
593 AddKeyword ("static", Token.STATIC);
594 AddKeyword ("string", Token.STRING);
595 AddKeyword ("struct", Token.STRUCT);
596 AddKeyword ("switch", Token.SWITCH);
597 AddKeyword ("this", Token.THIS);
598 AddKeyword ("throw", Token.THROW);
599 AddKeyword ("true", Token.TRUE);
600 AddKeyword ("try", Token.TRY);
601 AddKeyword ("typeof", Token.TYPEOF);
602 AddKeyword ("uint", Token.UINT);
603 AddKeyword ("ulong", Token.ULONG);
604 AddKeyword ("unchecked", Token.UNCHECKED);
605 AddKeyword ("unsafe", Token.UNSAFE);
606 AddKeyword ("ushort", Token.USHORT);
607 AddKeyword ("using", Token.USING);
608 AddKeyword ("virtual", Token.VIRTUAL);
609 AddKeyword ("void", Token.VOID);
610 AddKeyword ("volatile", Token.VOLATILE);
611 AddKeyword ("while", Token.WHILE);
612 AddKeyword ("partial", Token.PARTIAL);
613 AddKeyword ("where", Token.WHERE);
616 AddKeyword ("from", Token.FROM);
617 AddKeyword ("join", Token.JOIN);
618 AddKeyword ("on", Token.ON);
619 AddKeyword ("equals", Token.EQUALS);
620 AddKeyword ("select", Token.SELECT);
621 AddKeyword ("group", Token.GROUP);
622 AddKeyword ("by", Token.BY);
623 AddKeyword ("let", Token.LET);
624 AddKeyword ("orderby", Token.ORDERBY);
625 AddKeyword ("ascending", Token.ASCENDING);
626 AddKeyword ("descending", Token.DESCENDING);
627 AddKeyword ("into", Token.INTO);
629 // Contextual async keywords
630 AddKeyword ("async", Token.ASYNC);
631 AddKeyword ("await", Token.AWAIT);
633 keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
635 AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
636 AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
637 AddPreprocessorKeyword ("if", PreprocessorDirective.If);
638 AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
639 AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
640 AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
641 AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
642 AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
643 AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
644 AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
645 AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
646 AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
648 csharp_format_info = NumberFormatInfo.InvariantInfo;
649 styles = NumberStyles.Float;
652 int GetKeyword (char[] id, int id_len)
655 // Keywords are stored in an array of arrays grouped by their
656 // length and then by the first character
658 if (id_len >= keywords.Length || keywords [id_len] == null)
661 int first_index = id [0] - '_';
662 if (first_index > 'z' - '_')
665 var kwe = keywords [id_len] [first_index];
672 for (int i = 1; i < id_len; ++i) {
673 if (id [i] != kwe.Value [i]) {
679 } while (res == 0 && kwe != null);
693 if (!handle_remove_add)
697 if (parsing_declaration == 0)
698 res = Token.EXTERN_ALIAS;
701 if (peek_token () == Token.COLON) {
703 res = Token.DEFAULT_COLON;
707 if (!(handle_where && current_token != Token.COLON) && !query_parsing)
712 // A query expression is any expression that starts with `from identifier'
713 // followed by any token except ; , =
715 if (!query_parsing) {
716 if (lambda_arguments_parsing || parsing_block == 0) {
722 // HACK: to disable generics micro-parser, because PushPosition does not
723 // store identifiers array
724 parsing_generic_less_than = 1;
726 case Token.IDENTIFIER:
738 next_token = xtoken ();
739 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
742 res = Token.FROM_FIRST;
743 query_parsing = true;
744 if (context.Settings.Version <= LanguageVersion.ISO_2)
745 Report.FeatureIsNotAvailable (context, Location, "query expressions");
748 Expression.Error_VoidInvalidInTheContext (Location, Report);
752 // HACK: A token is not a keyword so we need to restore identifiers buffer
753 // which has been overwritten before we grabbed the identifier
754 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
768 case Token.ASCENDING:
769 case Token.DESCENDING:
776 case Token.NAMESPACE:
777 // TODO: some explanation needed
778 check_incorrect_doc_comment ();
779 parsing_modifiers = false;
783 if (parsing_block > 0) {
788 // Save current position and parse next token.
791 next_token = token ();
792 bool ok = (next_token == Token.CLASS) ||
793 (next_token == Token.STRUCT) ||
794 (next_token == Token.INTERFACE) ||
795 (next_token == Token.VOID);
800 if (next_token == Token.VOID) {
801 if (context.Settings.Version <= LanguageVersion.ISO_2)
802 Report.FeatureIsNotAvailable (context, Location, "partial methods");
803 } else if (context.Settings.Version == LanguageVersion.ISO_1)
804 Report.FeatureIsNotAvailable (context, Location, "partial types");
809 if (next_token < Token.LAST_KEYWORD) {
810 Report.Error (267, Location,
811 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
815 // HACK: A token is not a keyword so we need to restore identifiers buffer
816 // which has been overwritten before we grabbed the identifier
828 if (parsing_modifiers) {
830 // Skip attributes section or constructor called async
832 if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
837 } else if (parsing_block > 0) {
838 switch (peek_token ()) {
840 case Token.OPEN_PARENS_LAMBDA:
843 case Token.IDENTIFIER:
846 if (xtoken () != Token.ARROW) {
854 // peek_token could overwrite id_buffer
855 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
863 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
864 Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
870 if (parsing_block == 0)
880 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
883 // Keywords are stored in an array of arrays grouped by their
884 // length and then by the first character
886 if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
887 return PreprocessorDirective.Invalid;
889 int first_index = id[0] - '_';
890 if (first_index > 'z' - '_')
891 return PreprocessorDirective.Invalid;
893 var kwe = keywords_preprocessor[id_len][first_index];
895 return PreprocessorDirective.Invalid;
897 PreprocessorDirective res = PreprocessorDirective.Invalid;
900 for (int i = 1; i < id_len; ++i) {
901 if (id[i] != kwe.Value[i]) {
907 } while (res == PreprocessorDirective.Invalid && kwe != null);
912 public Location Location {
914 return new Location (current_source, ref_line, col);
918 static bool is_identifier_start_character (int c)
920 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
923 static bool is_identifier_part_character (char c)
925 if (c >= 'a' && c <= 'z')
928 if (c >= 'A' && c <= 'Z')
931 if (c == '_' || (c >= '0' && c <= '9'))
937 return is_identifier_part_character_slow_part (c);
940 static bool is_identifier_part_character_slow_part (char c)
942 if (Char.IsLetter (c))
945 switch (Char.GetUnicodeCategory (c)) {
946 case UnicodeCategory.ConnectorPunctuation:
948 // combining-character: A Unicode character of classes Mn or Mc
949 case UnicodeCategory.NonSpacingMark:
950 case UnicodeCategory.SpacingCombiningMark:
952 // decimal-digit-character: A Unicode character of the class Nd
953 case UnicodeCategory.DecimalDigitNumber:
960 public static bool IsKeyword (string s)
962 return keyword_strings.Contains (s);
966 // Open parens micro parser. Detects both lambda and cast ambiguity.
968 int TokenizeOpenParens ()
973 int bracket_level = 0;
974 bool is_type = false;
975 bool can_be_type = false;
978 ptoken = current_token;
981 switch (current_token) {
982 case Token.CLOSE_PARENS:
986 // Expression inside parens is lambda, (int i) =>
988 if (current_token == Token.ARROW)
989 return Token.OPEN_PARENS_LAMBDA;
992 // Expression inside parens is single type, (int[])
995 if (current_token == Token.SEMICOLON)
996 return Token.OPEN_PARENS;
998 return Token.OPEN_PARENS_CAST;
1002 // Expression is possible cast, look at next token, (T)null
1005 switch (current_token) {
1006 case Token.OPEN_PARENS:
1009 case Token.IDENTIFIER:
1013 case Token.DELEGATE:
1023 case Token.UNCHECKED:
1029 // These can be part of a member access
1043 return Token.OPEN_PARENS_CAST;
1046 return Token.OPEN_PARENS;
1049 case Token.DOUBLE_COLON:
1050 if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1055 case Token.IDENTIFIER:
1059 if (bracket_level == 0) {
1065 case Token.OP_GENERICS_LT:
1067 case Token.DOUBLE_COLON:
1069 if (bracket_level == 0)
1073 can_be_type = is_type = false;
1093 if (bracket_level == 0)
1098 if (bracket_level == 0) {
1099 bracket_level = 100;
1100 can_be_type = is_type = false;
1104 case Token.OP_GENERICS_LT:
1105 case Token.OPEN_BRACKET:
1106 if (bracket_level++ == 0)
1110 case Token.OP_GENERICS_GT:
1111 case Token.CLOSE_BRACKET:
1115 case Token.INTERR_NULLABLE:
1117 if (bracket_level == 0)
1123 can_be_type = is_type = false;
1127 return Token.OPEN_PARENS;
1132 public static bool IsValidIdentifier (string s)
1134 if (s == null || s.Length == 0)
1137 if (!is_identifier_start_character (s [0]))
1140 for (int i = 1; i < s.Length; i ++)
1141 if (! is_identifier_part_character (s [i]))
1147 bool parse_less_than ()
1150 int the_token = token ();
1151 if (the_token == Token.OPEN_BRACKET) {
1153 the_token = token ();
1154 if (the_token == Token.EOF)
1157 if (the_token == Token.CLOSE_BRACKET)
1160 the_token = token ();
1161 } else if (the_token == Token.IN || the_token == Token.OUT) {
1162 the_token = token ();
1164 switch (the_token) {
1165 case Token.IDENTIFIER:
1183 case Token.OP_GENERICS_GT:
1192 the_token = token ();
1194 if (the_token == Token.OP_GENERICS_GT)
1196 else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1198 else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1200 else if (the_token == Token.OP_GENERICS_LT) {
1201 if (!parse_less_than ())
1204 } else if (the_token == Token.OPEN_BRACKET) {
1206 the_token = token ();
1207 if (the_token == Token.CLOSE_BRACKET)
1209 else if (the_token == Token.COMMA)
1210 goto rank_specifiers;
1217 bool parse_generic_dimension (out int dimension)
1222 int the_token = token ();
1223 if (the_token == Token.OP_GENERICS_GT)
1225 else if (the_token == Token.COMMA) {
1233 public int peek_token ()
1238 the_token = token ();
1245 // Tonizes `?' using custom disambiguous rules to return one
1246 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1248 // Tricky expression looks like:
1250 // Foo ? a = x ? b : c;
1252 int TokenizePossibleNullableType ()
1254 if (parsing_block == 0 || parsing_type > 0)
1255 return Token.INTERR_NULLABLE;
1257 int d = peek_char ();
1260 return Token.OP_COALESCING;
1264 return Token.INTERR_OPERATOR;
1268 if (d == ',' || d == ';' || d == '>')
1269 return Token.INTERR_NULLABLE;
1270 if (d == '*' || (d >= '0' && d <= '9'))
1271 return Token.INTERR;
1275 current_token = Token.NONE;
1279 switch (xtoken ()) {
1281 case Token.OPEN_BRACKET_EXPR:
1282 next_token = Token.INTERR_OPERATOR;
1290 next_token = Token.INTERR;
1293 case Token.SEMICOLON:
1295 case Token.CLOSE_PARENS:
1296 case Token.OPEN_BRACKET:
1297 case Token.OP_GENERICS_GT:
1299 case Token.OP_COALESCING:
1301 next_token = Token.INTERR_NULLABLE;
1304 case Token.OPEN_PARENS:
1305 case Token.OPEN_PARENS_CAST:
1306 case Token.OPEN_PARENS_LAMBDA:
1316 if (next_token == -1) {
1317 switch (xtoken ()) {
1319 case Token.SEMICOLON:
1320 case Token.OPEN_BRACE:
1321 case Token.CLOSE_PARENS:
1323 next_token = Token.INTERR_NULLABLE;
1327 next_token = Token.INTERR;
1330 case Token.OPEN_PARENS:
1331 case Token.OPEN_PARENS_CAST:
1332 case Token.OPEN_PARENS_LAMBDA:
1342 // All shorcuts failed, do it hard way
1344 while ((ntoken = xtoken ()) != Token.EOF) {
1346 case Token.OPEN_BRACE:
1349 case Token.OPEN_PARENS:
1350 case Token.OPEN_PARENS_CAST:
1351 case Token.OPEN_PARENS_LAMBDA:
1354 case Token.CLOSE_BRACE:
1357 case Token.CLOSE_PARENS:
1364 return Token.INTERR_NULLABLE;
1370 if (ntoken == Token.SEMICOLON)
1376 if (ntoken == Token.COLON) {
1377 if (++colons == interrs)
1382 if (ntoken == Token.INTERR) {
1388 next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1397 bool decimal_digits (int c)
1400 bool seen_digits = false;
1403 if (number_pos == MaxNumberLength)
1404 Error_NumericConstantTooLong ();
1405 number_builder [number_pos++] = (char) c;
1409 // We use peek_char2, because decimal_digits needs to do a
1410 // 2-character look-ahead (5.ToString for example).
1412 while ((d = peek_char2 ()) != -1){
1413 if (d >= '0' && d <= '9'){
1414 if (number_pos == MaxNumberLength)
1415 Error_NumericConstantTooLong ();
1416 number_builder [number_pos++] = (char) d;
1426 static bool is_hex (int e)
1428 return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1431 static TypeCode real_type_suffix (int c)
1435 return TypeCode.Single;
1437 return TypeCode.Double;
1439 return TypeCode.Decimal;
1441 return TypeCode.Empty;
1445 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1447 bool is_unsigned = false;
1448 bool is_long = false;
1451 bool scanning = true;
1464 // if we have not seen anything in between
1465 // report this error
1467 Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1487 if (is_long && is_unsigned){
1488 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1492 // uint if possible, or ulong else.
1494 if ((ul & 0xffffffff00000000) == 0)
1495 return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1497 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1498 } else if (is_long){
1499 // long if possible, ulong otherwise
1500 if ((ul & 0x8000000000000000) != 0)
1501 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1503 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1505 // int, uint, long or ulong in that order
1506 if ((ul & 0xffffffff00000000) == 0){
1507 uint ui = (uint) ul;
1509 if ((ui & 0x80000000) != 0)
1510 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1512 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1514 if ((ul & 0x8000000000000000) != 0)
1515 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1517 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1523 // given `c' as the next char in the input decide whether
1524 // we need to convert to a special type, and then choose
1525 // the best representation for the integer
1527 ILiteralConstant adjust_int (int c, Location loc)
1530 if (number_pos > 9){
1531 ulong ul = (uint) (number_builder [0] - '0');
1533 for (int i = 1; i < number_pos; i++){
1534 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1537 return integer_type_suffix (ul, c, loc);
1539 uint ui = (uint) (number_builder [0] - '0');
1541 for (int i = 1; i < number_pos; i++){
1542 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1545 return integer_type_suffix (ui, c, loc);
1547 } catch (OverflowException) {
1548 Error_NumericConstantTooLong ();
1549 return new IntLiteral (context.BuiltinTypes, 0, loc);
1551 catch (FormatException) {
1552 Report.Error (1013, Location, "Invalid number");
1553 return new IntLiteral (context.BuiltinTypes, 0, loc);
1557 ILiteralConstant adjust_real (TypeCode t, Location loc)
1559 string s = new string (number_builder, 0, number_pos);
1560 const string error_details = "Floating-point constant is outside the range of type `{0}'";
1563 case TypeCode.Decimal:
1565 return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1566 } catch (OverflowException) {
1567 Report.Error (594, Location, error_details, "decimal");
1568 return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1570 case TypeCode.Single:
1572 return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1573 } catch (OverflowException) {
1574 Report.Error (594, Location, error_details, "float");
1575 return new FloatLiteral (context.BuiltinTypes, 0, loc);
1579 return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1580 } catch (OverflowException) {
1581 Report.Error (594, loc, error_details, "double");
1582 return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1587 ILiteralConstant handle_hex (Location loc)
1593 while ((d = peek_char ()) != -1){
1595 number_builder [number_pos++] = (char) d;
1601 string s = new String (number_builder, 0, number_pos);
1604 if (number_pos <= 8)
1605 ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1607 ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1609 return integer_type_suffix (ul, peek_char (), loc);
1610 } catch (OverflowException){
1611 Error_NumericConstantTooLong ();
1612 return new IntLiteral (context.BuiltinTypes, 0, loc);
1614 catch (FormatException) {
1615 Report.Error (1013, Location, "Invalid number");
1616 return new IntLiteral (context.BuiltinTypes, 0, loc);
1621 // Invoked if we know we have .digits or digits
1623 int is_number (int c, bool dotLead)
1625 ILiteralConstant res;
1628 int read_start = reader.Position - 1;
1631 // Caller did peek_char
1641 int peek = peek_char ();
1643 if (peek == 'x' || peek == 'X') {
1644 val = res = handle_hex (loc);
1646 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1649 return Token.LITERAL;
1657 // We need to handle the case of
1658 // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1660 bool is_real = false;
1665 if (decimal_digits ('.')){
1671 val = res = adjust_int (-1, loc);
1674 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1676 return Token.LITERAL;
1680 if (c == 'e' || c == 'E'){
1683 if (number_pos == MaxNumberLength)
1684 Error_NumericConstantTooLong ();
1685 number_builder [number_pos++] = (char) c;
1689 if (number_pos == MaxNumberLength)
1690 Error_NumericConstantTooLong ();
1691 number_builder [number_pos++] = '+';
1693 } else if (c == '-') {
1694 if (number_pos == MaxNumberLength)
1695 Error_NumericConstantTooLong ();
1696 number_builder [number_pos++] = '-';
1699 if (number_pos == MaxNumberLength)
1700 Error_NumericConstantTooLong ();
1701 number_builder [number_pos++] = '+';
1708 var type = real_type_suffix (c);
1709 if (type == TypeCode.Empty && !is_real) {
1710 res = adjust_int (c, loc);
1714 if (type != TypeCode.Empty) {
1718 res = adjust_real (type, loc);
1724 var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1725 if (chars[chars.Length - 1] == '\r')
1726 Array.Resize (ref chars, chars.Length - 1);
1727 res.ParsedValue = chars;
1730 return Token.LITERAL;
1734 // Accepts exactly count (4 or 8) hex, no more no less
1736 int getHex (int count, out int surrogate, out bool error)
1741 int top = count != -1 ? count : 4;
1746 for (i = 0; i < top; i++){
1749 if (c >= '0' && c <= '9')
1750 c = (int) c - (int) '0';
1751 else if (c >= 'A' && c <= 'F')
1752 c = (int) c - (int) 'A' + 10;
1753 else if (c >= 'a' && c <= 'f')
1754 c = (int) c - (int) 'a' + 10;
1760 total = (total * 16) + c;
1762 int p = peek_char ();
1765 if (!is_hex ((char)p))
1771 if (total > 0x0010FFFF) {
1776 if (total >= 0x00010000) {
1777 surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);
1778 total = ((total - 0x00010000) / 0x0400 + 0xD800);
1785 int escape (int c, out int surrogate)
1821 v = getHex (-1, out surrogate, out error);
1827 return EscapeUnicode (d, out surrogate);
1830 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1839 int EscapeUnicode (int ch, out int surrogate)
1843 ch = getHex (8, out surrogate, out error);
1845 ch = getHex (4, out surrogate, out error);
1849 Report.Error (1009, Location, "Unrecognized escape sequence");
1857 if (putback_char != -1) {
1866 if (peek_char () == '\n') {
1872 } else if (x == '\n') {
1877 } else if (x >= UnicodeLS && x <= UnicodePS) {
1886 void advance_line ()
1896 if (putback_char == -1)
1897 putback_char = reader.Read ();
1898 return putback_char;
1903 if (putback_char != -1)
1904 return putback_char;
1905 return reader.Peek ();
1908 public void putback (int c)
1910 if (putback_char != -1) {
1911 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
1914 if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
1915 // It won't happen though.
1925 public bool advance ()
1927 return peek_char () != -1 || CompleteOnEOF;
1930 public Object Value {
1936 public Object value ()
1943 current_token = xtoken ();
1944 return current_token;
1947 int TokenizePreprocessorIdentifier (out int c)
1949 // skip over white space
1952 } while (c == ' ' || c == '\t');
1956 while (c != -1 && c >= 'a' && c <= 'z') {
1957 id_builder[pos++] = (char) c;
1960 int peek = peek_char ();
1961 if (peek == 'U' || peek == 'u') {
1963 c = EscapeUnicode (c, out surrogate);
1964 if (surrogate != 0) {
1965 if (is_identifier_part_character ((char) c)) {
1966 id_builder[pos++] = (char) c;
1977 PreprocessorDirective get_cmd_arg (out string arg)
1981 tokens_seen = false;
1984 var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1986 if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1989 // skip over white space
1990 while (c == ' ' || c == '\t')
1993 int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1996 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
1997 if (c == '\\' && has_identifier_argument >= 0) {
1998 if (has_identifier_argument != 0) {
1999 has_identifier_argument = 1;
2001 int peek = peek_char ();
2002 if (peek == 'U' || peek == 'u') {
2004 c = EscapeUnicode (c, out surrogate);
2005 if (surrogate != 0) {
2006 if (is_identifier_part_character ((char) c)) {
2007 if (pos == value_builder.Length)
2008 Array.Resize (ref value_builder, pos * 2);
2010 value_builder[pos++] = (char) c;
2016 has_identifier_argument = -1;
2018 } else if (c == '/' && peek_char () == '/') {
2020 // Eat single-line comments
2027 if (pos == value_builder.Length)
2028 Array.Resize (ref value_builder, pos * 2);
2030 value_builder[pos++] = (char) c;
2035 if (pos > MaxIdentifierLength)
2036 arg = new string (value_builder, 0, pos);
2038 arg = InternIdentifier (value_builder, pos);
2040 // Eat any trailing whitespaces
2041 arg = arg.Trim (simple_whitespaces);
2048 // Handles the #line directive
2050 bool PreProcessLine ()
2052 Location loc = Location;
2056 int length = TokenizePreprocessorIdentifier (out c);
2057 if (length == line_default.Length) {
2058 if (!IsTokenIdentifierEqual (line_default))
2061 current_source = source_file.SourceFile;
2062 if (!hidden_block_start.IsNull) {
2063 current_source.RegisterHiddenScope (hidden_block_start, loc);
2064 hidden_block_start = Location.Null;
2071 if (length == line_hidden.Length) {
2072 if (!IsTokenIdentifierEqual (line_hidden))
2075 if (hidden_block_start.IsNull)
2076 hidden_block_start = loc;
2081 if (length != 0 || c < '0' || c > '9') {
2083 // Eat any remaining characters to continue parsing on next line
2089 int new_line = TokenizeNumber (c);
2092 // Eat any remaining characters to continue parsing on next line
2095 return new_line != 0;
2100 // skip over white space
2103 } while (c == ' ' || c == '\t');
2104 } else if (c == '"') {
2108 if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2110 // Eat any remaining characters to continue parsing on next line
2114 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2118 string new_file_name = null;
2120 new_file_name = TokenizeFileName (ref c);
2122 // skip over white space
2123 while (c == ' ' || c == '\t') {
2128 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2130 } else if (c == '/') {
2131 ReadSingleLineComment ();
2134 // Eat any remaining characters to continue parsing on next line
2138 Error_EndLineExpected ();
2142 if (new_file_name != null) {
2143 current_source = context.LookupFile (source_file, new_file_name);
2144 source_file.AddIncludeFile (current_source);
2147 if (!hidden_block_start.IsNull) {
2148 current_source.RegisterHiddenScope (hidden_block_start, loc);
2149 hidden_block_start = Location.Null;
2152 ref_line = new_line;
2157 // Handles #define and #undef
2159 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2161 if (ident.Length == 0 || ident == "true" || ident == "false"){
2162 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2166 if (ident.IndexOfAny (simple_whitespaces) != -1){
2167 Error_EndLineExpected ();
2171 if (!is_identifier_start_character (ident [0]))
2172 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2174 foreach (char c in ident.Substring (1)){
2175 if (!is_identifier_part_character (c)){
2176 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2181 if (!caller_is_taking)
2188 if (context.Settings.IsConditionalSymbolDefined (ident))
2191 source_file.AddDefine (ident);
2196 source_file.AddUndefine (ident);
2200 byte read_hex (out bool error)
2203 int c = get_char ();
2205 if ((c >= '0') && (c <= '9'))
2206 total = (int) c - (int) '0';
2207 else if ((c >= 'A') && (c <= 'F'))
2208 total = (int) c - (int) 'A' + 10;
2209 else if ((c >= 'a') && (c <= 'f'))
2210 total = (int) c - (int) 'a' + 10;
2219 if ((c >= '0') && (c <= '9'))
2220 total += (int) c - (int) '0';
2221 else if ((c >= 'A') && (c <= 'F'))
2222 total += (int) c - (int) 'A' + 10;
2223 else if ((c >= 'a') && (c <= 'f'))
2224 total += (int) c - (int) 'a' + 10;
2231 return (byte) total;
2235 // Parses #pragma checksum
2237 bool ParsePragmaChecksum ()
2240 // The syntax is ` "foo.txt" "{guid}" "hash"'
2242 // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2244 int c = get_char ();
2249 string file_name = TokenizeFileName (ref c);
2251 // TODO: Any white-spaces count
2255 SourceFile file = context.LookupFile (source_file, file_name);
2257 if (get_char () != '"' || get_char () != '{')
2261 byte[] guid_bytes = new byte [16];
2264 for (; i < 4; i++) {
2265 guid_bytes [i] = read_hex (out error);
2270 if (get_char () != '-')
2273 for (; i < 10; i++) {
2274 guid_bytes [i] = read_hex (out error);
2278 guid_bytes [i++] = read_hex (out error);
2282 if (get_char () != '-')
2286 for (; i < 16; i++) {
2287 guid_bytes [i] = read_hex (out error);
2292 if (get_char () != '}' || get_char () != '"')
2295 // TODO: Any white-spaces count
2300 if (get_char () != '"')
2303 // Any length of checksum
2304 List<byte> checksum_bytes = new List<byte> (16);
2306 var checksum_location = Location;
2308 while (c != '"' && c != -1) {
2309 checksum_bytes.Add (read_hex (out error));
2317 ReadSingleLineComment ();
2318 } else if (get_char () != '"') {
2322 if (context.Settings.GenerateDebugInfo) {
2323 var chsum = checksum_bytes.ToArray ();
2325 if (file.HasChecksum) {
2326 if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2327 // TODO: Report.SymbolRelatedToPreviousError
2328 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2332 file.SetChecksum (guid_bytes, chsum);
2333 current_source.AutoGenerated = true;
2339 bool IsTokenIdentifierEqual (char[] identifier)
2341 for (int i = 0; i < identifier.Length; ++i) {
2342 if (identifier[i] != id_builder[i])
2349 int TokenizeNumber (int value)
2353 decimal_digits (value);
2354 uint ui = (uint) (number_builder[0] - '0');
2357 for (int i = 1; i < number_pos; i++) {
2358 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2362 } catch (OverflowException) {
2363 Error_NumericConstantTooLong ();
2368 string TokenizeFileName (ref int c)
2370 var string_builder = new StringBuilder ();
2371 while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2378 string_builder.Append ((char) c);
2381 if (string_builder.Length == 0) {
2382 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2386 return string_builder.ToString ();
2389 int TokenizePragmaNumber (ref int c)
2395 if (c >= '0' && c <= '9') {
2396 number = TokenizeNumber (c);
2400 // skip over white space
2401 while (c == ' ' || c == '\t')
2408 // skip over white space
2409 while (c == ' ' || c == '\t')
2414 ReadSingleLineComment ();
2416 Report.Warning (1692, 1, Location, "Invalid number");
2418 // Read everything till the end of the line or file
2426 void ReadToEndOfLine ()
2431 } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2434 void ReadSingleLineComment ()
2436 if (peek_char () != '/')
2437 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2439 // Read everything till the end of the line or file
2444 /// Handles #pragma directive
2446 void ParsePragmaDirective ()
2449 int length = TokenizePreprocessorIdentifier (out c);
2450 if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2451 length = TokenizePreprocessorIdentifier (out c);
2454 // #pragma warning disable
2455 // #pragma warning restore
2457 if (length == pragma_warning_disable.Length) {
2458 bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2459 if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2460 // skip over white space
2461 while (c == ' ' || c == '\t')
2466 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2468 ReadSingleLineComment ();
2471 // Disable/Restore all warnings
2474 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2476 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2480 // Disable/Restore a warning or group of warnings
2484 code = TokenizePragmaNumber (ref c);
2487 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2489 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2492 } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2499 Report.Warning (1634, 1, Location, "Expected disable or restore");
2501 // Eat any remaining characters on the line
2510 if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2511 if (c != ' ' || !ParsePragmaChecksum ()) {
2512 Report.Warning (1695, 1, Location,
2513 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2519 Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2522 bool eval_val (string s)
2529 return source_file.IsConditionalDefined (s);
2532 bool pp_primary (ref string s)
2541 s = s.Substring (1);
2542 bool val = pp_expr (ref s, false);
2543 if (s.Length > 0 && s [0] == ')'){
2544 s = s.Substring (1);
2547 Error_InvalidDirective ();
2551 if (is_identifier_start_character (c)){
2557 if (is_identifier_part_character (c)){
2561 bool v = eval_val (s.Substring (0, j));
2562 s = s.Substring (j);
2565 bool vv = eval_val (s);
2570 Error_InvalidDirective ();
2574 bool pp_unary (ref string s)
2581 if (len > 1 && s [1] == '='){
2582 Error_InvalidDirective ();
2585 s = s.Substring (1);
2586 return ! pp_primary (ref s);
2588 return pp_primary (ref s);
2590 Error_InvalidDirective ();
2595 bool pp_eq (ref string s)
2597 bool va = pp_unary (ref s);
2603 if (len > 2 && s [1] == '='){
2604 s = s.Substring (2);
2605 return va == pp_unary (ref s);
2607 Error_InvalidDirective ();
2610 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2611 s = s.Substring (2);
2613 return va != pp_unary (ref s);
2622 bool pp_and (ref string s)
2624 bool va = pp_eq (ref s);
2630 if (len > 2 && s [1] == '&'){
2631 s = s.Substring (2);
2632 return (va & pp_and (ref s));
2634 Error_InvalidDirective ();
2643 // Evaluates an expression for `#if' or `#elif'
2645 bool pp_expr (ref string s, bool isTerm)
2647 bool va = pp_and (ref s);
2654 if (len > 2 && s [1] == '|'){
2655 s = s.Substring (2);
2656 return va | pp_expr (ref s, isTerm);
2658 Error_InvalidDirective ();
2663 Error_EndLineExpected ();
2671 bool eval (string s)
2673 bool v = pp_expr (ref s, true);
2682 void Error_NumericConstantTooLong ()
2684 Report.Error (1021, Location, "Integral constant is too large");
2687 void Error_InvalidDirective ()
2689 Report.Error (1517, Location, "Invalid preprocessor directive");
2692 void Error_UnexpectedDirective (string extra)
2696 "Unexpected processor directive ({0})", extra);
2699 void Error_TokensSeen ()
2701 Report.Error (1032, Location,
2702 "Cannot define or undefine preprocessor symbols after first token in file");
2705 void Eror_WrongPreprocessorLocation ()
2707 Report.Error (1040, Location,
2708 "Preprocessor directives must appear as the first non-whitespace character on a line");
2711 void Error_EndLineExpected ()
2713 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2717 // Raises a warning when tokenizer found documentation comment
2718 // on unexpected place
2720 void WarningMisplacedComment (Location loc)
2722 if (doc_state != XmlCommentState.Error) {
2723 doc_state = XmlCommentState.Error;
2724 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2729 // if true, then the code continues processing the code
2730 // if false, the code stays in a loop until another directive is
2732 // When caller_is_taking is false we ignore all directives except the ones
2733 // which can help us to identify where the #if block ends
2734 bool ParsePreprocessingDirective (bool caller_is_taking)
2737 bool region_directive = false;
2739 var directive = get_cmd_arg (out arg);
2742 // The first group of pre-processing instructions is always processed
2744 switch (directive) {
2745 case PreprocessorDirective.Region:
2746 region_directive = true;
2748 goto case PreprocessorDirective.If;
2750 case PreprocessorDirective.Endregion:
2751 if (ifstack == null || ifstack.Count == 0){
2752 Error_UnexpectedDirective ("no #region for this #endregion");
2755 int pop = ifstack.Pop ();
2757 if ((pop & REGION) == 0)
2758 Report.Error (1027, Location, "Expected `#endif' directive");
2760 return caller_is_taking;
2762 case PreprocessorDirective.If:
2763 if (ifstack == null)
2764 ifstack = new Stack<int> (2);
2766 int flags = region_directive ? REGION : 0;
2767 if (ifstack.Count == 0){
2768 flags |= PARENT_TAKING;
2770 int state = ifstack.Peek ();
2771 if ((state & TAKING) != 0) {
2772 flags |= PARENT_TAKING;
2776 if (eval (arg) && caller_is_taking) {
2777 ifstack.Push (flags | TAKING);
2780 ifstack.Push (flags);
2783 case PreprocessorDirective.Endif:
2784 if (ifstack == null || ifstack.Count == 0){
2785 Error_UnexpectedDirective ("no #if for this #endif");
2788 pop = ifstack.Pop ();
2790 if ((pop & REGION) != 0)
2791 Report.Error (1038, Location, "#endregion directive expected");
2793 if (arg.Length != 0) {
2794 Error_EndLineExpected ();
2797 if (ifstack.Count == 0)
2800 int state = ifstack.Peek ();
2801 return (state & TAKING) != 0;
2804 case PreprocessorDirective.Elif:
2805 if (ifstack == null || ifstack.Count == 0){
2806 Error_UnexpectedDirective ("no #if for this #elif");
2809 int state = ifstack.Pop ();
2811 if ((state & REGION) != 0) {
2812 Report.Error (1038, Location, "#endregion directive expected");
2816 if ((state & ELSE_SEEN) != 0){
2817 Error_UnexpectedDirective ("#elif not valid after #else");
2821 if ((state & TAKING) != 0) {
2826 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2827 ifstack.Push (state | TAKING);
2831 ifstack.Push (state);
2835 case PreprocessorDirective.Else:
2836 if (ifstack == null || ifstack.Count == 0){
2837 Error_UnexpectedDirective ("no #if for this #else");
2840 int state = ifstack.Peek ();
2842 if ((state & REGION) != 0) {
2843 Report.Error (1038, Location, "#endregion directive expected");
2847 if ((state & ELSE_SEEN) != 0){
2848 Error_UnexpectedDirective ("#else within #else");
2854 if (arg.Length != 0) {
2855 Error_EndLineExpected ();
2860 if ((state & PARENT_TAKING) != 0) {
2861 ret = (state & TAKING) == 0;
2869 ifstack.Push (state | ELSE_SEEN);
2873 case PreprocessorDirective.Define:
2874 if (any_token_seen){
2875 if (caller_is_taking)
2876 Error_TokensSeen ();
2877 return caller_is_taking;
2879 PreProcessDefinition (true, arg, caller_is_taking);
2880 return caller_is_taking;
2882 case PreprocessorDirective.Undef:
2883 if (any_token_seen){
2884 if (caller_is_taking)
2885 Error_TokensSeen ();
2886 return caller_is_taking;
2888 PreProcessDefinition (false, arg, caller_is_taking);
2889 return caller_is_taking;
2891 case PreprocessorDirective.Invalid:
2892 Report.Error (1024, Location, "Wrong preprocessor directive");
2897 // These are only processed if we are in a `taking' block
2899 if (!caller_is_taking)
2903 case PreprocessorDirective.Error:
2904 Report.Error (1029, Location, "#error: '{0}'", arg);
2907 case PreprocessorDirective.Warning:
2908 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2911 case PreprocessorDirective.Pragma:
2912 if (context.Settings.Version == LanguageVersion.ISO_1) {
2913 Report.FeatureIsNotAvailable (context, Location, "#pragma");
2916 ParsePragmaDirective ();
2919 case PreprocessorDirective.Line:
2920 Location loc = Location;
2921 if (!PreProcessLine ())
2922 Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
2924 return caller_is_taking;
2927 throw new NotImplementedException (directive.ToString ());
2930 private int consume_string (bool quoted)
2934 Location start_location = Location;
2936 start_location = start_location - 1;
2939 int reader_pos = reader.Position;
2943 // Cannot use get_char because of \r in quoted strings
2944 if (putback_char != -1) {
2954 if (quoted && peek_char () == '"') {
2955 if (pos == value_builder.Length)
2956 Array.Resize (ref value_builder, pos * 2);
2958 value_builder[pos++] = (char) c;
2967 s = InternIdentifier (value_builder, pos);
2969 s = new string (value_builder, 0, pos);
2971 ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
2974 res.ParsedValue = quoted ?
2975 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
2976 reader.ReadChars (reader_pos - 1, reader.Position);
2979 return Token.LITERAL;
2982 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2984 Report.Error (1010, Location, "Newline in constant");
2988 // Don't add \r to string literal
2989 if (pos > 1 && value_builder [pos - 1] == '\r')
2992 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
2993 return Token.LITERAL;
2997 } else if (c == '\\' && !quoted) {
3000 c = escape (c, out surrogate);
3003 if (surrogate != 0) {
3004 if (pos == value_builder.Length)
3005 Array.Resize (ref value_builder, pos * 2);
3007 value_builder[pos++] = (char) c;
3010 } else if (c == -1) {
3011 Report.Error (1039, Location, "Unterminated string literal");
3017 if (pos == value_builder.Length)
3018 Array.Resize (ref value_builder, pos * 2);
3020 value_builder[pos++] = (char) c;
3024 private int consume_identifier (int s)
3026 int res = consume_identifier (s, false);
3028 if (doc_state == XmlCommentState.Allowed)
3029 doc_state = XmlCommentState.NotAllowed;
3034 int consume_identifier (int c, bool quoted)
3037 // This method is very performance sensitive. It accounts
3038 // for approximately 25% of all parser time
3048 c = escape (c, out surrogate);
3049 if (surrogate != 0) {
3050 id_builder [pos++] = (char) c;
3055 id_builder [pos++] = (char) c;
3061 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3062 id_builder [pos++] = (char) c;
3069 c = escape (c, out surrogate);
3070 if (is_identifier_part_character ((char) c))
3071 id_builder[pos++] = (char) c;
3073 if (surrogate != 0) {
3079 } else if (is_identifier_part_character_slow_part ((char) c)) {
3080 id_builder [pos++] = (char) c;
3087 } catch (IndexOutOfRangeException) {
3088 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3096 // Optimization: avoids doing the keyword lookup
3097 // on uppercase letters
3099 if (id_builder [0] >= '_' && !quoted) {
3100 int keyword = GetKeyword (id_builder, pos);
3101 if (keyword != -1) {
3102 val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3107 string s = InternIdentifier (id_builder, pos);
3108 val = ltb.Create (s, current_source, ref_line, column);
3109 if (quoted && parsing_attribute_section)
3110 AddEscapedIdentifier (((LocatedToken) val).Location);
3112 return Token.IDENTIFIER;
3115 string InternIdentifier (char[] charBuffer, int length)
3118 // Keep identifiers in an array of hashtables to avoid needless
3121 var identifiers_group = identifiers[length];
3123 if (identifiers_group != null) {
3124 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3128 // TODO: this should be number of files dependant
3129 // corlib compilation peaks at 1000 and System.Core at 150
3130 int capacity = length > 20 ? 10 : 100;
3131 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3132 identifiers[length] = identifiers_group;
3135 char[] chars = new char[length];
3136 Array.Copy (charBuffer, chars, length);
3138 s = new string (charBuffer, 0, length);
3139 identifiers_group.Add (chars, s);
3143 public int xtoken ()
3147 // Whether we have seen comments on the current line
3148 bool comments_seen = false;
3149 while ((c = get_char ()) != -1) {
3152 col = ((col - 1 + tab_size) / tab_size) * tab_size;
3160 case 0xFEFF: // Ignore BOM anywhere in the file
3163 /* This is required for compatibility with .NET
3165 if (peek_char () == 0xBB) {
3168 if (get_char () == 0xBF)
3176 return consume_identifier (c);
3179 val = ltb.Create (current_source, ref_line, col);
3180 return Token.OPEN_BRACE;
3182 val = ltb.Create (current_source, ref_line, col);
3183 return Token.CLOSE_BRACE;
3185 // To block doccomment inside attribute declaration.
3186 if (doc_state == XmlCommentState.Allowed)
3187 doc_state = XmlCommentState.NotAllowed;
3189 val = ltb.Create (current_source, ref_line, col);
3191 if (parsing_block == 0 || lambda_arguments_parsing)
3192 return Token.OPEN_BRACKET;
3194 int next = peek_char ();
3198 return Token.OPEN_BRACKET;
3208 next = peek_token ();
3209 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3210 return Token.OPEN_BRACKET;
3212 return Token.OPEN_BRACKET_EXPR;
3214 return Token.OPEN_BRACKET_EXPR;
3217 ltb.CreateOptional (current_source, ref_line, col, ref val);
3218 return Token.CLOSE_BRACKET;
3220 val = ltb.Create (current_source, ref_line, col);
3222 // An expression versions of parens can appear in block context only
3224 if (parsing_block != 0 && !lambda_arguments_parsing) {
3227 // Optmize most common case where we know that parens
3230 switch (current_token) {
3231 case Token.IDENTIFIER:
3240 case Token.DELEGATE:
3241 case Token.OP_GENERICS_GT:
3242 return Token.OPEN_PARENS;
3245 // Optimize using peek
3246 int xx = peek_char ();
3253 return Token.OPEN_PARENS;
3256 lambda_arguments_parsing = true;
3258 d = TokenizeOpenParens ();
3260 lambda_arguments_parsing = false;
3264 return Token.OPEN_PARENS;
3266 ltb.CreateOptional (current_source, ref_line, col, ref val);
3267 return Token.CLOSE_PARENS;
3269 ltb.CreateOptional (current_source, ref_line, col, ref val);
3272 ltb.CreateOptional (current_source, ref_line, col, ref val);
3273 return Token.SEMICOLON;
3275 val = ltb.Create (current_source, ref_line, col);
3278 val = ltb.Create (current_source, ref_line, col);
3279 return TokenizePossibleNullableType ();
3281 val = ltb.Create (current_source, ref_line, col);
3282 if (parsing_generic_less_than++ > 0)
3283 return Token.OP_GENERICS_LT;
3285 return TokenizeLessThan ();
3288 val = ltb.Create (current_source, ref_line, col);
3296 if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3297 parsing_generic_less_than--;
3298 return Token.OP_GENERICS_GT;
3307 return Token.OP_SHIFT_RIGHT_ASSIGN;
3309 return Token.OP_SHIFT_RIGHT;
3315 val = ltb.Create (current_source, ref_line, col);
3319 } else if (d == '=') {
3320 d = Token.OP_ADD_ASSIGN;
3328 val = ltb.Create (current_source, ref_line, col);
3332 } else if (d == '=')
3333 d = Token.OP_SUB_ASSIGN;
3343 val = ltb.Create (current_source, ref_line, col);
3344 if (peek_char () == '='){
3351 val = ltb.Create (current_source, ref_line, col);
3362 return Token.ASSIGN;
3365 val = ltb.Create (current_source, ref_line, col);
3369 return Token.OP_AND;
3373 return Token.OP_AND_ASSIGN;
3375 return Token.BITWISE_AND;
3378 val = ltb.Create (current_source, ref_line, col);
3386 return Token.OP_OR_ASSIGN;
3388 return Token.BITWISE_OR;
3391 val = ltb.Create (current_source, ref_line, col);
3392 if (peek_char () == '='){
3394 return Token.OP_MULT_ASSIGN;
3401 val = ltb.Create (current_source, ref_line, col);
3403 return Token.OP_DIV_ASSIGN;
3406 // Handle double-slash comments.
3409 if (doc_processing) {
3410 if (peek_char () == '/') {
3412 // Don't allow ////.
3413 if ((d = peek_char ()) != '/') {
3414 if (doc_state == XmlCommentState.Allowed)
3415 handle_one_line_xml_comment ();
3416 else if (doc_state == XmlCommentState.NotAllowed)
3417 WarningMisplacedComment (Location - 3);
3420 if (xml_comment_buffer.Length > 0)
3421 doc_state = XmlCommentState.NotAllowed;
3427 any_token_seen |= tokens_seen;
3428 tokens_seen = false;
3429 comments_seen = false;
3431 } else if (d == '*'){
3433 bool docAppend = false;
3434 if (doc_processing && peek_char () == '*') {
3436 // But when it is /**/, just do nothing.
3437 if (peek_char () == '/') {
3441 if (doc_state == XmlCommentState.Allowed)
3443 else if (doc_state == XmlCommentState.NotAllowed) {
3444 WarningMisplacedComment (Location - 2);
3448 int current_comment_start = 0;
3450 current_comment_start = xml_comment_buffer.Length;
3451 xml_comment_buffer.Append (Environment.NewLine);
3454 while ((d = get_char ()) != -1){
3455 if (d == '*' && peek_char () == '/'){
3457 comments_seen = true;
3461 xml_comment_buffer.Append ((char) d);
3463 if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3464 any_token_seen |= tokens_seen;
3465 tokens_seen = false;
3467 // Reset 'comments_seen' just to be consistent.
3468 // It doesn't matter either way, here.
3470 comments_seen = false;
3474 Report.Error (1035, Location, "End-of-file found, '*/' expected");
3477 update_formatted_doc_comment (current_comment_start);
3480 val = ltb.Create (current_source, ref_line, col);
3484 val = ltb.Create (current_source, ref_line, col);
3485 if (peek_char () == '='){
3487 return Token.OP_MOD_ASSIGN;
3489 return Token.PERCENT;
3492 val = ltb.Create (current_source, ref_line, col);
3493 if (peek_char () == '='){
3495 return Token.OP_XOR_ASSIGN;
3497 return Token.CARRET;
3500 val = ltb.Create (current_source, ref_line, col);
3501 if (peek_char () == ':') {
3503 return Token.DOUBLE_COLON;
3507 case '0': case '1': case '2': case '3': case '4':
3508 case '5': case '6': case '7': case '8': case '9':
3510 return is_number (c, false);
3512 case '\n': // white space
3515 any_token_seen |= tokens_seen;
3516 tokens_seen = false;
3517 comments_seen = false;
3523 if (d >= '0' && d <= '9')
3524 return is_number (c, true);
3526 ltb.CreateOptional (current_source, ref_line, col, ref val);
3530 if (tokens_seen || comments_seen) {
3531 Eror_WrongPreprocessorLocation ();
3535 if (ParsePreprocessingDirective (true))
3538 bool directive_expected = false;
3539 while ((c = get_char ()) != -1) {
3541 directive_expected = true;
3542 } else if (!directive_expected) {
3543 // TODO: Implement comment support for disabled code and uncomment this code
3545 // Eror_WrongPreprocessorLocation ();
3546 // return Token.ERROR;
3551 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3555 if (ParsePreprocessingDirective (false))
3558 directive_expected = false;
3562 tokens_seen = false;
3569 return consume_string (false);
3572 return TokenizeBackslash ();
3578 return consume_string (true);
3581 if (is_identifier_start_character (c)){
3582 return consume_identifier (c, true);
3585 Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3588 case EvalStatementParserCharacter:
3589 return Token.EVAL_STATEMENT_PARSER;
3590 case EvalCompilationUnitParserCharacter:
3591 return Token.EVAL_COMPILATION_UNIT_PARSER;
3592 case EvalUsingDeclarationsParserCharacter:
3593 return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3594 case DocumentationXref:
3595 return Token.DOC_SEE;
3598 if (is_identifier_start_character (c)) {
3600 return consume_identifier (c);
3603 if (char.IsWhiteSpace ((char) c))
3606 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3611 return Token.COMPLETE_COMPLETION;
3614 return Token.GENERATE_COMPLETION;
3621 int TokenizeBackslash ()
3624 int read_start = reader.Position;
3626 Location start_location = Location;
3627 int c = get_char ();
3630 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3631 Report.Error (1011, start_location, "Empty character literal");
3632 return Token.LITERAL;
3635 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3636 Report.Error (1010, start_location, "Newline in constant");
3641 c = escape (c, out d);
3645 throw new NotImplementedException ();
3647 ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3652 Report.Error (1012, start_location, "Too many characters in character literal");
3654 // Try to recover, read until newline or next "'"
3655 while ((c = get_char ()) != -1) {
3656 if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3662 res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3665 return Token.LITERAL;
3668 int TokenizeLessThan ()
3671 if (handle_typeof) {
3673 if (parse_generic_dimension (out d)) {
3676 return Token.GENERIC_DIMENSION;
3681 // Save current position and parse next token.
3683 if (parse_less_than ()) {
3684 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3685 d = Token.OP_GENERICS_LT_DECL;
3687 d = Token.OP_GENERICS_LT;
3694 parsing_generic_less_than = 0;
3703 return Token.OP_SHIFT_LEFT_ASSIGN;
3705 return Token.OP_SHIFT_LEFT;
3716 // Handles one line xml comment
3718 private void handle_one_line_xml_comment ()
3721 while ((c = peek_char ()) == ' ')
3722 get_char (); // skip heading whitespaces.
3723 while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3724 xml_comment_buffer.Append ((char) get_char ());
3726 if (c == '\r' || c == '\n')
3727 xml_comment_buffer.Append (Environment.NewLine);
3731 // Remove heading "*" in Javadoc-like xml documentation.
3733 private void update_formatted_doc_comment (int current_comment_start)
3735 int length = xml_comment_buffer.Length - current_comment_start;
3736 string [] lines = xml_comment_buffer.ToString (
3737 current_comment_start,
3738 length).Replace ("\r", "").Split ('\n');
3740 // The first line starts with /**, thus it is not target
3741 // for the format check.
3742 for (int i = 1; i < lines.Length; i++) {
3743 string s = lines [i];
3744 int idx = s.IndexOf ('*');
3747 if (i < lines.Length - 1)
3751 head = s.Substring (0, idx);
3752 foreach (char c in head)
3755 lines [i] = s.Substring (idx + 1);
3757 xml_comment_buffer.Remove (current_comment_start, length);
3758 xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3762 // Checks if there was incorrect doc comments and raise
3765 public void check_incorrect_doc_comment ()
3767 if (xml_comment_buffer.Length > 0)
3768 WarningMisplacedComment (Location);
3772 // Consumes the saved xml comment lines (if any)
3773 // as for current target member or type.
3775 public string consume_doc_comment ()
3777 if (xml_comment_buffer.Length > 0) {
3778 string ret = xml_comment_buffer.ToString ();
3779 reset_doc_comment ();
3785 void reset_doc_comment ()
3787 xml_comment_buffer.Length = 0;
3790 public void cleanup ()
3792 if (ifstack != null && ifstack.Count >= 1) {
3793 int state = ifstack.Pop ();
3794 if ((state & REGION) != 0)
3795 Report.Error (1038, Location, "#endregion directive expected");
3797 Report.Error (1027, Location, "Expected `#endif' directive");
3803 // Indicates whether it accepts XML documentation or not.
3805 public enum XmlCommentState {
3806 // comment is allowed in this state.
3808 // comment is not allowed in this state.
3810 // once comments appeared when it is NotAllowed, then the
3811 // state is changed to it, until the state is changed to