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