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