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