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