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