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