d6314ff005a3222079d9eb1eb746b258780da2f8
[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                         }
898
899
900                         return res;
901                 }
902
903                 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
904                 {
905                         //
906                         // Keywords are stored in an array of arrays grouped by their
907                         // length and then by the first character
908                         //
909                         if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
910                                 return PreprocessorDirective.Invalid;
911
912                         int first_index = id[0] - '_';
913                         if (first_index > 'z' - '_')
914                                 return PreprocessorDirective.Invalid;
915
916                         var kwe = keywords_preprocessor[id_len][first_index];
917                         if (kwe == null)
918                                 return PreprocessorDirective.Invalid;
919
920                         PreprocessorDirective res = PreprocessorDirective.Invalid;
921                         do {
922                                 res = kwe.Token;
923                                 for (int i = 1; i < id_len; ++i) {
924                                         if (id[i] != kwe.Value[i]) {
925                                                 res = 0;
926                                                 kwe = kwe.Next;
927                                                 break;
928                                         }
929                                 }
930                         } while (res == PreprocessorDirective.Invalid && kwe != null);
931
932                         return res;
933                 }
934
935                 public Location Location {
936                         get {
937                                 return new Location (current_source, ref_line, col);
938                         }
939                 }
940
941                 static bool is_identifier_start_character (int c)
942                 {
943                         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')
944                                 return true;
945
946                         if (c < 0x80)
947                                 return false;
948
949                         return is_identifier_start_character_slow_part ((char) c);
950                 }
951
952                 static bool is_identifier_part_character (char c)
953                 {
954                         if (c >= 'a' && c <= 'z')
955                                 return true;
956
957                         if (c >= 'A' && c <= 'Z')
958                                 return true;
959
960                         if (c == '_' || (c >= '0' && c <= '9'))
961                                 return true;
962
963                         if (c < 0x80)
964                                 return false;
965
966                         return is_identifier_part_character_slow_part (c);
967                 }
968
969                 static bool is_identifier_start_character_slow_part (char c)
970                 {
971                         switch (Char.GetUnicodeCategory (c)) {
972                         case UnicodeCategory.LetterNumber:
973                         case UnicodeCategory.UppercaseLetter:
974                         case UnicodeCategory.LowercaseLetter:
975                         case UnicodeCategory.TitlecaseLetter:
976                         case UnicodeCategory.ModifierLetter:
977                         case UnicodeCategory.OtherLetter:
978                                 return true;
979                         }
980                         return false;
981                 }
982
983                 static bool is_identifier_part_character_slow_part (char c)
984                 {
985                         switch (Char.GetUnicodeCategory (c)) {
986                         // connecting-character:  A Unicode character of the class Pc
987                         case UnicodeCategory.ConnectorPunctuation:
988
989                         // combining-character: A Unicode character of classes Mn or Mc
990                         case UnicodeCategory.NonSpacingMark:
991                         case UnicodeCategory.SpacingCombiningMark:
992
993                         // decimal-digit-character: A Unicode character of the class Nd 
994                         case UnicodeCategory.DecimalDigitNumber:
995
996                         // plus is_identifier_start_character_slow_part
997                         case UnicodeCategory.LetterNumber:
998                         case UnicodeCategory.UppercaseLetter:
999                         case UnicodeCategory.LowercaseLetter:
1000                         case UnicodeCategory.TitlecaseLetter:
1001                         case UnicodeCategory.ModifierLetter:
1002                         case UnicodeCategory.OtherLetter:
1003                                 return true;
1004
1005                         // formatting-character: A Unicode character of the class Cf
1006                         case UnicodeCategory.Format:
1007                                 // csc bug compatibility which recognizes it as a whitespace
1008                                 return c != 0xFEFF;
1009                         }
1010
1011                         return false;
1012                 }
1013
1014                 public static bool IsKeyword (string s)
1015                 {
1016                         return keyword_strings.Contains (s);
1017                 }
1018
1019                 //
1020                 // Open parens micro parser. Detects both lambda and cast ambiguity.
1021                 //      
1022                 int TokenizeOpenParens ()
1023                 {
1024                         int ptoken;
1025                         current_token = -1;
1026
1027                         int bracket_level = 0;
1028                         bool is_type = false;
1029                         bool can_be_type = false;
1030                         
1031                         while (true) {
1032                                 ptoken = current_token;
1033                                 token ();
1034
1035                                 switch (current_token) {
1036                                 case Token.CLOSE_PARENS:
1037                                         token ();
1038                                         
1039                                         //
1040                                         // Expression inside parens is lambda, (int i) => 
1041                                         //
1042                                         if (current_token == Token.ARROW)
1043                                                 return Token.OPEN_PARENS_LAMBDA;
1044
1045                                         //
1046                                         // Expression inside parens is single type, (int[])
1047                                         //
1048                                         if (is_type) {
1049                                                 if (current_token == Token.SEMICOLON)
1050                                                         return Token.OPEN_PARENS;
1051
1052                                                 return Token.OPEN_PARENS_CAST;
1053                                         }
1054
1055                                         //
1056                                         // Expression is possible cast, look at next token, (T)null
1057                                         //
1058                                         if (can_be_type) {
1059                                                 switch (current_token) {
1060                                                 case Token.OPEN_PARENS:
1061                                                 case Token.BANG:
1062                                                 case Token.TILDE:
1063                                                 case Token.IDENTIFIER:
1064                                                 case Token.LITERAL:
1065                                                 case Token.BASE:
1066                                                 case Token.CHECKED:
1067                                                 case Token.DELEGATE:
1068                                                 case Token.FALSE:
1069                                                 case Token.FIXED:
1070                                                 case Token.NEW:
1071                                                 case Token.NULL:
1072                                                 case Token.SIZEOF:
1073                                                 case Token.THIS:
1074                                                 case Token.THROW:
1075                                                 case Token.TRUE:
1076                                                 case Token.TYPEOF:
1077                                                 case Token.UNCHECKED:
1078                                                 case Token.UNSAFE:
1079                                                 case Token.DEFAULT:
1080                                                 case Token.AWAIT:
1081
1082                                                 //
1083                                                 // These can be part of a member access
1084                                                 //
1085                                                 case Token.INT:
1086                                                 case Token.UINT:
1087                                                 case Token.SHORT:
1088                                                 case Token.USHORT:
1089                                                 case Token.LONG:
1090                                                 case Token.ULONG:
1091                                                 case Token.DOUBLE:
1092                                                 case Token.FLOAT:
1093                                                 case Token.CHAR:
1094                                                 case Token.BYTE:
1095                                                 case Token.DECIMAL:
1096                                                 case Token.BOOL:
1097                                                 case Token.STRING:
1098                                                 case Token.SBYTE:
1099                                                         return Token.OPEN_PARENS_CAST;
1100                                                 }
1101                                         }
1102                                         return Token.OPEN_PARENS;
1103                                         
1104                                 case Token.DOT:
1105                                 case Token.DOUBLE_COLON:
1106                                         if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
1107                                                 goto default;
1108
1109                                         continue;
1110
1111                                 case Token.IDENTIFIER:
1112                                 case Token.AWAIT:
1113                                         switch (ptoken) {
1114                                         case Token.DOT:
1115                                                 if (bracket_level == 0) {
1116                                                         is_type = false;
1117                                                         can_be_type = true;
1118                                                 }
1119
1120                                                 continue;
1121                                         case Token.OP_GENERICS_LT:
1122                                         case Token.COMMA:
1123                                         case Token.DOUBLE_COLON:
1124                                         case -1:
1125                                                 if (bracket_level == 0)
1126                                                         can_be_type = true;
1127                                                 continue;
1128                                         default:
1129                                                 can_be_type = is_type = false;
1130                                                 continue;
1131                                         }
1132
1133                                 case Token.OBJECT:
1134                                 case Token.STRING:
1135                                 case Token.BOOL:
1136                                 case Token.DECIMAL:
1137                                 case Token.FLOAT:
1138                                 case Token.DOUBLE:
1139                                 case Token.SBYTE:
1140                                 case Token.BYTE:
1141                                 case Token.SHORT:
1142                                 case Token.USHORT:
1143                                 case Token.INT:
1144                                 case Token.UINT:
1145                                 case Token.LONG:
1146                                 case Token.ULONG:
1147                                 case Token.CHAR:
1148                                 case Token.VOID:
1149                                         if (bracket_level == 0)
1150                                                 is_type = true;
1151                                         continue;
1152
1153                                 case Token.COMMA:
1154                                         if (bracket_level == 0) {
1155                                                 bracket_level = 100;
1156                                                 can_be_type = is_type = false;
1157                                         }
1158                                         continue;
1159
1160                                 case Token.OP_GENERICS_LT:
1161                                 case Token.OPEN_BRACKET:
1162                                         if (bracket_level++ == 0)
1163                                                 is_type = true;
1164                                         continue;
1165
1166                                 case Token.OP_GENERICS_GT:
1167                                 case Token.CLOSE_BRACKET:
1168                                         --bracket_level;
1169                                         continue;
1170
1171                                 case Token.INTERR_NULLABLE:
1172                                 case Token.STAR:
1173                                         if (bracket_level == 0)
1174                                                 is_type = true;
1175                                         continue;
1176
1177                                 case Token.REF:
1178                                 case Token.OUT:
1179                                         can_be_type = is_type = false;
1180                                         continue;
1181
1182                                 default:
1183                                         return Token.OPEN_PARENS;
1184                                 }
1185                         }
1186                 }
1187
1188                 public static bool IsValidIdentifier (string s)
1189                 {
1190                         if (s == null || s.Length == 0)
1191                                 return false;
1192
1193                         if (!is_identifier_start_character (s [0]))
1194                                 return false;
1195                         
1196                         for (int i = 1; i < s.Length; i ++)
1197                                 if (! is_identifier_part_character (s [i]))
1198                                         return false;
1199                         
1200                         return true;
1201                 }
1202
1203                 bool parse_less_than (ref int genericDimension)
1204                 {
1205                 start:
1206                         int the_token = token ();
1207                         if (the_token == Token.OPEN_BRACKET) {
1208                                 while (true) {
1209                                         the_token = token ();
1210                                         if (the_token == Token.EOF)
1211                                                 return true;
1212
1213                                         if (the_token == Token.CLOSE_BRACKET)
1214                                                 break;
1215                                 }
1216                                 the_token = token ();
1217                         } else if (the_token == Token.IN || the_token == Token.OUT) {
1218                                 the_token = token ();
1219                         }
1220                         switch (the_token) {
1221                         case Token.IDENTIFIER:
1222                         case Token.OBJECT:
1223                         case Token.STRING:
1224                         case Token.BOOL:
1225                         case Token.DECIMAL:
1226                         case Token.FLOAT:
1227                         case Token.DOUBLE:
1228                         case Token.SBYTE:
1229                         case Token.BYTE:
1230                         case Token.SHORT:
1231                         case Token.USHORT:
1232                         case Token.INT:
1233                         case Token.UINT:
1234                         case Token.LONG:
1235                         case Token.ULONG:
1236                         case Token.CHAR:
1237                         case Token.VOID:
1238                                 break;
1239                         case Token.OP_GENERICS_GT:
1240                                 genericDimension = 1;
1241                                 return true;
1242                         case Token.IN:
1243                         case Token.OUT:
1244                                 return true;
1245                         case Token.COMMA:
1246                                 do {
1247                                         ++genericDimension;
1248                                         the_token = token ();
1249                                 } while (the_token == Token.COMMA);
1250
1251                                 if (the_token == Token.OP_GENERICS_GT) {
1252                                         ++genericDimension;
1253                                         return true;
1254                                 }
1255
1256                                 return false;
1257                         default:
1258                                 return false;
1259                         }
1260                 again:
1261                         the_token = token ();
1262
1263                         if (the_token == Token.OP_GENERICS_GT)
1264                                 return true;
1265                         else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1266                                 goto start;
1267                         else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1268                                 goto again;
1269                         else if (the_token == Token.OP_GENERICS_LT) {
1270                                 int unused = 0;
1271                                 if (!parse_less_than (ref unused))
1272                                         return false;
1273                                 goto again;
1274                         } else if (the_token == Token.OPEN_BRACKET) {
1275                         rank_specifiers:
1276                                 the_token = token ();
1277                                 if (the_token == Token.CLOSE_BRACKET)
1278                                         goto again;
1279                                 else if (the_token == Token.COMMA)
1280                                         goto rank_specifiers;
1281                                 return false;
1282                         }
1283
1284                         return false;
1285                 }
1286
1287                 public int peek_token ()
1288                 {
1289                         int the_token;
1290
1291                         PushPosition ();
1292                         the_token = token ();
1293                         PopPosition ();
1294                         
1295                         return the_token;
1296                 }
1297                                         
1298                 //
1299                 // Tonizes `?' using custom disambiguous rules to return one
1300                 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1301                 //
1302                 // Tricky expression looks like:
1303                 //
1304                 // Foo ? a = x ? b : c;
1305                 //
1306                 int TokenizePossibleNullableType ()
1307                 {
1308                         if (parsing_block == 0 || parsing_type > 0)
1309                                 return Token.INTERR_NULLABLE;
1310
1311                         int d = peek_char ();
1312                         if (d == '?') {
1313                                 get_char ();
1314                                 return Token.OP_COALESCING;
1315                         }
1316
1317                         if (d == '.') {
1318                                 return Token.INTERR_OPERATOR;
1319                         }
1320
1321                         if (d != ' ') {
1322                                 if (d == ',' || d == ';' || d == '>')
1323                                         return Token.INTERR_NULLABLE;
1324                                 if (d == '*' || (d >= '0' && d <= '9'))
1325                                         return Token.INTERR;
1326                         }
1327
1328                         PushPosition ();
1329                         current_token = Token.NONE;
1330                         int next_token;
1331                         int parens = 0;
1332                         int generics = 0;
1333                         int brackets = 0;
1334
1335                         var nt = xtoken ();
1336                         switch (nt) {
1337                         case Token.DOT:
1338                         case Token.OPEN_BRACKET_EXPR:
1339                                 next_token = Token.INTERR_OPERATOR;
1340                                 break;
1341                         case Token.LITERAL:
1342                         case Token.TRUE:
1343                         case Token.FALSE:
1344                         case Token.NULL:
1345                         case Token.THIS:
1346                         case Token.NEW:
1347                         case Token.INTERPOLATED_STRING:
1348                                 next_token = Token.INTERR;
1349                                 break;
1350                                 
1351                         case Token.SEMICOLON:
1352                         case Token.COMMA:
1353                         case Token.CLOSE_PARENS:
1354                         case Token.OPEN_BRACKET:
1355                         case Token.OP_GENERICS_GT:
1356                         case Token.INTERR:
1357                         case Token.OP_COALESCING:
1358                         case Token.COLON:
1359                                 next_token = Token.INTERR_NULLABLE;
1360                                 break;
1361
1362                         case Token.OPEN_PARENS:
1363                         case Token.OPEN_PARENS_CAST:
1364                         case Token.OPEN_PARENS_LAMBDA:
1365                                 next_token = -1;
1366                                 ++parens;
1367                                 break;
1368
1369                         case Token.OP_GENERICS_LT:
1370                         case Token.OP_GENERICS_LT_DECL:
1371                         case Token.GENERIC_DIMENSION:
1372                                 next_token = -1;
1373                                 ++generics;
1374                                 break;
1375
1376                         default:
1377                                 next_token = -1;
1378                                 break;
1379                         }
1380
1381                         if (next_token == -1) {
1382                                 switch (xtoken ()) {
1383                                 case Token.COMMA:
1384                                 case Token.SEMICOLON:
1385                                 case Token.OPEN_BRACE:
1386                                 case Token.IN:
1387                                         next_token = Token.INTERR_NULLABLE;
1388                                         break;
1389                                         
1390                                 case Token.COLON:
1391                                         next_token = Token.INTERR;
1392                                         break;
1393
1394                                 case Token.OPEN_PARENS:
1395                                 case Token.OPEN_PARENS_CAST:
1396                                 case Token.OPEN_PARENS_LAMBDA:
1397                                         ++parens;
1398                                         goto default;
1399
1400                                 case Token.OPEN_BRACKET:
1401                                 case Token.OPEN_BRACKET_EXPR:
1402                                         ++brackets;
1403                                         goto default;
1404
1405                                 case Token.CLOSE_PARENS:
1406                                         --parens;
1407                                         goto default;
1408
1409                                 case Token.OP_GENERICS_LT:
1410                                 case Token.OP_GENERICS_LT_DECL:
1411                                 case Token.GENERIC_DIMENSION:
1412                                         ++generics;
1413                                         goto default;
1414
1415                                 default:
1416                                         int ntoken;
1417                                         int interrs = 1;
1418                                         int colons = 0;
1419                                         int braces = 0;
1420                                         //
1421                                         // All shorcuts failed, do it hard way
1422                                         //
1423                                         while ((ntoken = xtoken ()) != Token.EOF) {
1424                                                 switch (ntoken) {
1425                                                 case Token.OPEN_BRACE:
1426                                                         ++braces;
1427                                                         continue;
1428                                                 case Token.OPEN_PARENS:
1429                                                 case Token.OPEN_PARENS_CAST:
1430                                                 case Token.OPEN_PARENS_LAMBDA:
1431                                                         ++parens;
1432                                                         continue;
1433                                                 case Token.CLOSE_BRACE:
1434                                                         --braces;
1435                                                         continue;
1436                                                 case Token.OP_GENERICS_LT:
1437                                                 case Token.OP_GENERICS_LT_DECL:
1438                                                 case Token.GENERIC_DIMENSION:
1439                                                         ++generics;
1440                                                         continue;
1441                                                 case Token.OPEN_BRACKET:
1442                                                 case Token.OPEN_BRACKET_EXPR:
1443                                                         ++brackets;
1444                                                         continue;
1445                                                 case Token.CLOSE_BRACKET:
1446                                                         --brackets;
1447                                                         continue;
1448                                                 case Token.CLOSE_PARENS:
1449                                                         if (parens > 0) {
1450                                                                 --parens;
1451                                                                 continue;
1452                                                         }
1453
1454                                                         PopPosition ();
1455                                                         return Token.INTERR_NULLABLE;
1456
1457                                                 case Token.OP_GENERICS_GT:
1458                                                         if (generics > 0) {
1459                                                                 --generics;
1460                                                                 continue;
1461                                                         }
1462
1463                                                         PopPosition ();
1464                                                         return Token.INTERR_NULLABLE;
1465                                                 }
1466
1467                                                 if (braces != 0)
1468                                                         continue;
1469
1470                                                 if (ntoken == Token.SEMICOLON)
1471                                                         break;
1472
1473                                                 if (parens != 0)
1474                                                         continue;
1475
1476                                                 if (ntoken == Token.COMMA) {
1477                                                         if (generics != 0 || brackets != 0)
1478                                                                 continue;
1479
1480                                                         PopPosition ();
1481                                                         return Token.INTERR_NULLABLE;
1482                                                 }
1483                                                 
1484                                                 if (ntoken == Token.COLON) {
1485                                                         if (++colons == interrs)
1486                                                                 break;
1487                                                         continue;
1488                                                 }
1489                                                 
1490                                                 if (ntoken == Token.INTERR) {
1491                                                         ++interrs;
1492                                                         continue;
1493                                                 }
1494                                         }
1495                                         
1496                                         next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
1497                                         break;
1498                                 }
1499                         }
1500                         
1501                         PopPosition ();
1502                         return next_token;
1503                 }
1504
1505                 bool decimal_digits (int c)
1506                 {
1507                         int d;
1508                         bool seen_digits = false;
1509                         
1510                         if (c != -1){
1511                                 if (number_pos == MaxNumberLength)
1512                                         Error_NumericConstantTooLong ();
1513                                 number_builder [number_pos++] = (char) c;
1514                         }
1515                         
1516                         //
1517                         // We use peek_char2, because decimal_digits needs to do a 
1518                         // 2-character look-ahead (5.ToString for example).
1519                         //
1520                         while ((d = peek_char2 ()) != -1){
1521                                 if (d >= '0' && d <= '9'){
1522                                         if (number_pos == MaxNumberLength)
1523                                                 Error_NumericConstantTooLong ();
1524                                         number_builder [number_pos++] = (char) d;
1525                                         get_char ();
1526                                         seen_digits = true;
1527                                 } else
1528                                         break;
1529                         }
1530                         
1531                         return seen_digits;
1532                 }
1533
1534                 static bool is_hex (int e)
1535                 {
1536                         return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1537                 }
1538
1539                 static TypeCode real_type_suffix (int c)
1540                 {
1541                         switch (c){
1542                         case 'F': case 'f':
1543                                 return TypeCode.Single;
1544                         case 'D': case 'd':
1545                                 return TypeCode.Double;
1546                         case 'M': case 'm':
1547                                 return TypeCode.Decimal;
1548                         default:
1549                                 return TypeCode.Empty;
1550                         }
1551                 }
1552
1553                 ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
1554                 {
1555                         bool is_unsigned = false;
1556                         bool is_long = false;
1557
1558                         if (c != -1){
1559                                 bool scanning = true;
1560                                 do {
1561                                         switch (c){
1562                                         case 'U': case 'u':
1563                                                 if (is_unsigned)
1564                                                         scanning = false;
1565                                                 is_unsigned = true;
1566                                                 get_char ();
1567                                                 break;
1568
1569                                         case 'l':
1570                                                 if (!is_unsigned){
1571                                                         //
1572                                                         // if we have not seen anything in between
1573                                                         // report this error
1574                                                         //
1575                                                         Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
1576                                                 }
1577
1578                                                 goto case 'L';
1579
1580                                         case 'L': 
1581                                                 if (is_long)
1582                                                         scanning = false;
1583                                                 is_long = true;
1584                                                 get_char ();
1585                                                 break;
1586                                                 
1587                                         default:
1588                                                 scanning = false;
1589                                                 break;
1590                                         }
1591                                         c = peek_char ();
1592                                 } while (scanning);
1593                         }
1594
1595                         if (is_long && is_unsigned){
1596                                 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1597                         }
1598                         
1599                         if (is_unsigned){
1600                                 // uint if possible, or ulong else.
1601
1602                                 if ((ul & 0xffffffff00000000) == 0)
1603                                         return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
1604                                 else
1605                                         return new ULongLiteral (context.BuiltinTypes, ul, loc);
1606                         } else if (is_long){
1607                                 // long if possible, ulong otherwise
1608                                 if ((ul & 0x8000000000000000) != 0)
1609                                         return new ULongLiteral (context.BuiltinTypes, ul, loc);
1610                                 else
1611                                         return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1612                         } else {
1613                                 // int, uint, long or ulong in that order
1614                                 if ((ul & 0xffffffff00000000) == 0){
1615                                         uint ui = (uint) ul;
1616                                         
1617                                         if ((ui & 0x80000000) != 0)
1618                                                 return new UIntLiteral (context.BuiltinTypes, ui, loc);
1619                                         else
1620                                                 return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
1621                                 } else {
1622                                         if ((ul & 0x8000000000000000) != 0)
1623                                                 return new ULongLiteral (context.BuiltinTypes, ul, loc);
1624                                         else
1625                                                 return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
1626                                 }
1627                         }
1628                 }
1629                                 
1630                 //
1631                 // given `c' as the next char in the input decide whether
1632                 // we need to convert to a special type, and then choose
1633                 // the best representation for the integer
1634                 //
1635                 ILiteralConstant adjust_int (int c, Location loc)
1636                 {
1637                         try {
1638                                 if (number_pos > 9){
1639                                         ulong ul = (uint) (number_builder [0] - '0');
1640
1641                                         for (int i = 1; i < number_pos; i++){
1642                                                 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1643                                         }
1644
1645                                         return integer_type_suffix (ul, c, loc);
1646                                 } else {
1647                                         uint ui = (uint) (number_builder [0] - '0');
1648
1649                                         for (int i = 1; i < number_pos; i++){
1650                                                 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1651                                         }
1652
1653                                         return integer_type_suffix (ui, c, loc);
1654                                 }
1655                         } catch (OverflowException) {
1656                                 Error_NumericConstantTooLong ();
1657                                 return new IntLiteral (context.BuiltinTypes, 0, loc);
1658                         }
1659                         catch (FormatException) {
1660                                 Report.Error (1013, Location, "Invalid number");
1661                                 return new IntLiteral (context.BuiltinTypes, 0, loc);
1662                         }
1663                 }
1664                 
1665                 ILiteralConstant adjust_real (TypeCode t, Location loc)
1666                 {
1667                         string s = new string (number_builder, 0, number_pos);
1668                         const string error_details = "Floating-point constant is outside the range of type `{0}'";
1669
1670                         switch (t){
1671                         case TypeCode.Decimal:
1672                                 try {
1673                                         return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
1674                                 } catch (OverflowException) {
1675                                         Report.Error (594, Location, error_details, "decimal");
1676                                         return new DecimalLiteral (context.BuiltinTypes, 0, loc);
1677                                 }
1678                         case TypeCode.Single:
1679                                 try {
1680                                         return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
1681                                 } catch (OverflowException) {
1682                                         Report.Error (594, Location, error_details, "float");
1683                                         return new FloatLiteral (context.BuiltinTypes, 0, loc);
1684                                 }
1685                         default:
1686                                 try {
1687                                         return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
1688                                 } catch (OverflowException) {
1689                                         Report.Error (594, loc, error_details, "double");
1690                                         return new DoubleLiteral (context.BuiltinTypes, 0, loc);
1691                                 }
1692                         }
1693                 }
1694
1695                 ILiteralConstant handle_hex (Location loc)
1696                 {
1697                         int d;
1698                         ulong ul;
1699                         
1700                         get_char ();
1701                         while ((d = peek_char ()) != -1){
1702                                 if (is_hex (d)){
1703                                         number_builder [number_pos++] = (char) d;
1704                                         get_char ();
1705                                 } else
1706                                         break;
1707                         }
1708                         
1709                         string s = new String (number_builder, 0, number_pos);
1710
1711                         try {
1712                                 if (number_pos <= 8)
1713                                         ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1714                                 else
1715                                         ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1716
1717                                 return integer_type_suffix (ul, peek_char (), loc);
1718                         } catch (OverflowException){
1719                                 Error_NumericConstantTooLong ();
1720                                 return new IntLiteral (context.BuiltinTypes, 0, loc);
1721                         }
1722                         catch (FormatException) {
1723                                 Report.Error (1013, Location, "Invalid number");
1724                                 return new IntLiteral (context.BuiltinTypes, 0, loc);
1725                         }
1726                 }
1727
1728                 //
1729                 // Invoked if we know we have .digits or digits
1730                 //
1731                 int is_number (int c, bool dotLead)
1732                 {
1733                         ILiteralConstant res;
1734
1735 #if FULL_AST
1736                         int read_start = reader.Position - 1;
1737                         if (dotLead) {
1738                                 //
1739                                 // Caller did peek_char
1740                                 //
1741                                 --read_start;
1742                         }
1743 #endif
1744                         number_pos = 0;
1745                         var loc = Location;
1746
1747                         if (!dotLead){
1748                                 if (c == '0'){
1749                                         int peek = peek_char ();
1750
1751                                         if (peek == 'x' || peek == 'X') {
1752                                                 val = res = handle_hex (loc);
1753 #if FULL_AST
1754                                                 res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1755 #endif
1756
1757                                                 return Token.LITERAL;
1758                                         }
1759                                 }
1760                                 decimal_digits (c);
1761                                 c = peek_char ();
1762                         }
1763
1764                         //
1765                         // We need to handle the case of
1766                         // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1767                         //
1768                         bool is_real = false;
1769                         if (c == '.'){
1770                                 if (!dotLead)
1771                                         get_char ();
1772
1773                                 if (decimal_digits ('.')){
1774                                         is_real = true;
1775                                         c = peek_char ();
1776                                 } else {
1777                                         putback ('.');
1778                                         number_pos--;
1779                                         val = res = adjust_int (-1, loc);
1780
1781 #if FULL_AST
1782                                         res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
1783 #endif
1784                                         return Token.LITERAL;
1785                                 }
1786                         }
1787                         
1788                         if (c == 'e' || c == 'E'){
1789                                 is_real = true;
1790                                 get_char ();
1791                                 if (number_pos == MaxNumberLength)
1792                                         Error_NumericConstantTooLong ();
1793                                 number_builder [number_pos++] = (char) c;
1794                                 c = get_char ();
1795                                 
1796                                 if (c == '+'){
1797                                         if (number_pos == MaxNumberLength)
1798                                                 Error_NumericConstantTooLong ();
1799                                         number_builder [number_pos++] = '+';
1800                                         c = -1;
1801                                 } else if (c == '-') {
1802                                         if (number_pos == MaxNumberLength)
1803                                                 Error_NumericConstantTooLong ();
1804                                         number_builder [number_pos++] = '-';
1805                                         c = -1;
1806                                 } else {
1807                                         if (number_pos == MaxNumberLength)
1808                                                 Error_NumericConstantTooLong ();
1809                                         number_builder [number_pos++] = '+';
1810                                 }
1811                                         
1812                                 decimal_digits (c);
1813                                 c = peek_char ();
1814                         }
1815
1816                         var type = real_type_suffix (c);
1817                         if (type == TypeCode.Empty && !is_real) {
1818                                 res = adjust_int (c, loc);
1819                         } else {
1820                                 is_real = true;
1821
1822                                 if (type != TypeCode.Empty) {
1823                                         get_char ();
1824                                 }
1825
1826                                 res = adjust_real (type, loc);
1827                         }
1828
1829                         val = res;
1830
1831 #if FULL_AST
1832                         var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
1833                         if (chars[chars.Length - 1] == '\r')
1834                                 Array.Resize (ref chars, chars.Length - 1);
1835                         res.ParsedValue = chars;
1836 #endif
1837
1838                         return Token.LITERAL;
1839                 }
1840
1841                 //
1842                 // Accepts exactly count (4 or 8) hex, no more no less
1843                 //
1844                 int getHex (int count, out int surrogate, out bool error)
1845                 {
1846                         int i;
1847                         int total = 0;
1848                         int c;
1849                         int top = count != -1 ? count : 4;
1850                         
1851                         get_char ();
1852                         error = false;
1853                         surrogate = 0;
1854                         for (i = 0; i < top; i++){
1855                                 c = get_char ();
1856
1857                                 if (c >= '0' && c <= '9')
1858                                         c = (int) c - (int) '0';
1859                                 else if (c >= 'A' && c <= 'F')
1860                                         c = (int) c - (int) 'A' + 10;
1861                                 else if (c >= 'a' && c <= 'f')
1862                                         c = (int) c - (int) 'a' + 10;
1863                                 else {
1864                                         error = true;
1865                                         return 0;
1866                                 }
1867                                 
1868                                 total = (total * 16) + c;
1869                                 if (count == -1){
1870                                         int p = peek_char ();
1871                                         if (p == -1)
1872                                                 break;
1873                                         if (!is_hex ((char)p))
1874                                                 break;
1875                                 }
1876                         }
1877
1878                         if (top == 8) {
1879                                 if (total > 0x0010FFFF) {
1880                                         error = true;
1881                                         return 0;
1882                                 }
1883
1884                                 if (total >= 0x00010000) {
1885                                         surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);                                   
1886                                         total = ((total - 0x00010000) / 0x0400 + 0xD800);
1887                                 }
1888                         }
1889
1890                         return total;
1891                 }
1892
1893                 int escape (int c, out int surrogate)
1894                 {
1895                         bool error;
1896                         int d;
1897                         int v;
1898
1899                         d = peek_char ();
1900                         if (c != '\\') {
1901                                 surrogate = 0;
1902                                 return c;
1903                         }
1904                         
1905                         switch (d){
1906                         case 'a':
1907                                 v = '\a'; break;
1908                         case 'b':
1909                                 v = '\b'; break;
1910                         case 'n':
1911                                 v = '\n'; break;
1912                         case 't':
1913                                 v = '\t'; break;
1914                         case 'v':
1915                                 v = '\v'; break;
1916                         case 'r':
1917                                 v = '\r'; break;
1918                         case '\\':
1919                                 v = '\\'; break;
1920                         case 'f':
1921                                 v = '\f'; break;
1922                         case '0':
1923                                 v = 0; break;
1924                         case '"':
1925                                 v = '"'; break;
1926                         case '\'':
1927                                 v = '\''; break;
1928                         case 'x':
1929                                 v = getHex (-1, out surrogate, out error);
1930                                 if (error)
1931                                         goto default;
1932                                 return v;
1933                         case 'u':
1934                         case 'U':
1935                                 return EscapeUnicode (d, out surrogate);
1936                         default:
1937                                 surrogate = 0;
1938                                 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1939                                 return d;
1940                         }
1941
1942                         get_char ();
1943                         surrogate = 0;
1944                         return v;
1945                 }
1946
1947                 int EscapeUnicode (int ch, out int surrogate)
1948                 {
1949                         bool error;
1950                         if (ch == 'U') {
1951                                 ch = getHex (8, out surrogate, out error);
1952                         } else {
1953                                 ch = getHex (4, out surrogate, out error);
1954                         }
1955
1956                         if (error)
1957                                 Report.Error (1009, Location, "Unrecognized escape sequence");
1958
1959                         return ch;
1960                 }
1961
1962                 int get_char ()
1963                 {
1964                         int x;
1965                         if (putback_char != -1) {
1966                                 x = putback_char;
1967                                 putback_char = -1;
1968                         } else {
1969                                 x = reader.Read ();
1970                         }
1971                         
1972                         if (x <= 13) {
1973                                 if (x == '\r') {
1974                                         if (peek_char () == '\n') {
1975                                                 putback_char = -1;
1976                                         }
1977
1978                                         x = '\n';
1979                                         advance_line ();
1980                                 } else if (x == '\n') {
1981                                         advance_line ();
1982                                 } else {
1983                                         col++;
1984                                 }
1985                         } else if (x >= UnicodeLS && x <= UnicodePS) {
1986                                 advance_line ();
1987                         } else {
1988                                 col++;
1989                         }
1990
1991                         return x;
1992                 }
1993
1994                 void advance_line ()
1995                 {
1996                         line++;
1997                         ref_line++;
1998                         previous_col = col;
1999                         col = 0;
2000                 }
2001
2002                 int peek_char ()
2003                 {
2004                         if (putback_char == -1)
2005                                 putback_char = reader.Read ();
2006                         return putback_char;
2007                 }
2008
2009                 int peek_char2 ()
2010                 {
2011                         if (putback_char != -1)
2012                                 return putback_char;
2013                         return reader.Peek ();
2014                 }
2015                 
2016                 public void putback (int c)
2017                 {
2018                         if (putback_char != -1) {
2019                                 throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
2020                         }
2021
2022                         if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
2023                                 // It won't happen though.
2024                                 line--;
2025                                 ref_line--;
2026                                 col = previous_col;
2027                         }
2028                         else
2029                                 col--;
2030                         putback_char = c;
2031                 }
2032
2033                 public bool advance ()
2034                 {
2035                         return peek_char () != -1 || CompleteOnEOF;
2036                 }
2037
2038                 public Object Value {
2039                         get {
2040                                 return val;
2041                         }
2042                 }
2043
2044                 public Object value ()
2045                 {
2046                         return val;
2047                 }
2048
2049                 public int token ()
2050                 {
2051                         current_token = xtoken ();
2052                         return current_token;
2053                 }
2054
2055                 int TokenizePreprocessorKeyword (out int c)
2056                 {
2057                         // skip over white space
2058                         do {
2059                                 c = get_char ();
2060                         } while (c == ' ' || c == '\t');
2061
2062
2063                         int pos = 0;
2064                         while (c != -1 && c >= 'a' && c <= 'z') {
2065                                 id_builder[pos++] = (char) c;
2066                                 c = get_char ();
2067                                 if (c == '\\') {
2068                                         int peek = peek_char ();
2069                                         if (peek == 'U' || peek == 'u') {
2070                                                 int surrogate;
2071                                                 c = EscapeUnicode (c, out surrogate);
2072                                                 if (surrogate != 0) {
2073                                                         if (is_identifier_part_character ((char) c)) {
2074                                                                 id_builder[pos++] = (char) c;
2075                                                         }
2076                                                         c = surrogate;
2077                                                 }
2078                                         }
2079                                 }
2080                         }
2081
2082                         return pos;
2083                 }
2084
2085                 PreprocessorDirective get_cmd_arg (out string arg)
2086                 {
2087                         int c;          
2088
2089                         tokens_seen = false;
2090                         arg = "";
2091
2092                         var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorKeyword (out c));
2093
2094                         if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
2095                                 return cmd;
2096
2097                         // skip over white space
2098                         while (c == ' ' || c == '\t')
2099                                 c = get_char ();
2100
2101                         int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
2102                         int pos = 0;
2103
2104                         while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2105                                 if (c == '\\' && has_identifier_argument >= 0) {
2106                                         if (has_identifier_argument != 0) {
2107                                                 has_identifier_argument = 1;
2108
2109                                                 int peek = peek_char ();
2110                                                 if (peek == 'U' || peek == 'u') {
2111                                                         int surrogate;
2112                                                         c = EscapeUnicode (c, out surrogate);
2113                                                         if (surrogate != 0) {
2114                                                                 if (is_identifier_part_character ((char) c)) {
2115                                                                         if (pos == value_builder.Length)
2116                                                                                 Array.Resize (ref value_builder, pos * 2);
2117
2118                                                                         value_builder[pos++] = (char) c;
2119                                                                 }
2120                                                                 c = surrogate;
2121                                                         }
2122                                                 }
2123                                         } else {
2124                                                 has_identifier_argument = -1;
2125                                         }
2126                                 } else if (c == '/' && peek_char () == '/') {
2127                                         //
2128                                         // Eat single-line comments
2129                                         //
2130                                         get_char ();
2131                                         ReadToEndOfLine ();
2132                                         break;
2133                                 }
2134
2135                                 if (pos == value_builder.Length)
2136                                         Array.Resize (ref value_builder, pos * 2);
2137
2138                                 value_builder[pos++] = (char) c;
2139                                 c = get_char ();
2140                         }
2141
2142                         if (pos != 0) {
2143                                 if (pos > MaxIdentifierLength)
2144                                         arg = new string (value_builder, 0, pos);
2145                                 else
2146                                         arg = InternIdentifier (value_builder, pos);
2147
2148                                 // Eat any trailing whitespaces
2149                                 arg = arg.Trim (simple_whitespaces);
2150                         }
2151
2152                         return cmd;
2153                 }
2154
2155                 //
2156                 // Handles the #line directive
2157                 //
2158                 bool PreProcessLine ()
2159                 {
2160                         Location loc = Location;
2161
2162                         int c;
2163
2164                         int length = TokenizePreprocessorKeyword (out c);
2165                         if (length == line_default.Length) {
2166                                 if (!IsTokenIdentifierEqual (line_default))
2167                                         return false;
2168
2169                                 current_source = source_file.SourceFile;
2170                                 if (!hidden_block_start.IsNull) {
2171                                         current_source.RegisterHiddenScope (hidden_block_start, loc);
2172                                         hidden_block_start = Location.Null;
2173                                 }
2174
2175                                 ref_line = line;
2176                                 return true;
2177                         }
2178
2179                         if (length == line_hidden.Length) {
2180                                 if (!IsTokenIdentifierEqual (line_hidden))
2181                                         return false;
2182
2183                                 if (hidden_block_start.IsNull)
2184                                         hidden_block_start = loc;
2185
2186                                 return true;
2187                         }
2188
2189                         if (length != 0 || c < '0' || c > '9') {
2190                                 //
2191                                 // Eat any remaining characters to continue parsing on next line
2192                                 //
2193                                 ReadToEndOfLine ();
2194                                 return false;
2195                         }
2196
2197                         int new_line = TokenizeNumber (c);
2198                         if (new_line < 1) {
2199                                 //
2200                                 // Eat any remaining characters to continue parsing on next line
2201                                 //
2202                                 ReadToEndOfLine ();
2203                                 return new_line != 0;
2204                         }
2205
2206                         c = get_char ();
2207                         if (c == ' ') {
2208                                 // skip over white space
2209                                 do {
2210                                         c = get_char ();
2211                                 } while (c == ' ' || c == '\t');
2212                         } else if (c == '"') {
2213                                 c = 0;
2214                         }
2215
2216                         if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
2217                                 //
2218                                 // Eat any remaining characters to continue parsing on next line
2219                                 //
2220                                 ReadToEndOfLine ();
2221
2222                                 Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
2223                                 return true;
2224                         }
2225
2226                         string new_file_name = null;
2227                         if (c == '"') {
2228                                 new_file_name = TokenizeFileName (ref c);
2229
2230                                 // skip over white space
2231                                 while (c == ' ' || c == '\t') {
2232                                         c = get_char ();
2233                                 }
2234                         }
2235
2236                         if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2237
2238                         } else if (c == '/') {
2239                                 ReadSingleLineComment ();
2240                         } else {
2241                                 //
2242                                 // Eat any remaining characters to continue parsing on next line
2243                                 //
2244                                 ReadToEndOfLine ();
2245
2246                                 Error_EndLineExpected ();
2247                                 return true;
2248                         }
2249
2250                         if (new_file_name != null) {
2251                                 current_source = context.LookupFile (source_file, new_file_name);
2252                                 source_file.AddIncludeFile (current_source);
2253                         }
2254
2255                         if (!hidden_block_start.IsNull) {
2256                                 current_source.RegisterHiddenScope (hidden_block_start, loc);
2257                                 hidden_block_start = Location.Null;
2258                         }
2259
2260                         ref_line = new_line;
2261                         return true;
2262                 }
2263
2264                 //
2265                 // Handles #define and #undef
2266                 //
2267                 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
2268                 {
2269                         if (ident.Length == 0 || ident == "true" || ident == "false"){
2270                                 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
2271                                 return;
2272                         }
2273
2274                         if (ident.IndexOfAny (simple_whitespaces) != -1){
2275                                 Error_EndLineExpected ();
2276                                 return;
2277                         }
2278
2279                         if (!is_identifier_start_character (ident [0]))
2280                                 Report.Error (1001, Location, "Identifier expected: {0}", ident);
2281                         
2282                         foreach (char c in ident.Substring (1)){
2283                                 if (!is_identifier_part_character (c)){
2284                                         Report.Error (1001, Location, "Identifier expected: {0}",  ident);
2285                                         return;
2286                                 }
2287                         }
2288
2289                         if (!caller_is_taking)
2290                                 return;
2291
2292                         if (is_define) {
2293                                 //
2294                                 // #define ident
2295                                 //
2296                                 if (context.Settings.IsConditionalSymbolDefined (ident))
2297                                         return;
2298
2299                                 source_file.AddDefine (ident);
2300                         } else {
2301                                 //
2302                                 // #undef ident
2303                                 //
2304                                 source_file.AddUndefine (ident);
2305                         }
2306                 }
2307
2308                 byte read_hex (out bool error)
2309                 {
2310                         int total;
2311                         int c = get_char ();
2312
2313                         if ((c >= '0') && (c <= '9'))
2314                                 total = (int) c - (int) '0';
2315                         else if ((c >= 'A') && (c <= 'F'))
2316                                 total = (int) c - (int) 'A' + 10;
2317                         else if ((c >= 'a') && (c <= 'f'))
2318                                 total = (int) c - (int) 'a' + 10;
2319                         else {
2320                                 error = true;
2321                                 return 0;
2322                         }
2323
2324                         total *= 16;
2325                         c = get_char ();
2326
2327                         if ((c >= '0') && (c <= '9'))
2328                                 total += (int) c - (int) '0';
2329                         else if ((c >= 'A') && (c <= 'F'))
2330                                 total += (int) c - (int) 'A' + 10;
2331                         else if ((c >= 'a') && (c <= 'f'))
2332                                 total += (int) c - (int) 'a' + 10;
2333                         else {
2334                                 error = true;
2335                                 return 0;
2336                         }
2337
2338                         error = false;
2339                         return (byte) total;
2340                 }
2341
2342                 //
2343                 // Parses #pragma checksum
2344                 //
2345                 bool ParsePragmaChecksum ()
2346                 {
2347                         //
2348                         // The syntax is ` "foo.txt" "{guid}" "hash"'
2349                         //
2350                         // guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
2351                         //
2352                         int c = get_char ();
2353
2354                         if (c != '"')
2355                                 return false;
2356
2357                         string file_name = TokenizeFileName (ref c);
2358
2359                         // TODO: Any white-spaces count
2360                         if (c != ' ')
2361                                 return false;
2362
2363                         SourceFile file = context.LookupFile (source_file, file_name);
2364
2365                         if (get_char () != '"' || get_char () != '{')
2366                                 return false;
2367
2368                         bool error;
2369                         byte[] guid_bytes = new byte [16];
2370                         int i = 0;
2371
2372                         for (; i < 4; i++) {
2373                                 guid_bytes [i] = read_hex (out error);
2374                                 if (error)
2375                                         return false;
2376                         }
2377
2378                         if (get_char () != '-')
2379                                 return false;
2380
2381                         for (; i < 10; i++) {
2382                                 guid_bytes [i] = read_hex (out error);
2383                                 if (error)
2384                                         return false;
2385
2386                                 guid_bytes [i++] = read_hex (out error);
2387                                 if (error)
2388                                         return false;
2389
2390                                 if (get_char () != '-')
2391                                         return false;
2392                         }
2393
2394                         for (; i < 16; i++) {
2395                                 guid_bytes [i] = read_hex (out error);
2396                                 if (error)
2397                                         return false;
2398                         }
2399
2400                         if (get_char () != '}' || get_char () != '"')
2401                                 return false;
2402
2403                         // TODO: Any white-spaces count
2404                         c = get_char ();
2405                         if (c != ' ')
2406                                 return false;
2407
2408                         if (get_char () != '"')
2409                                 return false;
2410
2411                         // Any length of checksum
2412                         List<byte> checksum_bytes = new List<byte> (16);
2413
2414                         var checksum_location = Location;
2415                         c = peek_char ();
2416                         while (c != '"' && c != -1) {
2417                                 checksum_bytes.Add (read_hex (out error));
2418                                 if (error)
2419                                         return false;
2420
2421                                 c = peek_char ();
2422                         }
2423
2424                         if (c == '/') {
2425                                 ReadSingleLineComment ();
2426                         } else if (get_char () != '"') {
2427                                 return false;
2428                         }
2429
2430                         if (context.Settings.GenerateDebugInfo) {
2431                                 var chsum = checksum_bytes.ToArray ();
2432
2433                                 if (file.HasChecksum) {
2434                                         if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
2435                                                 // TODO: Report.SymbolRelatedToPreviousError
2436                                                 Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
2437                                         }
2438                                 }
2439
2440                                 file.SetChecksum (guid_bytes, chsum);
2441                                 current_source.AutoGenerated = true;
2442                         }
2443
2444                         return true;
2445                 }
2446
2447                 bool IsTokenIdentifierEqual (char[] identifier)
2448                 {
2449                         for (int i = 0; i < identifier.Length; ++i) {
2450                                 if (identifier[i] != id_builder[i])
2451                                         return false;
2452                         }
2453
2454                         return true;
2455                 }
2456
2457                 bool ScanClosingInterpolationBrace ()
2458                 {
2459                         PushPosition ();
2460
2461                         bool? res = null;
2462                         int str_quote = 0;
2463                         do {
2464                                 var c = reader.Read ();
2465                                 switch (c) {
2466                                 case '\"':
2467                                         ++str_quote;
2468                                         break;
2469                                 case '\\':
2470                                         // Skip escaped " character
2471                                         c = reader.Read ();
2472                                         if (c == -1)
2473                                                 res = false;
2474                                         break;
2475                                 case -1:
2476                                         res = false;
2477                                         break;
2478                                 case '}':
2479                                         if (str_quote % 2 == 1) {
2480                                                 res = true;
2481                                         }
2482
2483                                         break;
2484                                 }
2485                         } while (res == null);
2486
2487                         PopPosition ();
2488                         return res.Value;
2489                 }
2490
2491                 int TokenizeNumber (int value)
2492                 {
2493                         number_pos = 0;
2494
2495                         decimal_digits (value);
2496                         uint ui = (uint) (number_builder[0] - '0');
2497
2498                         try {
2499                                 for (int i = 1; i < number_pos; i++) {
2500                                         ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2501                                 }
2502
2503                                 return (int) ui;
2504                         } catch (OverflowException) {
2505                                 Error_NumericConstantTooLong ();
2506                                 return -1;
2507                         }
2508                 }
2509
2510                 string TokenizeFileName (ref int c)
2511                 {
2512                         var string_builder = new StringBuilder ();
2513                         while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2514                                 c = get_char ();
2515                                 if (c == '"') {
2516                                         c = get_char ();
2517                                         break;
2518                                 }
2519
2520                                 string_builder.Append ((char) c);
2521                         }
2522
2523                         if (string_builder.Length == 0) {
2524                                 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2525                         }
2526
2527                 
2528                         return string_builder.ToString ();
2529                 }
2530
2531                 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2532                 {
2533                         if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2534                                 int number;
2535
2536                                 if (c >= '0' && c <= '9') {
2537                                         number_pos = 0;
2538                                         number = TokenizeNumber (c);
2539
2540                                         c = get_char ();
2541
2542                                         if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2543                                                 return ReadPragmaWarningComment (c);
2544                                         }
2545                                 } else {
2546                                         //
2547                                         // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2548                                         //
2549                                         int pos = 0;
2550                                         number = -1;
2551                                         id_builder [pos++] = (char)c;
2552                                         while (c < MaxIdentifierLength) {
2553                                                 c = reader.Read ();
2554                                                 id_builder [pos] = (char)c;
2555
2556                                                 if (c >= '0' && c <= '9') {
2557                                                         if (pos == 5 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2558                                                                 // Recognize CSXXXX as C# XXXX warning
2559                                                                 number = 0;
2560                                                                 int pow = 1000;
2561                                                                 for (int i = 0; i < 4; ++i) {
2562                                                                         var ch = id_builder [i + 2];
2563                                                                         if (ch < '0' || ch > '9') {
2564                                                                                 number = -1;
2565                                                                                 break;
2566                                                                         }
2567
2568                                                                         number += (ch - '0') * pow;
2569                                                                         pow /= 10;
2570                                                                 }
2571                                                         }
2572                                                 } else if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
2573                                                         advance_line ();
2574                                                         break;
2575                                                 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2576                                                         break;
2577                                                 }
2578
2579                                                 ++pos;
2580                                         }
2581
2582                                         if (number < 0) {
2583                                                 identifier = true;
2584                                                 number = pos;
2585                                         }
2586                                 }
2587
2588                                 // skip over white space
2589                                 while (c == ' ' || c == '\t')
2590                                         c = get_char ();
2591
2592                                 if (c == ',') {
2593                                         c = get_char ();
2594                                 }
2595
2596                                 // skip over white space
2597                                 while (c == ' ' || c == '\t')
2598                                         c = get_char ();
2599
2600                                 return number;
2601                         }
2602
2603                         return ReadPragmaWarningComment (c);
2604                 }
2605
2606                 int ReadPragmaWarningComment (int c)
2607                 {
2608                         if (c == '/') {
2609                                 ReadSingleLineComment ();
2610                         } else {
2611                                 Report.Warning (1692, 1, Location, "Invalid number");
2612
2613                                 // Read everything till the end of the line or file
2614                                 ReadToEndOfLine ();
2615                         }
2616
2617                         return -1;
2618                 }
2619
2620                 void ReadToEndOfLine ()
2621                 {
2622                         int c;
2623                         do {
2624                                 c = get_char ();
2625                         } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2626                 }
2627
2628                 void ReadSingleLineComment ()
2629                 {
2630                         if (peek_char () != '/')
2631                                 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2632
2633                         // Read everything till the end of the line or file
2634                         ReadToEndOfLine ();
2635                 }
2636
2637                 /// <summary>
2638                 /// Handles #pragma directive
2639                 /// </summary>
2640                 void ParsePragmaDirective ()
2641                 {
2642                         int c;
2643                         int length = TokenizePreprocessorKeyword (out c);
2644                         if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2645                                 length = TokenizePreprocessorKeyword (out c);
2646
2647                                 //
2648                                 // #pragma warning disable
2649                                 // #pragma warning restore
2650                                 //
2651                                 if (length == pragma_warning_disable.Length) {
2652                                         bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2653                                         if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2654                                                 // skip over white space
2655                                                 while (c == ' ' || c == '\t')
2656                                                         c = get_char ();
2657
2658                                                 var loc = Location;
2659
2660                                                 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2661                                                         if (c == '/')
2662                                                                 ReadSingleLineComment ();
2663
2664                                                         //
2665                                                         // Disable/Restore all warnings
2666                                                         //
2667                                                         if (disable) {
2668                                                                 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2669                                                         } else {
2670                                                                 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2671                                                         }
2672                                                 } else {
2673                                                         //
2674                                                         // Disable/Restore a warning or group of warnings
2675                                                         //
2676                                                         int code;
2677                                                         do {
2678                                                                 bool identifier = false;
2679                                                                 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2680                                                                 if (code > 0) {
2681                                                                         if (identifier) {
2682                                                                                 // no-op, custom warnings cannot occur in mcs
2683                                                                         } else if (disable) {
2684                                                                                 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2685                                                                         } else {
2686                                                                                 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2687                                                                         }
2688                                                                 }
2689                                                         } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2690                                                 }
2691
2692                                                 return;
2693                                         }
2694                                 }
2695
2696                                 Report.Warning (1634, 1, Location, "Expected disable or restore");
2697
2698                                 // Eat any remaining characters on the line
2699                                 ReadToEndOfLine ();
2700
2701                                 return;
2702                         }
2703
2704                         //
2705                         // #pragma checksum
2706                         //
2707                         if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2708                                 if (c != ' ' || !ParsePragmaChecksum ()) {
2709                                         Report.Warning (1695, 1, Location,
2710                                                 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2711                                 }
2712
2713                                 return;
2714                         }
2715
2716                         Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2717
2718                         // Eat any remaining characters on the line
2719                         ReadToEndOfLine ();
2720                 }
2721
2722                 bool eval_val (string s)
2723                 {
2724                         if (s == "true")
2725                                 return true;
2726                         if (s == "false")
2727                                 return false;
2728
2729                         return source_file.IsConditionalDefined (s);
2730                 }
2731
2732                 bool pp_primary (ref string s)
2733                 {
2734                         s = s.Trim ();
2735                         int len = s.Length;
2736
2737                         if (len > 0){
2738                                 char c = s [0];
2739                                 
2740                                 if (c == '('){
2741                                         s = s.Substring (1);
2742                                         bool val = pp_expr (ref s, false);
2743                                         if (s.Length > 0 && s [0] == ')'){
2744                                                 s = s.Substring (1);
2745                                                 return val;
2746                                         }
2747                                         Error_InvalidDirective ();
2748                                         return false;
2749                                 }
2750                                 
2751                                 if (is_identifier_start_character (c)){
2752                                         int j = 1;
2753
2754                                         while (j < len){
2755                                                 c = s [j];
2756                                                 
2757                                                 if (is_identifier_part_character (c)){
2758                                                         j++;
2759                                                         continue;
2760                                                 }
2761                                                 bool v = eval_val (s.Substring (0, j));
2762                                                 s = s.Substring (j);
2763                                                 return v;
2764                                         }
2765                                         bool vv = eval_val (s);
2766                                         s = "";
2767                                         return vv;
2768                                 }
2769                         }
2770                         Error_InvalidDirective ();
2771                         return false;
2772                 }
2773                 
2774                 bool pp_unary (ref string s)
2775                 {
2776                         s = s.Trim ();
2777                         int len = s.Length;
2778
2779                         if (len > 0){
2780                                 if (s [0] == '!'){
2781                                         if (len > 1 && s [1] == '='){
2782                                                 Error_InvalidDirective ();
2783                                                 return false;
2784                                         }
2785                                         s = s.Substring (1);
2786                                         return ! pp_primary (ref s);
2787                                 } else
2788                                         return pp_primary (ref s);
2789                         } else {
2790                                 Error_InvalidDirective ();
2791                                 return false;
2792                         }
2793                 }
2794                 
2795                 bool pp_eq (ref string s)
2796                 {
2797                         bool va = pp_unary (ref s);
2798
2799                         s = s.Trim ();
2800                         int len = s.Length;
2801                         if (len > 0){
2802                                 if (s [0] == '='){
2803                                         if (len > 2 && s [1] == '='){
2804                                                 s = s.Substring (2);
2805                                                 return va == pp_unary (ref s);
2806                                         } else {
2807                                                 Error_InvalidDirective ();
2808                                                 return false;
2809                                         }
2810                                 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2811                                         s = s.Substring (2);
2812
2813                                         return va != pp_unary (ref s);
2814
2815                                 } 
2816                         }
2817
2818                         return va;
2819                                 
2820                 }
2821                 
2822                 bool pp_and (ref string s)
2823                 {
2824                         bool va = pp_eq (ref s);
2825
2826                         s = s.Trim ();
2827                         int len = s.Length;
2828                         if (len > 0){
2829                                 if (s [0] == '&'){
2830                                         if (len > 2 && s [1] == '&'){
2831                                                 s = s.Substring (2);
2832                                                 return (va & pp_and (ref s));
2833                                         } else {
2834                                                 Error_InvalidDirective ();
2835                                                 return false;
2836                                         }
2837                                 } 
2838                         }
2839                         return va;
2840                 }
2841                 
2842                 //
2843                 // Evaluates an expression for `#if' or `#elif'
2844                 //
2845                 bool pp_expr (ref string s, bool isTerm)
2846                 {
2847                         bool va = pp_and (ref s);
2848                         s = s.Trim ();
2849                         int len = s.Length;
2850                         if (len > 0){
2851                                 char c = s [0];
2852                                 
2853                                 if (c == '|'){
2854                                         if (len > 2 && s [1] == '|'){
2855                                                 s = s.Substring (2);
2856                                                 return va | pp_expr (ref s, isTerm);
2857                                         } else {
2858                                                 Error_InvalidDirective ();
2859                                                 return false;
2860                                         }
2861                                 }
2862                                 if (isTerm) {
2863                                         Error_EndLineExpected ();
2864                                         return false;
2865                                 }
2866                         }
2867                         
2868                         return va;
2869                 }
2870
2871                 bool eval (string s)
2872                 {
2873                         bool v = pp_expr (ref s, true);
2874                         s = s.Trim ();
2875                         if (s.Length != 0){
2876                                 return false;
2877                         }
2878
2879                         return v;
2880                 }
2881
2882                 void Error_NumericConstantTooLong ()
2883                 {
2884                         Report.Error (1021, Location, "Integral constant is too large");                        
2885                 }
2886                 
2887                 void Error_InvalidDirective ()
2888                 {
2889                         Report.Error (1517, Location, "Invalid preprocessor directive");
2890                 }
2891
2892                 void Error_UnexpectedDirective (string extra)
2893                 {
2894                         Report.Error (
2895                                 1028, Location,
2896                                 "Unexpected processor directive ({0})", extra);
2897                 }
2898
2899                 void Error_TokensSeen ()
2900                 {
2901                         Report.Error (1032, Location,
2902                                 "Cannot define or undefine preprocessor symbols after first token in file");
2903                 }
2904
2905                 void Eror_WrongPreprocessorLocation ()
2906                 {
2907                         Report.Error (1040, Location,
2908                                 "Preprocessor directives must appear as the first non-whitespace character on a line");
2909                 }
2910
2911                 void Error_EndLineExpected ()
2912                 {
2913                         Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2914                 }
2915
2916                 //
2917                 // Raises a warning when tokenizer found documentation comment
2918                 // on unexpected place
2919                 //
2920                 void WarningMisplacedComment (Location loc)
2921                 {
2922                         if (doc_state != XmlCommentState.Error) {
2923                                 doc_state = XmlCommentState.Error;
2924                                 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2925                         }
2926                 }
2927                 
2928                 //
2929                 // if true, then the code continues processing the code
2930                 // if false, the code stays in a loop until another directive is
2931                 // reached.
2932                 // When caller_is_taking is false we ignore all directives except the ones
2933                 // which can help us to identify where the #if block ends
2934                 bool ParsePreprocessingDirective (bool caller_is_taking)
2935                 {
2936                         string arg;
2937                         bool region_directive = false;
2938
2939                         var directive = get_cmd_arg (out arg);
2940
2941                         //
2942                         // The first group of pre-processing instructions is always processed
2943                         //
2944                         switch (directive) {
2945                         case PreprocessorDirective.Region:
2946                                 region_directive = true;
2947                                 arg = "true";
2948                                 goto case PreprocessorDirective.If;
2949
2950                         case PreprocessorDirective.Endregion:
2951                                 if (ifstack == null || ifstack.Count == 0){
2952                                         Error_UnexpectedDirective ("no #region for this #endregion");
2953                                         return true;
2954                                 }
2955                                 int pop = ifstack.Pop ();
2956                                         
2957                                 if ((pop & REGION) == 0)
2958                                         Report.Error (1027, Location, "Expected `#endif' directive");
2959                                         
2960                                 return caller_is_taking;
2961                                 
2962                         case PreprocessorDirective.If:
2963                                 if (ifstack == null)
2964                                         ifstack = new Stack<int> (2);
2965
2966                                 int flags = region_directive ? REGION : 0;
2967                                 if (ifstack.Count == 0){
2968                                         flags |= PARENT_TAKING;
2969                                 } else {
2970                                         int state = ifstack.Peek ();
2971                                         if ((state & TAKING) != 0) {
2972                                                 flags |= PARENT_TAKING;
2973                                         }
2974                                 }
2975
2976                                 if (eval (arg) && caller_is_taking) {
2977                                         ifstack.Push (flags | TAKING);
2978                                         return true;
2979                                 }
2980                                 ifstack.Push (flags);
2981                                 return false;
2982
2983                         case PreprocessorDirective.Endif:
2984                                 if (ifstack == null || ifstack.Count == 0){
2985                                         Error_UnexpectedDirective ("no #if for this #endif");
2986                                         return true;
2987                                 } else {
2988                                         pop = ifstack.Pop ();
2989                                         
2990                                         if ((pop & REGION) != 0)
2991                                                 Report.Error (1038, Location, "#endregion directive expected");
2992                                         
2993                                         if (arg.Length != 0) {
2994                                                 Error_EndLineExpected ();
2995                                         }
2996                                         
2997                                         if (ifstack.Count == 0)
2998                                                 return true;
2999
3000                                         int state = ifstack.Peek ();
3001                                         return (state & TAKING) != 0;
3002                                 }
3003
3004                         case PreprocessorDirective.Elif:
3005                                 if (ifstack == null || ifstack.Count == 0){
3006                                         Error_UnexpectedDirective ("no #if for this #elif");
3007                                         return true;
3008                                 } else {
3009                                         int state = ifstack.Pop ();
3010
3011                                         if ((state & REGION) != 0) {
3012                                                 Report.Error (1038, Location, "#endregion directive expected");
3013                                                 return true;
3014                                         }
3015
3016                                         if ((state & ELSE_SEEN) != 0){
3017                                                 Error_UnexpectedDirective ("#elif not valid after #else");
3018                                                 return true;
3019                                         }
3020
3021                                         if ((state & TAKING) != 0) {
3022                                                 ifstack.Push (0);
3023                                                 return false;
3024                                         }
3025
3026                                         if (eval (arg) && ((state & PARENT_TAKING) != 0)){
3027                                                 ifstack.Push (state | TAKING);
3028                                                 return true;
3029                                         }
3030
3031                                         ifstack.Push (state);
3032                                         return false;
3033                                 }
3034
3035                         case PreprocessorDirective.Else:
3036                                 if (ifstack == null || ifstack.Count == 0){
3037                                         Error_UnexpectedDirective ("no #if for this #else");
3038                                         return true;
3039                                 } else {
3040                                         int state = ifstack.Peek ();
3041
3042                                         if ((state & REGION) != 0) {
3043                                                 Report.Error (1038, Location, "#endregion directive expected");
3044                                                 return true;
3045                                         }
3046
3047                                         if ((state & ELSE_SEEN) != 0){
3048                                                 Error_UnexpectedDirective ("#else within #else");
3049                                                 return true;
3050                                         }
3051
3052                                         ifstack.Pop ();
3053
3054                                         if (arg.Length != 0) {
3055                                                 Error_EndLineExpected ();
3056                                                 return true;
3057                                         }
3058
3059                                         bool ret = false;
3060                                         if ((state & PARENT_TAKING) != 0) {
3061                                                 ret = (state & TAKING) == 0;
3062                                         
3063                                                 if (ret)
3064                                                         state |= TAKING;
3065                                                 else
3066                                                         state &= ~TAKING;
3067                                         }
3068         
3069                                         ifstack.Push (state | ELSE_SEEN);
3070                                         
3071                                         return ret;
3072                                 }
3073                         case PreprocessorDirective.Define:
3074                                 if (any_token_seen){
3075                                         if (caller_is_taking)
3076                                                 Error_TokensSeen ();
3077                                         return caller_is_taking;
3078                                 }
3079                                 PreProcessDefinition (true, arg, caller_is_taking);
3080                                 return caller_is_taking;
3081
3082                         case PreprocessorDirective.Undef:
3083                                 if (any_token_seen){
3084                                         if (caller_is_taking)
3085                                                 Error_TokensSeen ();
3086                                         return caller_is_taking;
3087                                 }
3088                                 PreProcessDefinition (false, arg, caller_is_taking);
3089                                 return caller_is_taking;
3090
3091                         case PreprocessorDirective.Invalid:
3092                                 Report.Error (1024, Location, "Wrong preprocessor directive");
3093                                 return true;
3094                         }
3095
3096                         //
3097                         // These are only processed if we are in a `taking' block
3098                         //
3099                         if (!caller_is_taking)
3100                                 return false;
3101                                         
3102                         switch (directive){
3103                         case PreprocessorDirective.Error:
3104                                 Report.Error (1029, Location, "#error: '{0}'", arg);
3105                                 return true;
3106
3107                         case PreprocessorDirective.Warning:
3108                                 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3109                                 return true;
3110
3111                         case PreprocessorDirective.Pragma:
3112                                 if (context.Settings.Version == LanguageVersion.ISO_1) {
3113                                         Report.FeatureIsNotAvailable (context, Location, "#pragma");
3114                                 }
3115
3116                                 ParsePragmaDirective ();
3117                                 return true;
3118
3119                         case PreprocessorDirective.Line:
3120                                 Location loc = Location;
3121                                 if (!PreProcessLine ())
3122                                         Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3123
3124                                 return caller_is_taking;
3125                         }
3126
3127                         throw new NotImplementedException (directive.ToString ());
3128                 }
3129
3130                 int consume_string (bool quoted)
3131                 {
3132                         int c;
3133                         int pos = 0;
3134                         Location start_location = Location;
3135                         if (quoted)
3136                                 start_location = start_location - 1;
3137
3138 #if FULL_AST
3139                         int reader_pos = reader.Position;
3140 #endif
3141
3142                         while (true){
3143                                 // Cannot use get_char because of \r in quoted strings
3144                                 if (putback_char != -1) {
3145                                         c = putback_char;
3146                                         putback_char = -1;
3147                                 } else {
3148                                         c = reader.Read ();
3149                                 }
3150
3151                                 if (c == '"') {
3152                                         ++col;
3153
3154                                         if (quoted && peek_char () == '"') {
3155                                                 if (pos == value_builder.Length)
3156                                                         Array.Resize (ref value_builder, pos * 2);
3157
3158                                                 value_builder[pos++] = (char) c;
3159                                                 get_char ();
3160                                                 continue;
3161                                         }
3162
3163                                         ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3164                                         val = res;
3165 #if FULL_AST
3166                                         res.ParsedValue = quoted ?
3167                                                 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3168                                                 reader.ReadChars (reader_pos - 1, reader.Position);
3169 #endif
3170
3171                                         return Token.LITERAL;
3172                                 }
3173
3174                                 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3175                                         if (!quoted) {
3176                                                 Report.Error (1010, Location, "Newline in constant");
3177
3178                                                 advance_line ();
3179
3180                                                 // Don't add \r to string literal
3181                                                 if (pos > 1 && value_builder [pos - 1] == '\r')
3182                                                         --pos;
3183
3184                                                 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3185                                                 return Token.LITERAL;
3186                                         }
3187
3188                                         advance_line ();
3189                                 } else if (c == '\\' && !quoted) {
3190                                         ++col;
3191                                         int surrogate;
3192                                         c = escape (c, out surrogate);
3193                                         if (c == -1)
3194                                                 return Token.ERROR;
3195                                         if (surrogate != 0) {
3196                                                 if (pos == value_builder.Length)
3197                                                         Array.Resize (ref value_builder, pos * 2);
3198
3199                                                 value_builder[pos++] = (char) c;
3200                                                 c = surrogate;
3201                                         }
3202                                 } else if (c == -1) {
3203                                         Report.Error (1039, Location, "Unterminated string literal");
3204                                         return Token.EOF;
3205                                 } else {
3206                                         ++col;
3207                                 }
3208
3209                                 if (pos == value_builder.Length)
3210                                         Array.Resize (ref value_builder, pos * 2);
3211
3212                                 value_builder[pos++] = (char) c;
3213                         }
3214                 }
3215
3216                 private int consume_identifier (int s)
3217                 {
3218                         int res = consume_identifier (s, false);
3219
3220                         if (doc_state == XmlCommentState.Allowed)
3221                                 doc_state = XmlCommentState.NotAllowed;
3222
3223                         return res;
3224                 }
3225
3226                 int consume_identifier (int c, bool quoted) 
3227                 {
3228                         //
3229                         // This method is very performance sensitive. It accounts
3230                         // for approximately 25% of all parser time
3231                         //
3232
3233                         int pos = 0;
3234                         int column = col;
3235                         if (quoted)
3236                                 --column;
3237
3238                         if (c == '\\') {
3239                                 int surrogate;
3240                                 c = escape (c, out surrogate);
3241                                 if (quoted || is_identifier_start_character (c)) {
3242                                         // it's added bellow
3243                                 } else if (surrogate != 0) {
3244                                         id_builder [pos++] = (char)c;
3245                                         c = surrogate;
3246                                 } else {
3247                                         Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3248                                         return Token.ERROR;
3249                                 }
3250                         }
3251
3252                         id_builder [pos++] = (char) c;
3253
3254                         try {
3255                                 while (true) {
3256                                         c = reader.Read ();
3257
3258                                         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3259                                                 id_builder [pos++] = (char) c;
3260                                                 continue;
3261                                         }
3262
3263                                         if (c < 0x80) {
3264                                                 if (c == '\\') {
3265                                                         int surrogate;
3266                                                         c = escape (c, out surrogate);
3267                                                         if (is_identifier_part_character ((char) c))
3268                                                                 id_builder[pos++] = (char) c;
3269                                                         else if (surrogate != 0) {
3270                                                                 c = surrogate;
3271                                                         } else {
3272                                                                 switch (c) {
3273                                                                 // TODO: Probably need more whitespace characters
3274                                                                 case 0xFEFF:
3275                                                                         putback_char = c;
3276                                                                         break;
3277                                                                 default:
3278                                                                         Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3279                                                                         return Token.ERROR;
3280                                                                 }
3281                                                         }
3282
3283                                                         continue;
3284                                                 }
3285                                         } else if (is_identifier_part_character_slow_part ((char) c)) {
3286                                                 id_builder [pos++] = (char) c;
3287                                                 continue;
3288                                         }
3289
3290                                         putback_char = c;
3291                                         break;
3292                                 }
3293                         } catch (IndexOutOfRangeException) {
3294                                 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3295                                 --pos;
3296                                 col += pos;
3297                         }
3298
3299                         col += pos - 1;
3300
3301                         //
3302                         // Optimization: avoids doing the keyword lookup
3303                         // on uppercase letters
3304                         //
3305                         if (id_builder [0] >= '_' && !quoted) {
3306                                 int keyword = GetKeyword (id_builder, pos);
3307                                 if (keyword != -1) {
3308                                         val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3309                                         return keyword;
3310                                 }
3311                         }
3312
3313                         string s = InternIdentifier (id_builder, pos);
3314                         val = ltb.Create (s, current_source, ref_line, column);
3315                         if (quoted && parsing_attribute_section)
3316                                 AddEscapedIdentifier (((LocatedToken) val).Location);
3317
3318                         return Token.IDENTIFIER;
3319                 }
3320
3321                 string InternIdentifier (char[] charBuffer, int length)
3322                 {
3323                         //
3324                         // Keep identifiers in an array of hashtables to avoid needless
3325                         // allocations
3326                         //
3327                         var identifiers_group = identifiers[length];
3328                         string s;
3329                         if (identifiers_group != null) {
3330                                 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3331                                         return s;
3332                                 }
3333                         } else {
3334                                 // TODO: this should be number of files dependant
3335                                 // corlib compilation peaks at 1000 and System.Core at 150
3336                                 int capacity = length > 20 ? 10 : 100;
3337                                 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3338                                 identifiers[length] = identifiers_group;
3339                         }
3340
3341                         char[] chars = new char[length];
3342                         Array.Copy (charBuffer, chars, length);
3343
3344                         s = new string (charBuffer, 0, length);
3345                         identifiers_group.Add (chars, s);
3346                         return s;
3347                 }
3348                 
3349                 public int xtoken ()
3350                 {
3351                         if (parsing_interpolation_format) {
3352                                 return TokenizeInterpolationFormat ();
3353                         }
3354
3355                         int d, c;
3356
3357                         // Whether we have seen comments on the current line
3358                         bool comments_seen = false;
3359                         while ((c = get_char ()) != -1) {
3360                                 switch (c) {
3361                                 case '\t':
3362                                         col = ((col - 1 + tab_size) / tab_size) * tab_size;
3363                                         continue;
3364
3365                                 case ' ':
3366                                 case '\f':
3367                                 case '\v':
3368                                 case 0xa0:
3369                                 case 0:
3370                                 case 0xFEFF:    // Ignore BOM anywhere in the file
3371                                         continue;
3372
3373 /*                              This is required for compatibility with .NET
3374                                 case 0xEF:
3375                                         if (peek_char () == 0xBB) {
3376                                                 PushPosition ();
3377                                                 get_char ();
3378                                                 if (get_char () == 0xBF)
3379                                                         continue;
3380                                                 PopPosition ();
3381                                         }
3382                                         break;
3383 */
3384                                 case '\\':
3385                                         tokens_seen = true;
3386                                         return consume_identifier (c);
3387
3388                                 case '{':
3389                                         val = ltb.Create (current_source, ref_line, col);
3390
3391                                         if (parsing_string_interpolation > 0)
3392                                                 ++string_interpolation_section;
3393
3394                                         return Token.OPEN_BRACE;
3395                                 case '}':
3396                                         if (parsing_string_interpolation > 0) {
3397                                                 if (string_interpolation_section == 0) {
3398                                                         --parsing_string_interpolation;
3399                                                         bool quoted;
3400                                                         if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Count > 0) {
3401                                                                 quoted = parsing_string_interpolation_quoted.Pop ();
3402                                                         } else {
3403                                                                 quoted = false;
3404                                                         }
3405
3406                                                         return TokenizeInterpolatedString (quoted);
3407                                                 }
3408
3409                                                 --string_interpolation_section;
3410                                         }
3411
3412                                         val = ltb.Create (current_source, ref_line, col);
3413                                         return Token.CLOSE_BRACE;
3414                                 case '[':
3415                                         // To block doccomment inside attribute declaration.
3416                                         if (doc_state == XmlCommentState.Allowed)
3417                                                 doc_state = XmlCommentState.NotAllowed;
3418
3419                                         val = ltb.Create (current_source, ref_line, col);
3420
3421                                         if (parsing_block == 0 || lambda_arguments_parsing)
3422                                                 return Token.OPEN_BRACKET;
3423
3424                                         int next = peek_char ();
3425                                         switch (next) {
3426                                         case ']':
3427                                         case ',':
3428                                                 return Token.OPEN_BRACKET;
3429
3430                                         case ' ':
3431                                         case '\f':
3432                                         case '\v':
3433                                         case '\r':
3434                                         case '\n':
3435                                         case UnicodeLS:
3436                                         case UnicodePS:
3437                                         case '/':
3438                                                 next = peek_token ();
3439                                                 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3440                                                         return Token.OPEN_BRACKET;
3441
3442                                                 return Token.OPEN_BRACKET_EXPR;
3443                                         default:
3444                                                 return Token.OPEN_BRACKET_EXPR;
3445                                         }
3446                                 case ']':
3447                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3448                                         return Token.CLOSE_BRACKET;
3449                                 case '(':
3450                                         val = ltb.Create (current_source, ref_line, col);
3451                                         //
3452                                         // An expression versions of parens can appear in block context only
3453                                         //
3454                                         if (parsing_block != 0 && !lambda_arguments_parsing) {
3455                                                 
3456                                                 //
3457                                                 // Optmize most common case where we know that parens
3458                                                 // is not special
3459                                                 //
3460                                                 switch (current_token) {
3461                                                 case Token.IDENTIFIER:
3462                                                 case Token.IF:
3463                                                 case Token.FOR:
3464                                                 case Token.FOREACH:
3465                                                 case Token.TYPEOF:
3466                                                 case Token.WHILE:
3467                                                 case Token.SWITCH:
3468                                                 case Token.USING:
3469                                                 case Token.DEFAULT:
3470                                                 case Token.DELEGATE:
3471                                                 case Token.OP_GENERICS_GT:
3472                                                         return Token.OPEN_PARENS;
3473                                                 }
3474
3475                                                 // Optimize using peek
3476                                                 int xx = peek_char ();
3477                                                 switch (xx) {
3478                                                 case '(':
3479                                                 case '\'':
3480                                                 case '"':
3481                                                 case '0':
3482                                                 case '1':
3483                                                         return Token.OPEN_PARENS;
3484                                                 }
3485
3486                                                 lambda_arguments_parsing = true;
3487                                                 PushPosition ();
3488                                                 d = TokenizeOpenParens ();
3489                                                 PopPosition ();
3490                                                 lambda_arguments_parsing = false;
3491                                                 return d;
3492                                         }
3493
3494                                         return Token.OPEN_PARENS;
3495                                 case ')':
3496                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3497                                         return Token.CLOSE_PARENS;
3498                                 case ',':
3499                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3500                                         return Token.COMMA;
3501                                 case ';':
3502                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3503                                         return Token.SEMICOLON;
3504                                 case '~':
3505                                         val = ltb.Create (current_source, ref_line, col);
3506                                         return Token.TILDE;
3507                                 case '?':
3508                                         val = ltb.Create (current_source, ref_line, col);
3509                                         return TokenizePossibleNullableType ();
3510                                 case '<':
3511                                         val = ltb.Create (current_source, ref_line, col);
3512                                         if (parsing_generic_less_than++ > 0)
3513                                                 return Token.OP_GENERICS_LT;
3514
3515                                         return TokenizeLessThan ();
3516
3517                                 case '>':
3518                                         val = ltb.Create (current_source, ref_line, col);
3519                                         d = peek_char ();
3520
3521                                         if (d == '='){
3522                                                 get_char ();
3523                                                 return Token.OP_GE;
3524                                         }
3525
3526                                         if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3527                                                 parsing_generic_less_than--;
3528                                                 return Token.OP_GENERICS_GT;
3529                                         }
3530
3531                                         if (d == '>') {
3532                                                 get_char ();
3533                                                 d = peek_char ();
3534
3535                                                 if (d == '=') {
3536                                                         get_char ();
3537                                                         return Token.OP_SHIFT_RIGHT_ASSIGN;
3538                                                 }
3539                                                 return Token.OP_SHIFT_RIGHT;
3540                                         }
3541
3542                                         return Token.OP_GT;
3543
3544                                 case '+':
3545                                         val = ltb.Create (current_source, ref_line, col);
3546                                         d = peek_char ();
3547                                         if (d == '+') {
3548                                                 d = Token.OP_INC;
3549                                         } else if (d == '=') {
3550                                                 d = Token.OP_ADD_ASSIGN;
3551                                         } else {
3552                                                 return Token.PLUS;
3553                                         }
3554                                         get_char ();
3555                                         return d;
3556
3557                                 case '-':
3558                                         val = ltb.Create (current_source, ref_line, col);
3559                                         d = peek_char ();
3560                                         if (d == '-') {
3561                                                 d = Token.OP_DEC;
3562                                         } else if (d == '=')
3563                                                 d = Token.OP_SUB_ASSIGN;
3564                                         else if (d == '>')
3565                                                 d = Token.OP_PTR;
3566                                         else {
3567                                                 return Token.MINUS;
3568                                         }
3569                                         get_char ();
3570                                         return d;
3571
3572                                 case '!':
3573                                         val = ltb.Create (current_source, ref_line, col);
3574                                         if (peek_char () == '='){
3575                                                 get_char ();
3576                                                 return Token.OP_NE;
3577                                         }
3578                                         return Token.BANG;
3579
3580                                 case '=':
3581                                         val = ltb.Create (current_source, ref_line, col);
3582                                         d = peek_char ();
3583                                         if (d == '='){
3584                                                 get_char ();
3585                                                 return Token.OP_EQ;
3586                                         }
3587                                         if (d == '>'){
3588                                                 get_char ();
3589                                                 return Token.ARROW;
3590                                         }
3591
3592                                         return Token.ASSIGN;
3593
3594                                 case '&':
3595                                         val = ltb.Create (current_source, ref_line, col);
3596                                         d = peek_char ();
3597                                         if (d == '&'){
3598                                                 get_char ();
3599                                                 return Token.OP_AND;
3600                                         }
3601                                         if (d == '='){
3602                                                 get_char ();
3603                                                 return Token.OP_AND_ASSIGN;
3604                                         }
3605                                         return Token.BITWISE_AND;
3606
3607                                 case '|':
3608                                         val = ltb.Create (current_source, ref_line, col);
3609                                         d = peek_char ();
3610                                         if (d == '|'){
3611                                                 get_char ();
3612                                                 return Token.OP_OR;
3613                                         }
3614                                         if (d == '='){
3615                                                 get_char ();
3616                                                 return Token.OP_OR_ASSIGN;
3617                                         }
3618                                         return Token.BITWISE_OR;
3619
3620                                 case '*':
3621                                         val = ltb.Create (current_source, ref_line, col);
3622                                         if (peek_char () == '='){
3623                                                 get_char ();
3624                                                 return Token.OP_MULT_ASSIGN;
3625                                         }
3626                                         return Token.STAR;
3627
3628                                 case '/':
3629                                         d = peek_char ();
3630                                         if (d == '='){
3631                                                 val = ltb.Create (current_source, ref_line, col);
3632                                                 get_char ();
3633                                                 return Token.OP_DIV_ASSIGN;
3634                                         }
3635
3636                                         // Handle double-slash comments.
3637                                         if (d == '/'){
3638                                                 if (parsing_string_interpolation > 0) {
3639                                                         Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3640                                                         goto case '}';
3641                                                 }
3642
3643                                                 get_char ();
3644                                                 if (doc_processing) {
3645                                                         if (peek_char () == '/') {
3646                                                                 get_char ();
3647                                                                 // Don't allow ////.
3648                                                                 if ((d = peek_char ()) != '/') {
3649                                                                         if (doc_state == XmlCommentState.Allowed)
3650                                                                                 handle_one_line_xml_comment ();
3651                                                                         else if (doc_state == XmlCommentState.NotAllowed)
3652                                                                                 WarningMisplacedComment (Location - 3);
3653                                                                 }
3654                                                         } else {
3655                                                                 if (xml_comment_buffer.Length > 0)
3656                                                                         doc_state = XmlCommentState.NotAllowed;
3657                                                         }
3658                                                 }
3659
3660                                                 ReadToEndOfLine ();
3661
3662                                                 any_token_seen |= tokens_seen;
3663                                                 tokens_seen = false;
3664                                                 comments_seen = false;
3665                                                 continue;
3666                                         } else if (d == '*'){
3667                                                 get_char ();
3668                                                 bool docAppend = false;
3669                                                 if (doc_processing && peek_char () == '*') {
3670                                                         get_char ();
3671                                                         // But when it is /**/, just do nothing.
3672                                                         if (peek_char () == '/') {
3673                                                                 get_char ();
3674                                                                 continue;
3675                                                         }
3676                                                         if (doc_state == XmlCommentState.Allowed)
3677                                                                 docAppend = true;
3678                                                         else if (doc_state == XmlCommentState.NotAllowed) {
3679                                                                 WarningMisplacedComment (Location - 2);
3680                                                         }
3681                                                 }
3682
3683                                                 int current_comment_start = 0;
3684                                                 if (docAppend) {
3685                                                         current_comment_start = xml_comment_buffer.Length;
3686                                                         xml_comment_buffer.Append (Environment.NewLine);
3687                                                 }
3688
3689                                                 while ((d = get_char ()) != -1){
3690                                                         if (d == '*' && peek_char () == '/'){
3691                                                                 get_char ();
3692                                                                 comments_seen = true;
3693                                                                 break;
3694                                                         }
3695                                                         if (docAppend)
3696                                                                 xml_comment_buffer.Append ((char) d);
3697                                                         
3698                                                         if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3699                                                                 any_token_seen |= tokens_seen;
3700                                                                 tokens_seen = false;
3701                                                                 // 
3702                                                                 // Reset 'comments_seen' just to be consistent.
3703                                                                 // It doesn't matter either way, here.
3704                                                                 //
3705                                                                 comments_seen = false;
3706                                                         }
3707                                                 }
3708                                                 if (!comments_seen)
3709                                                         Report.Error (1035, Location, "End-of-file found, '*/' expected");
3710
3711                                                 if (docAppend)
3712                                                         update_formatted_doc_comment (current_comment_start);
3713                                                 continue;
3714                                         }
3715                                         val = ltb.Create (current_source, ref_line, col);
3716                                         return Token.DIV;
3717
3718                                 case '%':
3719                                         val = ltb.Create (current_source, ref_line, col);
3720                                         if (peek_char () == '='){
3721                                                 get_char ();
3722                                                 return Token.OP_MOD_ASSIGN;
3723                                         }
3724                                         return Token.PERCENT;
3725
3726                                 case '^':
3727                                         val = ltb.Create (current_source, ref_line, col);
3728                                         if (peek_char () == '='){
3729                                                 get_char ();
3730                                                 return Token.OP_XOR_ASSIGN;
3731                                         }
3732                                         return Token.CARRET;
3733
3734                                 case ':':
3735                                         val = ltb.Create (current_source, ref_line, col);
3736                                         if (peek_char () == ':') {
3737                                                 get_char ();
3738                                                 return Token.DOUBLE_COLON;
3739                                         }
3740                                         return Token.COLON;
3741
3742                                 case '0': case '1': case '2': case '3': case '4':
3743                                 case '5': case '6': case '7': case '8': case '9':
3744                                         tokens_seen = true;
3745                                         return is_number (c, false);
3746
3747                                 case '\n': // white space
3748                                 case UnicodeLS:
3749                                 case UnicodePS:
3750                                         any_token_seen |= tokens_seen;
3751                                         tokens_seen = false;
3752                                         comments_seen = false;
3753                                         continue;
3754
3755                                 case '.':
3756                                         tokens_seen = true;
3757                                         d = peek_char ();
3758                                         if (d >= '0' && d <= '9')
3759                                                 return is_number (c, true);
3760
3761                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3762                                         return Token.DOT;
3763                                 
3764                                 case '#':
3765                                         if (tokens_seen || comments_seen) {
3766                                                 Eror_WrongPreprocessorLocation ();
3767                                                 return Token.ERROR;
3768                                         }
3769                                         
3770                                         if (ParsePreprocessingDirective (true))
3771                                                 continue;
3772
3773                                         bool directive_expected = false;
3774                                         while ((c = get_char ()) != -1) {
3775                                                 if (col == 1) {
3776                                                         directive_expected = true;
3777                                                 } else if (!directive_expected) {
3778                                                         // TODO: Implement comment support for disabled code and uncomment this code
3779 //                                                      if (c == '#') {
3780 //                                                              Eror_WrongPreprocessorLocation ();
3781 //                                                              return Token.ERROR;
3782 //                                                      }
3783                                                         continue;
3784                                                 }
3785
3786                                                 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3787                                                         continue;
3788
3789                                                 if (c == '#') {
3790                                                         if (ParsePreprocessingDirective (false))
3791                                                                 break;
3792                                                 }
3793                                                 directive_expected = false;
3794                                         }
3795
3796                                         if (c != -1) {
3797                                                 tokens_seen = false;
3798                                                 continue;
3799                                         }
3800
3801                                         return Token.EOF;
3802                                 
3803                                 case '"':
3804                                         if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3805                                                 parsing_string_interpolation = 0;
3806                                                 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3807                                                 val = new StringLiteral (context.BuiltinTypes, "", Location);
3808                                                 return Token.INTERPOLATED_STRING_END;
3809                                         }
3810
3811                                         return consume_string (false);
3812
3813                                 case '\'':
3814                                         return TokenizeBackslash ();
3815                                 
3816                                 case '@':
3817                                         c = get_char ();
3818                                         if (c == '"') {
3819                                                 tokens_seen = true;
3820                                                 return consume_string (true);
3821                                         }
3822
3823                                         if (is_identifier_start_character (c)){
3824                                                 return consume_identifier (c, true);
3825                                         }
3826
3827                                         Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3828                                         return Token.ERROR;
3829
3830                                 case '$':
3831                                         switch (peek_char ()) {
3832                                         case '"':
3833                                                 get_char ();
3834                                                 return TokenizeInterpolatedString (false);
3835                                         case '@':
3836                                                 get_char ();
3837                                                 if (peek_char () == '"') {
3838                                                         get_char ();
3839                                                         return TokenizeInterpolatedString (true);
3840                                                 }
3841
3842                                                 break;
3843                                         }
3844
3845                                         break;
3846                                 case EvalStatementParserCharacter:
3847                                         return Token.EVAL_STATEMENT_PARSER;
3848                                 case EvalCompilationUnitParserCharacter:
3849                                         return Token.EVAL_COMPILATION_UNIT_PARSER;
3850                                 case EvalUsingDeclarationsParserCharacter:
3851                                         return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3852                                 case DocumentationXref:
3853                                         return Token.DOC_SEE;
3854                                 }
3855
3856                                 if (is_identifier_start_character (c)) {
3857                                         tokens_seen = true;
3858                                         return consume_identifier (c);
3859                                 }
3860
3861                                 if (char.IsWhiteSpace ((char) c))
3862                                         continue;
3863
3864                                 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3865                         }
3866
3867                         if (CompleteOnEOF){
3868                                 if (generated)
3869                                         return Token.COMPLETE_COMPLETION;
3870                                 
3871                                 generated = true;
3872                                 return Token.GENERATE_COMPLETION;
3873                         }
3874                         
3875
3876                         return Token.EOF;
3877                 }
3878
3879                 int TokenizeBackslash ()
3880                 {
3881 #if FULL_AST
3882                         int read_start = reader.Position;
3883 #endif
3884                         Location start_location = Location;
3885                         int c = get_char ();
3886                         tokens_seen = true;
3887                         if (c == '\'') {
3888                                 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3889                                 Report.Error (1011, start_location, "Empty character literal");
3890                                 return Token.LITERAL;
3891                         }
3892
3893                         if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3894                                 Report.Error (1010, start_location, "Newline in constant");
3895                                 return Token.ERROR;
3896                         }
3897
3898                         int d;
3899                         c = escape (c, out d);
3900                         if (c == -1)
3901                                 return Token.ERROR;
3902                         if (d != 0)
3903                                 throw new NotImplementedException ();
3904
3905                         ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3906                         val = res;
3907                         c = get_char ();
3908
3909                         if (c != '\'') {
3910                                 Report.Error (1012, start_location, "Too many characters in character literal");
3911
3912                                 // Try to recover, read until newline or next "'"
3913                                 while ((c = get_char ()) != -1) {
3914                                         if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3915                                                 break;
3916                                 }
3917                         }
3918
3919 #if FULL_AST
3920                         res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3921 #endif
3922
3923                         return Token.LITERAL;
3924                 }
3925
3926                 int TokenizeLessThan ()
3927                 {
3928                         int d;
3929
3930                         // Save current position and parse next token.
3931                         PushPosition ();
3932                         int generic_dimension = 0;
3933                         if (parse_less_than (ref generic_dimension)) {
3934                                 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3935                                         d = Token.OP_GENERICS_LT_DECL;
3936                                 } else {
3937                                         if (generic_dimension > 0) {
3938                                                 val = generic_dimension;
3939                                                 DiscardPosition ();
3940                                                 return Token.GENERIC_DIMENSION;
3941                                         }
3942
3943                                         d = Token.OP_GENERICS_LT;
3944                                 }
3945                                 PopPosition ();
3946                                 return d;
3947                         }
3948
3949                         PopPosition ();
3950                         parsing_generic_less_than = 0;
3951
3952                         d = peek_char ();
3953                         if (d == '<') {
3954                                 get_char ();
3955                                 d = peek_char ();
3956
3957                                 if (d == '=') {
3958                                         get_char ();
3959                                         return Token.OP_SHIFT_LEFT_ASSIGN;
3960                                 }
3961                                 return Token.OP_SHIFT_LEFT;
3962                         }
3963
3964                         if (d == '=') {
3965                                 get_char ();
3966                                 return Token.OP_LE;
3967                         }
3968                         return Token.OP_LT;
3969                 }
3970
3971                 int TokenizeInterpolatedString (bool quoted)
3972                 {
3973                         int pos = 0;
3974                         var start_location = Location;
3975
3976                         while (true) {
3977                                 var ch = get_char ();
3978                                 switch (ch) {
3979                                 case '"':
3980                                         if (quoted && peek_char () == '"') {
3981                                                 get_char ();
3982                                                 break;
3983                                         }
3984
3985                                         val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3986                                         return Token.INTERPOLATED_STRING_END;
3987                                 case '{':
3988                                         if (peek_char () == '{') {
3989                                                 value_builder [pos++] = (char)ch;
3990                                                 get_char ();
3991                                                 break;
3992                                         }
3993
3994                                         ++parsing_string_interpolation;
3995                                         if (quoted) {
3996                                                 if (parsing_string_interpolation_quoted == null)
3997                                                         parsing_string_interpolation_quoted = new Stack<bool> ();
3998                                         }
3999
4000                                         if (parsing_string_interpolation_quoted != null) {
4001                                                 parsing_string_interpolation_quoted.Push (quoted);
4002                                         }
4003
4004                                         val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
4005                                         return Token.INTERPOLATED_STRING;
4006                                 case '\\':
4007                                         if (quoted)
4008                                                 break;
4009                                         
4010                                         ++col;
4011                                         int surrogate;
4012                                         ch = escape (ch, out surrogate);
4013                                         if (ch == -1)
4014                                                 return Token.ERROR;
4015
4016                                         if (ch == '{' || ch == '}') {
4017                                                 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4018                                         }
4019
4020                                         if (surrogate != 0) {
4021                                                 if (pos == value_builder.Length)
4022                                                         Array.Resize (ref value_builder, pos * 2);
4023
4024                                                 if (pos == value_builder.Length)
4025                                                         Array.Resize (ref value_builder, pos * 2);
4026
4027                                                 value_builder [pos++] = (char)ch;
4028                                                 ch = surrogate;
4029                                         }
4030
4031                                         break;
4032                                 case -1:
4033                                         return Token.EOF;
4034                                 }
4035
4036                                 ++col;
4037                                 if (pos == value_builder.Length)
4038                                         Array.Resize (ref value_builder, pos * 2);
4039
4040                                 value_builder[pos++] = (char) ch;
4041                         }
4042                 }
4043
4044                 int TokenizeInterpolationFormat ()
4045                 {
4046                         int pos = 0;
4047                         int braces = 0;
4048                         while (true) {
4049                                 var ch = get_char ();
4050                                 switch (ch) {
4051                                 case '{':
4052                                         ++braces;
4053                                         break;
4054                                 case '}':
4055                                         if (braces == 0) {
4056                                                 putback_char = ch;
4057                                                 if (pos == 0) {
4058                                                         Report.Error (8089, Location, "Empty interpolated expression format specifier");
4059                                                 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
4060                                                         Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
4061                                                 }
4062
4063                                                 val = CreateStringFromBuilder (pos);
4064                                                 return Token.LITERAL;
4065                                         }
4066
4067                                         --braces;
4068                                         break;
4069                                 case '\\':
4070                                         if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Peek ())
4071                                                 break;
4072
4073                                         ++col;
4074                                         int surrogate;
4075                                         ch = escape (ch, out surrogate);
4076                                         if (ch == -1)
4077                                                 return Token.ERROR;
4078
4079                                         if (ch == '{' || ch == '}') {
4080                                                 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4081                                         }
4082
4083                                         if (surrogate != 0) {
4084                                                 if (pos == value_builder.Length)
4085                                                         Array.Resize (ref value_builder, pos * 2);
4086
4087                                                 value_builder [pos++] = (char)ch;
4088                                                 ch = surrogate;
4089                                         }
4090
4091                                         break;
4092                                 case -1:
4093                                         return Token.EOF;
4094                                 }
4095
4096                                 ++col;
4097                                 value_builder[pos++] = (char) ch;
4098                         }
4099                 }
4100
4101                 string CreateStringFromBuilder (int pos)
4102                 {
4103                         if (pos == 0)
4104                                 return string.Empty;
4105                         if (pos <= 4)
4106                                 return InternIdentifier (value_builder, pos);
4107
4108                         return new string (value_builder, 0, pos);
4109                 }
4110
4111                 //
4112                 // Handles one line xml comment
4113                 //
4114                 private void handle_one_line_xml_comment ()
4115                 {
4116                         int c;
4117                         while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4118                                 xml_comment_buffer.Append ((char) get_char ());
4119                         }
4120                         if (c == '\r' || c == '\n')
4121                                 xml_comment_buffer.Append (Environment.NewLine);
4122                 }
4123
4124                 //
4125                 // Remove heading "*" in Javadoc-like xml documentation.
4126                 //
4127                 private void update_formatted_doc_comment (int current_comment_start)
4128                 {
4129                         int length = xml_comment_buffer.Length - current_comment_start;
4130                         string [] lines = xml_comment_buffer.ToString (
4131                                 current_comment_start,
4132                                 length).Replace ("\r", "").Split ('\n');
4133                         
4134                         // The first line starts with /**, thus it is not target
4135                         // for the format check.
4136                         for (int i = 1; i < lines.Length; i++) {
4137                                 string s = lines [i];
4138                                 int idx = s.IndexOf ('*');
4139                                 string head = null;
4140                                 if (idx < 0) {
4141                                         if (i < lines.Length - 1)
4142                                                 return;
4143                                         head = s;
4144                                 } else
4145                                         head = s.Substring (0, idx);
4146                                 foreach (char c in head)
4147                                         if (c != ' ')
4148                                                 return;
4149                                 lines [i] = s.Substring (idx + 1);
4150                         }
4151                         xml_comment_buffer.Remove (current_comment_start, length);
4152                         xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4153                 }
4154
4155                 //
4156                 // Checks if there was incorrect doc comments and raise
4157                 // warnings.
4158                 //
4159                 public void check_incorrect_doc_comment ()
4160                 {
4161                         if (xml_comment_buffer.Length > 0)
4162                                 WarningMisplacedComment (Location);
4163                 }
4164
4165                 //
4166                 // Consumes the saved xml comment lines (if any)
4167                 // as for current target member or type.
4168                 //
4169                 public string consume_doc_comment ()
4170                 {
4171                         if (xml_comment_buffer.Length > 0) {
4172                                 string ret = xml_comment_buffer.ToString ();
4173                                 reset_doc_comment ();
4174                                 return ret;
4175                         }
4176                         return null;
4177                 }
4178
4179                 void reset_doc_comment ()
4180                 {
4181                         xml_comment_buffer.Length = 0;
4182                 }
4183
4184                 public void cleanup ()
4185                 {
4186                         if (ifstack != null && ifstack.Count >= 1) {
4187                                 int state = ifstack.Pop ();
4188                                 if ((state & REGION) != 0)
4189                                         Report.Error (1038, Location, "#endregion directive expected");
4190                                 else 
4191                                         Report.Error (1027, Location, "Expected `#endif' directive");
4192                         }
4193                 }
4194         }
4195
4196         //
4197         // Indicates whether it accepts XML documentation or not.
4198         //
4199         public enum XmlCommentState {
4200                 // comment is allowed in this state.
4201                 Allowed,
4202                 // comment is not allowed in this state.
4203                 NotAllowed,
4204                 // once comments appeared when it is NotAllowed, then the
4205                 // state is changed to it, until the state is changed to
4206                 // .Allowed.
4207                 Error
4208         }
4209 }
4210