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