Allow XML documentation predefined types to be used with parameters for methods
[mono.git] / mcs / mcs / cs-tokenizer.cs
1 //
2 // cs-tokenizer.cs: The Tokenizer for the C# compiler
3 //                  This also implements the preprocessor
4 //
5 // Author: Miguel de Icaza (miguel@gnu.org)
6 //         Marek Safar (marek.safar@seznam.cz)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 //
13 //
14
15 using System;
16 using System.Text;
17 using System.Collections.Generic;
18 using System.Globalization;
19 using System.Diagnostics;
20
21 namespace Mono.CSharp
22 {
23         /// <summary>
24         ///    Tokenizer for C# source code. 
25         /// </summary>
26
27         public class Tokenizer : yyParser.yyInput
28         {
29                 class KeywordEntry<T>
30                 {
31                         public readonly T Token;
32                         public KeywordEntry<T> Next;
33                         public readonly char[] Value;
34
35                         public KeywordEntry (string value, T token)
36                         {
37                                 this.Value = value.ToCharArray ();
38                                 this.Token = token;
39                         }
40                 }
41
42                 sealed class IdentifiersComparer : IEqualityComparer<char[]>
43                 {
44                         readonly int length;
45
46                         public IdentifiersComparer (int length)
47                         {
48                                 this.length = length;
49                         }
50
51                         public bool Equals (char[] x, char[] y)
52                         {
53                                 for (int i = 0; i < length; ++i)
54                                         if (x [i] != y [i])
55                                                 return false;
56
57                                 return true;
58                         }
59
60                         public int GetHashCode (char[] obj)
61                         {
62                                 int h = 0;
63                                 for (int i = 0; i < length; ++i)
64                                         h = (h << 5) - h + obj [i];
65
66                                 return h;
67                         }
68                 }
69
70                 //
71                 // This class has to be used in the parser only, it reuses token
72                 // details after each parse
73                 //
74                 public class LocatedToken
75                 {
76                         int row, column;
77                         string value;
78
79                         static LocatedToken[] buffer;
80                         static int pos;
81
82                         private LocatedToken ()
83                         {
84                         }
85
86                         public static LocatedToken Create (int row, int column)
87                         {
88                                 return Create (null, row, column);
89                         }
90                         
91                         public static LocatedToken Create (string value, int row, int column)
92                         {
93                                 //
94                                 // TODO: I am not very happy about the logic but it's the best
95                                 // what I could come up with for now.
96                                 // Ideally we should be using just tiny buffer (256 elements) which
97                                 // is enough to hold all details for currect stack and recycle elements
98                                 // poped from the stack but there is a trick needed to recycle
99                                 // them properly.
100                                 //
101                                 LocatedToken entry;
102                                 if (pos >= buffer.Length) {
103                                         entry = new LocatedToken ();
104                                 } else {
105                                         entry = buffer [pos];
106                                         if (entry == null) {
107                                                 entry = new LocatedToken ();
108                                                 buffer [pos] = entry;
109                                         }
110
111                                         ++pos;
112                                 }
113                                 entry.value = value;
114                                 entry.row = row;
115                                 entry.column = column;
116                                 return entry;
117                         }
118
119                         //
120                         // Used for token not required by expression evaluator
121                         //
122                         [Conditional ("FULL_AST")]
123                         public static void CreateOptional (int row, int col, ref object token)
124                         {
125                                 token = Create (row, col);
126                         }
127                         
128                         public static void Initialize ()
129                         {
130                                 if (buffer == null)
131                                         buffer = new LocatedToken [10000];
132                                 pos = 0;
133                         }
134
135                         public Location Location {
136                                 get { return new Location (row, column); }
137                         }
138
139                         public string Value {
140                                 get { return value; }
141                         }
142                 }
143
144                 enum PreprocessorDirective
145                 {
146                         Invalid = 0,
147
148                         Region = 1,
149                         Endregion = 2,
150                         If = 3 | RequiresArgument,
151                         Endif = 4,
152                         Elif = 5 | RequiresArgument,
153                         Else = 6,
154                         Define = 7 | RequiresArgument,
155                         Undef = 8 | RequiresArgument,
156                         Error = 9,
157                         Warning = 10,
158                         Pragma = 11 | CustomArgumentsParsing,
159                         Line = 12,
160
161                         CustomArgumentsParsing = 1 << 10,
162                         RequiresArgument = 1 << 11
163                 }
164
165                 SeekableStreamReader reader;
166                 SourceFile ref_name;
167                 CompilationSourceFile file_name;
168                 CompilerContext context;
169                 bool hidden = false;
170                 int ref_line = 1;
171                 int line = 1;
172                 int col = 0;
173                 int previous_col;
174                 int current_token;
175                 int tab_size;
176                 bool handle_get_set = false;
177                 bool handle_remove_add = false;
178                 bool handle_where = false;
179                 bool handle_typeof = false;
180                 bool lambda_arguments_parsing;
181                 List<Location> escaped_identifiers;
182                 int parsing_generic_less_than;
183                 readonly bool doc_processing;
184                 
185                 //
186                 // Used mainly for parser optimizations. Some expressions for instance
187                 // can appear only in block (including initializer, base initializer)
188                 // scope only
189                 //
190                 public int parsing_block;
191                 internal bool query_parsing;
192                 
193                 // 
194                 // When parsing type only, useful for ambiguous nullable types
195                 //
196                 public int parsing_type;
197                 
198                 //
199                 // Set when parsing generic declaration (type or method header)
200                 //
201                 public bool parsing_generic_declaration;
202                 public bool parsing_generic_declaration_doc;
203                 
204                 //
205                 // The value indicates that we have not reach any declaration or
206                 // namespace yet
207                 //
208                 public int parsing_declaration;
209
210                 public bool parsing_attribute_section;
211
212                 //
213                 // The special characters to inject on streams to run the unit parser
214                 // in the special expression mode. Using private characters from
215                 // Plane Sixteen (U+100000 to U+10FFFD)
216                 //
217                 // This character is only tested just before the tokenizer is about to report
218                 // an error;   So on the regular operation mode, this addition will have no
219                 // impact on the tokenizer's performance.
220                 //
221                 
222                 public const int EvalStatementParserCharacter = 0x100000;
223                 public const int EvalCompilationUnitParserCharacter = 0x100001;
224                 public const int EvalUsingDeclarationsParserCharacter = 0x100002;
225                 public const int DocumentationXref = 0x100003;
226                 
227                 //
228                 // XML documentation buffer. The save point is used to divide
229                 // comments on types and comments on members.
230                 //
231                 StringBuilder xml_comment_buffer;
232
233                 //
234                 // See comment on XmlCommentState enumeration.
235                 //
236                 XmlCommentState xml_doc_state = XmlCommentState.Allowed;
237
238                 //
239                 // Whether tokens have been seen on this line
240                 //
241                 bool tokens_seen = false;
242
243                 //
244                 // Set to true once the GENERATE_COMPLETION token has bee
245                 // returned.   This helps produce one GENERATE_COMPLETION,
246                 // as many COMPLETE_COMPLETION as necessary to complete the
247                 // AST tree and one final EOF.
248                 //
249                 bool generated;
250                 
251                 //
252                 // Whether a token has been seen on the file
253                 // This is needed because `define' is not allowed to be used
254                 // after a token has been seen.
255                 //
256                 bool any_token_seen;
257
258                 //
259                 // Class variables
260                 // 
261                 static readonly KeywordEntry<int>[][] keywords;
262                 static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
263                 static readonly Dictionary<string, object> keyword_strings;             // TODO: HashSet
264                 static readonly NumberStyles styles;
265                 static readonly NumberFormatInfo csharp_format_info;
266
267                 // Pragma arguments
268                 static readonly char[] pragma_warning = "warning".ToCharArray ();
269                 static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
270                 static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
271                 static readonly char[] pragma_checksum = "checksum".ToCharArray ();
272
273                 static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
274
275                 public bool PropertyParsing {
276                         get { return handle_get_set; }
277                         set { handle_get_set = value; }
278                 }
279
280                 public bool EventParsing {
281                         get { return handle_remove_add; }
282                         set { handle_remove_add = value; }
283                 }
284
285                 public bool ConstraintsParsing {
286                         get { return handle_where; }
287                         set { handle_where = value; }
288                 }
289
290                 public bool TypeOfParsing {
291                         get { return handle_typeof; }
292                         set { handle_typeof = value; }
293                 }
294
295                 public int TabSize {
296                         get { return tab_size; }
297                         set { tab_size = value; }
298                 }
299                 
300                 public XmlCommentState doc_state {
301                         get { return xml_doc_state; }
302                         set {
303                                 if (value == XmlCommentState.Allowed) {
304                                         check_incorrect_doc_comment ();
305                                         reset_doc_comment ();
306                                 }
307                                 xml_doc_state = value;
308                         }
309                 }
310
311                 //
312                 // This is used to trigger completion generation on the parser
313                 public bool CompleteOnEOF;
314                 
315                 void AddEscapedIdentifier (Location loc)
316                 {
317                         if (escaped_identifiers == null)
318                                 escaped_identifiers = new List<Location> ();
319
320                         escaped_identifiers.Add (loc);
321                 }
322
323                 public bool IsEscapedIdentifier (MemberName name)
324                 {
325                         return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
326                 }
327
328                 //
329                 // Values for the associated token returned
330                 //
331                 internal int putback_char;      // Used by repl only
332                 object val;
333
334                 //
335                 // Pre-processor
336                 //
337                 const int TAKING        = 1;
338                 const int ELSE_SEEN     = 4;
339                 const int PARENT_TAKING = 8;
340                 const int REGION        = 16;           
341
342                 //
343                 // pre-processor if stack state:
344                 //
345                 Stack<int> ifstack;
346
347                 static System.Text.StringBuilder string_builder;
348
349                 const int max_id_size = 512;
350                 static readonly char [] id_builder = new char [max_id_size];
351
352                 public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
353
354                 const int max_number_size = 512;
355                 static char [] number_builder = new char [max_number_size];
356                 static int number_pos;
357
358                 static char[] value_builder = new char[256];
359
360                 public int Line {
361                         get {
362                                 return ref_line;
363                         }
364                 }
365
366                 //
367                 // This is used when the tokenizer needs to save
368                 // the current position as it needs to do some parsing
369                 // on its own to deamiguate a token in behalf of the
370                 // parser.
371                 //
372                 Stack<Position> position_stack = new Stack<Position> (2);
373
374                 class Position {
375                         public int position;
376                         public int line;
377                         public int ref_line;
378                         public int col;
379                         public bool hidden;
380                         public int putback_char;
381                         public int previous_col;
382                         public Stack<int> ifstack;
383                         public int parsing_generic_less_than;
384                         public int current_token;
385                         public object val;
386
387                         public Position (Tokenizer t)
388                         {
389                                 position = t.reader.Position;
390                                 line = t.line;
391                                 ref_line = t.ref_line;
392                                 col = t.col;
393                                 hidden = t.hidden;
394                                 putback_char = t.putback_char;
395                                 previous_col = t.previous_col;
396                                 if (t.ifstack != null && t.ifstack.Count != 0) {
397                                         // There is no simple way to clone Stack<T> all
398                                         // methods reverse the order
399                                         var clone = t.ifstack.ToArray ();
400                                         Array.Reverse (clone);
401                                         ifstack = new Stack<int> (clone);
402                                 }
403                                 parsing_generic_less_than = t.parsing_generic_less_than;
404                                 current_token = t.current_token;
405                                 val = t.val;
406                         }
407                 }
408
409                 public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, CompilerContext ctx)
410                 {
411                         this.ref_name = file;
412                         this.file_name = file;
413                         this.context = ctx;
414                         reader = input;
415
416                         putback_char = -1;
417
418                         xml_comment_buffer = new StringBuilder ();
419                         doc_processing = ctx.Settings.DocumentationFile != null;
420
421                         if (Environment.OSVersion.Platform == PlatformID.Win32NT)
422                                 tab_size = 4;
423                         else
424                                 tab_size = 8;
425
426                         //
427                         // FIXME: This could be `Location.Push' but we have to
428                         // find out why the MS compiler allows this
429                         //
430                         Mono.CSharp.Location.Push (file, file);
431                 }
432                 
433                 public void PushPosition ()
434                 {
435                         position_stack.Push (new Position (this));
436                 }
437
438                 public void PopPosition ()
439                 {
440                         Position p = position_stack.Pop ();
441
442                         reader.Position = p.position;
443                         ref_line = p.ref_line;
444                         line = p.line;
445                         col = p.col;
446                         hidden = p.hidden;
447                         putback_char = p.putback_char;
448                         previous_col = p.previous_col;
449                         ifstack = p.ifstack;
450                         parsing_generic_less_than = p.parsing_generic_less_than;
451                         current_token = p.current_token;
452                         val = p.val;
453                 }
454
455                 // Do not reset the position, ignore it.
456                 public void DiscardPosition ()
457                 {
458                         position_stack.Pop ();
459                 }
460                 
461                 static void AddKeyword (string kw, int token)
462                 {
463                         keyword_strings.Add (kw, null);
464
465                         AddKeyword (keywords, kw, token);
466                 }
467
468                 static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
469                 {
470                         AddKeyword (keywords_preprocessor, kw, directive);
471                 }
472
473                 static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
474                 {
475                         int length = kw.Length;
476                         if (keywords[length] == null) {
477                                 keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
478                         }
479
480                         int char_index = kw[0] - '_';
481                         var kwe = keywords[length][char_index];
482                         if (kwe == null) {
483                                 keywords[length][char_index] = new KeywordEntry<T> (kw, token);
484                                 return;
485                         }
486
487                         while (kwe.Next != null) {
488                                 kwe = kwe.Next;
489                         }
490
491                         kwe.Next = new KeywordEntry<T> (kw, token);
492                 }
493
494                 //
495                 // Class initializer
496                 // 
497                 static Tokenizer ()
498                 {
499                         keyword_strings = new Dictionary<string, object> ();
500
501                         // 11 is the length of the longest keyword for now
502                         keywords = new KeywordEntry<int>[11][];
503
504                         AddKeyword ("__arglist", Token.ARGLIST);
505                         AddKeyword ("__makeref", Token.MAKEREF);
506                         AddKeyword ("__reftype", Token.REFTYPE);
507                         AddKeyword ("__refvalue", Token.REFVALUE);
508                         AddKeyword ("abstract", Token.ABSTRACT);
509                         AddKeyword ("as", Token.AS);
510                         AddKeyword ("add", Token.ADD);
511                         AddKeyword ("base", Token.BASE);
512                         AddKeyword ("bool", Token.BOOL);
513                         AddKeyword ("break", Token.BREAK);
514                         AddKeyword ("byte", Token.BYTE);
515                         AddKeyword ("case", Token.CASE);
516                         AddKeyword ("catch", Token.CATCH);
517                         AddKeyword ("char", Token.CHAR);
518                         AddKeyword ("checked", Token.CHECKED);
519                         AddKeyword ("class", Token.CLASS);
520                         AddKeyword ("const", Token.CONST);
521                         AddKeyword ("continue", Token.CONTINUE);
522                         AddKeyword ("decimal", Token.DECIMAL);
523                         AddKeyword ("default", Token.DEFAULT);
524                         AddKeyword ("delegate", Token.DELEGATE);
525                         AddKeyword ("do", Token.DO);
526                         AddKeyword ("double", Token.DOUBLE);
527                         AddKeyword ("else", Token.ELSE);
528                         AddKeyword ("enum", Token.ENUM);
529                         AddKeyword ("event", Token.EVENT);
530                         AddKeyword ("explicit", Token.EXPLICIT);
531                         AddKeyword ("extern", Token.EXTERN);
532                         AddKeyword ("false", Token.FALSE);
533                         AddKeyword ("finally", Token.FINALLY);
534                         AddKeyword ("fixed", Token.FIXED);
535                         AddKeyword ("float", Token.FLOAT);
536                         AddKeyword ("for", Token.FOR);
537                         AddKeyword ("foreach", Token.FOREACH);
538                         AddKeyword ("goto", Token.GOTO);
539                         AddKeyword ("get", Token.GET);
540                         AddKeyword ("if", Token.IF);
541                         AddKeyword ("implicit", Token.IMPLICIT);
542                         AddKeyword ("in", Token.IN);
543                         AddKeyword ("int", Token.INT);
544                         AddKeyword ("interface", Token.INTERFACE);
545                         AddKeyword ("internal", Token.INTERNAL);
546                         AddKeyword ("is", Token.IS);
547                         AddKeyword ("lock", Token.LOCK);
548                         AddKeyword ("long", Token.LONG);
549                         AddKeyword ("namespace", Token.NAMESPACE);
550                         AddKeyword ("new", Token.NEW);
551                         AddKeyword ("null", Token.NULL);
552                         AddKeyword ("object", Token.OBJECT);
553                         AddKeyword ("operator", Token.OPERATOR);
554                         AddKeyword ("out", Token.OUT);
555                         AddKeyword ("override", Token.OVERRIDE);
556                         AddKeyword ("params", Token.PARAMS);
557                         AddKeyword ("private", Token.PRIVATE);
558                         AddKeyword ("protected", Token.PROTECTED);
559                         AddKeyword ("public", Token.PUBLIC);
560                         AddKeyword ("readonly", Token.READONLY);
561                         AddKeyword ("ref", Token.REF);
562                         AddKeyword ("remove", Token.REMOVE);
563                         AddKeyword ("return", Token.RETURN);
564                         AddKeyword ("sbyte", Token.SBYTE);
565                         AddKeyword ("sealed", Token.SEALED);
566                         AddKeyword ("set", Token.SET);
567                         AddKeyword ("short", Token.SHORT);
568                         AddKeyword ("sizeof", Token.SIZEOF);
569                         AddKeyword ("stackalloc", Token.STACKALLOC);
570                         AddKeyword ("static", Token.STATIC);
571                         AddKeyword ("string", Token.STRING);
572                         AddKeyword ("struct", Token.STRUCT);
573                         AddKeyword ("switch", Token.SWITCH);
574                         AddKeyword ("this", Token.THIS);
575                         AddKeyword ("throw", Token.THROW);
576                         AddKeyword ("true", Token.TRUE);
577                         AddKeyword ("try", Token.TRY);
578                         AddKeyword ("typeof", Token.TYPEOF);
579                         AddKeyword ("uint", Token.UINT);
580                         AddKeyword ("ulong", Token.ULONG);
581                         AddKeyword ("unchecked", Token.UNCHECKED);
582                         AddKeyword ("unsafe", Token.UNSAFE);
583                         AddKeyword ("ushort", Token.USHORT);
584                         AddKeyword ("using", Token.USING);
585                         AddKeyword ("virtual", Token.VIRTUAL);
586                         AddKeyword ("void", Token.VOID);
587                         AddKeyword ("volatile", Token.VOLATILE);
588                         AddKeyword ("while", Token.WHILE);
589                         AddKeyword ("partial", Token.PARTIAL);
590                         AddKeyword ("where", Token.WHERE);
591                         AddKeyword ("async", Token.ASYNC);
592
593                         // LINQ keywords
594                         AddKeyword ("from", Token.FROM);
595                         AddKeyword ("join", Token.JOIN);
596                         AddKeyword ("on", Token.ON);
597                         AddKeyword ("equals", Token.EQUALS);
598                         AddKeyword ("select", Token.SELECT);
599                         AddKeyword ("group", Token.GROUP);
600                         AddKeyword ("by", Token.BY);
601                         AddKeyword ("let", Token.LET);
602                         AddKeyword ("orderby", Token.ORDERBY);
603                         AddKeyword ("ascending", Token.ASCENDING);
604                         AddKeyword ("descending", Token.DESCENDING);
605                         AddKeyword ("into", Token.INTO);
606
607                         keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
608
609                         AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
610                         AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
611                         AddPreprocessorKeyword ("if", PreprocessorDirective.If);
612                         AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
613                         AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
614                         AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
615                         AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
616                         AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
617                         AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
618                         AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
619                         AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
620                         AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
621
622                         csharp_format_info = NumberFormatInfo.InvariantInfo;
623                         styles = NumberStyles.Float;
624
625                         string_builder = new System.Text.StringBuilder ();
626                 }
627
628                 int GetKeyword (char[] id, int id_len)
629                 {
630                         //
631                         // Keywords are stored in an array of arrays grouped by their
632                         // length and then by the first character
633                         //
634                         if (id_len >= keywords.Length || keywords [id_len] == null)
635                                 return -1;
636
637                         int first_index = id [0] - '_';
638                         if (first_index > 'z' - '_')
639                                 return -1;
640
641                         var kwe = keywords [id_len] [first_index];
642                         if (kwe == null)
643                                 return -1;
644
645                         int res;
646                         do {
647                                 res = kwe.Token;
648                                 for (int i = 1; i < id_len; ++i) {
649                                         if (id [i] != kwe.Value [i]) {
650                                                 res = 0;
651                                                 kwe = kwe.Next;
652                                                 break;
653                                         }
654                                 }
655                         } while (res == 0 && kwe != null);
656
657                         if (res == 0)
658                                 return -1;
659
660                         int next_token;
661                         switch (res) {
662                         case Token.GET:
663                         case Token.SET:
664                                 if (!handle_get_set)
665                                         res = -1;
666                                 break;
667                         case Token.REMOVE:
668                         case Token.ADD:
669                                 if (!handle_remove_add)
670                                         res = -1;
671                                 break;
672                         case Token.EXTERN:
673                                 if (parsing_declaration == 0)
674                                         res = Token.EXTERN_ALIAS;
675                                 break;
676                         case Token.DEFAULT:
677                                 if (peek_token () == Token.COLON) {
678                                         token ();
679                                         res = Token.DEFAULT_COLON;
680                                 }
681                                 break;
682                         case Token.WHERE:
683                                 if (!handle_where && !query_parsing)
684                                         res = -1;
685                                 break;
686                         case Token.FROM:
687                                 //
688                                 // A query expression is any expression that starts with `from identifier'
689                                 // followed by any token except ; , =
690                                 // 
691                                 if (!query_parsing) {
692                                         if (lambda_arguments_parsing) {
693                                                 res = -1;
694                                                 break;
695                                         }
696
697                                         PushPosition ();
698                                         // HACK: to disable generics micro-parser, because PushPosition does not
699                                         // store identifiers array
700                                         parsing_generic_less_than = 1;
701                                         switch (xtoken ()) {
702                                         case Token.IDENTIFIER:
703                                         case Token.INT:
704                                         case Token.BOOL:
705                                         case Token.BYTE:
706                                         case Token.CHAR:
707                                         case Token.DECIMAL:
708                                         case Token.FLOAT:
709                                         case Token.LONG:
710                                         case Token.OBJECT:
711                                         case Token.STRING:
712                                         case Token.UINT:
713                                         case Token.ULONG:
714                                                 next_token = xtoken ();
715                                                 if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS)
716                                                         goto default;
717                                                 
718                                                 res = Token.FROM_FIRST;
719                                                 query_parsing = true;
720                                                 if (context.Settings.Version <= LanguageVersion.ISO_2)
721                                                         Report.FeatureIsNotAvailable (context, Location, "query expressions");
722                                                 break;
723                                         case Token.VOID:
724                                                 Expression.Error_VoidInvalidInTheContext (Location, Report);
725                                                 break;
726                                         default:
727                                                 PopPosition ();
728                                                 // HACK: A token is not a keyword so we need to restore identifiers buffer
729                                                 // which has been overwritten before we grabbed the identifier
730                                                 id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
731                                                 return -1;
732                                         }
733                                         PopPosition ();
734                                 }
735                                 break;
736                         case Token.JOIN:
737                         case Token.ON:
738                         case Token.EQUALS:
739                         case Token.SELECT:
740                         case Token.GROUP:
741                         case Token.BY:
742                         case Token.LET:
743                         case Token.ORDERBY:
744                         case Token.ASCENDING:
745                         case Token.DESCENDING:
746                         case Token.INTO:
747                                 if (!query_parsing)
748                                         res = -1;
749                                 break;
750                                 
751                         case Token.USING:
752                         case Token.NAMESPACE:
753                                 // TODO: some explanation needed
754                                 check_incorrect_doc_comment ();
755                                 break;
756                                 
757                         case Token.PARTIAL:
758                                 if (parsing_block > 0) {
759                                         res = -1;
760                                         break;
761                                 }
762
763                                 // Save current position and parse next token.
764                                 PushPosition ();
765
766                                 next_token = token ();
767                                 bool ok = (next_token == Token.CLASS) ||
768                                         (next_token == Token.STRUCT) ||
769                                         (next_token == Token.INTERFACE) ||
770                                         (next_token == Token.VOID);
771
772                                 PopPosition ();
773
774                                 if (ok) {
775                                         if (next_token == Token.VOID) {
776                                                 if (context.Settings.Version <= LanguageVersion.ISO_2)
777                                                         Report.FeatureIsNotAvailable (context, Location, "partial methods");
778                                         } else if (context.Settings.Version == LanguageVersion.ISO_1)
779                                                 Report.FeatureIsNotAvailable (context, Location, "partial types");
780
781                                         return res;
782                                 }
783
784                                 if (next_token < Token.LAST_KEYWORD) {
785                                         Report.Error (267, Location,
786                                                 "The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
787                                         return token ();
788                                 }                                       
789
790                                 res = -1;
791                                 break;
792
793                         case Token.ASYNC:
794                                 if (parsing_block > 0 || context.Settings.Version != LanguageVersion.Future) {
795                                         res = -1;
796                                         break;
797                                 }
798                                 break;
799                         }
800
801                         return res;
802                 }
803
804                 static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
805                 {
806                         //
807                         // Keywords are stored in an array of arrays grouped by their
808                         // length and then by the first character
809                         //
810                         if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
811                                 return PreprocessorDirective.Invalid;
812
813                         int first_index = id[0] - '_';
814                         if (first_index > 'z' - '_')
815                                 return PreprocessorDirective.Invalid;
816
817                         var kwe = keywords_preprocessor[id_len][first_index];
818                         if (kwe == null)
819                                 return PreprocessorDirective.Invalid;
820
821                         PreprocessorDirective res = PreprocessorDirective.Invalid;
822                         do {
823                                 res = kwe.Token;
824                                 for (int i = 1; i < id_len; ++i) {
825                                         if (id[i] != kwe.Value[i]) {
826                                                 res = 0;
827                                                 kwe = kwe.Next;
828                                                 break;
829                                         }
830                                 }
831                         } while (res == PreprocessorDirective.Invalid && kwe != null);
832
833                         return res;
834                 }
835
836                 public Location Location {
837                         get {
838                                 return new Location (ref_line, hidden ? -1 : col);
839                         }
840                 }
841
842                 static bool is_identifier_start_character (int c)
843                 {
844                         return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
845                 }
846
847                 static bool is_identifier_part_character (char c)
848                 {
849                         if (c >= 'a' && c <= 'z')
850                                 return true;
851
852                         if (c >= 'A' && c <= 'Z')
853                                 return true;
854
855                         if (c == '_' || (c >= '0' && c <= '9'))
856                                 return true;
857
858                         if (c < 0x80)
859                                 return false;
860
861                         return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
862                 }
863
864                 public static bool IsKeyword (string s)
865                 {
866                         return keyword_strings.ContainsKey (s);
867                 }
868
869                 //
870                 // Open parens micro parser. Detects both lambda and cast ambiguity.
871                 //      
872                 int TokenizeOpenParens ()
873                 {
874                         int ptoken;
875                         current_token = -1;
876
877                         int bracket_level = 0;
878                         bool is_type = false;
879                         bool can_be_type = false;
880                         
881                         while (true) {
882                                 ptoken = current_token;
883                                 token ();
884
885                                 switch (current_token) {
886                                 case Token.CLOSE_PARENS:
887                                         token ();
888                                         
889                                         //
890                                         // Expression inside parens is lambda, (int i) => 
891                                         //
892                                         if (current_token == Token.ARROW)
893                                                 return Token.OPEN_PARENS_LAMBDA;
894
895                                         //
896                                         // Expression inside parens is single type, (int[])
897                                         //
898                                         if (is_type)
899                                                 return Token.OPEN_PARENS_CAST;
900
901                                         //
902                                         // Expression is possible cast, look at next token, (T)null
903                                         //
904                                         if (can_be_type) {
905                                                 switch (current_token) {
906                                                 case Token.OPEN_PARENS:
907                                                 case Token.BANG:
908                                                 case Token.TILDE:
909                                                 case Token.IDENTIFIER:
910                                                 case Token.LITERAL:
911                                                 case Token.BASE:
912                                                 case Token.CHECKED:
913                                                 case Token.DELEGATE:
914                                                 case Token.FALSE:
915                                                 case Token.FIXED:
916                                                 case Token.NEW:
917                                                 case Token.NULL:
918                                                 case Token.SIZEOF:
919                                                 case Token.THIS:
920                                                 case Token.THROW:
921                                                 case Token.TRUE:
922                                                 case Token.TYPEOF:
923                                                 case Token.UNCHECKED:
924                                                 case Token.UNSAFE:
925                                                 case Token.DEFAULT:
926
927                                                 //
928                                                 // These can be part of a member access
929                                                 //
930                                                 case Token.INT:
931                                                 case Token.UINT:
932                                                 case Token.SHORT:
933                                                 case Token.USHORT:
934                                                 case Token.LONG:
935                                                 case Token.ULONG:
936                                                 case Token.DOUBLE:
937                                                 case Token.FLOAT:
938                                                 case Token.CHAR:
939                                                 case Token.BYTE:
940                                                 case Token.DECIMAL:
941                                                 case Token.BOOL:
942                                                         return Token.OPEN_PARENS_CAST;
943                                                 }
944                                         }
945                                         return Token.OPEN_PARENS;
946                                         
947                                 case Token.DOT:
948                                 case Token.DOUBLE_COLON:
949                                         if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
950                                                 goto default;
951
952                                         continue;
953
954                                 case Token.IDENTIFIER:
955                                         switch (ptoken) {
956                                         case Token.DOT:
957                                                 if (bracket_level == 0) {
958                                                         is_type = false;
959                                                         can_be_type = true;
960                                                 }
961
962                                                 continue;
963                                         case Token.OP_GENERICS_LT:
964                                         case Token.COMMA:
965                                         case Token.DOUBLE_COLON:
966                                         case -1:
967                                                 if (bracket_level == 0)
968                                                         can_be_type = true;
969                                                 continue;
970                                         default:
971                                                 can_be_type = is_type = false;
972                                                 continue;
973                                         }
974
975                                 case Token.OBJECT:
976                                 case Token.STRING:
977                                 case Token.BOOL:
978                                 case Token.DECIMAL:
979                                 case Token.FLOAT:
980                                 case Token.DOUBLE:
981                                 case Token.SBYTE:
982                                 case Token.BYTE:
983                                 case Token.SHORT:
984                                 case Token.USHORT:
985                                 case Token.INT:
986                                 case Token.UINT:
987                                 case Token.LONG:
988                                 case Token.ULONG:
989                                 case Token.CHAR:
990                                 case Token.VOID:
991                                         if (bracket_level == 0)
992                                                 is_type = true;
993                                         continue;
994
995                                 case Token.COMMA:
996                                         if (bracket_level == 0) {
997                                                 bracket_level = 100;
998                                                 can_be_type = is_type = false;
999                                         }
1000                                         continue;
1001
1002                                 case Token.OP_GENERICS_LT:
1003                                 case Token.OPEN_BRACKET:
1004                                         if (bracket_level++ == 0)
1005                                                 is_type = true;
1006                                         continue;
1007
1008                                 case Token.OP_GENERICS_GT:
1009                                 case Token.CLOSE_BRACKET:
1010                                         --bracket_level;
1011                                         continue;
1012
1013                                 case Token.INTERR_NULLABLE:
1014                                 case Token.STAR:
1015                                         if (bracket_level == 0)
1016                                                 is_type = true;
1017                                         continue;
1018
1019                                 case Token.REF:
1020                                 case Token.OUT:
1021                                         can_be_type = is_type = false;
1022                                         continue;
1023
1024                                 default:
1025                                         return Token.OPEN_PARENS;
1026                                 }
1027                         }
1028                 }
1029
1030                 public static bool IsValidIdentifier (string s)
1031                 {
1032                         if (s == null || s.Length == 0)
1033                                 return false;
1034
1035                         if (!is_identifier_start_character (s [0]))
1036                                 return false;
1037                         
1038                         for (int i = 1; i < s.Length; i ++)
1039                                 if (! is_identifier_part_character (s [i]))
1040                                         return false;
1041                         
1042                         return true;
1043                 }
1044
1045                 bool parse_less_than ()
1046                 {
1047                 start:
1048                         int the_token = token ();
1049                         if (the_token == Token.OPEN_BRACKET) {
1050                                 do {
1051                                         the_token = token ();
1052                                 } while (the_token != Token.CLOSE_BRACKET);
1053                                 the_token = token ();
1054                         } else if (the_token == Token.IN || the_token == Token.OUT) {
1055                                 the_token = token ();
1056                         }
1057                         switch (the_token) {
1058                         case Token.IDENTIFIER:
1059                         case Token.OBJECT:
1060                         case Token.STRING:
1061                         case Token.BOOL:
1062                         case Token.DECIMAL:
1063                         case Token.FLOAT:
1064                         case Token.DOUBLE:
1065                         case Token.SBYTE:
1066                         case Token.BYTE:
1067                         case Token.SHORT:
1068                         case Token.USHORT:
1069                         case Token.INT:
1070                         case Token.UINT:
1071                         case Token.LONG:
1072                         case Token.ULONG:
1073                         case Token.CHAR:
1074                         case Token.VOID:
1075                                 break;
1076                         case Token.OP_GENERICS_GT:
1077                                 return true;
1078
1079                         default:
1080                                 return false;
1081                         }
1082                 again:
1083                         the_token = token ();
1084
1085                         if (the_token == Token.OP_GENERICS_GT)
1086                                 return true;
1087                         else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
1088                                 goto start;
1089                         else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
1090                                 goto again;
1091                         else if (the_token == Token.OP_GENERICS_LT) {
1092                                 if (!parse_less_than ())
1093                                         return false;
1094                                 goto again;
1095                         } else if (the_token == Token.OPEN_BRACKET) {
1096                         rank_specifiers:
1097                                 the_token = token ();
1098                                 if (the_token == Token.CLOSE_BRACKET)
1099                                         goto again;
1100                                 else if (the_token == Token.COMMA)
1101                                         goto rank_specifiers;
1102                                 return false;
1103                         }
1104
1105                         return false;
1106                 }
1107
1108                 bool parse_generic_dimension (out int dimension)
1109                 {
1110                         dimension = 1;
1111
1112                 again:
1113                         int the_token = token ();
1114                         if (the_token == Token.OP_GENERICS_GT)
1115                                 return true;
1116                         else if (the_token == Token.COMMA) {
1117                                 dimension++;
1118                                 goto again;
1119                         }
1120
1121                         return false;
1122                 }
1123                 
1124                 public int peek_token ()
1125                 {
1126                         int the_token;
1127
1128                         PushPosition ();
1129                         the_token = token ();
1130                         PopPosition ();
1131                         
1132                         return the_token;
1133                 }
1134                                         
1135                 //
1136                 // Tonizes `?' using custom disambiguous rules to return one
1137                 // of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
1138                 //
1139                 // Tricky expression look like:
1140                 //
1141                 // Foo ? a = x ? b : c;
1142                 //
1143                 int TokenizePossibleNullableType ()
1144                 {
1145                         if (parsing_block == 0 || parsing_type > 0)
1146                                 return Token.INTERR_NULLABLE;
1147
1148                         int d = peek_char ();
1149                         if (d == '?') {
1150                                 get_char ();
1151                                 return Token.OP_COALESCING;
1152                         }
1153
1154                         switch (current_token) {
1155                         case Token.CLOSE_PARENS:
1156                         case Token.TRUE:
1157                         case Token.FALSE:
1158                         case Token.NULL:
1159                         case Token.LITERAL:
1160                                 return Token.INTERR;
1161                         }
1162
1163                         if (d != ' ') {
1164                                 if (d == ',' || d == ';' || d == '>')
1165                                         return Token.INTERR_NULLABLE;
1166                                 if (d == '*' || (d >= '0' && d <= '9'))
1167                                         return Token.INTERR;
1168                         }
1169
1170                         PushPosition ();
1171                         current_token = Token.NONE;
1172                         int next_token;
1173                         switch (xtoken ()) {
1174                         case Token.LITERAL:
1175                         case Token.TRUE:
1176                         case Token.FALSE:
1177                         case Token.NULL:
1178                         case Token.THIS:
1179                         case Token.NEW:
1180                                 next_token = Token.INTERR;
1181                                 break;
1182                                 
1183                         case Token.SEMICOLON:
1184                         case Token.COMMA:
1185                         case Token.CLOSE_PARENS:
1186                         case Token.OPEN_BRACKET:
1187                         case Token.OP_GENERICS_GT:
1188                                 next_token = Token.INTERR_NULLABLE;
1189                                 break;
1190                                 
1191                         default:
1192                                 next_token = -1;
1193                                 break;
1194                         }
1195
1196                         if (next_token == -1) {
1197                                 switch (xtoken ()) {
1198                                 case Token.COMMA:
1199                                 case Token.SEMICOLON:
1200                                 case Token.OPEN_BRACE:
1201                                 case Token.CLOSE_PARENS:
1202                                 case Token.IN:
1203                                         next_token = Token.INTERR_NULLABLE;
1204                                         break;
1205                                         
1206                                 case Token.COLON:
1207                                         next_token = Token.INTERR;
1208                                         break;                                                  
1209                                         
1210                                 default:
1211                                         int ntoken;
1212                                         int interrs = 1;
1213                                         int colons = 0;
1214                                         //
1215                                         // All shorcuts failed, do it hard way
1216                                         //
1217                                         while ((ntoken = xtoken ()) != Token.EOF) {
1218                                                 if (ntoken == Token.SEMICOLON)
1219                                                         break;
1220                                                 
1221                                                 if (ntoken == Token.COLON) {
1222                                                         if (++colons == interrs)
1223                                                                 break;
1224                                                         continue;
1225                                                 }
1226                                                 
1227                                                 if (ntoken == Token.INTERR) {
1228                                                         ++interrs;
1229                                                         continue;
1230                                                 }
1231                                         }
1232                                         
1233                                         next_token = colons != interrs ? Token.INTERR_NULLABLE : Token.INTERR;
1234                                         break;
1235                                 }
1236                         }
1237                         
1238                         PopPosition ();
1239                         return next_token;
1240                 }
1241
1242                 bool decimal_digits (int c)
1243                 {
1244                         int d;
1245                         bool seen_digits = false;
1246                         
1247                         if (c != -1){
1248                                 if (number_pos == max_number_size)
1249                                         Error_NumericConstantTooLong ();
1250                                 number_builder [number_pos++] = (char) c;
1251                         }
1252                         
1253                         //
1254                         // We use peek_char2, because decimal_digits needs to do a 
1255                         // 2-character look-ahead (5.ToString for example).
1256                         //
1257                         while ((d = peek_char2 ()) != -1){
1258                                 if (d >= '0' && d <= '9'){
1259                                         if (number_pos == max_number_size)
1260                                                 Error_NumericConstantTooLong ();
1261                                         number_builder [number_pos++] = (char) d;
1262                                         get_char ();
1263                                         seen_digits = true;
1264                                 } else
1265                                         break;
1266                         }
1267                         
1268                         return seen_digits;
1269                 }
1270
1271                 static bool is_hex (int e)
1272                 {
1273                         return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
1274                 }
1275
1276                 static TypeCode real_type_suffix (int c)
1277                 {
1278                         switch (c){
1279                         case 'F': case 'f':
1280                                 return TypeCode.Single;
1281                         case 'D': case 'd':
1282                                 return TypeCode.Double;
1283                         case 'M': case 'm':
1284                                 return TypeCode.Decimal;
1285                         default:
1286                                 return TypeCode.Empty;
1287                         }
1288                 }
1289
1290                 int integer_type_suffix (ulong ul, int c)
1291                 {
1292                         bool is_unsigned = false;
1293                         bool is_long = false;
1294
1295                         if (c != -1){
1296                                 bool scanning = true;
1297                                 do {
1298                                         switch (c){
1299                                         case 'U': case 'u':
1300                                                 if (is_unsigned)
1301                                                         scanning = false;
1302                                                 is_unsigned = true;
1303                                                 get_char ();
1304                                                 break;
1305
1306                                         case 'l':
1307                                                 if (!is_unsigned){
1308                                                         //
1309                                                         // if we have not seen anything in between
1310                                                         // report this error
1311                                                         //
1312                                                         Report.Warning (78, 4, Location, "The 'l' suffix is easily confused with the digit '1' (use 'L' for clarity)");
1313                                                 }
1314
1315                                                 goto case 'L';
1316
1317                                         case 'L': 
1318                                                 if (is_long)
1319                                                         scanning = false;
1320                                                 is_long = true;
1321                                                 get_char ();
1322                                                 break;
1323                                                 
1324                                         default:
1325                                                 scanning = false;
1326                                                 break;
1327                                         }
1328                                         c = peek_char ();
1329                                 } while (scanning);
1330                         }
1331
1332                         if (is_long && is_unsigned){
1333                                 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1334                                 return Token.LITERAL;
1335                         }
1336                         
1337                         if (is_unsigned){
1338                                 // uint if possible, or ulong else.
1339
1340                                 if ((ul & 0xffffffff00000000) == 0)
1341                                         val = new UIntLiteral (context.BuiltinTypes, (uint) ul, Location);
1342                                 else
1343                                         val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1344                         } else if (is_long){
1345                                 // long if possible, ulong otherwise
1346                                 if ((ul & 0x8000000000000000) != 0)
1347                                         val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1348                                 else
1349                                         val = new LongLiteral (context.BuiltinTypes, (long) ul, Location);
1350                         } else {
1351                                 // int, uint, long or ulong in that order
1352                                 if ((ul & 0xffffffff00000000) == 0){
1353                                         uint ui = (uint) ul;
1354                                         
1355                                         if ((ui & 0x80000000) != 0)
1356                                                 val = new UIntLiteral (context.BuiltinTypes, ui, Location);
1357                                         else
1358                                                 val = new IntLiteral (context.BuiltinTypes, (int) ui, Location);
1359                                 } else {
1360                                         if ((ul & 0x8000000000000000) != 0)
1361                                                 val = new ULongLiteral (context.BuiltinTypes, ul, Location);
1362                                         else
1363                                                 val = new LongLiteral (context.BuiltinTypes, (long) ul, Location);
1364                                 }
1365                         }
1366                         return Token.LITERAL;
1367                 }
1368                                 
1369                 //
1370                 // given `c' as the next char in the input decide whether
1371                 // we need to convert to a special type, and then choose
1372                 // the best representation for the integer
1373                 //
1374                 int adjust_int (int c)
1375                 {
1376                         try {
1377                                 if (number_pos > 9){
1378                                         ulong ul = (uint) (number_builder [0] - '0');
1379
1380                                         for (int i = 1; i < number_pos; i++){
1381                                                 ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
1382                                         }
1383                                         return integer_type_suffix (ul, c);
1384                                 } else {
1385                                         uint ui = (uint) (number_builder [0] - '0');
1386
1387                                         for (int i = 1; i < number_pos; i++){
1388                                                 ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
1389                                         }
1390                                         return integer_type_suffix (ui, c);
1391                                 }
1392                         } catch (OverflowException) {
1393                                 Error_NumericConstantTooLong ();
1394                                 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1395                                 return Token.LITERAL;
1396                         }
1397                         catch (FormatException) {
1398                                 Report.Error (1013, Location, "Invalid number");
1399                                 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1400                                 return Token.LITERAL;
1401                         }
1402                 }
1403                 
1404                 int adjust_real (TypeCode t)
1405                 {
1406                         string s = new String (number_builder, 0, number_pos);
1407                         const string error_details = "Floating-point constant is outside the range of type `{0}'";
1408
1409                         switch (t){
1410                         case TypeCode.Decimal:
1411                                 try {
1412                                         val = new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), Location);
1413                                 } catch (OverflowException) {
1414                                         val = new DecimalLiteral (context.BuiltinTypes, 0, Location);
1415                                         Report.Error (594, Location, error_details, "decimal");
1416                                 }
1417                                 break;
1418                         case TypeCode.Single:
1419                                 try {
1420                                         val = new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), Location);
1421                                 } catch (OverflowException) {
1422                                         val = new FloatLiteral (context.BuiltinTypes, 0, Location);
1423                                         Report.Error (594, Location, error_details, "float");
1424                                 }
1425                                 break;
1426                         default:
1427                                 try {
1428                                         val = new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), Location);
1429                                 } catch (OverflowException) {
1430                                         val = new DoubleLiteral (context.BuiltinTypes, 0, Location);
1431                                         Report.Error (594, Location, error_details, "double");
1432                                 }
1433                                 break;
1434                         }
1435
1436                         return Token.LITERAL;
1437                 }
1438
1439                 int handle_hex ()
1440                 {
1441                         int d;
1442                         ulong ul;
1443                         
1444                         get_char ();
1445                         while ((d = peek_char ()) != -1){
1446                                 if (is_hex (d)){
1447                                         number_builder [number_pos++] = (char) d;
1448                                         get_char ();
1449                                 } else
1450                                         break;
1451                         }
1452                         
1453                         string s = new String (number_builder, 0, number_pos);
1454                         try {
1455                                 if (number_pos <= 8)
1456                                         ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
1457                                 else
1458                                         ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
1459                         } catch (OverflowException){
1460                                 Error_NumericConstantTooLong ();
1461                                 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1462                                 return Token.LITERAL;
1463                         }
1464                         catch (FormatException) {
1465                                 Report.Error (1013, Location, "Invalid number");
1466                                 val = new IntLiteral (context.BuiltinTypes, 0, Location);
1467                                 return Token.LITERAL;
1468                         }
1469                         
1470                         return integer_type_suffix (ul, peek_char ());
1471                 }
1472
1473                 //
1474                 // Invoked if we know we have .digits or digits
1475                 //
1476                 int is_number (int c)
1477                 {
1478                         bool is_real = false;
1479
1480                         number_pos = 0;
1481
1482                         if (c >= '0' && c <= '9'){
1483                                 if (c == '0'){
1484                                         int peek = peek_char ();
1485
1486                                         if (peek == 'x' || peek == 'X')
1487                                                 return handle_hex ();
1488                                 }
1489                                 decimal_digits (c);
1490                                 c = get_char ();
1491                         }
1492
1493                         //
1494                         // We need to handle the case of
1495                         // "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
1496                         //
1497                         if (c == '.'){
1498                                 if (decimal_digits ('.')){
1499                                         is_real = true;
1500                                         c = get_char ();
1501                                 } else {
1502                                         putback ('.');
1503                                         number_pos--;
1504                                         return adjust_int (-1);
1505                                 }
1506                         }
1507                         
1508                         if (c == 'e' || c == 'E'){
1509                                 is_real = true;
1510                                 if (number_pos == max_number_size)
1511                                         Error_NumericConstantTooLong ();
1512                                 number_builder [number_pos++] = 'e';
1513                                 c = get_char ();
1514                                 
1515                                 if (c == '+'){
1516                                         if (number_pos == max_number_size)
1517                                                 Error_NumericConstantTooLong ();
1518                                         number_builder [number_pos++] = '+';
1519                                         c = -1;
1520                                 } else if (c == '-') {
1521                                         if (number_pos == max_number_size)
1522                                                 Error_NumericConstantTooLong ();
1523                                         number_builder [number_pos++] = '-';
1524                                         c = -1;
1525                                 } else {
1526                                         if (number_pos == max_number_size)
1527                                                 Error_NumericConstantTooLong ();
1528                                         number_builder [number_pos++] = '+';
1529                                 }
1530                                         
1531                                 decimal_digits (c);
1532                                 c = get_char ();
1533                         }
1534
1535                         var type = real_type_suffix (c);
1536                         if (type == TypeCode.Empty && !is_real){
1537                                 putback (c);
1538                                 return adjust_int (c);
1539                         }
1540
1541                         is_real = true;
1542
1543                         if (type == TypeCode.Empty){
1544                                 putback (c);
1545                         }
1546                         
1547                         if (is_real)
1548                                 return adjust_real (type);
1549
1550                         throw new Exception ("Is Number should never reach this point");
1551                 }
1552
1553                 //
1554                 // Accepts exactly count (4 or 8) hex, no more no less
1555                 //
1556                 int getHex (int count, out int surrogate, out bool error)
1557                 {
1558                         int i;
1559                         int total = 0;
1560                         int c;
1561                         int top = count != -1 ? count : 4;
1562                         
1563                         get_char ();
1564                         error = false;
1565                         surrogate = 0;
1566                         for (i = 0; i < top; i++){
1567                                 c = get_char ();
1568
1569                                 if (c >= '0' && c <= '9')
1570                                         c = (int) c - (int) '0';
1571                                 else if (c >= 'A' && c <= 'F')
1572                                         c = (int) c - (int) 'A' + 10;
1573                                 else if (c >= 'a' && c <= 'f')
1574                                         c = (int) c - (int) 'a' + 10;
1575                                 else {
1576                                         error = true;
1577                                         return 0;
1578                                 }
1579                                 
1580                                 total = (total * 16) + c;
1581                                 if (count == -1){
1582                                         int p = peek_char ();
1583                                         if (p == -1)
1584                                                 break;
1585                                         if (!is_hex ((char)p))
1586                                                 break;
1587                                 }
1588                         }
1589
1590                         if (top == 8) {
1591                                 if (total > 0x0010FFFF) {
1592                                         error = true;
1593                                         return 0;
1594                                 }
1595
1596                                 if (total >= 0x00010000) {
1597                                         surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);                                   
1598                                         total = ((total - 0x00010000) / 0x0400 + 0xD800);
1599                                 }
1600                         }
1601
1602                         return total;
1603                 }
1604
1605                 int escape (int c, out int surrogate)
1606                 {
1607                         bool error;
1608                         int d;
1609                         int v;
1610
1611                         d = peek_char ();
1612                         if (c != '\\') {
1613                                 surrogate = 0;
1614                                 return c;
1615                         }
1616                         
1617                         switch (d){
1618                         case 'a':
1619                                 v = '\a'; break;
1620                         case 'b':
1621                                 v = '\b'; break;
1622                         case 'n':
1623                                 v = '\n'; break;
1624                         case 't':
1625                                 v = '\t'; break;
1626                         case 'v':
1627                                 v = '\v'; break;
1628                         case 'r':
1629                                 v = '\r'; break;
1630                         case '\\':
1631                                 v = '\\'; break;
1632                         case 'f':
1633                                 v = '\f'; break;
1634                         case '0':
1635                                 v = 0; break;
1636                         case '"':
1637                                 v = '"'; break;
1638                         case '\'':
1639                                 v = '\''; break;
1640                         case 'x':
1641                                 v = getHex (-1, out surrogate, out error);
1642                                 if (error)
1643                                         goto default;
1644                                 return v;
1645                         case 'u':
1646                         case 'U':
1647                                 return EscapeUnicode (d, out surrogate);
1648                         default:
1649                                 surrogate = 0;
1650                                 Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
1651                                 return d;
1652                         }
1653
1654                         get_char ();
1655                         surrogate = 0;
1656                         return v;
1657                 }
1658
1659                 int EscapeUnicode (int ch, out int surrogate)
1660                 {
1661                         bool error;
1662                         if (ch == 'U') {
1663                                 ch = getHex (8, out surrogate, out error);
1664                         } else {
1665                                 ch = getHex (4, out surrogate, out error);
1666                         }
1667
1668                         if (error)
1669                                 Report.Error (1009, Location, "Unrecognized escape sequence");
1670
1671                         return ch;
1672                 }
1673
1674                 int get_char ()
1675                 {
1676                         int x;
1677                         if (putback_char != -1) {
1678                                 x = putback_char;
1679                                 putback_char = -1;
1680                         } else {
1681                                 x = reader.Read ();
1682                         }
1683                         
1684                         if (x == '\r') {
1685                                 if (peek_char () == '\n') {
1686                                         putback_char = -1;
1687                                 }
1688
1689                                 x = '\n';
1690                                 advance_line ();
1691                         } else if (x == '\n') {
1692                                 advance_line ();
1693                         } else {
1694                                 col++;
1695                         }
1696                         return x;
1697                 }
1698
1699                 void advance_line ()
1700                 {
1701                         line++;
1702                         ref_line++;
1703                         previous_col = col;
1704                         col = 0;
1705                 }
1706
1707                 int peek_char ()
1708                 {
1709                         if (putback_char == -1)
1710                                 putback_char = reader.Read ();
1711                         return putback_char;
1712                 }
1713
1714                 int peek_char2 ()
1715                 {
1716                         if (putback_char != -1)
1717                                 return putback_char;
1718                         return reader.Peek ();
1719                 }
1720                 
1721                 void putback (int c)
1722                 {
1723                         if (putback_char != -1){
1724                                 Console.WriteLine ("Col: " + col);
1725                                 Console.WriteLine ("Row: " + line);
1726                                 Console.WriteLine ("Name: " + ref_name.Name);
1727                                 Console.WriteLine ("Current [{0}] putting back [{1}]  ", putback_char, c);
1728                                 throw new Exception ("This should not happen putback on putback");
1729                         }
1730                         if (c == '\n' || col == 0) {
1731                                 // It won't happen though.
1732                                 line--;
1733                                 ref_line--;
1734                                 col = previous_col;
1735                         }
1736                         else
1737                                 col--;
1738                         putback_char = c;
1739                 }
1740
1741                 public bool advance ()
1742                 {
1743                         return peek_char () != -1 || CompleteOnEOF;
1744                 }
1745
1746                 public Object Value {
1747                         get {
1748                                 return val;
1749                         }
1750                 }
1751
1752                 public Object value ()
1753                 {
1754                         return val;
1755                 }
1756
1757                 public int token ()
1758                 {
1759                         current_token = xtoken ();
1760                         return current_token;
1761                 }
1762
1763                 int TokenizePreprocessorIdentifier (out int c)
1764                 {
1765                         // skip over white space
1766                         do {
1767                                 c = get_char ();
1768                         } while (c == ' ' || c == '\t');
1769
1770
1771                         int pos = 0;
1772                         while (c != -1 && c >= 'a' && c <= 'z') {
1773                                 id_builder[pos++] = (char) c;
1774                                 c = get_char ();
1775                                 if (c == '\\') {
1776                                         int peek = peek_char ();
1777                                         if (peek == 'U' || peek == 'u') {
1778                                                 int surrogate;
1779                                                 c = EscapeUnicode (c, out surrogate);
1780                                                 if (surrogate != 0) {
1781                                                         if (is_identifier_part_character ((char) c)) {
1782                                                                 id_builder[pos++] = (char) c;
1783                                                         }
1784                                                         c = surrogate;
1785                                                 }
1786                                         }
1787                                 }
1788                         }
1789
1790                         return pos;
1791                 }
1792
1793                 PreprocessorDirective get_cmd_arg (out string arg)
1794                 {
1795                         int c;          
1796
1797                         tokens_seen = false;
1798                         arg = "";
1799
1800                         var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c));
1801
1802                         if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0)
1803                                 return cmd;
1804
1805                         // skip over white space
1806                         while (c == ' ' || c == '\t')
1807                                 c = get_char ();
1808
1809                         int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
1810                         int pos = 0;
1811
1812                         while (c != -1 && c != '\n') {
1813                                 if (c == '\\' && has_identifier_argument >= 0) {
1814                                         if (has_identifier_argument != 0) {
1815                                                 has_identifier_argument = 1;
1816
1817                                                 int peek = peek_char ();
1818                                                 if (peek == 'U' || peek == 'u') {
1819                                                         int surrogate;
1820                                                         c = EscapeUnicode (c, out surrogate);
1821                                                         if (surrogate != 0) {
1822                                                                 if (is_identifier_part_character ((char) c)) {
1823                                                                         if (pos == value_builder.Length)
1824                                                                                 Array.Resize (ref value_builder, pos * 2);
1825
1826                                                                         value_builder[pos++] = (char) c;
1827                                                                 }
1828                                                                 c = surrogate;
1829                                                         }
1830                                                 }
1831                                         } else {
1832                                                 has_identifier_argument = -1;
1833                                         }
1834                                 } else if (c == '/' && peek_char () == '/') {
1835                                         //
1836                                         // Eat single-line comments
1837                                         //
1838                                         get_char ();
1839                                         do {
1840                                                 c = get_char ();
1841                                         } while (c != -1 && c != '\n');
1842
1843                                         break;
1844                                 }
1845
1846                                 if (pos == value_builder.Length)
1847                                         Array.Resize (ref value_builder, pos * 2);
1848
1849                                 value_builder[pos++] = (char) c;
1850                                 c = get_char ();
1851                         }
1852
1853                         if (pos != 0) {
1854                                 if (pos > max_id_size)
1855                                         arg = new string (value_builder, 0, pos);
1856                                 else
1857                                         arg = InternIdentifier (value_builder, pos);
1858
1859                                 // Eat any trailing whitespaces
1860                                 arg = arg.Trim (simple_whitespaces);
1861                         }
1862
1863                         return cmd;
1864                 }
1865
1866                 //
1867                 // Handles the #line directive
1868                 //
1869                 bool PreProcessLine (string arg)
1870                 {
1871                         if (arg.Length == 0)
1872                                 return false;
1873
1874                         if (arg == "default"){
1875                                 ref_line = line;
1876                                 ref_name = file_name;
1877                                 hidden = false;
1878                                 Location.Push (file_name, ref_name);
1879                                 return true;
1880                         } else if (arg == "hidden"){
1881                                 hidden = true;
1882                                 return true;
1883                         }
1884                         
1885                         try {
1886                                 int pos;
1887
1888                                 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1889                                         ref_line = System.Int32.Parse (arg.Substring (0, pos));
1890                                         pos++;
1891                                         
1892                                         char [] quotes = { '\"' };
1893                                         
1894                                         string name = arg.Substring (pos). Trim (quotes);
1895                                         ref_name = context.LookupFile (file_name, name);
1896                                         file_name.AddIncludeFile (ref_name);
1897                                         hidden = false;
1898                                         Location.Push (file_name, ref_name);
1899                                 } else {
1900                                         ref_line = System.Int32.Parse (arg);
1901                                         hidden = false;
1902                                 }
1903                         } catch {
1904                                 return false;
1905                         }
1906                         
1907                         return true;
1908                 }
1909
1910                 //
1911                 // Handles #define and #undef
1912                 //
1913                 void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
1914                 {
1915                         if (ident.Length == 0 || ident == "true" || ident == "false"){
1916                                 Report.Error (1001, Location, "Missing identifier to pre-processor directive");
1917                                 return;
1918                         }
1919
1920                         if (ident.IndexOfAny (simple_whitespaces) != -1){
1921                                 Error_EndLineExpected ();
1922                                 return;
1923                         }
1924
1925                         if (!is_identifier_start_character (ident [0]))
1926                                 Report.Error (1001, Location, "Identifier expected: {0}", ident);
1927                         
1928                         foreach (char c in ident.Substring (1)){
1929                                 if (!is_identifier_part_character (c)){
1930                                         Report.Error (1001, Location, "Identifier expected: {0}",  ident);
1931                                         return;
1932                                 }
1933                         }
1934
1935                         if (!caller_is_taking)
1936                                 return;
1937
1938                         if (is_define) {
1939                                 //
1940                                 // #define ident
1941                                 //
1942                                 if (context.Settings.IsConditionalSymbolDefined (ident))
1943                                         return;
1944
1945                                 file_name.AddDefine (ident);
1946                         } else {
1947                                 //
1948                                 // #undef ident
1949                                 //
1950                                 file_name.AddUndefine (ident);
1951                         }
1952                 }
1953
1954                 byte read_hex (out bool error)
1955                 {
1956                         int total;
1957                         int c = get_char ();
1958
1959                         if ((c >= '0') && (c <= '9'))
1960                                 total = (int) c - (int) '0';
1961                         else if ((c >= 'A') && (c <= 'F'))
1962                                 total = (int) c - (int) 'A' + 10;
1963                         else if ((c >= 'a') && (c <= 'f'))
1964                                 total = (int) c - (int) 'a' + 10;
1965                         else {
1966                                 error = true;
1967                                 return 0;
1968                         }
1969
1970                         total *= 16;
1971                         c = get_char ();
1972
1973                         if ((c >= '0') && (c <= '9'))
1974                                 total += (int) c - (int) '0';
1975                         else if ((c >= 'A') && (c <= 'F'))
1976                                 total += (int) c - (int) 'A' + 10;
1977                         else if ((c >= 'a') && (c <= 'f'))
1978                                 total += (int) c - (int) 'a' + 10;
1979                         else {
1980                                 error = true;
1981                                 return 0;
1982                         }
1983
1984                         error = false;
1985                         return (byte) total;
1986                 }
1987
1988                 //
1989                 // Parses #pragma checksum
1990                 //
1991                 bool ParsePragmaChecksum ()
1992                 {
1993                         //
1994                         // The syntax is ` "foo.txt" "{guid}" "hash"'
1995                         //
1996                         int c = get_char ();
1997
1998                         if (c != '"')
1999                                 return false;
2000
2001                         string_builder.Length = 0;
2002                         while (c != -1 && c != '\n') {
2003                                 c = get_char ();
2004                                 if (c == '"') {
2005                                         c = get_char ();
2006                                         break;
2007                                 }
2008
2009                                 string_builder.Append ((char) c);
2010                         }
2011
2012                         if (string_builder.Length == 0) {
2013                                 Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
2014                         }
2015
2016                         // TODO: Any white-spaces count
2017                         if (c != ' ')
2018                                 return false;
2019
2020                         SourceFile file = context.LookupFile (file_name, string_builder.ToString ());
2021
2022                         if (get_char () != '"' || get_char () != '{')
2023                                 return false;
2024
2025                         bool error;
2026                         byte[] guid_bytes = new byte [16];
2027                         int i = 0;
2028
2029                         for (; i < 4; i++) {
2030                                 guid_bytes [i] = read_hex (out error);
2031                                 if (error)
2032                                         return false;
2033                         }
2034
2035                         if (get_char () != '-')
2036                                 return false;
2037
2038                         for (; i < 10; i++) {
2039                                 guid_bytes [i] = read_hex (out error);
2040                                 if (error)
2041                                         return false;
2042
2043                                 guid_bytes [i++] = read_hex (out error);
2044                                 if (error)
2045                                         return false;
2046
2047                                 if (get_char () != '-')
2048                                         return false;
2049                         }
2050
2051                         for (; i < 16; i++) {
2052                                 guid_bytes [i] = read_hex (out error);
2053                                 if (error)
2054                                         return false;
2055                         }
2056
2057                         if (get_char () != '}' || get_char () != '"')
2058                                 return false;
2059
2060                         // TODO: Any white-spaces count
2061                         c = get_char ();
2062                         if (c != ' ')
2063                                 return false;
2064
2065                         if (get_char () != '"')
2066                                 return false;
2067
2068                         // Any length of checksum
2069                         List<byte> checksum_bytes = new List<byte> (16);
2070
2071                         c = peek_char ();
2072                         while (c != '"' && c != -1) {
2073                                 checksum_bytes.Add (read_hex (out error));
2074                                 if (error)
2075                                         return false;
2076
2077                                 c = peek_char ();
2078                         }
2079
2080                         if (c == '/') {
2081                                 ReadSingleLineComment ();
2082                         } else if (get_char () != '"') {
2083                                 return false;
2084                         }
2085
2086                         file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
2087                         ref_name.AutoGenerated = true;
2088                         return true;
2089                 }
2090
2091                 bool IsTokenIdentifierEqual (char[] identifier)
2092                 {
2093                         for (int i = 0; i < identifier.Length; ++i) {
2094                                 if (identifier[i] != id_builder[i])
2095                                         return false;
2096                         }
2097
2098                         return true;
2099                 }
2100
2101                 int TokenizePragmaNumber (ref int c)
2102                 {
2103                         number_pos = 0;
2104
2105                         int number;
2106
2107                         if (c >= '0' && c <= '9') {
2108                                 decimal_digits (c);
2109                                 uint ui = (uint) (number_builder[0] - '0');
2110
2111                                 try {
2112                                         for (int i = 1; i < number_pos; i++) {
2113                                                 ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
2114                                         }
2115
2116                                         number = (int) ui;
2117                                 } catch (OverflowException) {
2118                                         Error_NumericConstantTooLong ();
2119                                         number = -1;
2120                                 }
2121
2122
2123                                 c = get_char ();
2124
2125                                 // skip over white space
2126                                 while (c == ' ' || c == '\t')
2127                                         c = get_char ();
2128
2129                                 if (c == ',') {
2130                                         c = get_char ();
2131                                 }
2132
2133                                 // skip over white space
2134                                 while (c == ' ' || c == '\t')
2135                                         c = get_char ();
2136                         } else {
2137                                 number = -1;
2138                                 if (c == '/') {
2139                                         ReadSingleLineComment ();
2140                                 } else {
2141                                         Report.Warning (1692, 1, Location, "Invalid number");
2142
2143                                         // Read everything till the end of the line or file
2144                                         do {
2145                                                 c = get_char ();
2146                                         } while (c != -1 && c != '\n');
2147                                 }
2148                         }
2149
2150                         return number;
2151                 }
2152
2153                 void ReadSingleLineComment ()
2154                 {
2155                         if (peek_char () != '/')
2156                                 Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
2157
2158                         // Read everything till the end of the line or file
2159                         int c;
2160                         do {
2161                                 c = get_char ();
2162                         } while (c != -1 && c != '\n');
2163                 }
2164
2165                 /// <summary>
2166                 /// Handles #pragma directive
2167                 /// </summary>
2168                 void ParsePragmaDirective (string arg)
2169                 {
2170                         int c;
2171                         int length = TokenizePreprocessorIdentifier (out c);
2172                         if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
2173                                 length = TokenizePreprocessorIdentifier (out c);
2174
2175                                 //
2176                                 // #pragma warning disable
2177                                 // #pragma warning restore
2178                                 //
2179                                 if (length == pragma_warning_disable.Length) {
2180                                         bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
2181                                         if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
2182                                                 // skip over white space
2183                                                 while (c == ' ' || c == '\t')
2184                                                         c = get_char ();
2185
2186                                                 var loc = Location;
2187
2188                                                 if (c == '\n' || c == '/') {
2189                                                         if (c == '/')
2190                                                                 ReadSingleLineComment ();
2191
2192                                                         //
2193                                                         // Disable/Restore all warnings
2194                                                         //
2195                                                         if (disable) {
2196                                                                 Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
2197                                                         } else {
2198                                                                 Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
2199                                                         }
2200                                                 } else {
2201                                                         //
2202                                                         // Disable/Restore a warning or group of warnings
2203                                                         //
2204                                                         int code;
2205                                                         do {
2206                                                                 code = TokenizePragmaNumber (ref c);
2207                                                                 if (code > 0) {
2208                                                                         if (disable) {
2209                                                                                 Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
2210                                                                         } else {
2211                                                                                 Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
2212                                                                         }
2213                                                                 }
2214                                                         } while (code >= 0 && c != '\n' && c != -1);
2215                                                 }
2216
2217                                                 return;
2218                                         }
2219                                 }
2220
2221                                 Report.Warning (1634, 1, Location, "Expected disable or restore");
2222                                 return;
2223                         }
2224
2225                         //
2226                         // #pragma checksum
2227                         //
2228                         if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
2229                                 if (c != ' ' || !ParsePragmaChecksum ()) {
2230                                         Report.Warning (1695, 1, Location,
2231                                                 "Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
2232                                 }
2233
2234                                 return;
2235                         }
2236
2237                         Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
2238                 }
2239
2240                 bool eval_val (string s)
2241                 {
2242                         if (s == "true")
2243                                 return true;
2244                         if (s == "false")
2245                                 return false;
2246
2247                         return file_name.IsConditionalDefined (context, s);
2248                 }
2249
2250                 bool pp_primary (ref string s)
2251                 {
2252                         s = s.Trim ();
2253                         int len = s.Length;
2254
2255                         if (len > 0){
2256                                 char c = s [0];
2257                                 
2258                                 if (c == '('){
2259                                         s = s.Substring (1);
2260                                         bool val = pp_expr (ref s, false);
2261                                         if (s.Length > 0 && s [0] == ')'){
2262                                                 s = s.Substring (1);
2263                                                 return val;
2264                                         }
2265                                         Error_InvalidDirective ();
2266                                         return false;
2267                                 }
2268                                 
2269                                 if (is_identifier_start_character (c)){
2270                                         int j = 1;
2271
2272                                         while (j < len){
2273                                                 c = s [j];
2274                                                 
2275                                                 if (is_identifier_part_character (c)){
2276                                                         j++;
2277                                                         continue;
2278                                                 }
2279                                                 bool v = eval_val (s.Substring (0, j));
2280                                                 s = s.Substring (j);
2281                                                 return v;
2282                                         }
2283                                         bool vv = eval_val (s);
2284                                         s = "";
2285                                         return vv;
2286                                 }
2287                         }
2288                         Error_InvalidDirective ();
2289                         return false;
2290                 }
2291                 
2292                 bool pp_unary (ref string s)
2293                 {
2294                         s = s.Trim ();
2295                         int len = s.Length;
2296
2297                         if (len > 0){
2298                                 if (s [0] == '!'){
2299                                         if (len > 1 && s [1] == '='){
2300                                                 Error_InvalidDirective ();
2301                                                 return false;
2302                                         }
2303                                         s = s.Substring (1);
2304                                         return ! pp_primary (ref s);
2305                                 } else
2306                                         return pp_primary (ref s);
2307                         } else {
2308                                 Error_InvalidDirective ();
2309                                 return false;
2310                         }
2311                 }
2312                 
2313                 bool pp_eq (ref string s)
2314                 {
2315                         bool va = pp_unary (ref s);
2316
2317                         s = s.Trim ();
2318                         int len = s.Length;
2319                         if (len > 0){
2320                                 if (s [0] == '='){
2321                                         if (len > 2 && s [1] == '='){
2322                                                 s = s.Substring (2);
2323                                                 return va == pp_unary (ref s);
2324                                         } else {
2325                                                 Error_InvalidDirective ();
2326                                                 return false;
2327                                         }
2328                                 } else if (s [0] == '!' && len > 1 && s [1] == '='){
2329                                         s = s.Substring (2);
2330
2331                                         return va != pp_unary (ref s);
2332
2333                                 } 
2334                         }
2335
2336                         return va;
2337                                 
2338                 }
2339                 
2340                 bool pp_and (ref string s)
2341                 {
2342                         bool va = pp_eq (ref s);
2343
2344                         s = s.Trim ();
2345                         int len = s.Length;
2346                         if (len > 0){
2347                                 if (s [0] == '&'){
2348                                         if (len > 2 && s [1] == '&'){
2349                                                 s = s.Substring (2);
2350                                                 return (va & pp_and (ref s));
2351                                         } else {
2352                                                 Error_InvalidDirective ();
2353                                                 return false;
2354                                         }
2355                                 } 
2356                         }
2357                         return va;
2358                 }
2359                 
2360                 //
2361                 // Evaluates an expression for `#if' or `#elif'
2362                 //
2363                 bool pp_expr (ref string s, bool isTerm)
2364                 {
2365                         bool va = pp_and (ref s);
2366                         s = s.Trim ();
2367                         int len = s.Length;
2368                         if (len > 0){
2369                                 char c = s [0];
2370                                 
2371                                 if (c == '|'){
2372                                         if (len > 2 && s [1] == '|'){
2373                                                 s = s.Substring (2);
2374                                                 return va | pp_expr (ref s, isTerm);
2375                                         } else {
2376                                                 Error_InvalidDirective ();
2377                                                 return false;
2378                                         }
2379                                 }
2380                                 if (isTerm) {
2381                                         Error_EndLineExpected ();
2382                                         return false;
2383                                 }
2384                         }
2385                         
2386                         return va;
2387                 }
2388
2389                 bool eval (string s)
2390                 {
2391                         bool v = pp_expr (ref s, true);
2392                         s = s.Trim ();
2393                         if (s.Length != 0){
2394                                 return false;
2395                         }
2396
2397                         return v;
2398                 }
2399
2400                 void Error_NumericConstantTooLong ()
2401                 {
2402                         Report.Error (1021, Location, "Integral constant is too large");                        
2403                 }
2404                 
2405                 void Error_InvalidDirective ()
2406                 {
2407                         Report.Error (1517, Location, "Invalid preprocessor directive");
2408                 }
2409
2410                 void Error_UnexpectedDirective (string extra)
2411                 {
2412                         Report.Error (
2413                                 1028, Location,
2414                                 "Unexpected processor directive ({0})", extra);
2415                 }
2416
2417                 void Error_TokensSeen ()
2418                 {
2419                         Report.Error (1032, Location,
2420                                 "Cannot define or undefine preprocessor symbols after first token in file");
2421                 }
2422
2423                 void Eror_WrongPreprocessorLocation ()
2424                 {
2425                         Report.Error (1040, Location,
2426                                 "Preprocessor directives must appear as the first non-whitespace character on a line");
2427                 }
2428
2429                 void Error_EndLineExpected ()
2430                 {
2431                         Report.Error (1025, Location, "Single-line comment or end-of-line expected");
2432                 }
2433
2434                 //
2435                 // Raises a warning when tokenizer found documentation comment
2436                 // on unexpected place
2437                 //
2438                 void WarningMisplacedComment (Location loc)
2439                 {
2440                         if (doc_state != XmlCommentState.Error) {
2441                                 doc_state = XmlCommentState.Error;
2442                                 Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
2443                         }
2444                 }
2445                 
2446                 //
2447                 // if true, then the code continues processing the code
2448                 // if false, the code stays in a loop until another directive is
2449                 // reached.
2450                 // When caller_is_taking is false we ignore all directives except the ones
2451                 // which can help us to identify where the #if block ends
2452                 bool ParsePreprocessingDirective (bool caller_is_taking)
2453                 {
2454                         string arg;
2455                         bool region_directive = false;
2456
2457                         var directive = get_cmd_arg (out arg);
2458
2459                         //
2460                         // The first group of pre-processing instructions is always processed
2461                         //
2462                         switch (directive) {
2463                         case PreprocessorDirective.Region:
2464                                 region_directive = true;
2465                                 arg = "true";
2466                                 goto case PreprocessorDirective.If;
2467
2468                         case PreprocessorDirective.Endregion:
2469                                 if (ifstack == null || ifstack.Count == 0){
2470                                         Error_UnexpectedDirective ("no #region for this #endregion");
2471                                         return true;
2472                                 }
2473                                 int pop = ifstack.Pop ();
2474                                         
2475                                 if ((pop & REGION) == 0)
2476                                         Report.Error (1027, Location, "Expected `#endif' directive");
2477                                         
2478                                 return caller_is_taking;
2479                                 
2480                         case PreprocessorDirective.If:
2481                                 if (ifstack == null)
2482                                         ifstack = new Stack<int> (2);
2483
2484                                 int flags = region_directive ? REGION : 0;
2485                                 if (ifstack.Count == 0){
2486                                         flags |= PARENT_TAKING;
2487                                 } else {
2488                                         int state = ifstack.Peek ();
2489                                         if ((state & TAKING) != 0) {
2490                                                 flags |= PARENT_TAKING;
2491                                         }
2492                                 }
2493
2494                                 if (eval (arg) && caller_is_taking) {
2495                                         ifstack.Push (flags | TAKING);
2496                                         return true;
2497                                 }
2498                                 ifstack.Push (flags);
2499                                 return false;
2500
2501                         case PreprocessorDirective.Endif:
2502                                 if (ifstack == null || ifstack.Count == 0){
2503                                         Error_UnexpectedDirective ("no #if for this #endif");
2504                                         return true;
2505                                 } else {
2506                                         pop = ifstack.Pop ();
2507                                         
2508                                         if ((pop & REGION) != 0)
2509                                                 Report.Error (1038, Location, "#endregion directive expected");
2510                                         
2511                                         if (arg.Length != 0) {
2512                                                 Error_EndLineExpected ();
2513                                         }
2514                                         
2515                                         if (ifstack.Count == 0)
2516                                                 return true;
2517
2518                                         int state = ifstack.Peek ();
2519                                         return (state & TAKING) != 0;
2520                                 }
2521
2522                         case PreprocessorDirective.Elif:
2523                                 if (ifstack == null || ifstack.Count == 0){
2524                                         Error_UnexpectedDirective ("no #if for this #elif");
2525                                         return true;
2526                                 } else {
2527                                         int state = ifstack.Pop ();
2528
2529                                         if ((state & REGION) != 0) {
2530                                                 Report.Error (1038, Location, "#endregion directive expected");
2531                                                 return true;
2532                                         }
2533
2534                                         if ((state & ELSE_SEEN) != 0){
2535                                                 Error_UnexpectedDirective ("#elif not valid after #else");
2536                                                 return true;
2537                                         }
2538
2539                                         if ((state & TAKING) != 0) {
2540                                                 ifstack.Push (0);
2541                                                 return false;
2542                                         }
2543
2544                                         if (eval (arg) && ((state & PARENT_TAKING) != 0)){
2545                                                 ifstack.Push (state | TAKING);
2546                                                 return true;
2547                                         }
2548
2549                                         ifstack.Push (state);
2550                                         return false;
2551                                 }
2552
2553                         case PreprocessorDirective.Else:
2554                                 if (ifstack == null || ifstack.Count == 0){
2555                                         Error_UnexpectedDirective ("no #if for this #else");
2556                                         return true;
2557                                 } else {
2558                                         int state = ifstack.Peek ();
2559
2560                                         if ((state & REGION) != 0) {
2561                                                 Report.Error (1038, Location, "#endregion directive expected");
2562                                                 return true;
2563                                         }
2564
2565                                         if ((state & ELSE_SEEN) != 0){
2566                                                 Error_UnexpectedDirective ("#else within #else");
2567                                                 return true;
2568                                         }
2569
2570                                         ifstack.Pop ();
2571
2572                                         if (arg.Length != 0) {
2573                                                 Error_EndLineExpected ();
2574                                                 return true;
2575                                         }
2576
2577                                         bool ret = false;
2578                                         if ((state & PARENT_TAKING) != 0) {
2579                                                 ret = (state & TAKING) == 0;
2580                                         
2581                                                 if (ret)
2582                                                         state |= TAKING;
2583                                                 else
2584                                                         state &= ~TAKING;
2585                                         }
2586         
2587                                         ifstack.Push (state | ELSE_SEEN);
2588                                         
2589                                         return ret;
2590                                 }
2591                         case PreprocessorDirective.Define:
2592                                 if (any_token_seen){
2593                                         Error_TokensSeen ();
2594                                         return caller_is_taking;
2595                                 }
2596                                 PreProcessDefinition (true, arg, caller_is_taking);
2597                                 return caller_is_taking;
2598
2599                         case PreprocessorDirective.Undef:
2600                                 if (any_token_seen){
2601                                         Error_TokensSeen ();
2602                                         return caller_is_taking;
2603                                 }
2604                                 PreProcessDefinition (false, arg, caller_is_taking);
2605                                 return caller_is_taking;
2606
2607                         case PreprocessorDirective.Invalid:
2608                                 Report.Error (1024, Location, "Wrong preprocessor directive");
2609                                 return true;
2610                         }
2611
2612                         //
2613                         // These are only processed if we are in a `taking' block
2614                         //
2615                         if (!caller_is_taking)
2616                                 return false;
2617                                         
2618                         switch (directive){
2619                         case PreprocessorDirective.Error:
2620                                 Report.Error (1029, Location, "#error: '{0}'", arg);
2621                                 return true;
2622
2623                         case PreprocessorDirective.Warning:
2624                                 Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
2625                                 return true;
2626
2627                         case PreprocessorDirective.Pragma:
2628                                 if (context.Settings.Version == LanguageVersion.ISO_1) {
2629                                         Report.FeatureIsNotAvailable (context, Location, "#pragma");
2630                                 }
2631
2632                                 ParsePragmaDirective (arg);
2633                                 return true;
2634
2635                         case PreprocessorDirective.Line:
2636                                 if (!PreProcessLine (arg))
2637                                         Report.Error (
2638                                                 1576, Location,
2639                                                 "The line number specified for #line directive is missing or invalid");
2640                                 return caller_is_taking;
2641                         }
2642
2643                         throw new NotImplementedException (directive.ToString ());
2644                 }
2645
2646                 private int consume_string (bool quoted)
2647                 {
2648                         int c;
2649                         int pos = 0;
2650                         Location start_location = Location;
2651                         while (true){
2652                                 c = get_char ();
2653                                 if (c == '"') {
2654                                         if (quoted && peek_char () == '"') {
2655                                                 if (pos == value_builder.Length)
2656                                                         Array.Resize (ref value_builder, pos * 2);
2657
2658                                                 value_builder[pos++] = (char) c;
2659                                                 get_char ();
2660                                                 continue;
2661                                         }
2662
2663                                         string s;
2664                                         if (pos == 0)
2665                                                 s = string.Empty;
2666                                         else if (pos <= 4)
2667                                                 s = InternIdentifier (value_builder, pos);
2668                                         else
2669                                                 s = new string (value_builder, 0, pos);
2670
2671                                         val = new StringLiteral (context.BuiltinTypes, s, start_location);
2672                                         return Token.LITERAL;
2673                                 }
2674
2675                                 if (c == '\n') {
2676                                         if (!quoted)
2677                                                 Report.Error (1010, Location, "Newline in constant");
2678                                 } else if (c == '\\' && !quoted) {
2679                                         int surrogate;
2680                                         c = escape (c, out surrogate);
2681                                         if (c == -1)
2682                                                 return Token.ERROR;
2683                                         if (surrogate != 0) {
2684                                                 if (pos == value_builder.Length)
2685                                                         Array.Resize (ref value_builder, pos * 2);
2686
2687                                                 value_builder[pos++] = (char) c;
2688                                                 c = surrogate;
2689                                         }
2690                                 } else if (c == -1) {
2691                                         Report.Error (1039, Location, "Unterminated string literal");
2692                                         return Token.EOF;
2693                                 }
2694
2695                                 if (pos == value_builder.Length)
2696                                         Array.Resize (ref value_builder, pos * 2);
2697
2698                                 value_builder[pos++] = (char) c;
2699                         }
2700                 }
2701
2702                 private int consume_identifier (int s)
2703                 {
2704                         int res = consume_identifier (s, false);
2705
2706                         if (doc_state == XmlCommentState.Allowed)
2707                                 doc_state = XmlCommentState.NotAllowed;
2708
2709                         return res;
2710                 }
2711
2712                 int consume_identifier (int c, bool quoted) 
2713                 {
2714                         //
2715                         // This method is very performance sensitive. It accounts
2716                         // for approximately 25% of all parser time
2717                         //
2718
2719                         int pos = 0;
2720                         int column = col;
2721
2722                         if (c == '\\') {
2723                                 int surrogate;
2724                                 c = escape (c, out surrogate);
2725                                 if (surrogate != 0) {
2726                                         id_builder [pos++] = (char) c;
2727                                         c = surrogate;
2728                                 }
2729                         }
2730
2731                         id_builder [pos++] = (char) c;
2732
2733                         try {
2734                                 while (true) {
2735                                         c = reader.Read ();
2736
2737                                         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
2738                                                 id_builder [pos++] = (char) c;
2739                                                 continue;
2740                                         }
2741
2742                                         if (c < 0x80) {
2743                                                 if (c == '\\') {
2744                                                         int surrogate;
2745                                                         c = escape (c, out surrogate);
2746                                                         if (surrogate != 0) {
2747                                                                 if (is_identifier_part_character ((char) c))
2748                                                                         id_builder[pos++] = (char) c;
2749                                                                 c = surrogate;
2750                                                         }
2751
2752                                                         continue;
2753                                                 }
2754                                         } else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
2755                                                 id_builder [pos++] = (char) c;
2756                                                 continue;
2757                                         }
2758
2759                                         putback_char = c;
2760                                         break;
2761                                 }
2762                         } catch (IndexOutOfRangeException) {
2763                                 Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
2764                                 --pos;
2765                                 col += pos;
2766                         }
2767
2768                         col += pos - 1;
2769
2770                         //
2771                         // Optimization: avoids doing the keyword lookup
2772                         // on uppercase letters
2773                         //
2774                         if (id_builder [0] >= '_' && !quoted) {
2775                                 int keyword = GetKeyword (id_builder, pos);
2776                                 if (keyword != -1) {
2777                                         val = LocatedToken.Create (null, ref_line, column);
2778                                         return keyword;
2779                                 }
2780                         }
2781
2782                         string s = InternIdentifier (id_builder, pos);
2783                         val = LocatedToken.Create (s, ref_line, column);
2784                         if (quoted && parsing_attribute_section)
2785                                 AddEscapedIdentifier (((LocatedToken) val).Location);
2786
2787                         return Token.IDENTIFIER;
2788                 }
2789
2790                 static string InternIdentifier (char[] charBuffer, int length)
2791                 {
2792                         //
2793                         // Keep identifiers in an array of hashtables to avoid needless
2794                         // allocations
2795                         //
2796                         var identifiers_group = identifiers[length];
2797                         string s;
2798                         if (identifiers_group != null) {
2799                                 if (identifiers_group.TryGetValue (charBuffer, out s)) {
2800                                         return s;
2801                                 }
2802                         } else {
2803                                 // TODO: this should be number of files dependant
2804                                 // corlib compilation peaks at 1000 and System.Core at 150
2805                                 int capacity = length > 20 ? 10 : 100;
2806                                 identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
2807                                 identifiers[length] = identifiers_group;
2808                         }
2809
2810                         char[] chars = new char[length];
2811                         Array.Copy (charBuffer, chars, length);
2812
2813                         s = new string (charBuffer, 0, length);
2814                         identifiers_group.Add (chars, s);
2815                         return s;
2816                 }
2817                 
2818                 public int xtoken ()
2819                 {
2820                         int d, c;
2821
2822                         // Whether we have seen comments on the current line
2823                         bool comments_seen = false;
2824                         while ((c = get_char ()) != -1) {
2825                                 switch (c) {
2826                                 case '\t':
2827                                         col = ((col - 1 + tab_size) / tab_size) * tab_size;
2828                                         continue;
2829
2830                                 case ' ':
2831                                 case '\f':
2832                                 case '\v':
2833                                 case 0xa0:
2834                                 case 0:
2835                                 case 0xFEFF:    // Ignore BOM anywhere in the file
2836                                         continue;
2837
2838 /*                              This is required for compatibility with .NET
2839                                 case 0xEF:
2840                                         if (peek_char () == 0xBB) {
2841                                                 PushPosition ();
2842                                                 get_char ();
2843                                                 if (get_char () == 0xBF)
2844                                                         continue;
2845                                                 PopPosition ();
2846                                         }
2847                                         break;
2848 */
2849                                 case '\\':
2850                                         tokens_seen = true;
2851                                         return consume_identifier (c);
2852
2853                                 case '{':
2854                                         val = LocatedToken.Create (ref_line, col);
2855                                         return Token.OPEN_BRACE;
2856                                 case '}':
2857                                         val = LocatedToken.Create (ref_line, col);
2858                                         return Token.CLOSE_BRACE;
2859                                 case '[':
2860                                         // To block doccomment inside attribute declaration.
2861                                         if (doc_state == XmlCommentState.Allowed)
2862                                                 doc_state = XmlCommentState.NotAllowed;
2863
2864                                         val = LocatedToken.Create (ref_line, col);
2865
2866                                         if (parsing_block == 0 || lambda_arguments_parsing)
2867                                                 return Token.OPEN_BRACKET;
2868
2869                                         int next = peek_char ();
2870                                         switch (next) {
2871                                         case ']':
2872                                         case ',':
2873                                                 return Token.OPEN_BRACKET;
2874
2875                                         case ' ':
2876                                         case '\f':
2877                                         case '\v':
2878                                         case '\r':
2879                                         case '\n':
2880                                         case '/':
2881                                                 next = peek_token ();
2882                                                 if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
2883                                                         return Token.OPEN_BRACKET;
2884
2885                                                 return Token.OPEN_BRACKET_EXPR;
2886                                         default:
2887                                                 return Token.OPEN_BRACKET_EXPR;
2888                                         }
2889                                 case ']':
2890                                         LocatedToken.CreateOptional (ref_line, col, ref val);
2891                                         return Token.CLOSE_BRACKET;
2892                                 case '(':
2893                                         val = LocatedToken.Create (ref_line, col);
2894                                         //
2895                                         // An expression versions of parens can appear in block context only
2896                                         //
2897                                         if (parsing_block != 0 && !lambda_arguments_parsing) {
2898                                                 
2899                                                 //
2900                                                 // Optmize most common case where we know that parens
2901                                                 // is not special
2902                                                 //
2903                                                 switch (current_token) {
2904                                                 case Token.IDENTIFIER:
2905                                                 case Token.IF:
2906                                                 case Token.FOR:
2907                                                 case Token.FOREACH:
2908                                                 case Token.TYPEOF:
2909                                                 case Token.WHILE:
2910                                                 case Token.USING:
2911                                                 case Token.DEFAULT:
2912                                                 case Token.DELEGATE:
2913                                                 case Token.OP_GENERICS_GT:
2914                                                         return Token.OPEN_PARENS;
2915                                                 }
2916
2917                                                 // Optimize using peek
2918                                                 int xx = peek_char ();
2919                                                 switch (xx) {
2920                                                 case '(':
2921                                                 case '\'':
2922                                                 case '"':
2923                                                 case '0':
2924                                                 case '1':
2925                                                         return Token.OPEN_PARENS;
2926                                                 }
2927
2928                                                 lambda_arguments_parsing = true;
2929                                                 PushPosition ();
2930                                                 d = TokenizeOpenParens ();
2931                                                 PopPosition ();
2932                                                 lambda_arguments_parsing = false;
2933                                                 return d;
2934                                         }
2935
2936                                         return Token.OPEN_PARENS;
2937                                 case ')':
2938                                         LocatedToken.CreateOptional (ref_line, col, ref val);
2939                                         return Token.CLOSE_PARENS;
2940                                 case ',':
2941                                         LocatedToken.CreateOptional (ref_line, col, ref val);
2942                                         return Token.COMMA;
2943                                 case ';':
2944                                         LocatedToken.CreateOptional (ref_line, col, ref val);
2945                                         return Token.SEMICOLON;
2946                                 case '~':
2947                                         val = LocatedToken.Create (ref_line, col);
2948                                         return Token.TILDE;
2949                                 case '?':
2950                                         val = LocatedToken.Create (ref_line, col);
2951                                         return TokenizePossibleNullableType ();
2952                                 case '<':
2953                                         val = LocatedToken.Create (ref_line, col);
2954                                         if (parsing_generic_less_than++ > 0)
2955                                                 return Token.OP_GENERICS_LT;
2956
2957                                         return TokenizeLessThan ();
2958
2959                                 case '>':
2960                                         val = LocatedToken.Create (ref_line, col);
2961                                         d = peek_char ();
2962
2963                                         if (d == '='){
2964                                                 get_char ();
2965                                                 return Token.OP_GE;
2966                                         }
2967
2968                                         if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
2969                                                 parsing_generic_less_than--;
2970                                                 return Token.OP_GENERICS_GT;
2971                                         }
2972
2973                                         if (d == '>') {
2974                                                 get_char ();
2975                                                 d = peek_char ();
2976
2977                                                 if (d == '=') {
2978                                                         get_char ();
2979                                                         return Token.OP_SHIFT_RIGHT_ASSIGN;
2980                                                 }
2981                                                 return Token.OP_SHIFT_RIGHT;
2982                                         }
2983
2984                                         return Token.OP_GT;
2985
2986                                 case '+':
2987                                         val = LocatedToken.Create (ref_line, col);
2988                                         d = peek_char ();
2989                                         if (d == '+') {
2990                                                 d = Token.OP_INC;
2991                                         } else if (d == '=') {
2992                                                 d = Token.OP_ADD_ASSIGN;
2993                                         } else {
2994                                                 return Token.PLUS;
2995                                         }
2996                                         get_char ();
2997                                         return d;
2998
2999                                 case '-':
3000                                         val = LocatedToken.Create (ref_line, col);
3001                                         d = peek_char ();
3002                                         if (d == '-') {
3003                                                 d = Token.OP_DEC;
3004                                         } else if (d == '=')
3005                                                 d = Token.OP_SUB_ASSIGN;
3006                                         else if (d == '>')
3007                                                 d = Token.OP_PTR;
3008                                         else {
3009                                                 return Token.MINUS;
3010                                         }
3011                                         get_char ();
3012                                         return d;
3013
3014                                 case '!':
3015                                         val = LocatedToken.Create (ref_line, col);
3016                                         if (peek_char () == '='){
3017                                                 get_char ();
3018                                                 return Token.OP_NE;
3019                                         }
3020                                         return Token.BANG;
3021
3022                                 case '=':
3023                                         val = LocatedToken.Create (ref_line, col);
3024                                         d = peek_char ();
3025                                         if (d == '='){
3026                                                 get_char ();
3027                                                 return Token.OP_EQ;
3028                                         }
3029                                         if (d == '>'){
3030                                                 get_char ();
3031                                                 return Token.ARROW;
3032                                         }
3033
3034                                         return Token.ASSIGN;
3035
3036                                 case '&':
3037                                         val = LocatedToken.Create (ref_line, col);
3038                                         d = peek_char ();
3039                                         if (d == '&'){
3040                                                 get_char ();
3041                                                 return Token.OP_AND;
3042                                         }
3043                                         if (d == '='){
3044                                                 get_char ();
3045                                                 return Token.OP_AND_ASSIGN;
3046                                         }
3047                                         return Token.BITWISE_AND;
3048
3049                                 case '|':
3050                                         val = LocatedToken.Create (ref_line, col);
3051                                         d = peek_char ();
3052                                         if (d == '|'){
3053                                                 get_char ();
3054                                                 return Token.OP_OR;
3055                                         }
3056                                         if (d == '='){
3057                                                 get_char ();
3058                                                 return Token.OP_OR_ASSIGN;
3059                                         }
3060                                         return Token.BITWISE_OR;
3061
3062                                 case '*':
3063                                         val = LocatedToken.Create (ref_line, col);
3064                                         if (peek_char () == '='){
3065                                                 get_char ();
3066                                                 return Token.OP_MULT_ASSIGN;
3067                                         }
3068                                         return Token.STAR;
3069
3070                                 case '/':
3071                                         d = peek_char ();
3072                                         if (d == '='){
3073                                                 val = LocatedToken.Create (ref_line, col);
3074                                                 get_char ();
3075                                                 return Token.OP_DIV_ASSIGN;
3076                                         }
3077
3078                                         // Handle double-slash comments.
3079                                         if (d == '/'){
3080                                                 get_char ();
3081                                                 if (doc_processing) {
3082                                                         if (peek_char () == '/') {
3083                                                                 get_char ();
3084                                                                 // Don't allow ////.
3085                                                                 if ((d = peek_char ()) != '/') {
3086                                                                         if (doc_state == XmlCommentState.Allowed)
3087                                                                                 handle_one_line_xml_comment ();
3088                                                                         else if (doc_state == XmlCommentState.NotAllowed)
3089                                                                                 WarningMisplacedComment (Location - 3);
3090                                                                 }
3091                                                         } else {
3092                                                                 if (xml_comment_buffer.Length > 0)
3093                                                                         doc_state = XmlCommentState.NotAllowed;
3094                                                         }
3095                                                 }
3096
3097                                                 while ((d = get_char ()) != -1 && d != '\n');
3098
3099                                                 any_token_seen |= tokens_seen;
3100                                                 tokens_seen = false;
3101                                                 comments_seen = false;
3102                                                 continue;
3103                                         } else if (d == '*'){
3104                                                 get_char ();
3105                                                 bool docAppend = false;
3106                                                 if (doc_processing && peek_char () == '*') {
3107                                                         get_char ();
3108                                                         // But when it is /**/, just do nothing.
3109                                                         if (peek_char () == '/') {
3110                                                                 get_char ();
3111                                                                 continue;
3112                                                         }
3113                                                         if (doc_state == XmlCommentState.Allowed)
3114                                                                 docAppend = true;
3115                                                         else if (doc_state == XmlCommentState.NotAllowed) {
3116                                                                 WarningMisplacedComment (Location - 2);
3117                                                         }
3118                                                 }
3119
3120                                                 int current_comment_start = 0;
3121                                                 if (docAppend) {
3122                                                         current_comment_start = xml_comment_buffer.Length;
3123                                                         xml_comment_buffer.Append (Environment.NewLine);
3124                                                 }
3125
3126                                                 while ((d = get_char ()) != -1){
3127                                                         if (d == '*' && peek_char () == '/'){
3128                                                                 get_char ();
3129                                                                 comments_seen = true;
3130                                                                 break;
3131                                                         }
3132                                                         if (docAppend)
3133                                                                 xml_comment_buffer.Append ((char) d);
3134                                                         
3135                                                         if (d == '\n'){
3136                                                                 any_token_seen |= tokens_seen;
3137                                                                 tokens_seen = false;
3138                                                                 // 
3139                                                                 // Reset 'comments_seen' just to be consistent.
3140                                                                 // It doesn't matter either way, here.
3141                                                                 //
3142                                                                 comments_seen = false;
3143                                                         }
3144                                                 }
3145                                                 if (!comments_seen)
3146                                                         Report.Error (1035, Location, "End-of-file found, '*/' expected");
3147
3148                                                 if (docAppend)
3149                                                         update_formatted_doc_comment (current_comment_start);
3150                                                 continue;
3151                                         }
3152                                         val = LocatedToken.Create (ref_line, col);
3153                                         return Token.DIV;
3154
3155                                 case '%':
3156                                         val = LocatedToken.Create (ref_line, col);
3157                                         if (peek_char () == '='){
3158                                                 get_char ();
3159                                                 return Token.OP_MOD_ASSIGN;
3160                                         }
3161                                         return Token.PERCENT;
3162
3163                                 case '^':
3164                                         val = LocatedToken.Create (ref_line, col);
3165                                         if (peek_char () == '='){
3166                                                 get_char ();
3167                                                 return Token.OP_XOR_ASSIGN;
3168                                         }
3169                                         return Token.CARRET;
3170
3171                                 case ':':
3172                                         val = LocatedToken.Create (ref_line, col);
3173                                         if (peek_char () == ':') {
3174                                                 get_char ();
3175                                                 return Token.DOUBLE_COLON;
3176                                         }
3177                                         return Token.COLON;
3178
3179                                 case '0': case '1': case '2': case '3': case '4':
3180                                 case '5': case '6': case '7': case '8': case '9':
3181                                         tokens_seen = true;
3182                                         return is_number (c);
3183
3184                                 case '\n': // white space
3185                                         any_token_seen |= tokens_seen;
3186                                         tokens_seen = false;
3187                                         comments_seen = false;
3188                                         continue;
3189
3190                                 case '.':
3191                                         tokens_seen = true;
3192                                         d = peek_char ();
3193                                         if (d >= '0' && d <= '9')
3194                                                 return is_number (c);
3195
3196                                         LocatedToken.CreateOptional (ref_line, col, ref val);
3197                                         return Token.DOT;
3198                                 
3199                                 case '#':
3200                                         if (tokens_seen || comments_seen) {
3201                                                 Eror_WrongPreprocessorLocation ();
3202                                                 return Token.ERROR;
3203                                         }
3204                                         
3205                                         if (ParsePreprocessingDirective (true))
3206                                                 continue;
3207
3208                                         bool directive_expected = false;
3209                                         while ((c = get_char ()) != -1) {
3210                                                 if (col == 1) {
3211                                                         directive_expected = true;
3212                                                 } else if (!directive_expected) {
3213                                                         // TODO: Implement comment support for disabled code and uncomment this code
3214 //                                                      if (c == '#') {
3215 //                                                              Eror_WrongPreprocessorLocation ();
3216 //                                                              return Token.ERROR;
3217 //                                                      }
3218                                                         continue;
3219                                                 }
3220
3221                                                 if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' )
3222                                                         continue;
3223
3224                                                 if (c == '#') {
3225                                                         if (ParsePreprocessingDirective (false))
3226                                                                 break;
3227                                                 }
3228                                                 directive_expected = false;
3229                                         }
3230
3231                                         if (c != -1) {
3232                                                 tokens_seen = false;
3233                                                 continue;
3234                                         }
3235
3236                                         return Token.EOF;
3237                                 
3238                                 case '"':
3239                                         return consume_string (false);
3240
3241                                 case '\'':
3242                                         return TokenizeBackslash ();
3243                                 
3244                                 case '@':
3245                                         c = get_char ();
3246                                         if (c == '"') {
3247                                                 tokens_seen = true;
3248                                                 return consume_string (true);
3249                                         }
3250
3251                                         if (is_identifier_start_character (c)){
3252                                                 return consume_identifier (c, true);
3253                                         }
3254
3255                                         Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
3256                                         return Token.ERROR;
3257
3258                                 case EvalStatementParserCharacter:
3259                                         return Token.EVAL_STATEMENT_PARSER;
3260                                 case EvalCompilationUnitParserCharacter:
3261                                         return Token.EVAL_COMPILATION_UNIT_PARSER;
3262                                 case EvalUsingDeclarationsParserCharacter:
3263                                         return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
3264                                 case DocumentationXref:
3265                                         return Token.DOC_SEE;
3266                                 }
3267
3268                                 if (is_identifier_start_character (c)) {
3269                                         tokens_seen = true;
3270                                         return consume_identifier (c);
3271                                 }
3272
3273                                 if (char.IsWhiteSpace ((char) c))
3274                                         continue;
3275
3276                                 Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
3277                         }
3278
3279                         if (CompleteOnEOF){
3280                                 if (generated)
3281                                         return Token.COMPLETE_COMPLETION;
3282                                 
3283                                 generated = true;
3284                                 return Token.GENERATE_COMPLETION;
3285                         }
3286                         
3287
3288                         return Token.EOF;
3289                 }
3290
3291                 int TokenizeBackslash ()
3292                 {
3293                         int c = get_char ();
3294                         tokens_seen = true;
3295                         if (c == '\'') {
3296                                 val = new CharLiteral (context.BuiltinTypes, (char) c, Location);
3297                                 Report.Error (1011, Location, "Empty character literal");
3298                                 return Token.LITERAL;
3299                         }
3300
3301                         if (c == '\n') {
3302                                 Report.Error (1010, Location, "Newline in constant");
3303                                 return Token.ERROR;
3304                         }
3305
3306                         int d;
3307                         c = escape (c, out d);
3308                         if (c == -1)
3309                                 return Token.ERROR;
3310                         if (d != 0)
3311                                 throw new NotImplementedException ();
3312
3313                         val = new CharLiteral (context.BuiltinTypes, (char) c, Location);
3314                         c = get_char ();
3315
3316                         if (c != '\'') {
3317                                 Report.Error (1012, Location, "Too many characters in character literal");
3318
3319                                 // Try to recover, read until newline or next "'"
3320                                 while ((c = get_char ()) != -1) {
3321                                         if (c == '\n' || c == '\'')
3322                                                 break;
3323                                 }
3324                         }
3325
3326                         return Token.LITERAL;
3327                 }
3328
3329                 int TokenizeLessThan ()
3330                 {
3331                         int d;
3332                         if (handle_typeof) {
3333                                 PushPosition ();
3334                                 if (parse_generic_dimension (out d)) {
3335                                         val = d;
3336                                         DiscardPosition ();
3337                                         return Token.GENERIC_DIMENSION;
3338                                 }
3339                                 PopPosition ();
3340                         }
3341
3342                         // Save current position and parse next token.
3343                         PushPosition ();
3344                         if (parse_less_than ()) {
3345                                 if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
3346                                         d = Token.OP_GENERICS_LT_DECL;
3347                                 } else {
3348                                         d = Token.OP_GENERICS_LT;
3349                                 }
3350                                 PopPosition ();
3351                                 return d;
3352                         }
3353
3354                         PopPosition ();
3355                         parsing_generic_less_than = 0;
3356
3357                         d = peek_char ();
3358                         if (d == '<') {
3359                                 get_char ();
3360                                 d = peek_char ();
3361
3362                                 if (d == '=') {
3363                                         get_char ();
3364                                         return Token.OP_SHIFT_LEFT_ASSIGN;
3365                                 }
3366                                 return Token.OP_SHIFT_LEFT;
3367                         }
3368
3369                         if (d == '=') {
3370                                 get_char ();
3371                                 return Token.OP_LE;
3372                         }
3373                         return Token.OP_LT;
3374                 }
3375
3376                 //
3377                 // Handles one line xml comment
3378                 //
3379                 private void handle_one_line_xml_comment ()
3380                 {
3381                         int c;
3382                         while ((c = peek_char ()) == ' ')
3383                                 get_char (); // skip heading whitespaces.
3384                         while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
3385                                 xml_comment_buffer.Append ((char) get_char ());
3386                         }
3387                         if (c == '\r' || c == '\n')
3388                                 xml_comment_buffer.Append (Environment.NewLine);
3389                 }
3390
3391                 //
3392                 // Remove heading "*" in Javadoc-like xml documentation.
3393                 //
3394                 private void update_formatted_doc_comment (int current_comment_start)
3395                 {
3396                         int length = xml_comment_buffer.Length - current_comment_start;
3397                         string [] lines = xml_comment_buffer.ToString (
3398                                 current_comment_start,
3399                                 length).Replace ("\r", "").Split ('\n');
3400                         
3401                         // The first line starts with /**, thus it is not target
3402                         // for the format check.
3403                         for (int i = 1; i < lines.Length; i++) {
3404                                 string s = lines [i];
3405                                 int idx = s.IndexOf ('*');
3406                                 string head = null;
3407                                 if (idx < 0) {
3408                                         if (i < lines.Length - 1)
3409                                                 return;
3410                                         head = s;
3411                                 } else
3412                                         head = s.Substring (0, idx);
3413                                 foreach (char c in head)
3414                                         if (c != ' ')
3415                                                 return;
3416                                 lines [i] = s.Substring (idx + 1);
3417                         }
3418                         xml_comment_buffer.Remove (current_comment_start, length);
3419                         xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
3420                 }
3421
3422                 //
3423                 // Checks if there was incorrect doc comments and raise
3424                 // warnings.
3425                 //
3426                 public void check_incorrect_doc_comment ()
3427                 {
3428                         if (xml_comment_buffer.Length > 0)
3429                                 WarningMisplacedComment (Location);
3430                 }
3431
3432                 //
3433                 // Consumes the saved xml comment lines (if any)
3434                 // as for current target member or type.
3435                 //
3436                 public string consume_doc_comment ()
3437                 {
3438                         if (xml_comment_buffer.Length > 0) {
3439                                 string ret = xml_comment_buffer.ToString ();
3440                                 reset_doc_comment ();
3441                                 return ret;
3442                         }
3443                         return null;
3444                 }
3445
3446                 Report Report {
3447                         get { return context.Report; }
3448                 }
3449
3450                 void reset_doc_comment ()
3451                 {
3452                         xml_comment_buffer.Length = 0;
3453                 }
3454
3455                 public void cleanup ()
3456                 {
3457                         if (ifstack != null && ifstack.Count >= 1) {
3458                                 int state = ifstack.Pop ();
3459                                 if ((state & REGION) != 0)
3460                                         Report.Error (1038, Location, "#endregion directive expected");
3461                                 else 
3462                                         Report.Error (1027, Location, "Expected `#endif' directive");
3463                         }
3464                 }
3465         }
3466
3467         //
3468         // Indicates whether it accepts XML documentation or not.
3469         //
3470         public enum XmlCommentState {
3471                 // comment is allowed in this state.
3472                 Allowed,
3473                 // comment is not allowed in this state.
3474                 NotAllowed,
3475                 // once comments appeared when it is NotAllowed, then the
3476                 // state is changed to it, until the state is changed to
3477                 // .Allowed.
3478                 Error
3479         }
3480 }
3481