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