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