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