Merge pull request #2274 from esdrubal/udpclientreceive
[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 -1:
2469                                         res = false;
2470                                         break;
2471                                 case '}':
2472                                         if (str_quote % 2 == 1) {
2473                                                 res = true;
2474                                         }
2475
2476                                         break;
2477                                 }
2478                         } while (res == null);
2479
2480                         PopPosition ();
2481                         return res.Value;
2482                 }
2483
2484                 int TokenizeNumber (int value)
2485                 {
2486                         number_pos = 0;
2487
2488                         decimal_digits (value);
2489                         uint ui = (uint) (number_builder[0] - '0');
2490
2491                         try {
2492                                 for (int i = 1; i < number_pos; i++) {
2493                                         ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2494                                 }
2495
2496                                 return (int) ui;
2497                         } catch (OverflowException) {
2498                                 Error_NumericConstantTooLong ();
2499                                 return -1;
2500                         }
2501                 }
2502
2503                 string TokenizeFileName (ref int c)
2504                 {
2505                         var string_builder = new StringBuilder ();
2506                         while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
2507                                 c = get_char ();
2508                                 if (c == '"') {
2509                                         c = get_char ();
2510                                         break;
2511                                 }
2512
2513                                 string_builder.Append ((char) c);
2514                         }
2515
2516                         if (string_builder.Length == 0) {
2517                                 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2518                         }
2519
2520                 
2521                         return string_builder.ToString ();
2522                 }
2523
2524                 int TokenizePragmaWarningIdentifier (ref int c, ref bool identifier)
2525                 {
2526
2527                         if ((c >= '0' && c <= '9') || is_identifier_start_character (c)) {
2528                                 int number;
2529
2530                                 if (c >= '0' && c <= '9') {
2531                                         number_pos = 0;
2532                                         number = TokenizeNumber (c);
2533
2534                                         c = get_char ();
2535
2536                                         if (c != ' ' && c != '\t' && c != ',' && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS) {
2537                                                 return ReadPragmaWarningComment (c);
2538                                         }
2539                                 } else {
2540                                         //
2541                                         // LAMESPEC v6: No spec what identifier really is in this context, it seems keywords are allowed too
2542                                         //
2543                                         int pos = 0;
2544                                         number = -1;
2545                                         id_builder [pos++] = (char)c;
2546                                         while (c < MaxIdentifierLength) {
2547                                                 c = reader.Read ();
2548                                                 id_builder [pos] = (char)c;
2549
2550                                                 if (c >= '0' && c <= '9') {
2551                                                         if (pos == 6 && id_builder [0] == 'C' && id_builder [1] == 'S') {
2552                                                                 // Recognize CSXXXX as C# XXXX warning
2553                                                                 number = 0;
2554                                                                 int pow = 1000;
2555                                                                 for (int i = 0; i < 4; ++i) {
2556                                                                         var ch = id_builder [i + 2];
2557                                                                         if (ch < '0' || ch > '9') {
2558                                                                                 number = -1;
2559                                                                                 break;
2560                                                                         }
2561
2562                                                                         number += (ch - '0') * pow;
2563                                                                         pow /= 10;
2564                                                                 }
2565                                                         }
2566                                                 } else if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
2567                                                         break;
2568                                                 }
2569
2570                                                 ++pos;
2571                                         }
2572
2573                                         if (number < 0) {
2574                                                 identifier = true;
2575                                                 number = pos;
2576                                         }
2577                                 }
2578
2579                                 // skip over white space
2580                                 while (c == ' ' || c == '\t')
2581                                         c = get_char ();
2582
2583                                 if (c == ',') {
2584                                         c = get_char ();
2585                                 }
2586
2587                                 // skip over white space
2588                                 while (c == ' ' || c == '\t')
2589                                         c = get_char ();
2590
2591                                 return number;
2592                         }
2593
2594                         return ReadPragmaWarningComment (c);
2595                 }
2596
2597                 int ReadPragmaWarningComment (int c)
2598                 {
2599                         if (c == '/') {
2600                                 ReadSingleLineComment ();
2601                         } else {
2602                                 Report.Warning (1692, 1, Location, "Invalid number");
2603
2604                                 // Read everything till the end of the line or file
2605                                 ReadToEndOfLine ();
2606                         }
2607
2608                         return -1;
2609                 }
2610
2611                 void ReadToEndOfLine ()
2612                 {
2613                         int c;
2614                         do {
2615                                 c = get_char ();
2616                         } while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
2617                 }
2618
2619                 void ReadSingleLineComment ()
2620                 {
2621                         if (peek_char () != '/')
2622                                 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2623
2624                         // Read everything till the end of the line or file
2625                         ReadToEndOfLine ();
2626                 }
2627
2628                 /// <summary>
2629                 /// Handles #pragma directive
2630                 /// </summary>
2631                 void ParsePragmaDirective ()
2632                 {
2633                         int c;
2634                         int length = TokenizePreprocessorKeyword (out c);
2635                         if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2636                                 length = TokenizePreprocessorKeyword (out c);
2637
2638                                 //
2639                                 // #pragma warning disable
2640                                 // #pragma warning restore
2641                                 //
2642                                 if (length == pragma_warning_disable.Length) {
2643                                         bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2644                                         if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2645                                                 // skip over white space
2646                                                 while (c == ' ' || c == '\t')
2647                                                         c = get_char ();
2648
2649                                                 var loc = Location;
2650
2651                                                 if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
2652                                                         if (c == '/')
2653                                                                 ReadSingleLineComment ();
2654
2655                                                         //
2656                                                         // Disable/Restore all warnings
2657                                                         //
2658                                                         if (disable) {
2659                                                                 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2660                                                         } else {
2661                                                                 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2662                                                         }
2663                                                 } else {
2664                                                         //
2665                                                         // Disable/Restore a warning or group of warnings
2666                                                         //
2667                                                         int code;
2668                                                         do {
2669                                                                 bool identifier = false;
2670                                                                 code = TokenizePragmaWarningIdentifier (ref c, ref identifier);
2671                                                                 if (code > 0) {
2672                                                                         if (identifier) {
2673                                                                                 // no-op, custom warnings cannot occur in mcs
2674                                                                         } else if (disable) {
2675                                                                                 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
2676                                                                         } else {
2677                                                                                 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
2678                                                                         }
2679                                                                 }
2680                                                         } while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
2681                                                 }
2682
2683                                                 return;
2684                                         }
2685                                 }
2686
2687                                 Report.Warning (1634, 1, Location, "Expected disable or restore");
2688
2689                                 // Eat any remaining characters on the line
2690                                 ReadToEndOfLine ();
2691
2692                                 return;
2693                         }
2694
2695                         //
2696                         // #pragma checksum
2697                         //
2698                         if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2699                                 if (c != ' ' || !ParsePragmaChecksum ()) {
2700                                         Report.Warning (1695, 1, Location,
2701                                                 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2702                                 }
2703
2704                                 return;
2705                         }
2706
2707                         Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2708
2709                         // Eat any remaining characters on the line
2710                         ReadToEndOfLine ();
2711                 }
2712
2713                 bool eval_val (string s)
2714                 {
2715                         if (s == "true")
2716                                 return true;
2717                         if (s == "false")
2718                                 return false;
2719
2720                         return source_file.IsConditionalDefined (s);
2721                 }
2722
2723                 bool pp_primary (ref string s)
2724                 {
2725                         s = s.Trim ();
2726                         int len = s.Length;
2727
2728                         if (len > 0){
2729                                 char c = s [0];
2730                                 
2731                                 if (c == '('){
2732                                         s = s.Substring (1);
2733                                         bool val = pp_expr (ref s, false);
2734                                         if (s.Length > 0 && s [0] == ')'){
2735                                                 s = s.Substring (1);
2736                                                 return val;
2737                                         }
2738                                         Error_InvalidDirective ();
2739                                         return false;
2740                                 }
2741                                 
2742                                 if (is_identifier_start_character (c)){
2743                                         int j = 1;
2744
2745                                         while (j < len){
2746                                                 c = s [j];
2747                                                 
2748                                                 if (is_identifier_part_character (c)){
2749                                                         j++;
2750                                                         continue;
2751                                                 }
2752                                                 bool v = eval_val (s.Substring (0, j));
2753                                                 s = s.Substring (j);
2754                                                 return v;
2755                                         }
2756                                         bool vv = eval_val (s);
2757                                         s = "";
2758                                         return vv;
2759                                 }
2760                         }
2761                         Error_InvalidDirective ();
2762                         return false;
2763                 }
2764                 
2765                 bool pp_unary (ref string s)
2766                 {
2767                         s = s.Trim ();
2768                         int len = s.Length;
2769
2770                         if (len > 0){
2771                                 if (s [0] == '!'){
2772                                         if (len > 1 && s [1] == '='){
2773                                                 Error_InvalidDirective ();
2774                                                 return false;
2775                                         }
2776                                         s = s.Substring (1);
2777                                         return ! pp_primary (ref s);
2778                                 } else
2779                                         return pp_primary (ref s);
2780                         } else {
2781                                 Error_InvalidDirective ();
2782                                 return false;
2783                         }
2784                 }
2785                 
2786                 bool pp_eq (ref string s)
2787                 {
2788                         bool va = pp_unary (ref s);
2789
2790                         s = s.Trim ();
2791                         int len = s.Length;
2792                         if (len > 0){
2793                                 if (s [0] == '='){
2794                                         if (len > 2 && s [1] == '='){
2795                                                 s = s.Substring (2);
2796                                                 return va == pp_unary (ref s);
2797                                         } else {
2798                                                 Error_InvalidDirective ();
2799                                                 return false;
2800                                         }
2801                                 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2802                                         s = s.Substring (2);
2803
2804                                         return va != pp_unary (ref s);
2805
2806                                 } 
2807                         }
2808
2809                         return va;
2810                                 
2811                 }
2812                 
2813                 bool pp_and (ref string s)
2814                 {
2815                         bool va = pp_eq (ref s);
2816
2817                         s = s.Trim ();
2818                         int len = s.Length;
2819                         if (len > 0){
2820                                 if (s [0] == '&'){
2821                                         if (len > 2 && s [1] == '&'){
2822                                                 s = s.Substring (2);
2823                                                 return (va & pp_and (ref s));
2824                                         } else {
2825                                                 Error_InvalidDirective ();
2826                                                 return false;
2827                                         }
2828                                 } 
2829                         }
2830                         return va;
2831                 }
2832                 
2833                 //
2834                 // Evaluates an expression for `#if' or `#elif'
2835                 //
2836                 bool pp_expr (ref string s, bool isTerm)
2837                 {
2838                         bool va = pp_and (ref s);
2839                         s = s.Trim ();
2840                         int len = s.Length;
2841                         if (len > 0){
2842                                 char c = s [0];
2843                                 
2844                                 if (c == '|'){
2845                                         if (len > 2 && s [1] == '|'){
2846                                                 s = s.Substring (2);
2847                                                 return va | pp_expr (ref s, isTerm);
2848                                         } else {
2849                                                 Error_InvalidDirective ();
2850                                                 return false;
2851                                         }
2852                                 }
2853                                 if (isTerm) {
2854                                         Error_EndLineExpected ();
2855                                         return false;
2856                                 }
2857                         }
2858                         
2859                         return va;
2860                 }
2861
2862                 bool eval (string s)
2863                 {
2864                         bool v = pp_expr (ref s, true);
2865                         s = s.Trim ();
2866                         if (s.Length != 0){
2867                                 return false;
2868                         }
2869
2870                         return v;
2871                 }
2872
2873                 void Error_NumericConstantTooLong ()
2874                 {
2875                         Report.Error (1021, Location, "Integral constant is too large");                        
2876                 }
2877                 
2878                 void Error_InvalidDirective ()
2879                 {
2880                         Report.Error (1517, Location, "Invalid preprocessor directive");
2881                 }
2882
2883                 void Error_UnexpectedDirective (string extra)
2884                 {
2885                         Report.Error (
2886                                 1028, Location,
2887                                 "Unexpected processor directive ({0})", extra);
2888                 }
2889
2890                 void Error_TokensSeen ()
2891                 {
2892                         Report.Error (1032, Location,
2893                                 "Cannot define or undefine preprocessor symbols after first token in file");
2894                 }
2895
2896                 void Eror_WrongPreprocessorLocation ()
2897                 {
2898                         Report.Error (1040, Location,
2899                                 "Preprocessor directives must appear as the first non-whitespace character on a line");
2900                 }
2901
2902                 void Error_EndLineExpected ()
2903                 {
2904                         Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2905                 }
2906
2907                 //
2908                 // Raises a warning when tokenizer found documentation comment
2909                 // on unexpected place
2910                 //
2911                 void WarningMisplacedComment (Location loc)
2912                 {
2913                         if (doc_state != XmlCommentState.Error) {
2914                                 doc_state = XmlCommentState.Error;
2915                                 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2916                         }
2917                 }
2918                 
2919                 //
2920                 // if true, then the code continues processing the code
2921                 // if false, the code stays in a loop until another directive is
2922                 // reached.
2923                 // When caller_is_taking is false we ignore all directives except the ones
2924                 // which can help us to identify where the #if block ends
2925                 bool ParsePreprocessingDirective (bool caller_is_taking)
2926                 {
2927                         string arg;
2928                         bool region_directive = false;
2929
2930                         var directive = get_cmd_arg (out arg);
2931
2932                         //
2933                         // The first group of pre-processing instructions is always processed
2934                         //
2935                         switch (directive) {
2936                         case PreprocessorDirective.Region:
2937                                 region_directive = true;
2938                                 arg = "true";
2939                                 goto case PreprocessorDirective.If;
2940
2941                         case PreprocessorDirective.Endregion:
2942                                 if (ifstack == null || ifstack.Count == 0){
2943                                         Error_UnexpectedDirective ("no #region for this #endregion");
2944                                         return true;
2945                                 }
2946                                 int pop = ifstack.Pop ();
2947                                         
2948                                 if ((pop & REGION) == 0)
2949                                         Report.Error (1027, Location, "Expected `#endif' directive");
2950                                         
2951                                 return caller_is_taking;
2952                                 
2953                         case PreprocessorDirective.If:
2954                                 if (ifstack == null)
2955                                         ifstack = new Stack<int> (2);
2956
2957                                 int flags = region_directive ? REGION : 0;
2958                                 if (ifstack.Count == 0){
2959                                         flags |= PARENT_TAKING;
2960                                 } else {
2961                                         int state = ifstack.Peek ();
2962                                         if ((state & TAKING) != 0) {
2963                                                 flags |= PARENT_TAKING;
2964                                         }
2965                                 }
2966
2967                                 if (eval (arg) && caller_is_taking) {
2968                                         ifstack.Push (flags | TAKING);
2969                                         return true;
2970                                 }
2971                                 ifstack.Push (flags);
2972                                 return false;
2973
2974                         case PreprocessorDirective.Endif:
2975                                 if (ifstack == null || ifstack.Count == 0){
2976                                         Error_UnexpectedDirective ("no #if for this #endif");
2977                                         return true;
2978                                 } else {
2979                                         pop = ifstack.Pop ();
2980                                         
2981                                         if ((pop & REGION) != 0)
2982                                                 Report.Error (1038, Location, "#endregion directive expected");
2983                                         
2984                                         if (arg.Length != 0) {
2985                                                 Error_EndLineExpected ();
2986                                         }
2987                                         
2988                                         if (ifstack.Count == 0)
2989                                                 return true;
2990
2991                                         int state = ifstack.Peek ();
2992                                         return (state & TAKING) != 0;
2993                                 }
2994
2995                         case PreprocessorDirective.Elif:
2996                                 if (ifstack == null || ifstack.Count == 0){
2997                                         Error_UnexpectedDirective ("no #if for this #elif");
2998                                         return true;
2999                                 } else {
3000                                         int state = ifstack.Pop ();
3001
3002                                         if ((state & REGION) != 0) {
3003                                                 Report.Error (1038, Location, "#endregion directive expected");
3004                                                 return true;
3005                                         }
3006
3007                                         if ((state & ELSE_SEEN) != 0){
3008                                                 Error_UnexpectedDirective ("#elif not valid after #else");
3009                                                 return true;
3010                                         }
3011
3012                                         if ((state & TAKING) != 0) {
3013                                                 ifstack.Push (0);
3014                                                 return false;
3015                                         }
3016
3017                                         if (eval (arg) && ((state & PARENT_TAKING) != 0)){
3018                                                 ifstack.Push (state | TAKING);
3019                                                 return true;
3020                                         }
3021
3022                                         ifstack.Push (state);
3023                                         return false;
3024                                 }
3025
3026                         case PreprocessorDirective.Else:
3027                                 if (ifstack == null || ifstack.Count == 0){
3028                                         Error_UnexpectedDirective ("no #if for this #else");
3029                                         return true;
3030                                 } else {
3031                                         int state = ifstack.Peek ();
3032
3033                                         if ((state & REGION) != 0) {
3034                                                 Report.Error (1038, Location, "#endregion directive expected");
3035                                                 return true;
3036                                         }
3037
3038                                         if ((state & ELSE_SEEN) != 0){
3039                                                 Error_UnexpectedDirective ("#else within #else");
3040                                                 return true;
3041                                         }
3042
3043                                         ifstack.Pop ();
3044
3045                                         if (arg.Length != 0) {
3046                                                 Error_EndLineExpected ();
3047                                                 return true;
3048                                         }
3049
3050                                         bool ret = false;
3051                                         if ((state & PARENT_TAKING) != 0) {
3052                                                 ret = (state & TAKING) == 0;
3053                                         
3054                                                 if (ret)
3055                                                         state |= TAKING;
3056                                                 else
3057                                                         state &= ~TAKING;
3058                                         }
3059         
3060                                         ifstack.Push (state | ELSE_SEEN);
3061                                         
3062                                         return ret;
3063                                 }
3064                         case PreprocessorDirective.Define:
3065                                 if (any_token_seen){
3066                                         if (caller_is_taking)
3067                                                 Error_TokensSeen ();
3068                                         return caller_is_taking;
3069                                 }
3070                                 PreProcessDefinition (true, arg, caller_is_taking);
3071                                 return caller_is_taking;
3072
3073                         case PreprocessorDirective.Undef:
3074                                 if (any_token_seen){
3075                                         if (caller_is_taking)
3076                                                 Error_TokensSeen ();
3077                                         return caller_is_taking;
3078                                 }
3079                                 PreProcessDefinition (false, arg, caller_is_taking);
3080                                 return caller_is_taking;
3081
3082                         case PreprocessorDirective.Invalid:
3083                                 Report.Error (1024, Location, "Wrong preprocessor directive");
3084                                 return true;
3085                         }
3086
3087                         //
3088                         // These are only processed if we are in a `taking' block
3089                         //
3090                         if (!caller_is_taking)
3091                                 return false;
3092                                         
3093                         switch (directive){
3094                         case PreprocessorDirective.Error:
3095                                 Report.Error (1029, Location, "#error: '{0}'", arg);
3096                                 return true;
3097
3098                         case PreprocessorDirective.Warning:
3099                                 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
3100                                 return true;
3101
3102                         case PreprocessorDirective.Pragma:
3103                                 if (context.Settings.Version == LanguageVersion.ISO_1) {
3104                                         Report.FeatureIsNotAvailable (context, Location, "#pragma");
3105                                 }
3106
3107                                 ParsePragmaDirective ();
3108                                 return true;
3109
3110                         case PreprocessorDirective.Line:
3111                                 Location loc = Location;
3112                                 if (!PreProcessLine ())
3113                                         Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
3114
3115                                 return caller_is_taking;
3116                         }
3117
3118                         throw new NotImplementedException (directive.ToString ());
3119                 }
3120
3121                 int consume_string (bool quoted)
3122                 {
3123                         int c;
3124                         int pos = 0;
3125                         Location start_location = Location;
3126                         if (quoted)
3127                                 start_location = start_location - 1;
3128
3129 #if FULL_AST
3130                         int reader_pos = reader.Position;
3131 #endif
3132
3133                         while (true){
3134                                 // Cannot use get_char because of \r in quoted strings
3135                                 if (putback_char != -1) {
3136                                         c = putback_char;
3137                                         putback_char = -1;
3138                                 } else {
3139                                         c = reader.Read ();
3140                                 }
3141
3142                                 if (c == '"') {
3143                                         ++col;
3144
3145                                         if (quoted && peek_char () == '"') {
3146                                                 if (pos == value_builder.Length)
3147                                                         Array.Resize (ref value_builder, pos * 2);
3148
3149                                                 value_builder[pos++] = (char) c;
3150                                                 get_char ();
3151                                                 continue;
3152                                         }
3153
3154                                         ILiteralConstant res = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3155                                         val = res;
3156 #if FULL_AST
3157                                         res.ParsedValue = quoted ?
3158                                                 reader.ReadChars (reader_pos - 2, reader.Position - 1) :
3159                                                 reader.ReadChars (reader_pos - 1, reader.Position);
3160 #endif
3161
3162                                         return Token.LITERAL;
3163                                 }
3164
3165                                 if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3166                                         if (!quoted) {
3167                                                 Report.Error (1010, Location, "Newline in constant");
3168
3169                                                 advance_line ();
3170
3171                                                 // Don't add \r to string literal
3172                                                 if (pos > 1 && value_builder [pos - 1] == '\r')
3173                                                         --pos;
3174
3175                                                 val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
3176                                                 return Token.LITERAL;
3177                                         }
3178
3179                                         advance_line ();
3180                                 } else if (c == '\\' && !quoted) {
3181                                         ++col;
3182                                         int surrogate;
3183                                         c = escape (c, out surrogate);
3184                                         if (c == -1)
3185                                                 return Token.ERROR;
3186                                         if (surrogate != 0) {
3187                                                 if (pos == value_builder.Length)
3188                                                         Array.Resize (ref value_builder, pos * 2);
3189
3190                                                 value_builder[pos++] = (char) c;
3191                                                 c = surrogate;
3192                                         }
3193                                 } else if (c == -1) {
3194                                         Report.Error (1039, Location, "Unterminated string literal");
3195                                         return Token.EOF;
3196                                 } else {
3197                                         ++col;
3198                                 }
3199
3200                                 if (pos == value_builder.Length)
3201                                         Array.Resize (ref value_builder, pos * 2);
3202
3203                                 value_builder[pos++] = (char) c;
3204                         }
3205                 }
3206
3207                 private int consume_identifier (int s)
3208                 {
3209                         int res = consume_identifier (s, false);
3210
3211                         if (doc_state == XmlCommentState.Allowed)
3212                                 doc_state = XmlCommentState.NotAllowed;
3213
3214                         return res;
3215                 }
3216
3217                 int consume_identifier (int c, bool quoted) 
3218                 {
3219                         //
3220                         // This method is very performance sensitive. It accounts
3221                         // for approximately 25% of all parser time
3222                         //
3223
3224                         int pos = 0;
3225                         int column = col;
3226                         if (quoted)
3227                                 --column;
3228
3229                         if (c == '\\') {
3230                                 int surrogate;
3231                                 c = escape (c, out surrogate);
3232                                 if (quoted || is_identifier_start_character (c)) {
3233                                         // it's added bellow
3234                                 } else if (surrogate != 0) {
3235                                         id_builder [pos++] = (char)c;
3236                                         c = surrogate;
3237                                 } else {
3238                                         Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3239                                         return Token.ERROR;
3240                                 }
3241                         }
3242
3243                         id_builder [pos++] = (char) c;
3244
3245                         try {
3246                                 while (true) {
3247                                         c = reader.Read ();
3248
3249                                         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
3250                                                 id_builder [pos++] = (char) c;
3251                                                 continue;
3252                                         }
3253
3254                                         if (c < 0x80) {
3255                                                 if (c == '\\') {
3256                                                         int surrogate;
3257                                                         c = escape (c, out surrogate);
3258                                                         if (is_identifier_part_character ((char) c))
3259                                                                 id_builder[pos++] = (char) c;
3260                                                         else if (surrogate != 0) {
3261                                                                 c = surrogate;
3262                                                         } else {
3263                                                                 switch (c) {
3264                                                                 // TODO: Probably need more whitespace characters
3265                                                                 case 0xFEFF:
3266                                                                         putback_char = c;
3267                                                                         break;
3268                                                                 default:
3269                                                                         Report.Error (1056, Location, "Unexpected character `\\{0}'", c.ToString ("x4"));
3270                                                                         return Token.ERROR;
3271                                                                 }
3272                                                         }
3273
3274                                                         continue;
3275                                                 }
3276                                         } else if (is_identifier_part_character_slow_part ((char) c)) {
3277                                                 id_builder [pos++] = (char) c;
3278                                                 continue;
3279                                         }
3280
3281                                         putback_char = c;
3282                                         break;
3283                                 }
3284                         } catch (IndexOutOfRangeException) {
3285                                 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
3286                                 --pos;
3287                                 col += pos;
3288                         }
3289
3290                         col += pos - 1;
3291
3292                         //
3293                         // Optimization: avoids doing the keyword lookup
3294                         // on uppercase letters
3295                         //
3296                         if (id_builder [0] >= '_' && !quoted) {
3297                                 int keyword = GetKeyword (id_builder, pos);
3298                                 if (keyword != -1) {
3299                                         val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
3300                                         return keyword;
3301                                 }
3302                         }
3303
3304                         string s = InternIdentifier (id_builder, pos);
3305                         val = ltb.Create (s, current_source, ref_line, column);
3306                         if (quoted && parsing_attribute_section)
3307                                 AddEscapedIdentifier (((LocatedToken) val).Location);
3308
3309                         return Token.IDENTIFIER;
3310                 }
3311
3312                 string InternIdentifier (char[] charBuffer, int length)
3313                 {
3314                         //
3315                         // Keep identifiers in an array of hashtables to avoid needless
3316                         // allocations
3317                         //
3318                         var identifiers_group = identifiers[length];
3319                         string s;
3320                         if (identifiers_group != null) {
3321                                 if (identifiers_group.TryGetValue (charBuffer, out s)) {
3322                                         return s;
3323                                 }
3324                         } else {
3325                                 // TODO: this should be number of files dependant
3326                                 // corlib compilation peaks at 1000 and System.Core at 150
3327                                 int capacity = length > 20 ? 10 : 100;
3328                                 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
3329                                 identifiers[length] = identifiers_group;
3330                         }
3331
3332                         char[] chars = new char[length];
3333                         Array.Copy (charBuffer, chars, length);
3334
3335                         s = new string (charBuffer, 0, length);
3336                         identifiers_group.Add (chars, s);
3337                         return s;
3338                 }
3339                 
3340                 public int xtoken ()
3341                 {
3342                         if (parsing_interpolation_format) {
3343                                 return TokenizeInterpolationFormat ();
3344                         }
3345
3346                         int d, c;
3347
3348                         // Whether we have seen comments on the current line
3349                         bool comments_seen = false;
3350                         while ((c = get_char ()) != -1) {
3351                                 switch (c) {
3352                                 case '\t':
3353                                         col = ((col - 1 + tab_size) / tab_size) * tab_size;
3354                                         continue;
3355
3356                                 case ' ':
3357                                 case '\f':
3358                                 case '\v':
3359                                 case 0xa0:
3360                                 case 0:
3361                                 case 0xFEFF:    // Ignore BOM anywhere in the file
3362                                         continue;
3363
3364 /*                              This is required for compatibility with .NET
3365                                 case 0xEF:
3366                                         if (peek_char () == 0xBB) {
3367                                                 PushPosition ();
3368                                                 get_char ();
3369                                                 if (get_char () == 0xBF)
3370                                                         continue;
3371                                                 PopPosition ();
3372                                         }
3373                                         break;
3374 */
3375                                 case '\\':
3376                                         tokens_seen = true;
3377                                         return consume_identifier (c);
3378
3379                                 case '{':
3380                                         val = ltb.Create (current_source, ref_line, col);
3381
3382                                         if (parsing_string_interpolation > 0)
3383                                                 ++string_interpolation_section;
3384
3385                                         return Token.OPEN_BRACE;
3386                                 case '}':
3387                                         if (parsing_string_interpolation > 0) {
3388                                                 if (string_interpolation_section == 0) {
3389                                                         --parsing_string_interpolation;
3390                                                         bool quoted;
3391                                                         if (parsing_string_interpolation_quoted != null && parsing_string_interpolation_quoted.Count > 0) {
3392                                                                 quoted = parsing_string_interpolation_quoted.Pop ();
3393                                                         } else {
3394                                                                 quoted = false;
3395                                                         }
3396
3397                                                         return TokenizeInterpolatedString (quoted);
3398                                                 }
3399
3400                                                 --string_interpolation_section;
3401                                         }
3402
3403                                         val = ltb.Create (current_source, ref_line, col);
3404                                         return Token.CLOSE_BRACE;
3405                                 case '[':
3406                                         // To block doccomment inside attribute declaration.
3407                                         if (doc_state == XmlCommentState.Allowed)
3408                                                 doc_state = XmlCommentState.NotAllowed;
3409
3410                                         val = ltb.Create (current_source, ref_line, col);
3411
3412                                         if (parsing_block == 0 || lambda_arguments_parsing)
3413                                                 return Token.OPEN_BRACKET;
3414
3415                                         int next = peek_char ();
3416                                         switch (next) {
3417                                         case ']':
3418                                         case ',':
3419                                                 return Token.OPEN_BRACKET;
3420
3421                                         case ' ':
3422                                         case '\f':
3423                                         case '\v':
3424                                         case '\r':
3425                                         case '\n':
3426                                         case UnicodeLS:
3427                                         case UnicodePS:
3428                                         case '/':
3429                                                 next = peek_token ();
3430                                                 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
3431                                                         return Token.OPEN_BRACKET;
3432
3433                                                 return Token.OPEN_BRACKET_EXPR;
3434                                         default:
3435                                                 return Token.OPEN_BRACKET_EXPR;
3436                                         }
3437                                 case ']':
3438                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3439                                         return Token.CLOSE_BRACKET;
3440                                 case '(':
3441                                         val = ltb.Create (current_source, ref_line, col);
3442                                         //
3443                                         // An expression versions of parens can appear in block context only
3444                                         //
3445                                         if (parsing_block != 0 && !lambda_arguments_parsing) {
3446                                                 
3447                                                 //
3448                                                 // Optmize most common case where we know that parens
3449                                                 // is not special
3450                                                 //
3451                                                 switch (current_token) {
3452                                                 case Token.IDENTIFIER:
3453                                                 case Token.IF:
3454                                                 case Token.FOR:
3455                                                 case Token.FOREACH:
3456                                                 case Token.TYPEOF:
3457                                                 case Token.WHILE:
3458                                                 case Token.SWITCH:
3459                                                 case Token.USING:
3460                                                 case Token.DEFAULT:
3461                                                 case Token.DELEGATE:
3462                                                 case Token.OP_GENERICS_GT:
3463                                                         return Token.OPEN_PARENS;
3464                                                 }
3465
3466                                                 // Optimize using peek
3467                                                 int xx = peek_char ();
3468                                                 switch (xx) {
3469                                                 case '(':
3470                                                 case '\'':
3471                                                 case '"':
3472                                                 case '0':
3473                                                 case '1':
3474                                                         return Token.OPEN_PARENS;
3475                                                 }
3476
3477                                                 lambda_arguments_parsing = true;
3478                                                 PushPosition ();
3479                                                 d = TokenizeOpenParens ();
3480                                                 PopPosition ();
3481                                                 lambda_arguments_parsing = false;
3482                                                 return d;
3483                                         }
3484
3485                                         return Token.OPEN_PARENS;
3486                                 case ')':
3487                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3488                                         return Token.CLOSE_PARENS;
3489                                 case ',':
3490                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3491                                         return Token.COMMA;
3492                                 case ';':
3493                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3494                                         return Token.SEMICOLON;
3495                                 case '~':
3496                                         val = ltb.Create (current_source, ref_line, col);
3497                                         return Token.TILDE;
3498                                 case '?':
3499                                         val = ltb.Create (current_source, ref_line, col);
3500                                         return TokenizePossibleNullableType ();
3501                                 case '<':
3502                                         val = ltb.Create (current_source, ref_line, col);
3503                                         if (parsing_generic_less_than++ > 0)
3504                                                 return Token.OP_GENERICS_LT;
3505
3506                                         return TokenizeLessThan ();
3507
3508                                 case '>':
3509                                         val = ltb.Create (current_source, ref_line, col);
3510                                         d = peek_char ();
3511
3512                                         if (d == '='){
3513                                                 get_char ();
3514                                                 return Token.OP_GE;
3515                                         }
3516
3517                                         if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
3518                                                 parsing_generic_less_than--;
3519                                                 return Token.OP_GENERICS_GT;
3520                                         }
3521
3522                                         if (d == '>') {
3523                                                 get_char ();
3524                                                 d = peek_char ();
3525
3526                                                 if (d == '=') {
3527                                                         get_char ();
3528                                                         return Token.OP_SHIFT_RIGHT_ASSIGN;
3529                                                 }
3530                                                 return Token.OP_SHIFT_RIGHT;
3531                                         }
3532
3533                                         return Token.OP_GT;
3534
3535                                 case '+':
3536                                         val = ltb.Create (current_source, ref_line, col);
3537                                         d = peek_char ();
3538                                         if (d == '+') {
3539                                                 d = Token.OP_INC;
3540                                         } else if (d == '=') {
3541                                                 d = Token.OP_ADD_ASSIGN;
3542                                         } else {
3543                                                 return Token.PLUS;
3544                                         }
3545                                         get_char ();
3546                                         return d;
3547
3548                                 case '-':
3549                                         val = ltb.Create (current_source, ref_line, col);
3550                                         d = peek_char ();
3551                                         if (d == '-') {
3552                                                 d = Token.OP_DEC;
3553                                         } else if (d == '=')
3554                                                 d = Token.OP_SUB_ASSIGN;
3555                                         else if (d == '>')
3556                                                 d = Token.OP_PTR;
3557                                         else {
3558                                                 return Token.MINUS;
3559                                         }
3560                                         get_char ();
3561                                         return d;
3562
3563                                 case '!':
3564                                         val = ltb.Create (current_source, ref_line, col);
3565                                         if (peek_char () == '='){
3566                                                 get_char ();
3567                                                 return Token.OP_NE;
3568                                         }
3569                                         return Token.BANG;
3570
3571                                 case '=':
3572                                         val = ltb.Create (current_source, ref_line, col);
3573                                         d = peek_char ();
3574                                         if (d == '='){
3575                                                 get_char ();
3576                                                 return Token.OP_EQ;
3577                                         }
3578                                         if (d == '>'){
3579                                                 get_char ();
3580                                                 return Token.ARROW;
3581                                         }
3582
3583                                         return Token.ASSIGN;
3584
3585                                 case '&':
3586                                         val = ltb.Create (current_source, ref_line, col);
3587                                         d = peek_char ();
3588                                         if (d == '&'){
3589                                                 get_char ();
3590                                                 return Token.OP_AND;
3591                                         }
3592                                         if (d == '='){
3593                                                 get_char ();
3594                                                 return Token.OP_AND_ASSIGN;
3595                                         }
3596                                         return Token.BITWISE_AND;
3597
3598                                 case '|':
3599                                         val = ltb.Create (current_source, ref_line, col);
3600                                         d = peek_char ();
3601                                         if (d == '|'){
3602                                                 get_char ();
3603                                                 return Token.OP_OR;
3604                                         }
3605                                         if (d == '='){
3606                                                 get_char ();
3607                                                 return Token.OP_OR_ASSIGN;
3608                                         }
3609                                         return Token.BITWISE_OR;
3610
3611                                 case '*':
3612                                         val = ltb.Create (current_source, ref_line, col);
3613                                         if (peek_char () == '='){
3614                                                 get_char ();
3615                                                 return Token.OP_MULT_ASSIGN;
3616                                         }
3617                                         return Token.STAR;
3618
3619                                 case '/':
3620                                         d = peek_char ();
3621                                         if (d == '='){
3622                                                 val = ltb.Create (current_source, ref_line, col);
3623                                                 get_char ();
3624                                                 return Token.OP_DIV_ASSIGN;
3625                                         }
3626
3627                                         // Handle double-slash comments.
3628                                         if (d == '/'){
3629                                                 if (parsing_string_interpolation > 0) {
3630                                                         Report.Error (8077, Location, "A single-line comment may not be used in an interpolated string");
3631                                                         goto case '}';
3632                                                 }
3633
3634                                                 get_char ();
3635                                                 if (doc_processing) {
3636                                                         if (peek_char () == '/') {
3637                                                                 get_char ();
3638                                                                 // Don't allow ////.
3639                                                                 if ((d = peek_char ()) != '/') {
3640                                                                         if (doc_state == XmlCommentState.Allowed)
3641                                                                                 handle_one_line_xml_comment ();
3642                                                                         else if (doc_state == XmlCommentState.NotAllowed)
3643                                                                                 WarningMisplacedComment (Location - 3);
3644                                                                 }
3645                                                         } else {
3646                                                                 if (xml_comment_buffer.Length > 0)
3647                                                                         doc_state = XmlCommentState.NotAllowed;
3648                                                         }
3649                                                 }
3650
3651                                                 ReadToEndOfLine ();
3652
3653                                                 any_token_seen |= tokens_seen;
3654                                                 tokens_seen = false;
3655                                                 comments_seen = false;
3656                                                 continue;
3657                                         } else if (d == '*'){
3658                                                 get_char ();
3659                                                 bool docAppend = false;
3660                                                 if (doc_processing && peek_char () == '*') {
3661                                                         get_char ();
3662                                                         // But when it is /**/, just do nothing.
3663                                                         if (peek_char () == '/') {
3664                                                                 get_char ();
3665                                                                 continue;
3666                                                         }
3667                                                         if (doc_state == XmlCommentState.Allowed)
3668                                                                 docAppend = true;
3669                                                         else if (doc_state == XmlCommentState.NotAllowed) {
3670                                                                 WarningMisplacedComment (Location - 2);
3671                                                         }
3672                                                 }
3673
3674                                                 int current_comment_start = 0;
3675                                                 if (docAppend) {
3676                                                         current_comment_start = xml_comment_buffer.Length;
3677                                                         xml_comment_buffer.Append (Environment.NewLine);
3678                                                 }
3679
3680                                                 while ((d = get_char ()) != -1){
3681                                                         if (d == '*' && peek_char () == '/'){
3682                                                                 get_char ();
3683                                                                 comments_seen = true;
3684                                                                 break;
3685                                                         }
3686                                                         if (docAppend)
3687                                                                 xml_comment_buffer.Append ((char) d);
3688                                                         
3689                                                         if (d == '\n' || d == UnicodeLS || d == UnicodePS){
3690                                                                 any_token_seen |= tokens_seen;
3691                                                                 tokens_seen = false;
3692                                                                 // 
3693                                                                 // Reset 'comments_seen' just to be consistent.
3694                                                                 // It doesn't matter either way, here.
3695                                                                 //
3696                                                                 comments_seen = false;
3697                                                         }
3698                                                 }
3699                                                 if (!comments_seen)
3700                                                         Report.Error (1035, Location, "End-of-file found, '*/' expected");
3701
3702                                                 if (docAppend)
3703                                                         update_formatted_doc_comment (current_comment_start);
3704                                                 continue;
3705                                         }
3706                                         val = ltb.Create (current_source, ref_line, col);
3707                                         return Token.DIV;
3708
3709                                 case '%':
3710                                         val = ltb.Create (current_source, ref_line, col);
3711                                         if (peek_char () == '='){
3712                                                 get_char ();
3713                                                 return Token.OP_MOD_ASSIGN;
3714                                         }
3715                                         return Token.PERCENT;
3716
3717                                 case '^':
3718                                         val = ltb.Create (current_source, ref_line, col);
3719                                         if (peek_char () == '='){
3720                                                 get_char ();
3721                                                 return Token.OP_XOR_ASSIGN;
3722                                         }
3723                                         return Token.CARRET;
3724
3725                                 case ':':
3726                                         val = ltb.Create (current_source, ref_line, col);
3727                                         if (peek_char () == ':') {
3728                                                 get_char ();
3729                                                 return Token.DOUBLE_COLON;
3730                                         }
3731                                         return Token.COLON;
3732
3733                                 case '0': case '1': case '2': case '3': case '4':
3734                                 case '5': case '6': case '7': case '8': case '9':
3735                                         tokens_seen = true;
3736                                         return is_number (c, false);
3737
3738                                 case '\n': // white space
3739                                 case UnicodeLS:
3740                                 case UnicodePS:
3741                                         any_token_seen |= tokens_seen;
3742                                         tokens_seen = false;
3743                                         comments_seen = false;
3744                                         continue;
3745
3746                                 case '.':
3747                                         tokens_seen = true;
3748                                         d = peek_char ();
3749                                         if (d >= '0' && d <= '9')
3750                                                 return is_number (c, true);
3751
3752                                         ltb.CreateOptional (current_source, ref_line, col, ref val);
3753                                         return Token.DOT;
3754                                 
3755                                 case '#':
3756                                         if (tokens_seen || comments_seen) {
3757                                                 Eror_WrongPreprocessorLocation ();
3758                                                 return Token.ERROR;
3759                                         }
3760                                         
3761                                         if (ParsePreprocessingDirective (true))
3762                                                 continue;
3763
3764                                         bool directive_expected = false;
3765                                         while ((c = get_char ()) != -1) {
3766                                                 if (col == 1) {
3767                                                         directive_expected = true;
3768                                                 } else if (!directive_expected) {
3769                                                         // TODO: Implement comment support for disabled code and uncomment this code
3770 //                                                      if (c == '#') {
3771 //                                                              Eror_WrongPreprocessorLocation ();
3772 //                                                              return Token.ERROR;
3773 //                                                      }
3774                                                         continue;
3775                                                 }
3776
3777                                                 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS)
3778                                                         continue;
3779
3780                                                 if (c == '#') {
3781                                                         if (ParsePreprocessingDirective (false))
3782                                                                 break;
3783                                                 }
3784                                                 directive_expected = false;
3785                                         }
3786
3787                                         if (c != -1) {
3788                                                 tokens_seen = false;
3789                                                 continue;
3790                                         }
3791
3792                                         return Token.EOF;
3793                                 
3794                                 case '"':
3795                                         if (parsing_string_interpolation > 0 && !ScanClosingInterpolationBrace ()) {
3796                                                 parsing_string_interpolation = 0;
3797                                                 Report.Error (8076, Location, "Missing close delimiter `}' for interpolated expression");
3798                                                 val = new StringLiteral (context.BuiltinTypes, "", Location);
3799                                                 return Token.INTERPOLATED_STRING_END;
3800                                         }
3801
3802                                         return consume_string (false);
3803
3804                                 case '\'':
3805                                         return TokenizeBackslash ();
3806                                 
3807                                 case '@':
3808                                         c = get_char ();
3809                                         if (c == '"') {
3810                                                 tokens_seen = true;
3811                                                 return consume_string (true);
3812                                         }
3813
3814                                         if (is_identifier_start_character (c)){
3815                                                 return consume_identifier (c, true);
3816                                         }
3817
3818                                         Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3819                                         return Token.ERROR;
3820
3821                                 case '$':
3822                                         switch (peek_char ()) {
3823                                         case '"':
3824                                                 get_char ();
3825                                                 return TokenizeInterpolatedString (false);
3826                                         case '@':
3827                                                 get_char ();
3828                                                 if (peek_char () == '"') {
3829                                                         get_char ();
3830                                                         return TokenizeInterpolatedString (true);
3831                                                 }
3832
3833                                                 break;
3834                                         }
3835
3836                                         break;
3837                                 case EvalStatementParserCharacter:
3838                                         return Token.EVAL_STATEMENT_PARSER;
3839                                 case EvalCompilationUnitParserCharacter:
3840                                         return Token.EVAL_COMPILATION_UNIT_PARSER;
3841                                 case EvalUsingDeclarationsParserCharacter:
3842                                         return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3843                                 case DocumentationXref:
3844                                         return Token.DOC_SEE;
3845                                 }
3846
3847                                 if (is_identifier_start_character (c)) {
3848                                         tokens_seen = true;
3849                                         return consume_identifier (c);
3850                                 }
3851
3852                                 if (char.IsWhiteSpace ((char) c))
3853                                         continue;
3854
3855                                 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3856                         }
3857
3858                         if (CompleteOnEOF){
3859                                 if (generated)
3860                                         return Token.COMPLETE_COMPLETION;
3861                                 
3862                                 generated = true;
3863                                 return Token.GENERATE_COMPLETION;
3864                         }
3865                         
3866
3867                         return Token.EOF;
3868                 }
3869
3870                 int TokenizeBackslash ()
3871                 {
3872 #if FULL_AST
3873                         int read_start = reader.Position;
3874 #endif
3875                         Location start_location = Location;
3876                         int c = get_char ();
3877                         tokens_seen = true;
3878                         if (c == '\'') {
3879                                 val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3880                                 Report.Error (1011, start_location, "Empty character literal");
3881                                 return Token.LITERAL;
3882                         }
3883
3884                         if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
3885                                 Report.Error (1010, start_location, "Newline in constant");
3886                                 return Token.ERROR;
3887                         }
3888
3889                         int d;
3890                         c = escape (c, out d);
3891                         if (c == -1)
3892                                 return Token.ERROR;
3893                         if (d != 0)
3894                                 throw new NotImplementedException ();
3895
3896                         ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
3897                         val = res;
3898                         c = get_char ();
3899
3900                         if (c != '\'') {
3901                                 Report.Error (1012, start_location, "Too many characters in character literal");
3902
3903                                 // Try to recover, read until newline or next "'"
3904                                 while ((c = get_char ()) != -1) {
3905                                         if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
3906                                                 break;
3907                                 }
3908                         }
3909
3910 #if FULL_AST
3911                         res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
3912 #endif
3913
3914                         return Token.LITERAL;
3915                 }
3916
3917                 int TokenizeLessThan ()
3918                 {
3919                         int d;
3920
3921                         // Save current position and parse next token.
3922                         PushPosition ();
3923                         int generic_dimension = 0;
3924                         if (parse_less_than (ref generic_dimension)) {
3925                                 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3926                                         d = Token.OP_GENERICS_LT_DECL;
3927                                 } else {
3928                                         if (generic_dimension > 0) {
3929                                                 val = generic_dimension;
3930                                                 DiscardPosition ();
3931                                                 return Token.GENERIC_DIMENSION;
3932                                         }
3933
3934                                         d = Token.OP_GENERICS_LT;
3935                                 }
3936                                 PopPosition ();
3937                                 return d;
3938                         }
3939
3940                         PopPosition ();
3941                         parsing_generic_less_than = 0;
3942
3943                         d = peek_char ();
3944                         if (d == '<') {
3945                                 get_char ();
3946                                 d = peek_char ();
3947
3948                                 if (d == '=') {
3949                                         get_char ();
3950                                         return Token.OP_SHIFT_LEFT_ASSIGN;
3951                                 }
3952                                 return Token.OP_SHIFT_LEFT;
3953                         }
3954
3955                         if (d == '=') {
3956                                 get_char ();
3957                                 return Token.OP_LE;
3958                         }
3959                         return Token.OP_LT;
3960                 }
3961
3962                 int TokenizeInterpolatedString (bool quoted)
3963                 {
3964                         int pos = 0;
3965                         var start_location = Location;
3966
3967                         while (true) {
3968                                 var ch = get_char ();
3969                                 switch (ch) {
3970                                 case '"':
3971                                         if (quoted && peek_char () == '"') {
3972                                                 get_char ();
3973                                                 break;
3974                                         }
3975
3976                                         val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3977                                         return Token.INTERPOLATED_STRING_END;
3978                                 case '{':
3979                                         if (peek_char () == '{') {
3980                                                 value_builder [pos++] = (char)ch;
3981                                                 get_char ();
3982                                                 break;
3983                                         }
3984
3985                                         ++parsing_string_interpolation;
3986                                         if (quoted) {
3987                                                 if (parsing_string_interpolation_quoted == null)
3988                                                         parsing_string_interpolation_quoted = new Stack<bool> ();
3989                                         }
3990
3991                                         if (parsing_string_interpolation_quoted != null) {
3992                                                 parsing_string_interpolation_quoted.Push (quoted);
3993                                         }
3994
3995                                         val = new StringLiteral (context.BuiltinTypes, CreateStringFromBuilder (pos), start_location);
3996                                         return Token.INTERPOLATED_STRING;
3997                                 case '\\':
3998                                         if (quoted)
3999                                                 break;
4000                                         
4001                                         ++col;
4002                                         int surrogate;
4003                                         ch = escape (ch, out surrogate);
4004                                         if (ch == -1)
4005                                                 return Token.ERROR;
4006
4007                                         if (ch == '{' || ch == '}') {
4008                                                 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4009                                         }
4010
4011                                         if (surrogate != 0) {
4012                                                 if (pos == value_builder.Length)
4013                                                         Array.Resize (ref value_builder, pos * 2);
4014
4015                                                 if (pos == value_builder.Length)
4016                                                         Array.Resize (ref value_builder, pos * 2);
4017
4018                                                 value_builder [pos++] = (char)ch;
4019                                                 ch = surrogate;
4020                                         }
4021
4022                                         break;
4023                                 case -1:
4024                                         return Token.EOF;
4025                                 }
4026
4027                                 ++col;
4028                                 if (pos == value_builder.Length)
4029                                         Array.Resize (ref value_builder, pos * 2);
4030
4031                                 value_builder[pos++] = (char) ch;
4032                         }
4033                 }
4034
4035                 int TokenizeInterpolationFormat ()
4036                 {
4037                         int pos = 0;
4038                         int braces = 0;
4039                         while (true) {
4040                                 var ch = get_char ();
4041                                 switch (ch) {
4042                                 case '{':
4043                                         ++braces;
4044                                         break;
4045                                 case '}':
4046                                         if (braces == 0) {
4047                                                 putback_char = ch;
4048                                                 if (pos == 0) {
4049                                                         Report.Error (8089, Location, "Empty interpolated expression format specifier");
4050                                                 } else if (Array.IndexOf (simple_whitespaces, value_builder [pos - 1]) >= 0) {
4051                                                         Report.Error (8088, Location, "A interpolated expression format specifier may not contain trailing whitespace");
4052                                                 }
4053
4054                                                 val = CreateStringFromBuilder (pos);
4055                                                 return Token.LITERAL;
4056                                         }
4057
4058                                         --braces;
4059                                         break;
4060                                 case '\\':
4061                                         ++col;
4062                                         int surrogate;
4063                                         ch = escape (ch, out surrogate);
4064                                         if (ch == -1)
4065                                                 return Token.ERROR;
4066
4067                                         if (ch == '{' || ch == '}') {
4068                                                 Report.Error (8087, Location, "A `{0}' character may only be escaped by doubling `{0}{0}' in an interpolated string", ((char) ch).ToString ());
4069                                         }
4070
4071                                         if (surrogate != 0) {
4072                                                 if (pos == value_builder.Length)
4073                                                         Array.Resize (ref value_builder, pos * 2);
4074
4075                                                 value_builder [pos++] = (char)ch;
4076                                                 ch = surrogate;
4077                                         }
4078
4079                                         break;
4080                                 case -1:
4081                                         return Token.EOF;
4082                                 }
4083
4084                                 ++col;
4085                                 value_builder[pos++] = (char) ch;
4086                         }
4087                 }
4088
4089                 string CreateStringFromBuilder (int pos)
4090                 {
4091                         if (pos == 0)
4092                                 return string.Empty;
4093                         if (pos <= 4)
4094                                 return InternIdentifier (value_builder, pos);
4095
4096                         return new string (value_builder, 0, pos);
4097                 }
4098
4099                 //
4100                 // Handles one line xml comment
4101                 //
4102                 private void handle_one_line_xml_comment ()
4103                 {
4104                         int c;
4105                         while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
4106                                 xml_comment_buffer.Append ((char) get_char ());
4107                         }
4108                         if (c == '\r' || c == '\n')
4109                                 xml_comment_buffer.Append (Environment.NewLine);
4110                 }
4111
4112                 //
4113                 // Remove heading "*" in Javadoc-like xml documentation.
4114                 //
4115                 private void update_formatted_doc_comment (int current_comment_start)
4116                 {
4117                         int length = xml_comment_buffer.Length - current_comment_start;
4118                         string [] lines = xml_comment_buffer.ToString (
4119                                 current_comment_start,
4120                                 length).Replace ("\r", "").Split ('\n');
4121                         
4122                         // The first line starts with /**, thus it is not target
4123                         // for the format check.
4124                         for (int i = 1; i < lines.Length; i++) {
4125                                 string s = lines [i];
4126                                 int idx = s.IndexOf ('*');
4127                                 string head = null;
4128                                 if (idx < 0) {
4129                                         if (i < lines.Length - 1)
4130                                                 return;
4131                                         head = s;
4132                                 } else
4133                                         head = s.Substring (0, idx);
4134                                 foreach (char c in head)
4135                                         if (c != ' ')
4136                                                 return;
4137                                 lines [i] = s.Substring (idx + 1);
4138                         }
4139                         xml_comment_buffer.Remove (current_comment_start, length);
4140                         xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
4141                 }
4142
4143                 //
4144                 // Checks if there was incorrect doc comments and raise
4145                 // warnings.
4146                 //
4147                 public void check_incorrect_doc_comment ()
4148                 {
4149                         if (xml_comment_buffer.Length > 0)
4150                                 WarningMisplacedComment (Location);
4151                 }
4152
4153                 //
4154                 // Consumes the saved xml comment lines (if any)
4155                 // as for current target member or type.
4156                 //
4157                 public string consume_doc_comment ()
4158                 {
4159                         if (xml_comment_buffer.Length > 0) {
4160                                 string ret = xml_comment_buffer.ToString ();
4161                                 reset_doc_comment ();
4162                                 return ret;
4163                         }
4164                         return null;
4165                 }
4166
4167                 void reset_doc_comment ()
4168                 {
4169                         xml_comment_buffer.Length = 0;
4170                 }
4171
4172                 public void cleanup ()
4173                 {
4174                         if (ifstack != null && ifstack.Count >= 1) {
4175                                 int state = ifstack.Pop ();
4176                                 if ((state & REGION) != 0)
4177                                         Report.Error (1038, Location, "#endregion directive expected");
4178                                 else 
4179                                         Report.Error (1027, Location, "Expected `#endif' directive");
4180                         }
4181                 }
4182         }
4183
4184         //
4185         // Indicates whether it accepts XML documentation or not.
4186         //
4187         public enum XmlCommentState {
4188                 // comment is allowed in this state.
4189                 Allowed,
4190                 // comment is not allowed in this state.
4191                 NotAllowed,
4192                 // once comments appeared when it is NotAllowed, then the
4193                 // state is changed to it, until the state is changed to
4194                 // .Allowed.
4195                 Error
4196         }
4197 }
4198