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