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