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