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