505173cb4f9e10a70e72432bae7cd9e4bcf323b3
[mono.git] / mcs / mcs / cs-tokenizer.cs
1 //
2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 //                  This also implements the preprocessor
4 //
5 // Author: Miguel de Icaza (miguel@gnu.org)
6 //         Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
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)
13 //
14
15 using System;
16 using System.Text;
17 using System.Collections.Generic;
18 using System.Globalization;
19 using System.Diagnostics;
20 using System.Collections;
21
22 namespace Mono.CSharp
23 {
24         //
25         // This class has to be used by parser only, it reuses token
26         // details once a file is parsed
27         //
28         public class LocatedToken
29         {
30                 public int row, column;
31                 public string value;
32                 public SourceFile file;
33
34                 public LocatedToken ()
35                 {
36                 }
37
38                 public LocatedToken (string value, Location loc)
39                 {
40                         this.value = value;
41                         file = loc.SourceFile;
42                         row = loc.Row;
43                         column = loc.Column;
44                 }
45
46                 public override string ToString ()
47                 {
48                         return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
49                 }
50
51                 public Location Location
52                 {
53                         get { return new Location (file, row, column); }
54                 }
55
56                 public string Value
57                 {
58                         get { return value; }
59                 }
60         }
61
62         /// <summary>
63         ///    Tokenizer for C# source code. 
64         /// </summary>
65         public class Tokenizer : yyParser.yyInput
66         {
67                 class KeywordEntry<T>
68                 {
69                         public readonly T Token;
70                         public KeywordEntry<T> Next;
71                         public readonly char[] Value;
72
73                         public KeywordEntry (string value, T token)
74                         {
75                                 this.Value = value.ToCharArray ();
76                                 this.Token = token;
77                         }
78                 }
79
80                 sealed class IdentifiersComparer : IEqualityComparer<char[]>
81                 {
82                         readonly int length;
83
84                         public IdentifiersComparer (int length)
85                         {
86                                 this.length = length;
87                         }
88
89                         public bool Equals (char[] x, char[] y)
90                         {
91                                 for (int i = 0; i < length; ++i)
92                                         if (x [i] != y [i])
93                                                 return false;
94
95                                 return true;
96                         }
97
98                         public int GetHashCode (char[] obj)
99                         {
100                                 int h = 0;
101                                 for (int i = 0; i < length; ++i)
102                                         h = (h << 5) - h + obj [i];
103
104                                 return h;
105                         }
106                 }
107
108                 public class LocatedTokenBuffer
109                 {
110                         readonly LocatedToken[] buffer;
111                         public int pos;
112
113                         public LocatedTokenBuffer ()
114                         {
115                                 buffer = new LocatedToken[0];
116                         }
117
118                         public LocatedTokenBuffer (LocatedToken[] buffer)
119                         {
120                                 this.buffer = buffer ?? new LocatedToken[0];
121                         }
122
123                         public LocatedToken Create (SourceFile file, int row, int column)
124                         {
125                                 return Create (null, file, row, column);
126                         }
127
128                         public LocatedToken Create (string value, SourceFile file, int row, int column)
129                         {
130                                 //
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
136                                 // them properly.
137                                 //
138                                 LocatedToken entry;
139                                 if (pos >= buffer.Length) {
140                                         entry = new LocatedToken ();
141                                 } else {
142                                         entry = buffer[pos];
143                                         if (entry == null) {
144                                                 entry = new LocatedToken ();
145                                                 buffer[pos] = entry;
146                                         }
147
148                                         ++pos;
149                                 }
150                                 entry.value = value;
151                                 entry.file = file;
152                                 entry.row = row;
153                                 entry.column = column;
154                                 return entry;
155                         }
156
157                         //
158                         // Used for token not required by expression evaluator
159                         //
160                         [Conditional ("FULL_AST")]
161                         public void CreateOptional (SourceFile file, int row, int col, ref object token)
162                         {
163                                 token = Create (file, row, col);
164                         }
165                 }
166
167                 public enum PreprocessorDirective
168                 {
169                         Invalid = 0,
170
171                         Region = 1,
172                         Endregion = 2,
173                         If = 3 | RequiresArgument,
174                         Endif = 4,
175                         Elif = 5 | RequiresArgument,
176                         Else = 6,
177                         Define = 7 | RequiresArgument,
178                         Undef = 8 | RequiresArgument,
179                         Error = 9,
180                         Warning = 10,
181                         Pragma = 11 | CustomArgumentsParsing,
182                         Line = 12 | CustomArgumentsParsing,
183
184                         CustomArgumentsParsing = 1 << 10,
185                         RequiresArgument = 1 << 11
186                 }
187
188                 readonly SeekableStreamReader reader;
189                 readonly CompilationSourceFile source_file;
190                 readonly CompilerContext context;
191                 readonly Report Report;
192
193
194                 SourceFile current_source;
195                 Location hidden_block_start;
196                 int ref_line = 1;
197                 int line = 1;
198                 int col = 0;
199                 int previous_col;
200                 int current_token;
201                 readonly int tab_size;
202                 bool handle_get_set = false;
203                 bool handle_remove_add = false;
204                 bool handle_where;
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;
210                 
211                 //
212                 // Used mainly for parser optimizations. Some expressions for instance
213                 // can appear only in block (including initializer, base initializer)
214                 // scope only
215                 //
216                 public int parsing_block;
217                 internal bool query_parsing;
218                 
219                 // 
220                 // When parsing type only, useful for ambiguous nullable types
221                 //
222                 public int parsing_type;
223                 
224                 //
225                 // Set when parsing generic declaration (type or method header)
226                 //
227                 public bool parsing_generic_declaration;
228                 public bool parsing_generic_declaration_doc;
229                 
230                 //
231                 // The value indicates that we have not reach any declaration or
232                 // namespace yet
233                 //
234                 public int parsing_declaration;
235
236                 public bool parsing_attribute_section;
237
238                 public bool parsing_modifiers;
239
240                 public bool parsing_catch_when;
241
242                 int parsing_string_interpolation;
243                 int string_interpolation_section;
244                 Stack<bool> parsing_string_interpolation_quoted;
245
246                 public bool parsing_interpolation_format;
247
248                 //
249                 // The special characters to inject on streams to run the unit parser
250                 // in the special expression mode. Using private characters from
251                 // Plane Sixteen (U+100000 to U+10FFFD)
252                 //
253                 // This character is only tested just before the tokenizer is about to report
254                 // an error;   So on the regular operation mode, this addition will have no
255                 // impact on the tokenizer's performance.
256                 //
257                 
258                 public const int EvalStatementParserCharacter = 0x100000;
259                 public const int EvalCompilationUnitParserCharacter = 0x100001;
260                 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
261                 public const int DocumentationXref = 0x100003;
262
263                 const int UnicodeLS = 0x2028;
264                 const int UnicodePS = 0x2029;
265                 
266                 //
267                 // XML documentation buffer. The save point is used to divide
268                 // comments on types and comments on members.
269                 //
270                 StringBuilder xml_comment_buffer;
271
272                 //
273                 // See comment on XmlCommentState enumeration.
274                 //
275                 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
276
277                 //
278                 // Whether tokens have been seen on this line
279                 //
280                 bool tokens_seen = false;
281
282                 //
283                 // Set to true once the GENERATE_COMPLETION token has bee
284                 // returned.   This helps produce one GENERATE_COMPLETION,
285                 // as many COMPLETE_COMPLETION as necessary to complete the
286                 // AST tree and one final EOF.
287                 //
288                 bool generated;
289                 
290                 //
291                 // Whether a token has been seen on the file
292                 // This is needed because `define' is not allowed to be used
293                 // after a token has been seen.
294                 //
295                 bool any_token_seen;
296
297                 //
298                 // Class variables
299                 // 
300                 static readonly KeywordEntry<int>[][] keywords;
301                 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
302                 static readonly HashSet<string> keyword_strings;
303                 static readonly NumberStyles styles;
304                 static readonly NumberFormatInfo csharp_format_info;
305
306                 // Pragma arguments
307                 static readonly char[] pragma_warning = "warning".ToCharArray ();
308                 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
309                 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
310                 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
311                 static readonly char[] line_hidden = "hidden".ToCharArray ();
312                 static readonly char[] line_default = "default".ToCharArray ();
313
314                 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
315
316                 public bool PropertyParsing {
317                         get { return handle_get_set; }
318                         set { handle_get_set = value; }
319                 }
320
321                 public bool EventParsing {
322                         get { return handle_remove_add; }
323                         set { handle_remove_add = value; }
324                 }
325
326                 public bool ConstraintsParsing {
327                         get { return handle_where; }
328                         set { handle_where = value; }
329                 }
330         
331                 public XmlCommentState doc_state {
332                         get { return xml_doc_state; }
333                         set {
334                                 if (value == XmlCommentState.Allowed) {
335                                         check_incorrect_doc_comment ();
336                                         reset_doc_comment ();
337                                 }
338                                 xml_doc_state = value;
339                         }
340                 }
341
342                 //
343                 // This is used to trigger completion generation on the parser
344                 public bool CompleteOnEOF;
345                 
346                 void AddEscapedIdentifier (Location loc)
347                 {
348                         if (escaped_identifiers == null)
349                                 escaped_identifiers = new List<Location> ();
350
351                         escaped_identifiers.Add (loc);
352                 }
353
354                 public bool IsEscapedIdentifier (ATypeNameExpression name)
355                 {
356                         return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
357                 }
358
359                 //
360                 // Values for the associated token returned
361                 //
362                 internal int putback_char;      // Used by repl only
363                 object val;
364
365                 //
366                 // Pre-processor
367                 //
368                 const int TAKING        = 1;
369                 const int ELSE_SEEN     = 4;
370                 const int PARENT_TAKING = 8;
371                 const int REGION        = 16;           
372
373                 //
374                 // pre-processor if stack state:
375                 //
376                 Stack<int> ifstack;
377
378                 public const int MaxIdentifierLength = 512;
379                 public const int MaxNumberLength = 512;
380
381                 readonly char[] id_builder;
382                 readonly Dictionary<char[], string>[] identifiers;
383                 readonly char[] number_builder;
384                 int number_pos;
385
386                 char[] value_builder = new char[64];
387
388                 public int Line {
389                         get {
390                                 return ref_line;
391                         }
392                 }
393
394                 //
395                 // This is used when the tokenizer needs to save
396                 // the current position as it needs to do some parsing
397                 // on its own to deamiguate a token in behalf of the
398                 // parser.
399                 //
400                 Stack<Position> position_stack = new Stack<Position> (2);
401
402                 class Position {
403                         public int position;
404                         public int line;
405                         public int ref_line;
406                         public int col;
407                         public Location hidden;
408                         public int putback_char;
409                         public int previous_col;
410                         public Stack<int> ifstack;
411                         public int parsing_generic_less_than;
412                         public int current_token;
413                         public object val;
414                         public int parsing_string_interpolation;
415                         public int string_interpolation_section;
416                         public Stack<bool> parsing_string_interpolation_quoted;
417
418                         public Position (Tokenizer t)
419                         {
420                                 position = t.reader.Position;
421                                 line = t.line;
422                                 ref_line = t.ref_line;
423                                 col = t.col;
424                                 hidden = t.hidden_block_start;
425                                 putback_char = t.putback_char;
426                                 previous_col = t.previous_col;
427                                 if (t.ifstack != null && t.ifstack.Count != 0) {
428                                         // There is no simple way to clone Stack<T> all
429                                         // methods reverse the order
430                                         var clone = t.ifstack.ToArray ();
431                                         Array.Reverse (clone);
432                                         ifstack = new Stack<int> (clone);
433                                 }
434                                 parsing_generic_less_than = t.parsing_generic_less_than;
435                                 string_interpolation_section = t.string_interpolation_section;
436                                 current_token = t.current_token;
437                                 val = t.val;
438                                 parsing_string_interpolation = t.parsing_string_interpolation;
439                                 string_interpolation_section = t.string_interpolation_section;
440                                 if (t.parsing_string_interpolation_quoted != null && t.parsing_string_interpolation_quoted.Count != 0) {
441                                         var clone = t.parsing_string_interpolation_quoted.ToArray ();
442                                         Array.Reverse (clone);
443                                         parsing_string_interpolation_quoted = new Stack<bool> (clone);
444                                 }
445                         }
446                 }
447
448                 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session, Report report)
449                 {
450                         this.source_file = file;
451                         this.context = file.Compiler;
452                         this.current_source = file.SourceFile;
453                         this.identifiers = session.Identifiers;
454                         this.id_builder = session.IDBuilder;
455                         this.number_builder = session.NumberBuilder;
456                         this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
457                         this.Report = report;
458
459                         reader = input;
460
461                         putback_char = -1;
462
463                         xml_comment_buffer = new StringBuilder ();
464                         doc_processing = context.Settings.DocumentationFile != null;
465
466                         tab_size = context.Settings.TabSize;
467                 }
468                 
469                 public void PushPosition ()
470                 {
471                         position_stack.Push (new Position (this));
472                 }
473
474                 public void PopPosition ()
475                 {
476                         Position p = position_stack.Pop ();
477
478                         reader.Position = p.position;
479                         ref_line = p.ref_line;
480                         line = p.line;
481                         col = p.col;
482                         hidden_block_start = p.hidden;
483                         putback_char = p.putback_char;
484                         previous_col = p.previous_col;
485                         ifstack = p.ifstack;
486                         parsing_generic_less_than = p.parsing_generic_less_than;
487                         parsing_string_interpolation = p.parsing_string_interpolation;
488                         parsing_string_interpolation_quoted = p.parsing_string_interpolation_quoted;
489                         current_token = p.current_token;
490                         val = p.val;
491                 }
492
493                 // Do not reset the position, ignore it.
494                 public void DiscardPosition ()
495                 {
496                         position_stack.Pop ();
497                 }
498                 
499                 static void AddKeyword (string kw, int token)
500                 {
501                         keyword_strings.Add (kw);
502
503                         AddKeyword (keywords, kw, token);
504                 }
505
506                 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
507                 {
508                         AddKeyword (keywords_preprocessor, kw, directive);
509                 }
510
511                 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
512                 {
513                         int length = kw.Length;
514                         if (keywords[length] == null) {
515                                 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
516                         }
517
518                         int char_index = kw[0] - '_';
519                         var kwe = keywords[length][char_index];
520                         if (kwe == null) {
521                                 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
522                                 return;
523                         }
524
525                         while (kwe.Next != null) {
526                                 kwe = kwe.Next;
527                         }
528
529                         kwe.Next = new KeywordEntry<T> (kw, token);
530                 }
531
532                 //
533                 // Class initializer
534                 // 
535                 static Tokenizer ()
536                 {
537                         keyword_strings = new HashSet<string> ();
538
539                         // 11 is the length of the longest keyword for now
540                         keywords = new KeywordEntry<int>[11][];
541
542                         AddKeyword ("__arglist", Token.ARGLIST);
543                         AddKeyword ("__makeref", Token.MAKEREF);
544                         AddKeyword ("__reftype", Token.REFTYPE);
545                         AddKeyword ("__refvalue", Token.REFVALUE);
546                         AddKeyword ("abstract", Token.ABSTRACT);
547                         AddKeyword ("as", Token.AS);
548                         AddKeyword ("add", Token.ADD);
549                         AddKeyword ("base", Token.BASE);
550                         AddKeyword ("bool", Token.BOOL);
551                         AddKeyword ("break", Token.BREAK);
552                         AddKeyword ("byte", Token.BYTE);
553                         AddKeyword ("case", Token.CASE);
554                         AddKeyword ("catch", Token.CATCH);
555                         AddKeyword ("char", Token.CHAR);
556                         AddKeyword ("checked", Token.CHECKED);
557                         AddKeyword ("class", Token.CLASS);
558                         AddKeyword ("const", Token.CONST);
559                         AddKeyword ("continue", Token.CONTINUE);
560                         AddKeyword ("decimal", Token.DECIMAL);
561                         AddKeyword ("default", Token.DEFAULT);
562                         AddKeyword ("delegate", Token.DELEGATE);
563                         AddKeyword ("do", Token.DO);
564                         AddKeyword ("double", Token.DOUBLE);
565                         AddKeyword ("else", Token.ELSE);
566                         AddKeyword ("enum", Token.ENUM);
567                         AddKeyword ("event", Token.EVENT);
568                         AddKeyword ("explicit", Token.EXPLICIT);
569                         AddKeyword ("extern", Token.EXTERN);
570                         AddKeyword ("false", Token.FALSE);
571                         AddKeyword ("finally", Token.FINALLY);
572                         AddKeyword ("fixed", Token.FIXED);
573                         AddKeyword ("float", Token.FLOAT);
574                         AddKeyword ("for", Token.FOR);
575                         AddKeyword ("foreach", Token.FOREACH);
576                         AddKeyword ("goto", Token.GOTO);
577                         AddKeyword ("get", Token.GET);
578                         AddKeyword ("if", Token.IF);
579                         AddKeyword ("implicit", Token.IMPLICIT);
580                         AddKeyword ("in", Token.IN);
581                         AddKeyword ("int", Token.INT);
582                         AddKeyword ("interface", Token.INTERFACE);
583                         AddKeyword ("internal", Token.INTERNAL);
584                         AddKeyword ("is", Token.IS);
585                         AddKeyword ("lock", Token.LOCK);
586                         AddKeyword ("long", Token.LONG);
587                         AddKeyword ("namespace", Token.NAMESPACE);
588                         AddKeyword ("new", Token.NEW);
589                         AddKeyword ("null", Token.NULL);
590                         AddKeyword ("object", Token.OBJECT);
591                         AddKeyword ("operator", Token.OPERATOR);
592                         AddKeyword ("out", Token.OUT);
593                         AddKeyword ("override", Token.OVERRIDE);
594                         AddKeyword ("params", Token.PARAMS);
595                         AddKeyword ("private", Token.PRIVATE);
596                         AddKeyword ("protected", Token.PROTECTED);
597                         AddKeyword ("public", Token.PUBLIC);
598                         AddKeyword ("readonly", Token.READONLY);
599                         AddKeyword ("ref", Token.REF);
600                         AddKeyword ("remove", Token.REMOVE);
601                         AddKeyword ("return", Token.RETURN);
602                         AddKeyword ("sbyte", Token.SBYTE);
603                         AddKeyword ("sealed", Token.SEALED);
604                         AddKeyword ("set", Token.SET);
605                         AddKeyword ("short", Token.SHORT);
606                         AddKeyword ("sizeof", Token.SIZEOF);
607                         AddKeyword ("stackalloc", Token.STACKALLOC);
608                         AddKeyword ("static", Token.STATIC);
609                         AddKeyword ("string", Token.STRING);
610                         AddKeyword ("struct", Token.STRUCT);
611                         AddKeyword ("switch", Token.SWITCH);
612                         AddKeyword ("this", Token.THIS);
613                         AddKeyword ("throw", Token.THROW);
614                         AddKeyword ("true", Token.TRUE);
615                         AddKeyword ("try", Token.TRY);
616                         AddKeyword ("typeof", Token.TYPEOF);
617                         AddKeyword ("uint", Token.UINT);
618                         AddKeyword ("ulong", Token.ULONG);
619                         AddKeyword ("unchecked", Token.UNCHECKED);
620                         AddKeyword ("unsafe", Token.UNSAFE);
621                         AddKeyword ("ushort", Token.USHORT);
622                         AddKeyword ("using", Token.USING);
623                         AddKeyword ("virtual", Token.VIRTUAL);
624                         AddKeyword ("void", Token.VOID);
625                         AddKeyword ("volatile", Token.VOLATILE);
626                         AddKeyword ("while", Token.WHILE);
627                         AddKeyword ("partial", Token.PARTIAL);
628                         AddKeyword ("where", Token.WHERE);
629
630                         // LINQ keywords
631                         AddKeyword ("from", Token.FROM);
632                         AddKeyword ("join", Token.JOIN);
633                         AddKeyword ("on", Token.ON);
634                         AddKeyword ("equals", Token.EQUALS);
635                         AddKeyword ("select", Token.SELECT);
636                         AddKeyword ("group", Token.GROUP);
637                         AddKeyword ("by", Token.BY);
638                         AddKeyword ("let", Token.LET);
639                         AddKeyword ("orderby", Token.ORDERBY);
640                         AddKeyword ("ascending", Token.ASCENDING);
641                         AddKeyword ("descending", Token.DESCENDING);
642                         AddKeyword ("into", Token.INTO);
643
644                         // Contextual async keywords
645                         AddKeyword ("async", Token.ASYNC);
646                         AddKeyword ("await", Token.AWAIT);
647
648                         // Contextual filter catch keyword
649                         AddKeyword ("when", Token.WHEN);
650
651                         keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
652
653                         AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
654                         AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
655                         AddPreprocessorKeyword ("if", PreprocessorDirective.If);
656                         AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
657                         AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
658                         AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
659                         AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
660                         AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
661                         AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
662                         AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
663                         AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
664                         AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
665
666                         csharp_format_info = NumberFormatInfo.InvariantInfo;
667                         styles = NumberStyles.Float;
668                 }
669
670                 int GetKeyword (char[] id, int id_len)
671                 {
672                         //
673                         // Keywords are stored in an array of arrays grouped by their
674                         // length and then by the first character
675                         //
676                         if (id_len >= keywords.Length || keywords [id_len] == null)
677                                 return -1;
678
679                         int first_index = id [0] - '_';
680                         if (first_index > 'z' - '_')
681                                 return -1;
682
683                         var kwe = keywords [id_len] [first_index];
684                         if (kwe == null)
685                                 return -1;
686
687                         int res;
688                         do {
689                                 res = kwe.Token;
690                                 for (int i = 1; i < id_len; ++i) {
691                                         if (id [i] != kwe.Value [i]) {
692                                                 res = 0;
693                                                 kwe = kwe.Next;
694                                                 break;
695                                         }
696                                 }
697                         } while (res == 0 && kwe != null);
698
699                         if (res == 0)
700                                 return -1;
701
702                         int next_token;
703                         switch (res) {
704                         case Token.GET:
705                         case Token.SET:
706                                 if (!handle_get_set)
707                                         res = -1;
708                                 break;
709                         case Token.REMOVE:
710                         case Token.ADD:
711                                 if (!handle_remove_add)
712                                         res = -1;
713                                 break;
714                         case Token.EXTERN:
715                                 if (parsing_declaration == 0)
716                                         res = Token.EXTERN_ALIAS;
717                                 break;
718                         case Token.DEFAULT:
719                                 if (peek_token () == Token.COLON) {
720                                         token ();
721                                         res = Token.DEFAULT_COLON;
722                                 }
723                                 break;
724                         case Token.WHEN:
725                                 if (current_token != Token.CATCH && !parsing_catch_when)
726                                         res = -1;
727                                 break;
728                         case Token.WHERE:
729                                 if (!(handle_where && current_token != Token.COLON) && !query_parsing)
730                                         res = -1;
731                                 break;
732                         case Token.FROM:
733                                 //
734                                 // A query expression is any expression that starts with `from identifier'
735                                 // followed by any token except ; , =
736                                 // 
737                                 if (!query_parsing) {
738                                         if (lambda_arguments_parsing || parsing_block == 0) {
739                                                 res = -1;
740                                                 break;
741                                         }
742
743                                         PushPosition ();
744                                         // HACK: to disable generics micro-parser, because PushPosition does not
745                                         // store identifiers array
746                                         parsing_generic_less_than = 1;
747                                         switch (xtoken ()) {
748                                         case Token.IDENTIFIER:
749                                         case Token.INT:
750                                         case Token.BOOL:
751                                         case Token.BYTE:
752                                         case Token.CHAR:
753                                         case Token.DECIMAL:
754                                         case Token.DOUBLE:
755                                         case Token.FLOAT:
756                                         case Token.LONG:
757                                         case Token.OBJECT:
758                                         case Token.STRING:
759                                         case Token.UINT:
760                                         case Token.ULONG:
761                                                 next_token = xtoken ();
762                                                 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
763                                                         goto default;
764                                                 
765                                                 res = Token.FROM_FIRST;
766                                                 query_parsing = true;
767                                                 if (context.Settings.Version <= LanguageVersion.ISO_2)
768                                                         Report.FeatureIsNotAvailable (context, Location, "query expressions");
769                                                 break;
770                                         case Token.VOID:
771                                                 Expression.Error_VoidInvalidInTheContext (Location, Report);
772                                                 break;
773                                         default:
774                                                 PopPosition ();
775                                                 // HACK: A token is not a keyword so we need to restore identifiers buffer
776                                                 // which has been overwritten before we grabbed the identifier
777                                                 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
778                                                 return -1;
779                                         }
780                                         PopPosition ();
781                                 }
782                                 break;
783                         case Token.JOIN:
784                         case Token.ON:
785                         case Token.EQUALS:
786                         case Token.SELECT:
787                         case Token.GROUP:
788                         case Token.BY:
789                         case Token.LET:
790                         case Token.ORDERBY:
791                         case Token.ASCENDING:
792                         case Token.DESCENDING:
793                         case Token.INTO:
794                                 if (!query_parsing)
795                                         res = -1;
796                                 break;
797                                 
798                         case Token.USING:
799                         case Token.NAMESPACE:
800                                 // TODO: some explanation needed
801                                 check_incorrect_doc_comment ();
802                                 parsing_modifiers = false;
803                                 break;
804                                 
805                         case Token.PARTIAL:
806                                 if (parsing_block > 0) {
807                                         res = -1;
808                                         break;
809                                 }
810
811                                 // Save current position and parse next token.
812                                 PushPosition ();
813
814                                 next_token = token ();
815                                 bool ok = (next_token == Token.CLASS) ||
816                                         (next_token == Token.STRUCT) ||
817                                         (next_token == Token.INTERFACE) ||
818                                         (next_token == Token.VOID);
819
820                                 PopPosition ();
821
822                                 if (ok) {
823                                         if (next_token == Token.VOID) {
824                                                 if (context.Settings.Version <= LanguageVersion.ISO_2)
825                                                         Report.FeatureIsNotAvailable (context, Location, "partial methods");
826                                         } else if (context.Settings.Version == LanguageVersion.ISO_1)
827                                                 Report.FeatureIsNotAvailable (context, Location, "partial types");
828
829                                         return res;
830                                 }
831
832                                 if (next_token < Token.LAST_KEYWORD) {
833                                         Report.Error (267, Location,
834                                                 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
835                                         return token ();
836                                 }
837
838                                 // HACK: A token is not a keyword so we need to restore identifiers buffer
839                                 // which has been overwritten before we grabbed the identifier
840                                 id_builder[0] = 'p';
841                                 id_builder[1] = 'a';
842                                 id_builder[2] = 'r';
843                                 id_builder[3] = 't';
844                                 id_builder[4] = 'i';
845                                 id_builder[5] = 'a';
846                                 id_builder[6] = 'l';
847                                 res = -1;
848                                 break;
849
850                         case Token.ASYNC:
851                                 if (parsing_modifiers) {
852                                         //
853                                         // Skip attributes section or constructor called async
854                                         //
855                                         if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
856                                                 res = -1;
857                                         } else {
858                                                 // async is keyword
859                                         }
860                                 } else if (parsing_block > 0) {
861                                         switch (peek_token ()) {
862                                         case Token.DELEGATE:
863                                         case Token.OPEN_PARENS_LAMBDA:
864                                                 // async is keyword
865                                                 break;
866                                         case Token.IDENTIFIER:
867                                                 PushPosition ();
868                                                 xtoken ();
869                                                 if (xtoken () != Token.ARROW) {
870                                                         PopPosition ();
871                                                         goto default;
872                                                 }
873
874                                                 PopPosition ();
875                                                 break;
876                                         default:
877                                                 // peek_token could overwrite id_buffer
878                                                 id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
879                                                 res = -1;
880                                                 break;
881                                         }
882                                 } else {
883                                         res = -1;
884                                 }
885
886                                 if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
887                                         Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
888                                 }
889                                 
890                                 break;
891
892                         case Token.AWAIT:
893                                 if (parsing_block == 0)
894                                         res = -1;
895
896                                 break;
897                         case Token.THROW:
898                                 switch (current_token) {
899                                 case Token.ARROW:
900                                 case Token.OP_COALESCING:
901                                 case Token.INTERR:
902                                         res = Token.THROW_EXPR;
903                                         break;
904                                 }
905
906                                 break;
907                         }
908
909
910                         return res;
911                 }
912
913                 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
914                 {
915                         //
916                         // Keywords are stored in an array of arrays grouped by their
917                         // length and then by the first character
918                         //
919                         if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
920                                 return PreprocessorDirective.Invalid;
921
922                         int first_index = id[0] - '_';
923                         if (first_index > 'z' - '_')
924                                 return PreprocessorDirective.Invalid;
925
926                         var kwe = keywords_preprocessor[id_len][first_index];
927                         if (kwe == null)
928                                 return PreprocessorDirective.Invalid;
929
930                         PreprocessorDirective res = PreprocessorDirective.Invalid;
931                         do {
932                                 res = kwe.Token;
933                                 for (int i = 1; i < id_len; ++i) {
934                                         if (id[i] != kwe.Value[i]) {
935                                                 res = 0;
936                                                 kwe = kwe.Next;
937                                                 break;
938                                         }
939                                 }
940                         } while (res == PreprocessorDirective.Invalid && kwe != null);
941
942                         return res;
943                 }
944
945                 public Location Location {
946                         get {
947                                 return new Location (current_source, ref_line, col);
948                         }
949                 }
950
951                 static bool is_identifier_start_character (int c)
952                 {
953                         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')
954                                 return true;
955
956                         if (c < 0x80)
957                                 return false;
958
959                         return is_identifier_start_character_slow_part ((char) c);
960                 }
961
962                 static bool is_identifier_part_character (char c)
963                 {
964                         if (c >= 'a' && c <= 'z')
965                                 return true;
966
967                         if (c >= 'A' && c <= 'Z')
968                                 return true;
969
970                         if (c == '_' || (c >= '0' && c <= '9'))
971                                 return true;
972
973                         if (c < 0x80)
974                                 return false;
975
976                         return is_identifier_part_character_slow_part (c);
977                 }
978
979                 static bool is_identifier_start_character_slow_part (char c)
980                 {
981                         switch (Char.GetUnicodeCategory (c)) {
982                         case UnicodeCategory.LetterNumber:
983                         case UnicodeCategory.UppercaseLetter:
984                         case UnicodeCategory.LowercaseLetter:
985                         case UnicodeCategory.TitlecaseLetter:
986                         case UnicodeCategory.ModifierLetter:
987                         case UnicodeCategory.OtherLetter:
988                                 return true;
989                         }
990                         return false;
991                 }
992
993                 static bool is_identifier_part_character_slow_part (char c)
994                 {
995                         switch (Char.GetUnicodeCategory (c)) {
996                         // connecting-character:  A Unicode character of the class Pc
997                         case UnicodeCategory.ConnectorPunctuation:
998
999                         // combining-character: A Unicode character of classes Mn or Mc
1000                         case UnicodeCategory.NonSpacingMark:
1001                         case UnicodeCategory.SpacingCombiningMark:
1002
1003                         // decimal-digit-character: A Unicode character of the class Nd 
1004                         case UnicodeCategory.DecimalDigitNumber:
1005
1006                         // plus is_identifier_start_character_slow_part
1007                         case UnicodeCategory.LetterNumber:
1008                         case UnicodeCategory.UppercaseLetter:
1009                         case UnicodeCategory.LowercaseLetter:
1010                         case UnicodeCategory.TitlecaseLetter:
1011                         case UnicodeCategory.ModifierLetter:
1012                         case UnicodeCategory.OtherLetter:
1013                                 return true;
1014
1015                         // formatting-character: A Unicode character of the class Cf
1016                         case UnicodeCategory.Format:
1017                                 // csc bug compatibility which recognizes it as a whitespace
1018                                 return c != 0xFEFF;
1019                         }
1020
1021                         return false;
1022                 }
1023
1024                 public static bool IsKeyword (string s)
1025                 {
1026                         return keyword_strings.Contains (s);
1027                 }
1028
1029                 //
1030                 // Open parens micro parser. Detects both lambda and cast ambiguity.
1031                 //      
1032                 int TokenizeOpenParens ()
1033                 {
1034                         int ptoken;
1035                         current_token = -1;
1036
1037                         int bracket_level = 0;
1038                         bool is_type = false;
1039                         bool can_be_type = false;
1040                         
1041                         while (true) {
1042                                 ptoken = current_token;
1043                                 token ();
1044
1045                                 switch (current_token) {
1046                                 case Token.CLOSE_PARENS:
1047                                         token ();
1048                                         
1049                                         //
1050                                         // Expression inside parens is lambda, (int i) => 
1051                                         //
1052                                         if (current_token == Token.ARROW)
1053                                                 return Token.OPEN_PARENS_LAMBDA;
1054
1055                                         //
1056                                         // Expression inside parens is single type, (int[])
1057                                         //
1058                                         if (is_type) {
1059                                                 if (current_token == Token.SEMICOLON)
1060                                                         return Token.OPEN_PARENS;
1061
1062                                                 return Token.OPEN_PARENS_CAST;
1063                                         }
1064
1065                                         //
1066                                         // Expression is possible cast, look at next token, (T)null
1067                                         //
1068                                         if (can_be_type) {
1069                                                 switch (current_token) {
1070                                                 case Token.OPEN_PARENS:
1071                                                 case Token.BANG:
1072                                                 case Token.TILDE:
1073                                                 case Token.IDENTIFIER:
1074                                                 case Token.LITERAL:
1075                                                 case Token.BASE:
1076                                                 case Token.CHECKED:
1077                                                 case Token.DELEGATE:
1078                                                 case Token.FALSE:
1079                                                 case Token.FIXED:
1080                                                 case Token.NEW:
1081                                                 case Token.NULL:
1082                                                 case Token.SIZEOF:
1083                                                 case Token.THIS:
1084                                                 case Token.THROW:
1085                                                 case Token.TRUE:
1086                                                 case Token.TYPEOF:
1087                                                 case Token.UNCHECKED:
1088                                                 case Token.UNSAFE:
1089                                                 case Token.DEFAULT:
1090                                                 case Token.AWAIT:
1091
1092                                                 //
1093                                                 // These can be part of a member access
1094                                                 //
1095                                                 case Token.INT:
1096                                                 case Token.UINT:
1097                                                 case Token.SHORT:
1098                                                 case Token.USHORT:
1099                                                 case Token.LONG:
1100                                                 case Token.ULONG:
1101                                                 case Token.DOUBLE:
1102                                                 case Token.FLOAT:
1103                                                 case Token.CHAR:
1104                                                 case Token.BYTE:
1105                                                 case Token.DECIMAL:
1106                                                 case Token.BOOL:
1107                                                 case Token.STRING:
1108                                                 case Token.SBYTE:
1109                                                         return Token.OPEN_PARENS_CAST;
1110                                                 }
1111                                         }
1112                                         return Token.OPEN_PARENS;
1113                                         
1114                                 case Token.DOT:
1115                                 case Token.DOUBLE_COLON:
1116                                         if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1117                                                 goto default;
1118
1119                                         continue;
1120
1121                                 case Token.IDENTIFIER:
1122                                 case Token.AWAIT:
1123                                         switch (ptoken) {
1124                                         case Token.DOT:
1125                                                 if (bracket_level == 0) {
1126                                                         is_type = false;
1127                                                         can_be_type = true;
1128                                                 }
1129
1130                                                 continue;
1131                                         case Token.OP_GENERICS_LT:
1132                                         case Token.COMMA:
1133                                         case Token.DOUBLE_COLON:
1134                                         case -1:
1135                                                 if (bracket_level == 0)
1136                                                         can_be_type = true;
1137                                                 continue;
1138                                         default:
1139                                                 can_be_type = is_type = false;
1140                                                 continue;
1141                                         }
1142
1143                                 case Token.OBJECT:
1144                                 case Token.STRING:
1145                                 case Token.BOOL:
1146                                 case Token.DECIMAL:
1147                                 case Token.FLOAT:
1148                                 case Token.DOUBLE:
1149                                 case Token.SBYTE:
1150                                 case Token.BYTE:
1151                                 case Token.SHORT:
1152                                 case Token.USHORT:
1153                                 case Token.INT:
1154                                 case Token.UINT:
1155                                 case Token.LONG:
1156                                 case Token.ULONG:
1157                                 case Token.CHAR:
1158                                 case Token.VOID:
1159                                         if (bracket_level == 0)
1160                                                 is_type = true;
1161                                         continue;
1162
1163                                 case Token.COMMA:
1164                                         if (bracket_level == 0) {
1165                                                 bracket_level = 100;
1166                                                 can_be_type = is_type = false;
1167                                         }
1168                                         continue;
1169
1170                                 case Token.OP_GENERICS_LT:
1171                                 case Token.OPEN_BRACKET:
1172                                         if (bracket_level++ == 0)
1173                                                 is_type = true;
1174                                         continue;
1175
1176                                 case Token.OP_GENERICS_GT:
1177                                 case Token.CLOSE_BRACKET:
1178                                         --bracket_level;
1179                                         continue;
1180
1181                                 case Token.INTERR_NULLABLE:
1182                                 case Token.STAR:
1183                                         if (bracket_level == 0)
1184                                                 is_type = true;
1185                                         continue;
1186
1187                                 case Token.REF:
1188                                 case Token.OUT:
1189                                         can_be_type = is_type = false;
1190                                         continue;
1191
1192                                 default:
1193                                         return Token.OPEN_PARENS;
1194                                 }
1195                         }
1196                 }
1197
1198                 public static bool IsValidIdentifier (string s)
1199                 {
1200                         if (s == null || s.Length == 0)
1201                                 return false;
1202
1203                         if (!is_identifier_start_character (s [0]))
1204                                 return false;
1205                         
1206                         for (int i = 1; i < s.Length; i ++)
1207                                 if (! is_identifier_part_character (s [i]))
1208                                         return false;
1209                         
1210                         return true;
1211                 }
1212
1213                 bool parse_less_than (ref int genericDimension)
1214                 {
1215                 start:
1216                         int the_token = token ();
1217                         if (the_token == Token.OPEN_BRACKET) {
1218                                 while (true) {
1219                                         the_token = token ();
1220                                         if (the_token == Token.EOF)
1221                                                 return true;
1222
1223                                         if (the_token == Token.CLOSE_BRACKET)
1224                                                 break;
1225                                 }
1226                                 the_token = token ();
1227                         } else if (the_token == Token.IN || the_token == Token.OUT) {
1228                                 the_token = token ();
1229                         }
1230                         switch (the_token) {
1231                         case Token.IDENTIFIER:
1232                         case Token.OBJECT:
1233                         case Token.STRING:
1234                         case Token.BOOL:
1235                         case Token.DECIMAL:
1236                         case Token.FLOAT:
1237                         case Token.DOUBLE:
1238                         case Token.SBYTE:
1239                         case Token.BYTE:
1240                         case Token.SHORT:
1241                         case Token.USHORT:
1242                         case Token.INT:
1243                         case Token.UINT:
1244                         case Token.LONG:
1245                         case Token.ULONG:
1246                         case Token.CHAR:
1247                         case Token.VOID:
1248                                 break;
1249                         case Token.OP_GENERICS_GT:
1250                                 genericDimension = 1;
1251                                 return true;
1252                         case Token.IN:
1253                         case Token.OUT:
1254                                 return true;
1255                         case Token.COMMA:
1256                                 do {
1257                                         ++genericDimension;
1258                                         the_token = token ();
1259                                 } while (the_token == Token.COMMA);
1260
1261                                 if (the_token == Token.OP_GENERICS_GT) {
1262                                         ++genericDimension;
1263                                         return true;
1264                                 }
1265
1266                                 return false;
1267                         default:
1268                                 return false;
1269                         }
1270                 again:
1271                         the_token = token ();
1272
1273                         if (the_token == Token.OP_GENERICS_GT)
1274                                 return true;
1275                         else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1276                                 goto start;
1277                         else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1278                                 goto again;
1279                         else if (the_token == Token.OP_GENERICS_LT) {
1280                                 int unused = 0;
1281                                 if (!parse_less_than (ref unused))
1282                                         return false;
1283                                 goto again;
1284                         } else if (the_token == Token.OPEN_BRACKET) {
1285                         rank_specifiers:
1286                                 the_token = token ();
1287                                 if (the_token == Token.CLOSE_BRACKET)
1288                                         goto again;
1289                                 else if (the_token == Token.COMMA)
1290                                         goto rank_specifiers;
1291                                 return false;
1292                         }
1293
1294                         return false;
1295                 }
1296
1297                 public int peek_token ()
1298                 {
1299                         int the_token;
1300
1301                         PushPosition ();
1302                         the_token = token ();
1303                         PopPosition ();
1304                         
1305                         return the_token;
1306                 }
1307                                         
1308                 //
1309                 // Tonizes `?' using custom disambiguous rules to return one
1310                 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1311                 //
1312                 // Tricky expression looks like:
1313                 //
1314                 // Foo ? a = x ? b : c;
1315                 //
1316                 int TokenizePossibleNullableType ()
1317                 {
1318                         if (parsing_block == 0 || parsing_type > 0)
1319                                 return Token.INTERR_NULLABLE;
1320
1321                         int d = peek_char ();
1322                         if (d == '?') {
1323                                 get_char ();
1324                                 return Token.OP_COALESCING;
1325                         }
1326
1327                         if (d == '.') {
1328                                 return Token.INTERR_OPERATOR;
1329                         }
1330
1331                         if (d != ' ') {
1332                                 if (d == ',' || d == ';' || d == '>')
1333                                         return Token.INTERR_NULLABLE;
1334                                 if (d == '*' || (d >= '0' && d <= '9'))
1335                                         return Token.INTERR;
1336                         }
1337
1338                         PushPosition ();
1339                         current_token = Token.NONE;
1340                         int next_token;
1341                         int parens = 0;
1342                         int generics = 0;
1343                         int brackets = 0;
1344
1345                         var nt = xtoken ();
1346                         switch (nt) {
1347                         case Token.DOT:
1348                         case Token.OPEN_BRACKET_EXPR:
1349                                 next_token = Token.INTERR_OPERATOR;
1350                                 break;
1351                         case Token.LITERAL:
1352                         case Token.TRUE:
1353                         case Token.FALSE:
1354                         case Token.NULL:
1355                         case Token.THIS:
1356                         case Token.NEW:
1357                         case Token.INTERPOLATED_STRING:
1358                         case Token.THROW:
1359                                 next_token = Token.INTERR;
1360                                 break;
1361                                 
1362                         case Token.SEMICOLON:
1363                         case Token.COMMA:
1364                         case Token.CLOSE_PARENS:
1365                         case Token.OPEN_BRACKET:
1366                         case Token.OP_GENERICS_GT:
1367                         case Token.INTERR:
1368                         case Token.OP_COALESCING:
1369                         case Token.COLON:
1370                                 next_token = Token.INTERR_NULLABLE;
1371                                 break;
1372
1373                         case Token.OPEN_PARENS:
1374                         case Token.OPEN_PARENS_CAST:
1375                         case Token.OPEN_PARENS_LAMBDA:
1376                                 next_token = -1;
1377                                 ++parens;
1378                                 break;
1379
1380                         case Token.OP_GENERICS_LT:
1381                         case Token.OP_GENERICS_LT_DECL:
1382                         case Token.GENERIC_DIMENSION:
1383                                 next_token = -1;
1384                                 ++generics;
1385                                 break;
1386
1387                         default:
1388                                 next_token = -1;
1389                                 break;
1390                         }
1391
1392                         if (next_token == -1) {
1393                                 switch (xtoken ()) {
1394                                 case Token.COMMA:
1395                                 case Token.SEMICOLON:
1396                                 case Token.OPEN_BRACE:
1397                                 case Token.IN:
1398                                         next_token = Token.INTERR_NULLABLE;
1399                                         break;
1400                                         
1401                                 case Token.COLON:
1402                                         next_token = Token.INTERR;
1403                                         break;
1404
1405                                 case Token.OPEN_PARENS:
1406                                 case Token.OPEN_PARENS_CAST:
1407                                 case Token.OPEN_PARENS_LAMBDA:
1408                                         ++parens;
1409                                         goto default;
1410
1411                                 case Token.OPEN_BRACKET:
1412                                 case Token.OPEN_BRACKET_EXPR:
1413                                         ++brackets;
1414                                         goto default;
1415
1416                                 case Token.CLOSE_PARENS:
1417                                         --parens;
1418                                         goto default;
1419
1420                                 case Token.OP_GENERICS_LT:
1421                                 case Token.OP_GENERICS_LT_DECL:
1422                                 case Token.GENERIC_DIMENSION:
1423                                         ++generics;
1424                                         goto default;
1425
1426                                 default:
1427                                         int ntoken;
1428                                         int interrs = 1;
1429                                         int colons = 0;
1430                                         int braces = 0;
1431                                         //
1432                                         // All shorcuts failed, do it hard way
1433                                         //
1434                                         while ((ntoken = xtoken ()) != Token.EOF) {
1435                                                 switch (ntoken) {
1436                                                 case Token.OPEN_BRACE:
1437                                                         ++braces;
1438                                                         continue;
1439                                                 case Token.OPEN_PARENS:
1440                                                 case Token.OPEN_PARENS_CAST:
1441                                                 case Token.OPEN_PARENS_LAMBDA:
1442                                                         ++parens;
1443                                                         continue;
1444                                                 case Token.CLOSE_BRACE:
1445                                                         --braces;
1446                                                         continue;
1447                                                 case Token.OP_GENERICS_LT:
1448                                                 case Token.OP_GENERICS_LT_DECL:
1449                                                 case Token.GENERIC_DIMENSION:
1450                                                         ++generics;
1451                                                         continue;
1452                                                 case Token.OPEN_BRACKET:
1453                                                 case Token.OPEN_BRACKET_EXPR:
1454                                                         ++brackets;
1455                                                         continue;
1456                                                 case Token.CLOSE_BRACKET:
1457                                                         --brackets;
1458                                                         continue;
1459                                                 case Token.CLOSE_PARENS:
1460                                                         if (parens > 0) {
1461                                                                 --parens;
1462                                                                 continue;
1463                                                         }
1464
1465                                                         PopPosition ();
1466                                                         return Token.INTERR_NULLABLE;
1467
1468                                                 case Token.OP_GENERICS_GT:
1469                                                         if (generics > 0) {
1470                                                                 --generics;
1471                                                                 continue;
1472                                                         }
1473
1474                                                         PopPosition ();
1475                                                         return Token.INTERR_NULLABLE;
1476                                                 }
1477
1478                                                 if (braces != 0)
1479                                                         continue;
1480
1481                                                 if (ntoken == Token.SEMICOLON)
1482                                                         break;
1483
1484                                                 if (parens != 0)
1485                                                         continue;
1486
1487                                                 if (ntoken == Token.COMMA) {
1488                                                         if (generics != 0 || brackets != 0)
1489                                                                 continue;
1490
1491                                                         PopPosition ();
1492                                                         return Token.INTERR_NULLABLE;
1493                                                 }
1494                                                 
1495                                                 if (ntoken == Token.COLON) {
1496                                                         if (++colons == interrs)
1497                                                                 break;
1498                                                         continue;
1499                                                 }
1500                                                 
1501                                                 if (ntoken == Token.INTERR) {
1502                                                         ++interrs;
1503                                                         continue;
1504                                                 }
1505                                         }
1506                                         
1507                                         next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1508                                         break;
1509                                 }
1510                         }
1511                         
1512                         PopPosition ();
1513                         return next_token;
1514                 }
1515
1516                 bool decimal_digits (int c)
1517                 {
1518                         int d;
1519                         bool seen_digits = false;
1520                         
1521                         if (c != -1){
1522                                 if (number_pos == MaxNumberLength)
1523                                         Error_NumericConstantTooLong ();
1524                                 number_builder [number_pos++] = (char) c;
1525                         }
1526                         
1527                         //
1528                         // We use peek_char2, because decimal_digits needs to do a 
1529                         // 2-character look-ahead (5.ToString for example).
1530                         //
1531                         while ((d = peek_char2 ()) != -1){
1532                                 if (d >= '0' && d <= '9'){
1533                                         if (number_pos == MaxNumberLength)
1534                                                 Error_NumericConstantTooLong ();
1535                                         number_builder [number_pos++] = (char) d;
1536                                         get_char ();
1537                                         seen_digits = true;
1538                                 } else
1539                                         break;
1540                         }
1541                         
1542                         return seen_digits;
1543                 }
1544
1545                 static bool is_hex (int e)
1546                 {
1547                         return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1548                 }
1549
1550                 static TypeCode real_type_suffix (int c)
1551                 {
1552                         switch (c){
1553                         case 'F': case 'f':
1554                                 return TypeCode.Single;
1555                         case 'D': case 'd':
1556                                 return TypeCode.Double;
1557                         case 'M': case 'm':
1558                                 return TypeCode.Decimal;
1559                         default:
1560                                 return TypeCode.Empty;
1561                         }
1562                 }
1563
1564                 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1565                 {
1566                         bool is_unsigned = false;
1567                         bool is_long = false;
1568
1569                         if (c != -1){
1570                                 bool scanning = true;
1571                                 do {
1572                                         switch (c){
1573                                         case 'U': case 'u':
1574                                                 if (is_unsigned)
1575                                                         scanning = false;
1576                                                 is_unsigned = true;
1577                                                 get_char ();
1578                                                 break;
1579
1580                                         case 'l':
1581                                                 if (!is_unsigned){
1582                                                         //
1583                                                         // if we have not seen anything in between
1584                                                         // report this error
1585                                                         //
1586                                                         Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1587                                                 }
1588
1589                                                 goto case 'L';
1590
1591                                         case 'L': 
1592                                                 if (is_long)
1593                                                         scanning = false;
1594                                                 is_long = true;
1595                                                 get_char ();
1596                                                 break;
1597                                                 
1598                                         default:
1599                                                 scanning = false;
1600                                                 break;
1601                                         }
1602                                         c = peek_char ();
1603                                 } while (scanning);
1604                         }
1605
1606                         if (is_long && is_unsigned){
1607                                 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1608                         }
1609                         
1610                         if (is_unsigned){
1611                                 // uint if possible, or ulong else.
1612
1613                                 if ((ul & 0xffffffff00000000) == 0)
1614                                         return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1615                                 else
1616                                         return new ULongLiteral (context.BuiltinTypes, ul, loc);
1617                         } else if (is_long){
1618                                 // long if possible, ulong otherwise
1619                                 if ((ul & 0x8000000000000000) != 0)
1620                                         return new ULongLiteral (context.BuiltinTypes, ul, loc);
1621                                 else
1622                                         return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1623                         } else {
1624                                 // int, uint, long or ulong in that order
1625                                 if ((ul & 0xffffffff00000000) == 0){
1626                                         uint ui = (uint) ul;
1627                                         
1628                                         if ((ui & 0x80000000) != 0)
1629                                                 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1630                                         else
1631                                                 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1632                                 } else {
1633                                         if ((ul & 0x8000000000000000) != 0)
1634                                                 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1635                                         else
1636                                                 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1637                                 }
1638                         }
1639                 }
1640                                 
1641                 //
1642                 // given `c' as the next char in the input decide whether
1643                 // we need to convert to a special type, and then choose
1644                 // the best representation for the integer
1645                 //
1646                 ILiteralConstant adjust_int (int c, Location loc)
1647                 {
1648                         try {
1649                                 if (number_pos > 9){
1650                                         ulong ul = (uint) (number_builder [0] - '0');
1651
1652                                         for (int i = 1; i < number_pos; i++){
1653                                                 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1654                                         }
1655
1656                                         return integer_type_suffix (ul, c, loc);
1657                                 } else {
1658                                         uint ui = (uint) (number_builder [0] - '0');
1659
1660                                         for (int i = 1; i < number_pos; i++){
1661                                                 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1662                                         }
1663
1664                                         return integer_type_suffix (ui, c, loc);
1665                                 }
1666                         } catch (OverflowException) {
1667                                 Error_NumericConstantTooLong ();
1668                                 return new IntLiteral (context.BuiltinTypes, 0, loc);
1669                         }
1670                         catch (FormatException) {
1671                                 Report.Error (1013, Location, "Invalid number");
1672                                 return new IntLiteral (context.BuiltinTypes, 0, loc);
1673                         }
1674                 }
1675                 
1676                 ILiteralConstant adjust_real (TypeCode t, Location loc)
1677                 {
1678                         string s = new string (number_builder, 0, number_pos);
1679                         const string error_details = "Floating-point constant is outside the range of type `{0}'";
1680
1681                         switch (t){
1682                         case TypeCode.Decimal:
1683                                 try {
1684                                         return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1685                                 } catch (OverflowException) {
1686                                         Report.Error (594, Location, error_details, "decimal");
1687                                         return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1688                                 }
1689                         case TypeCode.Single:
1690                                 try {
1691                                         return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1692                                 } catch (OverflowException) {
1693                                         Report.Error (594, Location, error_details, "float");
1694                                         return new FloatLiteral (context.BuiltinTypes, 0, loc);
1695                                 }
1696                         default:
1697                                 try {
1698                                         return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1699                                 } catch (OverflowException) {
1700                                         Report.Error (594, loc, error_details, "double");
1701                                         return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1702                                 }
1703                         }
1704                 }
1705
1706                 ILiteralConstant handle_hex (Location loc)
1707                 {
1708                         int d;
1709                         ulong ul;
1710                         
1711                         get_char ();
1712                         while ((d = peek_char ()) != -1){
1713                                 if (is_hex (d)){
1714                                         number_builder [number_pos++] = (char) d;
1715                                         get_char ();
1716                                 } else
1717                                         break;
1718                         }
1719                         
1720                         string s = new String (number_builder, 0, number_pos);
1721
1722                         try {
1723                                 if (number_pos <= 8)
1724                                         ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1725                                 else
1726                                         ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1727
1728                                 return integer_type_suffix (ul, peek_char (), loc);
1729                         } catch (OverflowException){
1730                                 Error_NumericConstantTooLong ();
1731                                 return new IntLiteral (context.BuiltinTypes, 0, loc);
1732                         }
1733                         catch (FormatException) {
1734                                 Report.Error (1013, Location, "Invalid number");
1735                                 return new IntLiteral (context.BuiltinTypes, 0, loc);
1736                         }
1737                 }
1738
1739                 //
1740                 // Invoked if we know we have .digits or digits
1741                 //
1742                 int is_number (int c, bool dotLead)
1743                 {
1744                         ILiteralConstant res;
1745
1746 #if FULL_AST
1747                         int read_start = reader.Position - 1;
1748                         if (dotLead) {
1749                                 //
1750                                 // Caller did peek_char
1751                                 //
1752                                 --read_start;
1753                         }
1754 #endif
1755                         number_pos = 0;
1756                         var loc = Location;
1757
1758                         if (!dotLead){
1759                                 if (c == '0'){
1760                                         int peek = peek_char ();
1761
1762                                         if (peek == 'x' || peek == 'X') {
1763                                                 val = res = handle_hex (loc);
1764 #if FULL_AST
1765                                                 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1766 #endif
1767
1768                                                 return Token.LITERAL;
1769                                         }
1770                                 }
1771                                 decimal_digits (c);
1772                                 c = peek_char ();
1773                         }
1774
1775                         //
1776                         // We need to handle the case of
1777                         // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1778                         //
1779                         bool is_real = false;
1780                         if (c == '.'){
1781                                 if (!dotLead)
1782                                         get_char ();
1783
1784                                 if (decimal_digits ('.')){
1785                                         is_real = true;
1786                                         c = peek_char ();
1787                                 } else {
1788                                         putback ('.');
1789                                         number_pos--;
1790                                         val = res = adjust_int (-1, loc);
1791
1792 #if FULL_AST
1793                                         res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1794 #endif
1795                                         return Token.LITERAL;
1796                                 }
1797                         }
1798                         
1799                         if (c == 'e' || c == 'E'){
1800                                 is_real = true;
1801                                 get_char ();
1802                                 if (number_pos == MaxNumberLength)
1803                                         Error_NumericConstantTooLong ();
1804                                 number_builder [number_pos++] = (char) c;
1805                                 c = get_char ();
1806                                 
1807                                 if (c == '+'){
1808                                         if (number_pos == MaxNumberLength)
1809                                                 Error_NumericConstantTooLong ();
1810                                         number_builder [number_pos++] = '+';
1811                                         c = -1;
1812                                 } else if (c == '-') {
1813                                         if (number_pos == MaxNumberLength)
1814                                                 Error_NumericConstantTooLong ();
1815                                         number_builder [number_pos++] = '-';
1816                                         c = -1;
1817                                 } else {
1818                                         if (number_pos == MaxNumberLength)
1819                                                 Error_NumericConstantTooLong ();
1820                                         number_builder [number_pos++] = '+';
1821                                 }
1822                                         
1823                                 decimal_digits (c);
1824                                 c = peek_char ();
1825                         }
1826
1827                         var type = real_type_suffix (c);
1828                         if (type == TypeCode.Empty && !is_real) {
1829                                 res = adjust_int (c, loc);
1830                         } else {
1831                                 is_real = true;
1832
1833                                 if (type != TypeCode.Empty) {
1834                                         get_char ();
1835                                 }
1836
1837                                 res = adjust_real (type, loc);
1838                         }
1839
1840                         val = res;
1841
1842 #if FULL_AST
1843                         var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1844                         if (chars[chars.Length - 1] == '\r')
1845                                 Array.Resize (ref chars, chars.Length - 1);
1846                         res.ParsedValue = chars;
1847 #endif
1848
1849                         return Token.LITERAL;
1850                 }
1851
1852                 //
1853                 // Accepts exactly count (4 or 8) hex, no more no less
1854                 //
1855                 int getHex (int count, out int surrogate, out bool error)
1856                 {
1857                         int i;
1858                         int total = 0;
1859                         int c;
1860                         int top = count != -1 ? count : 4;
1861                         
1862                         get_char ();
1863                         error = false;
1864                         surrogate = 0;
1865                         for (i = 0; i < top; i++){
1866                                 c = get_char ();
1867
1868                                 if (c >= '0' && c <= '9')
1869                                         c = (int) c - (int) '0';
1870                                 else if (c >= 'A' && c <= 'F')
1871                                         c = (int) c - (int) 'A' + 10;
1872                                 else if (c >= 'a' && c <= 'f')
1873                                         c = (int) c - (int) 'a' + 10;
1874                                 else {
1875                                         error = true;
1876                                         return 0;
1877                                 }
1878                                 
1879                                 total = (total * 16) + c;
1880                                 if (count == -1){
1881                                         int p = peek_char ();
1882                                         if (p == -1)
1883                                                 break;
1884                                         if (!is_hex ((char)p))
1885                                                 break;
1886                                 }
1887                         }
1888
1889                         if (top == 8) {
1890                                 if (total > 0x0010FFFF) {
1891                                         error = true;
1892                                         return 0;
1893                                 }
1894
1895                                 if (total >= 0x00010000) {
1896                                         surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);                                   
1897                                         total = ((total - 0x00010000) / 0x0400 + 0xD800);
1898                                 }
1899                         }
1900
1901                         return total;
1902                 }
1903
1904                 int escape (int c, out int surrogate)
1905                 {
1906                         bool error;
1907                         int d;
1908                         int v;
1909
1910                         d = peek_char ();
1911                         if (c != '\\') {
1912                                 surrogate = 0;
1913                                 return c;
1914                         }
1915                         
1916                         switch (d){
1917                         case 'a':
1918                                 v = '\a'; break;
1919                         case 'b':
1920                                 v = '\b'; break;
1921                         case 'n':
1922                                 v = '\n'; break;
1923                         case 't':
1924                                 v = '\t'; break;
1925                         case 'v':
1926                                 v = '\v'; break;
1927                         case 'r':
1928                                 v = '\r'; break;
1929                         case '\\':
1930                                 v = '\\'; break;
1931                         case 'f':
1932                                 v = '\f'; break;
1933                         case '0':
1934                                 v = 0; break;
1935                         case '"':
1936                                 v = '"'; break;
1937                         case '\'':
1938                                 v = '\''; break;
1939                         case 'x':
1940                                 v = getHex (-1, out surrogate, out error);
1941                                 if (error)
1942                                         goto default;
1943                                 return v;
1944                         case 'u':
1945                         case 'U':
1946                                 return EscapeUnicode (d, out surrogate);
1947                         default:
1948                                 surrogate = 0;
1949                                 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1950                                 return d;
1951                         }
1952
1953                         get_char ();
1954                         surrogate = 0;
1955                         return v;
1956                 }
1957
1958                 int EscapeUnicode (int ch, out int surrogate)
1959                 {
1960                         bool error;
1961                         if (ch == 'U') {
1962                                 ch = getHex (8, out surrogate, out error);
1963                         } else {
1964                                 ch = getHex (4, out surrogate, out error);
1965                         }
1966
1967                         if (error)
1968                                 Report.Error (1009, Location, "Unrecognized escape sequence");
1969
1970                         return ch;
1971                 }
1972
1973                 int get_char ()
1974                 {
1975                         int x;
1976                         if (putback_char != -1) {
1977                                 x = putback_char;
1978                                 putback_char = -1;
1979                         } else {
1980                                 x = reader.Read ();
1981                         }
1982                         
1983                         if (x <= 13) {
1984                                 if (x == '\r') {
1985                                         if (peek_char () == '\n') {
1986                                                 putback_char = -1;
1987                                         }
1988
1989                                         x = '\n';
1990                                         advance_line ();
1991                                 } else if (x == '\n') {
1992                                         advance_line ();
1993                                 } else {
1994                                         col++;
1995                                 }
1996                         } else if (x >= UnicodeLS && x <= UnicodePS) {
1997                                 advance_line ();
1998                         } else {
1999                                 col++;
2000                         }
2001
2002                         return x;
2003                 }
2004
2005                 void advance_line ()
2006                 {
2007                         line++;
2008                         ref_line++;
2009                         previous_col = col;
2010                         col = 0;
2011                 }
2012
2013                 int peek_char ()
2014                 {
2015                         if (putback_char == -1)
2016                                 putback_char = reader.Read ();
2017                         return putback_char;
2018                 }
2019
2020                 int peek_char2 ()
2021                 {
2022                         if (putback_char != -1)
2023                                 return putback_char;
2024                         return reader.Peek ();
2025                 }
2026                 
2027                 public void putback (int c)
2028                 {
2029                         if (putback_char != -1) {
2030                                 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
2031                         }
2032
2033                         if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
2034                                 // It won't happen though.
2035                                 line--;
2036                                 ref_line--;
2037                                 col = previous_col;
2038                         }
2039                         else
2040                                 col--;
2041                         putback_char = c;
2042                 }
2043
2044                 public bool advance ()
2045                 {
2046                         return peek_char () != -1 || CompleteOnEOF;
2047                 }
2048
2049                 public Object Value {
2050                         get {
2051                                 return val;
2052                         }
2053                 }
2054
2055                 public Object value ()
2056                 {
2057                         return val;
2058                 }
2059
2060                 public int token ()
2061                 {
2062                         current_token = xtoken ();
2063                         return current_token;
2064                 }
2065
2066                 int TokenizePreprocessorKeyword (out int c)
2067                 {
2068                         // skip over white space
2069                         do {
2070                                 c = get_char ();
2071                         } while (c == ' ' || c == '\t');
2072
2073
2074                         int pos = 0;
2075                         while (c != -1 && c >= 'a' && c <= 'z') {
2076                                 id_builder[pos++] = (char) c;
2077                                 c = get_char ();
2078                                 if (c == '\\') {
2079                                         int peek = peek_char ();
2080                                         if (peek == 'U' || peek == 'u') {
2081                                                 int surrogate;
2082                                                 c = EscapeUnicode (c, out surrogate);
2083                                                 if (surrogate != 0) {
2084                                                         if (is_identifier_part_character ((char) c)) {
2085                                                                 id_builder[pos++] = (char) c;
2086                                                         }
2087                                                         c = surrogate;
2088                                                 }
2089                                         }
2090                                 }
2091                         }
2092
2093                         return pos;
2094                 }
2095
2096                 PreprocessorDirective get_cmd_arg (out string arg)
2097                 {
2098                         int c;          
2099
2100                         tokens_seen = false;
2101                         arg = "";
2102
2103                         var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2104
2105                         if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2106                                 return cmd;
2107
2108                         // skip over white space
2109                         while (c == ' ' || c == '\t')
2110                                 c = get_char ();
2111
2112                         int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2113                         int pos = 0;
2114
2115                         while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2116                                 if (c == '\\' && has_identifier_argument >= 0) {
2117                                         if (has_identifier_argument != 0) {
2118                                                 has_identifier_argument = 1;
2119
2120                                                 int peek = peek_char ();
2121                                                 if (peek == 'U' || peek == 'u') {
2122                                                         int surrogate;
2123                                                         c = EscapeUnicode (c, out surrogate);
2124                                                         if (surrogate != 0) {
2125                                                                 if (is_identifier_part_character ((char) c)) {
2126                                                                         if (pos == value_builder.Length)
2127                                                                                 Array.Resize (ref value_builder, pos * 2);
2128
2129                                                                         value_builder[pos++] = (char) c;
2130                                                                 }
2131                                                                 c = surrogate;
2132                                                         }
2133                                                 }
2134                                         } else {
2135                                                 has_identifier_argument = -1;
2136                                         }
2137                                 } else if (c == '/' && peek_char () == '/') {
2138                                         //
2139                                         // Eat single-line comments
2140                                         //
2141                                         get_char ();
2142                                         ReadToEndOfLine ();
2143                                         break;
2144                                 }
2145
2146                                 if (pos == value_builder.Length)
2147                                         Array.Resize (ref value_builder, pos * 2);
2148
2149                                 value_builder[pos++] = (char) c;
2150                                 c = get_char ();
2151                         }
2152
2153                         if (pos != 0) {
2154                                 if (pos > MaxIdentifierLength)
2155                                         arg = new string (value_builder, 0, pos);
2156                                 else
2157                                         arg = InternIdentifier (value_builder, pos);
2158
2159                                 // Eat any trailing whitespaces
2160                                 arg = arg.Trim (simple_whitespaces);
2161                         }
2162
2163                         return cmd;
2164                 }
2165
2166                 //
2167                 // Handles the #line directive
2168                 //
2169                 bool PreProcessLine ()
2170                 {
2171                         Location loc = Location;
2172
2173                         int c;
2174
2175                         int length = TokenizePreprocessorKeyword (out c);
2176                         if (length == line_default.Length) {
2177                                 if (!IsTokenIdentifierEqual (line_default))
2178                                         return false;
2179
2180                                 current_source = source_file.SourceFile;
2181                                 if (!hidden_block_start.IsNull) {
2182                                         current_source.RegisterHiddenScope (hidden_block_start, loc);
2183                                         hidden_block_start = Location.Null;
2184                                 }
2185
2186                                 ref_line = line;
2187                                 return true;
2188                         }
2189
2190                         if (length == line_hidden.Length) {
2191                                 if (!IsTokenIdentifierEqual (line_hidden))
2192                                         return false;
2193
2194                                 if (hidden_block_start.IsNull)
2195                                         hidden_block_start = loc;
2196
2197                                 return true;
2198                         }
2199
2200                         if (length != 0 || c < '0' || c > '9') {
2201                                 //
2202                                 // Eat any remaining characters to continue parsing on next line
2203                                 //
2204                                 ReadToEndOfLine ();
2205                                 return false;
2206                         }
2207
2208                         int new_line = TokenizeNumber (c);
2209                         if (new_line < 1) {
2210                                 //
2211                                 // Eat any remaining characters to continue parsing on next line
2212                                 //
2213                                 ReadToEndOfLine ();
2214                                 return new_line != 0;
2215                         }
2216
2217                         c = get_char ();
2218                         if (c == ' ') {
2219                                 // skip over white space
2220                                 do {
2221                                         c = get_char ();
2222                                 } while (c == ' ' || c == '\t');
2223                         } else if (c == '"') {
2224                                 c = 0;
2225                         }
2226
2227                         if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2228                                 //
2229                                 // Eat any remaining characters to continue parsing on next line
2230                                 //
2231                                 ReadToEndOfLine ();
2232
2233                                 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2234                                 return true;
2235                         }
2236
2237                         string new_file_name = null;
2238                         if (c == '"') {
2239                                 new_file_name = TokenizeFileName (ref c);
2240
2241                                 // skip over white space
2242                                 while (c == ' ' || c == '\t') {
2243                                         c = get_char ();
2244                                 }
2245                         }
2246
2247                         if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2248
2249                         } else if (c == '/') {
2250                                 ReadSingleLineComment ();
2251                         } else {
2252                                 //
2253                                 // Eat any remaining characters to continue parsing on next line
2254                                 //
2255                                 ReadToEndOfLine ();
2256
2257                                 Error_EndLineExpected ();
2258                                 return true;
2259                         }
2260
2261                         if (new_file_name != null) {
2262                                 current_source = context.LookupFile (source_file, new_file_name);
2263                                 source_file.AddIncludeFile (current_source);
2264                         }
2265
2266                         if (!hidden_block_start.IsNull) {
2267                                 current_source.RegisterHiddenScope (hidden_block_start, loc);
2268                                 hidden_block_start = Location.Null;
2269                         }
2270
2271                         ref_line = new_line;
2272                         return true;
2273                 }
2274
2275                 //
2276                 // Handles #define and #undef
2277                 //
2278                 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2279                 {
2280                         if (ident.Length == 0 || ident == "true" || ident == "false"){
2281                                 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2282                                 return;
2283                         }
2284
2285                         if (ident.IndexOfAny (simple_whitespaces) != -1){
2286                                 Error_EndLineExpected ();
2287                                 return;
2288                         }
2289
2290                         if (!is_identifier_start_character (ident [0]))
2291                                 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2292                         
2293                         foreach (char c in ident.Substring (1)){
2294                                 if (!is_identifier_part_character (c)){
2295                                         Report.Error (1001, Location, "Identifier expected: {0}",  ident);
2296                                         return;
2297                                 }
2298                         }
2299
2300                         if (!caller_is_taking)
2301                                 return;
2302
2303                         if (is_define) {
2304                                 //
2305                                 // #define ident
2306                                 //
2307                                 if (context.Settings.IsConditionalSymbolDefined (ident))
2308                                         return;
2309
2310                                 source_file.AddDefine (ident);
2311                         } else {
2312                                 //
2313                                 // #undef ident
2314                                 //
2315                                 source_file.AddUndefine (ident);
2316                         }
2317                 }
2318
2319                 byte read_hex (out bool error)
2320                 {
2321                         int total;
2322                         int c = get_char ();
2323
2324                         if ((c >= '0') && (c <= '9'))
2325                                 total = (int) c - (int) '0';
2326                         else if ((c >= 'A') && (c <= 'F'))
2327                                 total = (int) c - (int) 'A' + 10;
2328                         else if ((c >= 'a') && (c <= 'f'))
2329                                 total = (int) c - (int) 'a' + 10;
2330                         else {
2331                                 error = true;
2332                                 return 0;
2333                         }
2334
2335                         total *= 16;
2336                         c = get_char ();
2337
2338                         if ((c >= '0') && (c <= '9'))
2339                                 total += (int) c - (int) '0';
2340                         else if ((c >= 'A') && (c <= 'F'))
2341                                 total += (int) c - (int) 'A' + 10;
2342                         else if ((c >= 'a') && (c <= 'f'))
2343                                 total += (int) c - (int) 'a' + 10;
2344                         else {
2345                                 error = true;
2346                                 return 0;
2347                         }
2348
2349                         error = false;
2350                         return (byte) total;
2351                 }
2352
2353                 //
2354                 // Parses #pragma checksum
2355                 //
2356                 bool ParsePragmaChecksum ()
2357                 {
2358                         //
2359                         // The syntax is ` "foo.txt" "{guid}" "hash"'
2360                         //
2361                         // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2362                         //
2363                         int c = get_char ();
2364
2365                         if (c != '"')
2366                                 return false;
2367
2368                         string file_name = TokenizeFileName (ref c);
2369
2370                         // TODO: Any white-spaces count
2371                         if (c != ' ')
2372                                 return false;
2373
2374                         SourceFile file = context.LookupFile (source_file, file_name);
2375
2376                         if (get_char () != '"' || get_char () != '{')
2377                                 return false;
2378
2379                         bool error;
2380                         byte[] guid_bytes = new byte [16];
2381                         int i = 0;
2382
2383                         for (; i < 4; i++) {
2384                                 guid_bytes [i] = read_hex (out error);
2385                                 if (error)
2386                                         return false;
2387                         }
2388
2389                         if (get_char () != '-')
2390                                 return false;
2391
2392                         for (; i < 10; i++) {
2393                                 guid_bytes [i] = read_hex (out error);
2394                                 if (error)
2395                                         return false;
2396
2397                                 guid_bytes [i++] = read_hex (out error);
2398                                 if (error)
2399                                         return false;
2400
2401                                 if (get_char () != '-')
2402                                         return false;
2403                         }
2404
2405                         for (; i < 16; i++) {
2406                                 guid_bytes [i] = read_hex (out error);
2407                                 if (error)
2408                                         return false;
2409                         }
2410
2411                         if (get_char () != '}' || get_char () != '"')
2412                                 return false;
2413
2414                         // TODO: Any white-spaces count
2415                         c = get_char ();
2416                         if (c != ' ')
2417                                 return false;
2418
2419                         if (get_char () != '"')
2420                                 return false;
2421
2422                         // Any length of checksum
2423                         List<byte> checksum_bytes = new List<byte> (16);
2424
2425                         var checksum_location = Location;
2426                         c = peek_char ();
2427                         while (c != '"' && c != -1) {
2428                                 checksum_bytes.Add (read_hex (out error));
2429                                 if (error)
2430                                         return false;
2431
2432                                 c = peek_char ();
2433                         }
2434
2435                         if (c == '/') {
2436                                 ReadSingleLineComment ();
2437                         } else if (get_char () != '"') {
2438                                 return false;
2439                         }
2440
2441                         if (context.Settings.GenerateDebugInfo) {
2442                                 var chsum = checksum_bytes.ToArray ();
2443
2444                                 if (file.HasChecksum) {
2445                                         if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2446                                                 // TODO: Report.SymbolRelatedToPreviousError
2447                                                 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2448                                         }
2449                                 }
2450
2451                                 file.SetChecksum (guid_bytes, chsum);
2452                                 current_source.AutoGenerated = true;
2453                         }
2454
2455                         return true;
2456                 }
2457
2458                 bool IsTokenIdentifierEqual (char[] identifier)
2459                 {
2460                         for (int i = 0; i < identifier.Length; ++i) {
2461                                 if (identifier[i] != id_builder[i])
2462                                         return false;
2463                         }
2464
2465                         return true;
2466                 }
2467
2468                 bool ScanClosingInterpolationBrace ()
2469                 {
2470                         PushPosition ();
2471
2472                         bool? res = null;
2473                         int str_quote = 0;
2474                         do {
2475                                 var c = reader.Read ();
2476                                 switch (c) {
2477                                 case '\"':
2478                                         ++str_quote;
2479                                         break;
2480                                 case '\\':
2481                                         // Skip escaped " character
2482                                         c = reader.Read ();
2483                                         if (c == -1)
2484                                                 res = false;
2485                                         break;
2486                                 case -1:
2487                                         res = false;
2488                                         break;
2489                                 case '}':
2490                                         if (str_quote % 2 == 1) {
2491                                                 res = true;
2492                                         }
2493
2494                                         break;
2495                                 }
2496                         } while (res == null);
2497
2498                         PopPosition ();
2499                         return res.Value;
2500                 }
2501
2502                 int TokenizeNumber (int value)
2503                 {
2504                         number_pos = 0;
2505
2506                         decimal_digits (value);
2507                         uint ui = (uint) (number_builder[0] - '0');
2508
2509                         try {
2510                                 for (int i = 1; i < number_pos; i++) {
2511                                         ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2512                                 }
2513
2514                                 return (int) ui;
2515                         } catch (OverflowException) {
2516                                 Error_NumericConstantTooLong ();
2517                                 return -1;
2518                         }
2519                 }
2520
2521                 string TokenizeFileName (ref int c)
2522                 {
2523                         var string_builder = new StringBuilder ();
2524                         while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2525                                 c = get_char ();
2526                                 if (c == '"') {
2527                                         c = get_char ();
2528                                         break;
2529                                 }
2530
2531                                 string_builder.Append ((char) c);
2532                         }
2533
2534                         if (string_builder.Length == 0) {
2535                                 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2536                         }
2537
2538                 
2539                         return string_builder.ToString ();
2540                 }
2541
2542                 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2543                 {
2544                         if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2545                                 int number;
2546
2547                                 if (c >= '0' && c <= '9') {
2548                                         number_pos = 0;
2549                                         number = TokenizeNumber (c);
2550
2551                                         c = get_char ();
2552
2553                                         if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2554                                                 return ReadPragmaWarningComment (c);
2555                                         }
2556                                 } else {
2557                                         //
2558                                         // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2559                                         //
2560                                         int pos = 0;
2561                                         number = -1;
2562                                         id_builder [pos++] = (char)c;
2563                                         while (c < MaxIdentifierLength) {
2564                                                 c = reader.Read ();
2565                                                 id_builder [pos] = (char)c;
2566
2567                                                 if (c >= '0' && c <= '9') {
2568                                                         if (pos == 5 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2569                                                                 // Recognize CSXXXX as C# XXXX warning
2570                                                                 number = 0;
2571                                                                 int pow = 1000;
2572                                                                 for (int i = 0; i < 4; ++i) {
2573                                                                         var ch = id_builder [i + 2];
2574                                                                         if (ch < '0' || ch > '9') {
2575                                                                                 number = -1;
2576                                                                                 break;
2577                                                                         }
2578
2579                                                                         number += (ch - '0') * pow;
2580                                                                         pow /= 10;
2581                                                                 }
2582                                                         }
2583                                                 } else if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2584                                                         advance_line ();
2585                                                         break;
2586                                                 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2587                                                         break;
2588                                                 }
2589
2590                                                 ++pos;
2591                                         }
2592
2593                                         if (number < 0) {
2594                                                 identifier = true;
2595                                                 number = pos;
2596                                         }
2597                                 }
2598
2599                                 // skip over white space
2600                                 while (c == ' ' || c == '\t')
2601                                         c = get_char ();
2602
2603                                 if (c == ',') {
2604                                         c = get_char ();
2605                                 }
2606
2607                                 // skip over white space
2608                                 while (c == ' ' || c == '\t')
2609                                         c = get_char ();
2610
2611                                 return number;
2612                         }
2613
2614                         return ReadPragmaWarningComment (c);
2615                 }
2616
2617                 int ReadPragmaWarningComment (int c)
2618                 {
2619                         if (c == '/') {
2620                                 ReadSingleLineComment ();
2621                         } else {
2622                                 Report.Warning (1692, 1, Location, "Invalid number");
2623
2624                                 // Read everything till the end of the line or file
2625                                 ReadToEndOfLine ();
2626                         }
2627
2628                         return -1;
2629                 }
2630
2631                 void ReadToEndOfLine ()
2632                 {
2633                         int c;
2634                         do {
2635                                 c = get_char ();
2636                         } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2637                 }
2638
2639                 void ReadSingleLineComment ()
2640                 {
2641                         if (peek_char () != '/')
2642                                 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2643
2644                         // Read everything till the end of the line or file
2645                         ReadToEndOfLine ();
2646                 }
2647
2648                 /// <summary>
2649                 /// Handles #pragma directive
2650                 /// </summary>
2651                 void ParsePragmaDirective ()
2652                 {
2653                         int c;
2654                         int length = TokenizePreprocessorKeyword (out c);
2655                         if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2656                                 length = TokenizePreprocessorKeyword (out c);
2657
2658                                 //
2659                                 // #pragma warning disable
2660                                 // #pragma warning restore
2661                                 //
2662                                 if (length == pragma_warning_disable.Length) {
2663                                         bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2664                                         if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2665                                                 // skip over white space
2666                                                 while (c == ' ' || c == '\t')
2667                                                         c = get_char ();
2668
2669                                                 var loc = Location;
2670
2671                                                 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2672                                                         if (c == '/')
2673                                                                 ReadSingleLineComment ();
2674
2675                                                         //
2676                                                         // Disable/Restore all warnings
2677                                                         //
2678                                                         if (disable) {
2679                                                                 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2680                                                         } else {
2681                                                                 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2682                                                         }
2683                                                 } else {
2684                                                         //
2685                                                         // Disable/Restore a warning or group of warnings
2686                                                         //
2687                                                         int code;
2688                                                         do {
2689                                                                 bool identifier = false;
2690                                                                 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2691                                                                 if (code > 0) {
2692                                                                         if (identifier) {
2693                                                                                 // no-op, custom warnings cannot occur in mcs
2694                                                                         } else if (disable) {
2695                                                                                 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2696                                                                         } else {
2697                                                                                 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2698                                                                         }
2699                                                                 }
2700                                                         } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2701                                                 }
2702
2703                                                 return;
2704                                         }
2705                                 }
2706
2707                                 Report.Warning (1634, 1, Location, "Expected disable or restore");
2708
2709                                 // Eat any remaining characters on the line
2710                                 ReadToEndOfLine ();
2711
2712                                 return;
2713                         }
2714
2715                         //
2716                         // #pragma checksum
2717                         //
2718                         if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2719                                 if (c != ' ' || !ParsePragmaChecksum ()) {
2720                                         Report.Warning (1695, 1, Location,
2721                                                 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2722                                 }
2723
2724                                 return;
2725                         }
2726
2727                         Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2728
2729                         // Eat any remaining characters on the line
2730                         ReadToEndOfLine ();
2731                 }
2732
2733                 bool eval_val (string s)
2734                 {
2735                         if (s == "true")
2736                                 return true;
2737                         if (s == "false")
2738                                 return false;
2739
2740                         return source_file.IsConditionalDefined (s);
2741                 }
2742
2743                 bool pp_primary (ref string s)
2744                 {
2745                         s = s.Trim ();
2746                         int len = s.Length;
2747
2748                         if (len > 0){
2749                                 char c = s [0];
2750                                 
2751                                 if (c == '('){
2752                                         s = s.Substring (1);
2753                                         bool val = pp_expr (ref s, false);
2754                                         if (s.Length > 0 && s [0] == ')'){
2755                                                 s = s.Substring (1);
2756                                                 return val;
2757                                         }
2758                                         Error_InvalidDirective ();
2759                                         return false;
2760                                 }
2761                                 
2762                                 if (is_identifier_start_character (c)){
2763                                         int j = 1;
2764
2765                                         while (j < len){
2766                                                 c = s [j];
2767                                                 
2768                                                 if (is_identifier_part_character (c)){
2769                                                         j++;
2770                                                         continue;
2771                                                 }
2772                                                 bool v = eval_val (s.Substring (0, j));
2773                                                 s = s.Substring (j);
2774                                                 return v;
2775                                         }
2776                                         bool vv = eval_val (s);
2777                                         s = "";
2778                                         return vv;
2779                                 }
2780                         }
2781                         Error_InvalidDirective ();
2782                         return false;
2783                 }
2784                 
2785                 bool pp_unary (ref string s)
2786                 {
2787                         s = s.Trim ();
2788                         int len = s.Length;
2789
2790                         if (len > 0){
2791                                 if (s [0] == '!'){
2792                                         if (len > 1 && s [1] == '='){
2793                                                 Error_InvalidDirective ();
2794                                                 return false;
2795                                         }
2796                                         s = s.Substring (1);
2797                                         return ! pp_primary (ref s);
2798                                 } else
2799                                         return pp_primary (ref s);
2800                         } else {
2801                                 Error_InvalidDirective ();
2802                                 return false;
2803                         }
2804                 }
2805                 
2806                 bool pp_eq (ref string s)
2807                 {
2808                         bool va = pp_unary (ref s);
2809
2810                         s = s.Trim ();
2811                         int len = s.Length;
2812                         if (len > 0){
2813                                 if (s [0] == '='){
2814                                         if (len > 2 && s [1] == '='){
2815                                                 s = s.Substring (2);
2816                                                 return va == pp_unary (ref s);
2817                                         } else {
2818                                                 Error_InvalidDirective ();
2819                                                 return false;
2820                                         }
2821                                 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2822                                         s = s.Substring (2);
2823
2824                                         return va != pp_unary (ref s);
2825
2826                                 } 
2827                         }
2828
2829                         return va;
2830                                 
2831                 }
2832                 
2833                 bool pp_and (ref string s)
2834                 {
2835                         bool va = pp_eq (ref s);
2836
2837                         s = s.Trim ();
2838                         int len = s.Length;
2839                         if (len > 0){
2840                                 if (s [0] == '&'){
2841                                         if (len > 2 && s [1] == '&'){
2842                                                 s = s.Substring (2);
2843                                                 return (va & pp_and (ref s));
2844                                         } else {
2845                                                 Error_InvalidDirective ();
2846                                                 return false;
2847                                         }
2848                                 } 
2849                         }
2850                         return va;
2851                 }
2852                 
2853                 //
2854                 // Evaluates an expression for `#if' or `#elif'
2855                 //
2856                 bool pp_expr (ref string s, bool isTerm)
2857                 {
2858                         bool va = pp_and (ref s);
2859                         s = s.Trim ();
2860                         int len = s.Length;
2861                         if (len > 0){
2862                                 char c = s [0];
2863                                 
2864                                 if (c == '|'){
2865                                         if (len > 2 && s [1] == '|'){
2866                                                 s = s.Substring (2);
2867                                                 return va | pp_expr (ref s, isTerm);
2868                                         } else {
2869                                                 Error_InvalidDirective ();
2870                                                 return false;
2871                                         }
2872                                 }
2873                                 if (isTerm) {
2874                                         Error_EndLineExpected ();
2875                                         return false;
2876                                 }
2877                         }
2878                         
2879                         return va;
2880                 }
2881
2882                 bool eval (string s)
2883                 {
2884                         bool v = pp_expr (ref s, true);
2885                         s = s.Trim ();
2886                         if (s.Length != 0){
2887                                 return false;
2888                         }
2889
2890                         return v;
2891                 }
2892
2893                 void Error_NumericConstantTooLong ()
2894                 {
2895                         Report.Error (1021, Location, "Integral constant is too large");                        
2896                 }
2897                 
2898                 void Error_InvalidDirective ()
2899                 {
2900                         Report.Error (1517, Location, "Invalid preprocessor directive");
2901                 }
2902
2903                 void Error_UnexpectedDirective (string extra)
2904                 {
2905                         Report.Error (
2906                                 1028, Location,
2907                                 "Unexpected processor directive ({0})", extra);
2908                 }
2909
2910                 void Error_TokensSeen ()
2911                 {
2912                         Report.Error (1032, Location,
2913                                 "Cannot define or undefine preprocessor symbols after first token in file");
2914                 }
2915
2916                 void Eror_WrongPreprocessorLocation ()
2917                 {
2918                         Report.Error (1040, Location,
2919                                 "Preprocessor directives must appear as the first non-whitespace character on a line");
2920                 }
2921
2922                 void Error_EndLineExpected ()
2923                 {
2924                         Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2925                 }
2926
2927                 //
2928                 // Raises a warning when tokenizer found documentation comment
2929                 // on unexpected place
2930                 //
2931                 void WarningMisplacedComment (Location loc)
2932                 {
2933                         if (doc_state != XmlCommentState.Error) {
2934                                 doc_state = XmlCommentState.Error;
2935                                 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2936                         }
2937                 }
2938                 
2939                 //
2940                 // if true, then the code continues processing the code
2941                 // if false, the code stays in a loop until another directive is
2942                 // reached.
2943                 // When caller_is_taking is false we ignore all directives except the ones
2944                 // which can help us to identify where the #if block ends
2945                 bool ParsePreprocessingDirective (bool caller_is_taking)
2946                 {
2947                         string arg;
2948                         bool region_directive = false;
2949
2950                         var directive = get_cmd_arg (out arg);
2951
2952                         //
2953                         // The first group of pre-processing instructions is always processed
2954                         //
2955                         switch (directive) {
2956                         case PreprocessorDirective.Region:
2957                                 region_directive = true;
2958                                 arg = "true";
2959                                 goto case PreprocessorDirective.If;
2960
2961                         case PreprocessorDirective.Endregion:
2962                                 if (ifstack == null || ifstack.Count == 0){
2963                                         Error_UnexpectedDirective ("no #region for this #endregion");
2964                                         return true;
2965                                 }
2966                                 int pop = ifstack.Pop ();
2967                                         
2968                                 if ((pop & REGION) == 0)
2969                                         Report.Error (1027, Location, "Expected `#endif' directive");
2970                                         
2971                                 return caller_is_taking;
2972                                 
2973                         case PreprocessorDirective.If:
2974                                 if (ifstack == null)
2975                                         ifstack = new Stack<int> (2);
2976
2977                                 int flags = region_directive ? REGION : 0;
2978                                 if (ifstack.Count == 0){
2979                                         flags |= PARENT_TAKING;
2980                                 } else {
2981                                         int state = ifstack.Peek ();
2982                                         if ((state & TAKING) != 0) {
2983                                                 flags |= PARENT_TAKING;
2984                                         }
2985                                 }
2986
2987                                 if (eval (arg) && caller_is_taking) {
2988                                         ifstack.Push (flags | TAKING);
2989                                         return true;
2990                                 }
2991                                 ifstack.Push (flags);
2992                                 return false;
2993
2994                         case PreprocessorDirective.Endif:
2995                                 if (ifstack == null || ifstack.Count == 0){
2996                                         Error_UnexpectedDirective ("no #if for this #endif");
2997                                         return true;
2998                                 } else {
2999                                         pop = ifstack.Pop ();
3000                                         
3001                                         if ((pop & REGION) != 0)
3002                                                 Report.Error (1038, Location, "#endregion directive expected");
3003                                         
3004                                         if (arg.Length != 0) {
3005                                                 Error_EndLineExpected ();
3006                                         }
3007                                         
3008                                         if (ifstack.Count == 0)
3009                                                 return true;
3010
3011                                         int state = ifstack.Peek ();
3012                                         return (state & TAKING) != 0;
3013                                 }
3014
3015                         case PreprocessorDirective.Elif:
3016                                 if (ifstack == null || ifstack.Count == 0){
3017                                         Error_UnexpectedDirective ("no #if for this #elif");
3018                                         return true;
3019                                 } else {
3020                                         int state = ifstack.Pop ();
3021
3022                                         if ((state & REGION) != 0) {
3023                                                 Report.Error (1038, Location, "#endregion directive expected");
3024                                                 return true;
3025                                         }
3026
3027                                         if ((state & ELSE_SEEN) != 0){
3028                                                 Error_UnexpectedDirective ("#elif not valid after #else");
3029                                                 return true;
3030                                         }
3031
3032                                         if ((state & TAKING) != 0) {
3033                                                 ifstack.Push (0);
3034                                                 return false;
3035                                         }
3036
3037                                         if (eval (arg) && ((state & PARENT_TAKING) != 0)){
3038                                                 ifstack.Push (state | TAKING);
3039                                                 return true;
3040                                         }
3041
3042                                         ifstack.Push (state);
3043                                         return false;
3044                                 }
3045
3046                         case PreprocessorDirective.Else:
3047                                 if (ifstack == null || ifstack.Count == 0){
3048                                         Error_UnexpectedDirective ("no #if for this #else");
3049                                         return true;
3050                                 } else {
3051                                         int state = ifstack.Peek ();
3052
3053                                         if ((state & REGION) != 0) {
3054                                                 Report.Error (1038, Location, "#endregion directive expected");
3055                                                 return true;
3056                                         }
3057
3058                                         if ((state & ELSE_SEEN) != 0){
3059                                                 Error_UnexpectedDirective ("#else within #else");
3060                                                 return true;
3061                                         }
3062
3063                                         ifstack.Pop ();
3064
3065                                         if (arg.Length != 0) {
3066                                                 Error_EndLineExpected ();
3067                                                 return true;
3068                                         }
3069
3070                                         bool ret = false;
3071                                         if ((state & PARENT_TAKING) != 0) {
3072                                                 ret = (state & TAKING) == 0;
3073                                         
3074                                                 if (ret)
3075                                                         state |= TAKING;
3076                                                 else
3077                                                         state &= ~TAKING;
3078                                         }
3079         
3080                                         ifstack.Push (state | ELSE_SEEN);
3081                                         
3082                                         return ret;
3083                                 }
3084                         case PreprocessorDirective.Define:
3085                                 if (any_token_seen){
3086                                         if (caller_is_taking)
3087                                                 Error_TokensSeen ();
3088                                         return caller_is_taking;
3089                                 }
3090                                 PreProcessDefinition (true, arg, caller_is_taking);
3091                                 return caller_is_taking;
3092
3093                         case PreprocessorDirective.Undef:
3094                                 if (any_token_seen){
3095                                         if (caller_is_taking)
3096                                                 Error_TokensSeen ();
3097                                         return caller_is_taking;
3098                                 }
3099                                 PreProcessDefinition (false, arg, caller_is_taking);
3100                                 return caller_is_taking;
3101
3102                         case PreprocessorDirective.Invalid:
3103                                 Report.Error (1024, Location, "Wrong preprocessor directive");
3104                                 return true;
3105                         }
3106
3107                         //
3108                         // These are only processed if we are in a `taking' block
3109                         //
3110                         if (!caller_is_taking)
3111                                 return false;
3112                                         
3113                         switch (directive){
3114                         case PreprocessorDirective.Error:
3115                                 Report.Error (1029, Location, "#error: '{0}'", arg);
3116                                 return true;
3117
3118                         case PreprocessorDirective.Warning:
3119                                 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3120                                 return true;
3121
3122                         case PreprocessorDirective.Pragma:
3123                                 if (context.Settings.Version == LanguageVersion.ISO_1) {
3124                                         Report.FeatureIsNotAvailable (context, Location, "#pragma");
3125                                 }
3126
3127                                 ParsePragmaDirective ();
3128                                 return true;
3129
3130                         case PreprocessorDirective.Line:
3131                                 Location loc = Location;
3132                                 if (!PreProcessLine ())
3133                                         Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3134
3135                                 return caller_is_taking;
3136                         }
3137
3138                         throw new NotImplementedException (directive.ToString ());
3139                 }
3140
3141                 int consume_string (bool quoted)
3142                 {
3143                         int c;
3144                         int pos = 0;
3145                         Location start_location = Location;
3146                         if (quoted)
3147                                 start_location = start_location - 1;
3148
3149 #if FULL_AST
3150                         int reader_pos = reader.Position;
3151 #endif
3152
3153                         while (true){
3154                                 // Cannot use get_char because of \r in quoted strings
3155                                 if (putback_char != -1) {
3156                                         c = putback_char;
3157                                         putback_char = -1;
3158                                 } else {
3159                                         c = reader.Read ();
3160                                 }
3161
3162                                 if (c == '"') {
3163                                         ++col;
3164
3165                                         if (quoted && peek_char () == '"') {
3166                                                 if (pos == value_builder.Length)
3167                                                         Array.Resize (ref value_builder, pos * 2);
3168
3169                                                 value_builder[pos++] = (char) c;
3170                                                 get_char ();
3171                                                 continue;
3172                                         }
3173
3174                                         ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3175                                         val = res;
3176 #if FULL_AST
3177                                         res.ParsedValue = quoted ?
3178                                                 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3179                                                 reader.ReadChars (reader_pos - 1, reader.Position);
3180 #endif
3181
3182                                         return Token.LITERAL;
3183                                 }
3184
3185                                 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3186                                         if (!quoted) {
3187                                                 Report.Error (1010, Location, "Newline in constant");
3188
3189                                                 advance_line ();
3190
3191                                                 // Don't add \r to string literal
3192                                                 if (pos > 1 && value_builder [pos - 1] == '\r')
3193                                                         --pos;
3194
3195                                                 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3196                                                 return Token.LITERAL;
3197                                         }
3198
3199                                         advance_line ();
3200                                 } else if (c == '\\' && !quoted) {
3201                                         ++col;
3202                                         int surrogate;
3203                                         c = escape (c, out surrogate);
3204                                         if (c == -1)
3205                                                 return Token.ERROR;
3206                                         if (surrogate != 0) {
3207                                                 if (pos == value_builder.Length)
3208                                                         Array.Resize (ref value_builder, pos * 2);
3209
3210                                                 value_builder[pos++] = (char) c;
3211                                                 c = surrogate;
3212                                         }
3213                                 } else if (c == -1) {
3214                                         Report.Error (1039, Location, "Unterminated string literal");
3215                                         return Token.EOF;
3216                                 } else {
3217                                         ++col;
3218                                 }
3219
3220                                 if (pos == value_builder.Length)
3221                                         Array.Resize (ref value_builder, pos * 2);
3222
3223                                 value_builder[pos++] = (char) c;
3224                         }
3225                 }
3226
3227                 private int consume_identifier (int s)
3228                 {
3229                         int res = consume_identifier (s, false);
3230
3231                         if (doc_state == XmlCommentState.Allowed)
3232                                 doc_state = XmlCommentState.NotAllowed;
3233
3234                         return res;
3235                 }
3236
3237                 int consume_identifier (int c, bool quoted) 
3238                 {
3239                         //
3240                         // This method is very performance sensitive. It accounts
3241                         // for approximately 25% of all parser time
3242                         //
3243
3244                         int pos = 0;
3245                         int column = col;
3246                         if (quoted)
3247                                 --column;
3248
3249                         if (c == '\\') {
3250                                 int surrogate;
3251                                 c = escape (c, out surrogate);
3252                                 if (quoted || is_identifier_start_character (c)) {
3253                                         // it's added bellow
3254                                 } else if (surrogate != 0) {
3255                                         id_builder [pos++] = (char)c;
3256                                         c = surrogate;
3257                                 } else {
3258                                         Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3259                                         return Token.ERROR;
3260                                 }
3261                         }
3262
3263                         id_builder [pos++] = (char) c;
3264
3265                         try {
3266                                 while (true) {
3267                                         c = reader.Read ();
3268
3269                                         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3270                                                 id_builder [pos++] = (char) c;
3271                                                 continue;
3272                                         }
3273
3274                                         if (c < 0x80) {
3275                                                 if (c == '\\') {
3276                                                         int surrogate;
3277                                                         c = escape (c, out surrogate);
3278                                                         if (is_identifier_part_character ((char) c))
3279                                                                 id_builder[pos++] = (char) c;
3280                                                         else if (surrogate != 0) {
3281                                                                 c = surrogate;
3282                                                         } else {
3283                                                                 switch (c) {
3284                                                                 // TODO: Probably need more whitespace characters
3285                                                                 case 0xFEFF:
3286                                                                         putback_char = c;
3287                                                                         break;
3288                                                                 default:
3289                                                                         Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3290                                                                         return Token.ERROR;
3291                                                                 }
3292                                                         }
3293
3294                                                         continue;
3295                                                 }
3296                                         } else if (is_identifier_part_character_slow_part ((char) c)) {
3297                                                 id_builder [pos++] = (char) c;
3298                                                 continue;
3299                                         }
3300
3301                                         putback_char = c;
3302                                         break;
3303                                 }
3304                         } catch (IndexOutOfRangeException) {
3305                                 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3306                                 --pos;
3307                                 col += pos;
3308                         }
3309
3310                         col += pos - 1;
3311
3312                         //
3313                         // Optimization: avoids doing the keyword lookup
3314                         // on uppercase letters
3315                         //
3316                         if (id_builder [0] >= '_' && !quoted) {
3317                                 int keyword = GetKeyword (id_builder, pos);
3318                                 if (keyword != -1) {
3319                                         val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3320                                         return keyword;
3321                                 }
3322                         }
3323
3324                         string s = InternIdentifier (id_builder, pos);
3325                         val = ltb.Create (s, current_source, ref_line, column);
3326                         if (quoted && parsing_attribute_section)
3327                                 AddEscapedIdentifier (((LocatedToken) val).Location);
3328
3329                         return Token.IDENTIFIER;
3330                 }
3331
3332                 string InternIdentifier (char[] charBuffer, int length)
3333                 {
3334                         //
3335                         // Keep identifiers in an array of hashtables to avoid needless
3336                         // allocations
3337                         //
3338                         var identifiers_group = identifiers[length];
3339                         string s;
3340                         if (identifiers_group != null) {
3341                                 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3342                                         return s;
3343                                 }
3344                         } else {
3345                                 // TODO: this should be number of files dependant
3346                                 // corlib compilation peaks at 1000 and System.Core at 150
3347                                 int capacity = length > 20 ? 10 : 100;
3348                                 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3349                                 identifiers[length] = identifiers_group;
3350                         }
3351
3352                         char[] chars = new char[length];
3353                         Array.Copy (charBuffer, chars, length);
3354
3355                         s = new string (charBuffer, 0, length);
3356                         identifiers_group.Add (chars, s);
3357                         return s;
3358                 }
3359                 
3360                 public int xtoken ()
3361                 {
3362                         if (parsing_interpolation_format) {
3363                                 return TokenizeInterpolationFormat ();
3364                         }
3365
3366                         int d, c;
3367
3368                         // Whether we have seen comments on the current line
3369                         bool comments_seen = false;
3370                         while ((c = get_char ()) != -1) {
3371                                 switch (c) {
3372                                 case '\t':
3373                                         col = ((col - 1 + tab_size) / tab_size) * tab_size;
3374                                         continue;
3375
3376                                 case ' ':
3377                                 case '\f':
3378                                 case '\v':
3379                                 case 0xa0:
3380                                 case 0:
3381                                 case 0xFEFF:    // Ignore BOM anywhere in the file
3382                                         continue;
3383
3384 /*                              This is required for compatibility with .NET
3385                                 case 0xEF:
3386                                         if (peek_char () == 0xBB) {
3387                                                 PushPosition ();
3388                                                 get_char ();
3389                                                 if (get_char () == 0xBF)
3390                                                         continue;
3391                                                 PopPosition ();
3392                                         }
3393                                         break;
3394 */
3395                                 case '\\':
3396                                         tokens_seen = true;
3397                                         return consume_identifier (c);
3398
3399                                 case '{':
3400                                         val = ltb.Create (current_source, ref_line, col);
3401
3402                                         if (parsing_string_interpolation > 0)
3403                                                 ++string_interpolation_section;
3404
3405                                         return Token.OPEN_BRACE;
3406                                 case '}':
3407                                         if (parsing_string_interpolation > 0) {
3408                                                 if (string_interpolation_section == 0) {
3409                                                         --parsing_string_interpolation;
3410                                                         bool quoted;
3411                                                         if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Count > 0) {
3412                                                                 quoted = parsing_string_interpolation_quoted.Pop ();
3413                                                         } else {
3414                                                                 quoted = false;
3415                                                         }
3416
3417                                                         return TokenizeInterpolatedString (quoted);
3418                                                 }
3419
3420                                                 --string_interpolation_section;
3421                                         }
3422
3423                                         val = ltb.Create (current_source, ref_line, col);
3424                                         return Token.CLOSE_BRACE;
3425                                 case '[':
3426                                         // To block doccomment inside attribute declaration.
3427                                         if (doc_state == XmlCommentState.Allowed)
3428                                                 doc_state = XmlCommentState.NotAllowed;
3429
3430                                         val = ltb.Create (current_source, ref_line, col);
3431
3432                                         if (parsing_block == 0 || lambda_arguments_parsing)
3433                                                 return Token.OPEN_BRACKET;
3434
3435                                         int next = peek_char ();
3436                                         switch (next) {
3437                                         case ']':
3438                                         case ',':
3439                                                 return Token.OPEN_BRACKET;
3440
3441                                         case ' ':
3442                                         case '\f':
3443                                         case '\v':
3444                                         case '\r':
3445                                         case '\n':
3446                                         case UnicodeLS:
3447                                         case UnicodePS:
3448                                         case '/':
3449                                                 next = peek_token ();
3450                                                 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3451                                                         return Token.OPEN_BRACKET;
3452
3453                                                 return Token.OPEN_BRACKET_EXPR;
3454                                         default:
3455                                                 return Token.OPEN_BRACKET_EXPR;
3456                                         }
3457                                 case ']':
3458                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3459                                         return Token.CLOSE_BRACKET;
3460                                 case '(':
3461                                         val = ltb.Create (current_source, ref_line, col);
3462                                         //
3463                                         // An expression versions of parens can appear in block context only
3464                                         //
3465                                         if (parsing_block != 0 && !lambda_arguments_parsing) {
3466                                                 
3467                                                 //
3468                                                 // Optmize most common case where we know that parens
3469                                                 // is not special
3470                                                 //
3471                                                 switch (current_token) {
3472                                                 case Token.IDENTIFIER:
3473                                                 case Token.IF:
3474                                                 case Token.FOR:
3475                                                 case Token.FOREACH:
3476                                                 case Token.TYPEOF:
3477                                                 case Token.WHILE:
3478                                                 case Token.SWITCH:
3479                                                 case Token.USING:
3480                                                 case Token.DEFAULT:
3481                                                 case Token.DELEGATE:
3482                                                 case Token.OP_GENERICS_GT:
3483                                                         return Token.OPEN_PARENS;
3484                                                 }
3485
3486                                                 // Optimize using peek
3487                                                 int xx = peek_char ();
3488                                                 switch (xx) {
3489                                                 case '(':
3490                                                 case '\'':
3491                                                 case '"':
3492                                                 case '0':
3493                                                 case '1':
3494                                                         return Token.OPEN_PARENS;
3495                                                 }
3496
3497                                                 lambda_arguments_parsing = true;
3498                                                 PushPosition ();
3499                                                 d = TokenizeOpenParens ();
3500                                                 PopPosition ();
3501                                                 lambda_arguments_parsing = false;
3502                                                 return d;
3503                                         }
3504
3505                                         return Token.OPEN_PARENS;
3506                                 case ')':
3507                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3508                                         return Token.CLOSE_PARENS;
3509                                 case ',':
3510                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3511                                         return Token.COMMA;
3512                                 case ';':
3513                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3514                                         return Token.SEMICOLON;
3515                                 case '~':
3516                                         val = ltb.Create (current_source, ref_line, col);
3517                                         return Token.TILDE;
3518                                 case '?':
3519                                         val = ltb.Create (current_source, ref_line, col);
3520                                         return TokenizePossibleNullableType ();
3521                                 case '<':
3522                                         val = ltb.Create (current_source, ref_line, col);
3523                                         if (parsing_generic_less_than++ > 0)
3524                                                 return Token.OP_GENERICS_LT;
3525
3526                                         return TokenizeLessThan ();
3527
3528                                 case '>':
3529                                         val = ltb.Create (current_source, ref_line, col);
3530                                         d = peek_char ();
3531
3532                                         if (d == '='){
3533                                                 get_char ();
3534                                                 return Token.OP_GE;
3535                                         }
3536
3537                                         if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3538                                                 parsing_generic_less_than--;
3539                                                 return Token.OP_GENERICS_GT;
3540                                         }
3541
3542                                         if (d == '>') {
3543                                                 get_char ();
3544                                                 d = peek_char ();
3545
3546                                                 if (d == '=') {
3547                                                         get_char ();
3548                                                         return Token.OP_SHIFT_RIGHT_ASSIGN;
3549                                                 }
3550                                                 return Token.OP_SHIFT_RIGHT;
3551                                         }
3552
3553                                         return Token.OP_GT;
3554
3555                                 case '+':
3556                                         val = ltb.Create (current_source, ref_line, col);
3557                                         d = peek_char ();
3558                                         if (d == '+') {
3559                                                 d = Token.OP_INC;
3560                                         } else if (d == '=') {
3561                                                 d = Token.OP_ADD_ASSIGN;
3562                                         } else {
3563                                                 return Token.PLUS;
3564                                         }
3565                                         get_char ();
3566                                         return d;
3567
3568                                 case '-':
3569                                         val = ltb.Create (current_source, ref_line, col);
3570                                         d = peek_char ();
3571                                         if (d == '-') {
3572                                                 d = Token.OP_DEC;
3573                                         } else if (d == '=')
3574                                                 d = Token.OP_SUB_ASSIGN;
3575                                         else if (d == '>')
3576                                                 d = Token.OP_PTR;
3577                                         else {
3578                                                 return Token.MINUS;
3579                                         }
3580                                         get_char ();
3581                                         return d;
3582
3583                                 case '!':
3584                                         val = ltb.Create (current_source, ref_line, col);
3585                                         if (peek_char () == '='){
3586                                                 get_char ();
3587                                                 return Token.OP_NE;
3588                                         }
3589                                         return Token.BANG;
3590
3591                                 case '=':
3592                                         val = ltb.Create (current_source, ref_line, col);
3593                                         d = peek_char ();
3594                                         if (d == '='){
3595                                                 get_char ();
3596                                                 return Token.OP_EQ;
3597                                         }
3598                                         if (d == '>'){
3599                                                 get_char ();
3600                                                 return Token.ARROW;
3601                                         }
3602
3603                                         return Token.ASSIGN;
3604
3605                                 case '&':
3606                                         val = ltb.Create (current_source, ref_line, col);
3607                                         d = peek_char ();
3608                                         if (d == '&'){
3609                                                 get_char ();
3610                                                 return Token.OP_AND;
3611                                         }
3612                                         if (d == '='){
3613                                                 get_char ();
3614                                                 return Token.OP_AND_ASSIGN;
3615                                         }
3616                                         return Token.BITWISE_AND;
3617
3618                                 case '|':
3619                                         val = ltb.Create (current_source, ref_line, col);
3620                                         d = peek_char ();
3621                                         if (d == '|'){
3622                                                 get_char ();
3623                                                 return Token.OP_OR;
3624                                         }
3625                                         if (d == '='){
3626                                                 get_char ();
3627                                                 return Token.OP_OR_ASSIGN;
3628                                         }
3629                                         return Token.BITWISE_OR;
3630
3631                                 case '*':
3632                                         val = ltb.Create (current_source, ref_line, col);
3633                                         if (peek_char () == '='){
3634                                                 get_char ();
3635                                                 return Token.OP_MULT_ASSIGN;
3636                                         }
3637                                         return Token.STAR;
3638
3639                                 case '/':
3640                                         d = peek_char ();
3641                                         if (d == '='){
3642                                                 val = ltb.Create (current_source, ref_line, col);
3643                                                 get_char ();
3644                                                 return Token.OP_DIV_ASSIGN;
3645                                         }
3646
3647                                         // Handle double-slash comments.
3648                                         if (d == '/'){
3649                                                 if (parsing_string_interpolation > 0) {
3650                                                         Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3651                                                         goto case '}';
3652                                                 }
3653
3654                                                 get_char ();
3655                                                 if (doc_processing) {
3656                                                         if (peek_char () == '/') {
3657                                                                 get_char ();
3658                                                                 // Don't allow ////.
3659                                                                 if ((d = peek_char ()) != '/') {
3660                                                                         if (doc_state == XmlCommentState.Allowed)
3661                                                                                 handle_one_line_xml_comment ();
3662                                                                         else if (doc_state == XmlCommentState.NotAllowed)
3663                                                                                 WarningMisplacedComment (Location - 3);
3664                                                                 }
3665                                                         } else {
3666                                                                 if (xml_comment_buffer.Length > 0)
3667                                                                         doc_state = XmlCommentState.NotAllowed;
3668                                                         }
3669                                                 }
3670
3671                                                 ReadToEndOfLine ();
3672
3673                                                 any_token_seen |= tokens_seen;
3674                                                 tokens_seen = false;
3675                                                 comments_seen = false;
3676                                                 continue;
3677                                         } else if (d == '*'){
3678                                                 get_char ();
3679                                                 bool docAppend = false;
3680                                                 if (doc_processing && peek_char () == '*') {
3681                                                         get_char ();
3682                                                         // But when it is /**/, just do nothing.
3683                                                         if (peek_char () == '/') {
3684                                                                 get_char ();
3685                                                                 continue;
3686                                                         }
3687                                                         if (doc_state == XmlCommentState.Allowed)
3688                                                                 docAppend = true;
3689                                                         else if (doc_state == XmlCommentState.NotAllowed) {
3690                                                                 WarningMisplacedComment (Location - 2);
3691                                                         }
3692                                                 }
3693
3694                                                 int current_comment_start = 0;
3695                                                 if (docAppend) {
3696                                                         current_comment_start = xml_comment_buffer.Length;
3697                                                         xml_comment_buffer.Append (Environment.NewLine);
3698                                                 }
3699
3700                                                 while ((d = get_char ()) != -1){
3701                                                         if (d == '*' && peek_char () == '/'){
3702                                                                 get_char ();
3703                                                                 comments_seen = true;
3704                                                                 break;
3705                                                         }
3706                                                         if (docAppend)
3707                                                                 xml_comment_buffer.Append ((char) d);
3708                                                         
3709                                                         if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3710                                                                 any_token_seen |= tokens_seen;
3711                                                                 tokens_seen = false;
3712                                                                 // 
3713                                                                 // Reset 'comments_seen' just to be consistent.
3714                                                                 // It doesn't matter either way, here.
3715                                                                 //
3716                                                                 comments_seen = false;
3717                                                         }
3718                                                 }
3719                                                 if (!comments_seen)
3720                                                         Report.Error (1035, Location, "End-of-file found, '*/' expected");
3721
3722                                                 if (docAppend)
3723                                                         update_formatted_doc_comment (current_comment_start);
3724                                                 continue;
3725                                         }
3726                                         val = ltb.Create (current_source, ref_line, col);
3727                                         return Token.DIV;
3728
3729                                 case '%':
3730                                         val = ltb.Create (current_source, ref_line, col);
3731                                         if (peek_char () == '='){
3732                                                 get_char ();
3733                                                 return Token.OP_MOD_ASSIGN;
3734                                         }
3735                                         return Token.PERCENT;
3736
3737                                 case '^':
3738                                         val = ltb.Create (current_source, ref_line, col);
3739                                         if (peek_char () == '='){
3740                                                 get_char ();
3741                                                 return Token.OP_XOR_ASSIGN;
3742                                         }
3743                                         return Token.CARRET;
3744
3745                                 case ':':
3746                                         val = ltb.Create (current_source, ref_line, col);
3747                                         if (peek_char () == ':') {
3748                                                 get_char ();
3749                                                 return Token.DOUBLE_COLON;
3750                                         }
3751                                         return Token.COLON;
3752
3753                                 case '0': case '1': case '2': case '3': case '4':
3754                                 case '5': case '6': case '7': case '8': case '9':
3755                                         tokens_seen = true;
3756                                         return is_number (c, false);
3757
3758                                 case '\n': // white space
3759                                 case UnicodeLS:
3760                                 case UnicodePS:
3761                                         any_token_seen |= tokens_seen;
3762                                         tokens_seen = false;
3763                                         comments_seen = false;
3764                                         continue;
3765
3766                                 case '.':
3767                                         tokens_seen = true;
3768                                         d = peek_char ();
3769                                         if (d >= '0' && d <= '9')
3770                                                 return is_number (c, true);
3771
3772                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3773                                         return Token.DOT;
3774                                 
3775                                 case '#':
3776                                         if (tokens_seen || comments_seen) {
3777                                                 Eror_WrongPreprocessorLocation ();
3778                                                 return Token.ERROR;
3779                                         }
3780                                         
3781                                         if (ParsePreprocessingDirective (true))
3782                                                 continue;
3783
3784                                         bool directive_expected = false;
3785                                         while ((c = get_char ()) != -1) {
3786                                                 if (col == 1) {
3787                                                         directive_expected = true;
3788                                                 } else if (!directive_expected) {
3789                                                         // TODO: Implement comment support for disabled code and uncomment this code
3790 //                                                      if (c == '#') {
3791 //                                                              Eror_WrongPreprocessorLocation ();
3792 //                                                              return Token.ERROR;
3793 //                                                      }
3794                                                         continue;
3795                                                 }
3796
3797                                                 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3798                                                         continue;
3799
3800                                                 if (c == '#') {
3801                                                         if (ParsePreprocessingDirective (false))
3802                                                                 break;
3803                                                 }
3804                                                 directive_expected = false;
3805                                         }
3806
3807                                         if (c != -1) {
3808                                                 tokens_seen = false;
3809                                                 continue;
3810                                         }
3811
3812                                         return Token.EOF;
3813                                 
3814                                 case '"':
3815                                         if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3816                                                 parsing_string_interpolation = 0;
3817                                                 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3818                                                 val = new StringLiteral (context.BuiltinTypes, "", Location);
3819                                                 return Token.INTERPOLATED_STRING_END;
3820                                         }
3821
3822                                         return consume_string (false);
3823
3824                                 case '\'':
3825                                         return TokenizeBackslash ();
3826                                 
3827                                 case '@':
3828                                         c = get_char ();
3829                                         if (c == '"') {
3830                                                 tokens_seen = true;
3831                                                 return consume_string (true);
3832                                         }
3833
3834                                         if (is_identifier_start_character (c)){
3835                                                 return consume_identifier (c, true);
3836                                         }
3837
3838                                         Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3839                                         return Token.ERROR;
3840
3841                                 case '$':
3842                                         switch (peek_char ()) {
3843                                         case '"':
3844                                                 get_char ();
3845                                                 return TokenizeInterpolatedString (false);
3846                                         case '@':
3847                                                 get_char ();
3848                                                 if (peek_char () == '"') {
3849                                                         get_char ();
3850                                                         return TokenizeInterpolatedString (true);
3851                                                 }
3852
3853                                                 break;
3854                                         }
3855
3856                                         break;
3857                                 case EvalStatementParserCharacter:
3858                                         return Token.EVAL_STATEMENT_PARSER;
3859                                 case EvalCompilationUnitParserCharacter:
3860                                         return Token.EVAL_COMPILATION_UNIT_PARSER;
3861                                 case EvalUsingDeclarationsParserCharacter:
3862                                         return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3863                                 case DocumentationXref:
3864                                         return Token.DOC_SEE;
3865                                 }
3866
3867                                 if (is_identifier_start_character (c)) {
3868                                         tokens_seen = true;
3869                                         return consume_identifier (c);
3870                                 }
3871
3872                                 if (char.IsWhiteSpace ((char) c))
3873                                         continue;
3874
3875                                 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3876                         }
3877
3878                         if (CompleteOnEOF){
3879                                 if (generated)
3880                                         return Token.COMPLETE_COMPLETION;
3881                                 
3882                                 generated = true;
3883                                 return Token.GENERATE_COMPLETION;
3884                         }
3885                         
3886
3887                         return Token.EOF;
3888                 }
3889
3890                 int TokenizeBackslash ()
3891                 {
3892 #if FULL_AST
3893                         int read_start = reader.Position;
3894 #endif
3895                         Location start_location = Location;
3896                         int c = get_char ();
3897                         tokens_seen = true;
3898                         if (c == '\'') {
3899                                 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3900                                 Report.Error (1011, start_location, "Empty character literal");
3901                                 return Token.LITERAL;
3902                         }
3903
3904                         if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3905                                 Report.Error (1010, start_location, "Newline in constant");
3906                                 return Token.ERROR;
3907                         }
3908
3909                         int d;
3910                         c = escape (c, out d);
3911                         if (c == -1)
3912                                 return Token.ERROR;
3913                         if (d != 0)
3914                                 throw new NotImplementedException ();
3915
3916                         ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3917                         val = res;
3918                         c = get_char ();
3919
3920                         if (c != '\'') {
3921                                 Report.Error (1012, start_location, "Too many characters in character literal");
3922
3923                                 // Try to recover, read until newline or next "'"
3924                                 while ((c = get_char ()) != -1) {
3925                                         if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3926                                                 break;
3927                                 }
3928                         }
3929
3930 #if FULL_AST
3931                         res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3932 #endif
3933
3934                         return Token.LITERAL;
3935                 }
3936
3937                 int TokenizeLessThan ()
3938                 {
3939                         int d;
3940
3941                         // Save current position and parse next token.
3942                         PushPosition ();
3943                         int generic_dimension = 0;
3944                         if (parse_less_than (ref generic_dimension)) {
3945                                 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3946                                         d = Token.OP_GENERICS_LT_DECL;
3947                                 } else {
3948                                         if (generic_dimension > 0) {
3949                                                 val = generic_dimension;
3950                                                 DiscardPosition ();
3951                                                 return Token.GENERIC_DIMENSION;
3952                                         }
3953
3954                                         d = Token.OP_GENERICS_LT;
3955                                 }
3956                                 PopPosition ();
3957                                 return d;
3958                         }
3959
3960                         PopPosition ();
3961                         parsing_generic_less_than = 0;
3962
3963                         d = peek_char ();
3964                         if (d == '<') {
3965                                 get_char ();
3966                                 d = peek_char ();
3967
3968                                 if (d == '=') {
3969                                         get_char ();
3970                                         return Token.OP_SHIFT_LEFT_ASSIGN;
3971                                 }
3972                                 return Token.OP_SHIFT_LEFT;
3973                         }
3974
3975                         if (d == '=') {
3976                                 get_char ();
3977                                 return Token.OP_LE;
3978                         }
3979                         return Token.OP_LT;
3980                 }
3981
3982                 int TokenizeInterpolatedString (bool quoted)
3983                 {
3984                         int pos = 0;
3985                         var start_location = Location;
3986
3987                         while (true) {
3988                                 var ch = get_char ();
3989                                 switch (ch) {
3990                                 case '"':
3991                                         if (quoted && peek_char () == '"') {
3992                                                 get_char ();
3993                                                 break;
3994                                         }
3995
3996                                         val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3997                                         return Token.INTERPOLATED_STRING_END;
3998                                 case '{':
3999                                         if (peek_char () == '{') {
4000                                                 value_builder [pos++] = (char)ch;
4001                                                 get_char ();
4002                                                 break;
4003                                         }
4004
4005                                         ++parsing_string_interpolation;
4006                                         if (quoted) {
4007                                                 if (parsing_string_interpolation_quoted == null)
4008                                                         parsing_string_interpolation_quoted = new Stack<bool> ();
4009                                         }
4010
4011                                         if (parsing_string_interpolation_quoted != null) {
4012                                                 parsing_string_interpolation_quoted.Push (quoted);
4013                                         }
4014
4015                                         val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
4016                                         return Token.INTERPOLATED_STRING;
4017                                 case '\\':
4018                                         if (quoted)
4019                                                 break;
4020                                         
4021                                         ++col;
4022                                         int surrogate;
4023                                         ch = escape (ch, out surrogate);
4024                                         if (ch == -1)
4025                                                 return Token.ERROR;
4026
4027                                         if (ch == '{' || ch == '}') {
4028                                                 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4029                                         }
4030
4031                                         if (surrogate != 0) {
4032                                                 if (pos == value_builder.Length)
4033                                                         Array.Resize (ref value_builder, pos * 2);
4034
4035                                                 if (pos == value_builder.Length)
4036                                                         Array.Resize (ref value_builder, pos * 2);
4037
4038                                                 value_builder [pos++] = (char)ch;
4039                                                 ch = surrogate;
4040                                         }
4041
4042                                         break;
4043                                 case -1:
4044                                         return Token.EOF;
4045                                 }
4046
4047                                 ++col;
4048                                 if (pos == value_builder.Length)
4049                                         Array.Resize (ref value_builder, pos * 2);
4050
4051                                 value_builder[pos++] = (char) ch;
4052                         }
4053                 }
4054
4055                 int TokenizeInterpolationFormat ()
4056                 {
4057                         int pos = 0;
4058                         int braces = 0;
4059                         while (true) {
4060                                 var ch = get_char ();
4061                                 switch (ch) {
4062                                 case '{':
4063                                         ++braces;
4064                                         break;
4065                                 case '}':
4066                                         if (braces == 0) {
4067                                                 putback_char = ch;
4068                                                 if (pos == 0) {
4069                                                         Report.Error (8089, Location, "Empty interpolated expression format specifier");
4070                                                 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
4071                                                         Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
4072                                                 }
4073
4074                                                 val = CreateStringFromBuilder (pos);
4075                                                 return Token.LITERAL;
4076                                         }
4077
4078                                         --braces;
4079                                         break;
4080                                 case '\\':
4081                                         if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Peek ())
4082                                                 break;
4083
4084                                         ++col;
4085                                         int surrogate;
4086                                         ch = escape (ch, out surrogate);
4087                                         if (ch == -1)
4088                                                 return Token.ERROR;
4089
4090                                         if (ch == '{' || ch == '}') {
4091                                                 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4092                                         }
4093
4094                                         if (surrogate != 0) {
4095                                                 if (pos == value_builder.Length)
4096                                                         Array.Resize (ref value_builder, pos * 2);
4097
4098                                                 value_builder [pos++] = (char)ch;
4099                                                 ch = surrogate;
4100                                         }
4101
4102                                         break;
4103                                 case -1:
4104                                         return Token.EOF;
4105                                 }
4106
4107                                 ++col;
4108                                 value_builder[pos++] = (char) ch;
4109                         }
4110                 }
4111
4112                 string CreateStringFromBuilder (int pos)
4113                 {
4114                         if (pos == 0)
4115                                 return string.Empty;
4116                         if (pos <= 4)
4117                                 return InternIdentifier (value_builder, pos);
4118
4119                         return new string (value_builder, 0, pos);
4120                 }
4121
4122                 //
4123                 // Handles one line xml comment
4124                 //
4125                 private void handle_one_line_xml_comment ()
4126                 {
4127                         int c;
4128                         while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4129                                 xml_comment_buffer.Append ((char) get_char ());
4130                         }
4131                         if (c == '\r' || c == '\n')
4132                                 xml_comment_buffer.Append (Environment.NewLine);
4133                 }
4134
4135                 //
4136                 // Remove heading "*" in Javadoc-like xml documentation.
4137                 //
4138                 private void update_formatted_doc_comment (int current_comment_start)
4139                 {
4140                         int length = xml_comment_buffer.Length - current_comment_start;
4141                         string [] lines = xml_comment_buffer.ToString (
4142                                 current_comment_start,
4143                                 length).Replace ("\r", "").Split ('\n');
4144                         
4145                         // The first line starts with /**, thus it is not target
4146                         // for the format check.
4147                         for (int i = 1; i < lines.Length; i++) {
4148                                 string s = lines [i];
4149                                 int idx = s.IndexOf ('*');
4150                                 string head = null;
4151                                 if (idx < 0) {
4152                                         if (i < lines.Length - 1)
4153                                                 return;
4154                                         head = s;
4155                                 } else
4156                                         head = s.Substring (0, idx);
4157                                 foreach (char c in head)
4158                                         if (c != ' ')
4159                                                 return;
4160                                 lines [i] = s.Substring (idx + 1);
4161                         }
4162                         xml_comment_buffer.Remove (current_comment_start, length);
4163                         xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4164                 }
4165
4166                 //
4167                 // Checks if there was incorrect doc comments and raise
4168                 // warnings.
4169                 //
4170                 public void check_incorrect_doc_comment ()
4171                 {
4172                         if (xml_comment_buffer.Length > 0)
4173                                 WarningMisplacedComment (Location);
4174                 }
4175
4176                 //
4177                 // Consumes the saved xml comment lines (if any)
4178                 // as for current target member or type.
4179                 //
4180                 public string consume_doc_comment ()
4181                 {
4182                         if (xml_comment_buffer.Length > 0) {
4183                                 string ret = xml_comment_buffer.ToString ();
4184                                 reset_doc_comment ();
4185                                 return ret;
4186                         }
4187                         return null;
4188                 }
4189
4190                 void reset_doc_comment ()
4191                 {
4192                         xml_comment_buffer.Length = 0;
4193                 }
4194
4195                 public void cleanup ()
4196                 {
4197                         if (ifstack != null && ifstack.Count >= 1) {
4198                                 int state = ifstack.Pop ();
4199                                 if ((state & REGION) != 0)
4200                                         Report.Error (1038, Location, "#endregion directive expected");
4201                                 else 
4202                                         Report.Error (1027, Location, "Expected `#endif' directive");
4203                         }
4204                 }
4205         }
4206
4207         //
4208         // Indicates whether it accepts XML documentation or not.
4209         //
4210         public enum XmlCommentState {
4211                 // comment is allowed in this state.
4212                 Allowed,
4213                 // comment is not allowed in this state.
4214                 NotAllowed,
4215                 // once comments appeared when it is NotAllowed, then the
4216                 // state is changed to it, until the state is changed to
4217                 // .Allowed.
4218                 Error
4219         }
4220 }
4221