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