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