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