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