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