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