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