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