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