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