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