2 // Mono.MonoBASIC.Tokenizer.cs: The Tokenizer for the MonoBASIC compiler
4 // Author: A Rafael D Teixeira (rafaelteixeirabr@hotmail.com)
6 // Based on cs-tokenizer.cs by Miguel de Icaza (miguel@gnu.org)
8 // Licensed under the terms of the GNU GPL
10 // Copyright (C) 2001 A Rafael D Teixeira
17 using System.Collections;
19 using System.Globalization;
20 // using Mono.Languages;
24 /// Tokenizer for MonoBASIC source code.
27 public class Tokenizer : yyParser.yyInput
29 SeekableStreamReader reader;
35 public int current_token = Token.ERROR;
36 bool handle_get_set = false;
37 bool cant_have_a_type_character = false;
39 public int ExpandedTabsSize = 4;
41 public string location {
45 if (current_token == Token.ERROR)
46 det = "detail: " + error_details;
50 return "Line: "+line+" Col: "+col + "\n" +
51 "VirtLine: "+ref_line +
52 " Token: "+current_token + " " + det;
56 public bool properties {
58 return handle_get_set;
62 handle_get_set = value;
69 static Hashtable keywords;
70 static NumberStyles styles;
71 static NumberFormatInfo csharp_format_info;
74 // Values for the associated token returned
77 int putback_char = -1;
81 // Details about the error encoutered by the tokenizer
91 // public string Source {
99 // //Location.SetCurrentSource(file_name);
103 // public string EffectiveSource {
109 // //Location.SetCurrentSource(ref_name);
119 public int EffectiveLine {
134 static void initTokens ()
136 keywords = new Hashtable ();
138 keywords.Add ("addhandler", Token.ADDHANDLER);
139 keywords.Add ("addressof", Token.ADDRESSOF);
140 keywords.Add ("alias", Token.ALIAS);
141 keywords.Add ("and", Token.AND);
142 keywords.Add ("andalso", Token.ANDALSO);
143 keywords.Add ("ansi", Token.ANSI);
144 keywords.Add ("as", Token.AS);
145 keywords.Add ("assembly", Token.ASSEMBLY);
146 keywords.Add ("auto", Token.AUTO);
147 keywords.Add ("binary", Token.BINARY); // Not a VB.NET Keyword
148 keywords.Add ("boolean", Token.BOOLEAN);
149 keywords.Add ("byref", Token.BYREF);
150 keywords.Add ("byte", Token.BYTE);
151 keywords.Add ("byval", Token.BYVAL);
152 keywords.Add ("call", Token.CALL);
153 keywords.Add ("case", Token.CASE);
154 keywords.Add ("catch", Token.CATCH);
155 keywords.Add ("cbool", Token.CBOOL);
156 keywords.Add ("cbyte", Token.CBYTE);
157 keywords.Add ("cchar", Token.CCHAR);
158 keywords.Add ("cdate", Token.CDATE);
159 keywords.Add ("cdec", Token.CDEC);
160 keywords.Add ("cdbl", Token.CDBL);
161 keywords.Add ("char", Token.CHAR);
162 keywords.Add ("cint", Token.CINT);
163 keywords.Add ("class", Token.CLASS);
164 keywords.Add ("clng", Token.CLNG);
165 keywords.Add ("cobj", Token.COBJ);
166 keywords.Add ("compare", Token.COMPARE); // Not a VB.NET Keyword
167 keywords.Add ("const", Token.CONST);
168 keywords.Add ("cshort", Token.CSHORT);
169 keywords.Add ("csng", Token.CSNG);
170 keywords.Add ("cstr", Token.CSTR);
171 keywords.Add ("ctype", Token.CTYPE);
172 keywords.Add ("date", Token.DATE);
173 keywords.Add ("decimal", Token.DECIMAL);
174 keywords.Add ("declare", Token.DECLARE);
175 keywords.Add ("default", Token.DEFAULT);
176 keywords.Add ("delegate", Token.DELEGATE);
177 keywords.Add ("dim", Token.DIM);
178 keywords.Add ("directcast", Token.DIRECTCAST);
179 keywords.Add ("do", Token.DO);
180 keywords.Add ("double", Token.DOUBLE);
181 keywords.Add ("each", Token.EACH);
182 keywords.Add ("else", Token.ELSE);
183 keywords.Add ("elseif", Token.ELSEIF);
184 keywords.Add ("end", Token.END);
185 keywords.Add ("endif", Token.ENDIF); // An unused VB.NET keyword
186 keywords.Add ("enum", Token.ENUM);
187 keywords.Add ("erase", Token.ERASE);
188 keywords.Add ("error", Token.ERROR);
189 keywords.Add ("event", Token.EVENT);
190 keywords.Add ("exit", Token.EXIT);
191 keywords.Add ("explicit", Token.EXPLICIT); // Not a VB.NET keyword
192 keywords.Add ("false", Token.FALSE);
193 keywords.Add ("finally", Token.FINALLY);
194 keywords.Add ("for", Token.FOR);
195 keywords.Add ("friend", Token.FRIEND);
196 keywords.Add ("function", Token.FUNCTION);
197 keywords.Add ("get", Token.GET);
198 keywords.Add ("gettype", Token.GETTYPE);
199 keywords.Add ("gosub", Token.GOSUB); // An unused VB.NET keyword
200 keywords.Add ("goto", Token.GOTO);
201 keywords.Add ("handles", Token.HANDLES);
202 keywords.Add ("if", Token.IF);
203 keywords.Add ("implements", Token.IMPLEMENTS);
204 keywords.Add ("imports", Token.IMPORTS);
205 keywords.Add ("in", Token.IN);
206 keywords.Add ("inherits", Token.INHERITS);
207 keywords.Add ("integer", Token.INTEGER);
208 keywords.Add ("interface", Token.INTERFACE);
209 keywords.Add ("is", Token.IS);
210 keywords.Add ("let ", Token.LET ); // An unused VB.NET keyword
211 keywords.Add ("lib ", Token.LIB );
212 keywords.Add ("like ", Token.LIKE );
213 keywords.Add ("long", Token.LONG);
214 keywords.Add ("loop", Token.LOOP);
215 keywords.Add ("me", Token.ME);
216 keywords.Add ("mod", Token.MOD);
217 keywords.Add ("module", Token.MODULE);
218 keywords.Add ("mustinherit", Token.MUSTINHERIT);
219 keywords.Add ("mustoverride", Token.MUSTOVERRIDE);
220 keywords.Add ("mybase", Token.MYBASE);
221 keywords.Add ("myclass", Token.MYCLASS);
222 keywords.Add ("namespace", Token.NAMESPACE);
223 keywords.Add ("new", Token.NEW);
224 keywords.Add ("next", Token.NEXT);
225 keywords.Add ("not", Token.NOT);
226 keywords.Add ("nothing", Token.NOTHING);
227 keywords.Add ("notinheritable", Token.NOTINHERITABLE);
228 keywords.Add ("notoverridable", Token.NOTOVERRIDABLE);
229 keywords.Add ("object", Token.OBJECT);
230 keywords.Add ("off", Token.OFF); // Not a VB.NET Keyword
231 keywords.Add ("on", Token.ON);
232 keywords.Add ("option", Token.OPTION);
233 keywords.Add ("optional", Token.OPTIONAL);
234 keywords.Add ("or", Token.OR);
235 keywords.Add ("orelse", Token.ORELSE);
236 keywords.Add ("overloads", Token.OVERLOADS);
237 keywords.Add ("overridable", Token.OVERRIDABLE);
238 keywords.Add ("overrides", Token.OVERRIDES);
239 keywords.Add ("paramarray", Token.PARAM_ARRAY);
240 keywords.Add ("preserve", Token.PRESERVE);
241 keywords.Add ("private", Token.PRIVATE);
242 keywords.Add ("property", Token.PROPERTY);
243 keywords.Add ("protected", Token.PROTECTED);
244 keywords.Add ("public", Token.PUBLIC);
245 keywords.Add ("raiseevent", Token.RAISEEVENT);
246 keywords.Add ("readonly", Token.READONLY);
247 keywords.Add ("redim", Token.REDIM);
248 keywords.Add ("rem", Token.REM);
249 keywords.Add ("removehandler", Token.REMOVEHANDLER);
250 keywords.Add ("resume", Token.RESUME);
251 keywords.Add ("return", Token.RETURN);
252 keywords.Add ("select", Token.SELECT);
253 keywords.Add ("set", Token.SET);
254 keywords.Add ("shadows", Token.SHADOWS);
255 keywords.Add ("shared", Token.SHARED);
256 keywords.Add ("short", Token.SHORT);
257 keywords.Add ("single", Token.SINGLE);
258 keywords.Add ("sizeof", Token.SIZEOF); // Not a VB.NET Keyword
259 keywords.Add ("static", Token.STATIC);
260 keywords.Add ("step", Token.STEP);
261 keywords.Add ("stop", Token.STOP);
262 keywords.Add ("strict", Token.STRICT); // Not a VB.NET Keyword
263 keywords.Add ("string", Token.STRING);
264 keywords.Add ("structure", Token.STRUCTURE);
265 keywords.Add ("sub", Token.SUB);
266 keywords.Add ("synclock", Token.SYNCLOCK);
267 keywords.Add ("text", Token.TEXT); // Not a VB.NET Keyword
268 keywords.Add ("then", Token.THEN);
269 keywords.Add ("throw", Token.THROW);
270 keywords.Add ("to", Token.TO);
271 keywords.Add ("true", Token.TRUE);
272 keywords.Add ("try", Token.TRY);
273 keywords.Add ("typeof", Token.TYPEOF);
274 keywords.Add ("unicode", Token.UNICODE);
275 keywords.Add ("until", Token.UNTIL);
276 keywords.Add ("variant", Token.VARIANT); // An unused VB.NET keyword
277 keywords.Add ("wend", Token.WEND); // An unused VB.NET keyword
278 keywords.Add ("when", Token.WHEN);
279 keywords.Add ("while", Token.WHILE);
280 keywords.Add ("with", Token.WITH);
281 keywords.Add ("withevents", Token.WITHEVENTS);
282 keywords.Add ("writeonly", Token.WRITEONLY);
283 keywords.Add ("xor", Token.XOR);
287 if (Parser.UseExtendedSyntax){
288 keywords.Add ("yield", Token.YIELD);
298 csharp_format_info = new NumberFormatInfo ();
299 csharp_format_info.CurrencyDecimalSeparator = ".";
300 styles = NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint;
303 public Tokenizer (SeekableStreamReader input, SourceFile fname, ArrayList defines)
305 this.ref_name = fname;
306 this.file_name = fname;
310 // putback an EOL at the beginning of a stream. This is a convenience that
311 // allows pre-processor directives to be added to the beginning of a vb file.
315 bool is_keyword (string name)
318 name = name.ToLower();
320 res = keywords.Contains(name);
321 if ((name == "GET" || name == "SET") && handle_get_set == false)
326 int getKeyword (string name)
328 return (int) (keywords [name.ToLower()]);
331 public Location Location {
333 return new Location (ref_line);
337 public bool PropertyParsing {
339 return handle_get_set;
343 handle_get_set = value;
347 static bool is_identifier_start_character (char c)
349 return Char.IsLetter (c) || c == '_' ;
352 static bool is_identifier_part_character (char c)
354 return (Char.IsLetter (c) || Char.IsDigit (c) || c == '_');
357 public static bool IsValidIdentifier (string s)
359 if (s == null || s.Length == 0)
362 if (!is_identifier_start_character (s [0]))
365 for (int i = 1; i < s.Length; i ++)
366 if (! is_identifier_part_character (s [i]))
372 int is_punct (char c, ref bool doread)
379 error_details = c.ToString();
385 return Token.OPEN_BRACKET;
387 return Token.CLOSE_BRACKET;
389 return Token.OPEN_BRACE;
391 return Token.CLOSE_BRACE;
393 return Token.OPEN_PARENS;
395 return Token.CLOSE_PARENS;
401 if (is_identifier_start_character((char)d) || cant_have_a_type_character)
402 return Token.EXCLAMATION;
403 return Token.SINGLETYPECHAR;
405 if (cant_have_a_type_character)
407 return Token.DOLAR_SIGN;
409 if (cant_have_a_type_character)
411 return Token.AT_SIGN;
413 if (cant_have_a_type_character)
415 return Token.PERCENT;
419 if (cant_have_a_type_character)
420 return ExtractDateTimeLiteral();
422 return Token.NUMBER_SIGN;
430 if (!cant_have_a_type_character)
431 return Token.LONGTYPECHAR;
432 t = handle_integer_literal_in_other_bases(d);
433 if (t == Token.NONE) {
464 return Token.OP_IDIV;
484 return Token.OP_SHIFT_LEFT;
497 return Token.OP_SHIFT_RIGHT;
505 return Token.ATTR_ASSIGN;
513 bool decimal_digits (int c)
516 bool seen_digits = false;
519 number.Append ((char) c);
521 while ((d = peekChar ()) != -1){
522 if (Char.IsDigit ((char)d)){
523 number.Append ((char) d);
533 int real_type_suffix (int c)
539 t = Token.LITERAL_SINGLE;
542 t = Token.LITERAL_DOUBLE;
545 t= Token.LITERAL_DECIMAL;
554 int integer_type_suffix (int c)
562 t = Token.LITERAL_INTEGER; // SHORT ?
563 val = ((IConvertible)val).ToInt16(null);
566 t = Token.LITERAL_INTEGER;
567 val = ((IConvertible)val).ToInt32(null);
570 t= Token.LITERAL_INTEGER; // LONG ?
571 val = ((IConvertible)val).ToInt64(null);
574 if ((long)val <= System.Int32.MaxValue &&
575 (long)val >= System.Int32.MinValue) {
576 val = ((IConvertible)val).ToInt32(null);
577 return Token.LITERAL_INTEGER;
579 val = ((IConvertible)val).ToInt64(null);
580 return Token.LITERAL_INTEGER; // LONG ?
585 } catch (Exception e) {
591 int adjust_real (int t)
593 string s = number.ToString ();
596 case Token.LITERAL_DECIMAL:
597 val = new System.Decimal ();
598 val = System.Decimal.Parse (
599 s, styles, csharp_format_info);
601 case Token.LITERAL_DOUBLE:
602 val = new System.Double ();
603 val = System.Double.Parse (
604 s, styles, csharp_format_info);
606 case Token.LITERAL_SINGLE:
607 val = new System.Double ();
608 val = (float) System.Double.Parse (
609 s, styles, csharp_format_info);
613 val = new System.Double ();
614 val = System.Double.Parse (
615 s, styles, csharp_format_info);
616 t = Token.LITERAL_DOUBLE;
624 StringBuilder hexNumber = new StringBuilder ();
628 while ((d = peekChar ()) != -1){
629 char e = Char.ToUpper ((char) d);
631 if (Char.IsDigit (e) || (e >= 'A' && e <= 'F')){
632 hexNumber.Append (e);
637 return System.Int64.Parse (hexNumber.ToString(), NumberStyles.HexNumber);
642 long valueToReturn = 0;
646 while ((d = peekChar ()) != -1){
648 if (Char.IsDigit (e) && (e < '8')){
650 valueToReturn += (d - (int)'0');
656 return valueToReturn;
659 int handle_integer_literal_in_other_bases(int peek)
661 if (peek == 'h' || peek == 'H'){
664 return integer_type_suffix (peekChar ());
667 if (peek == 'o' || peek == 'O'){
669 val = octal_digits ();
670 return integer_type_suffix (peekChar ());
677 // Invoked if we know we have .digits or digits
679 int is_number (int c)
681 bool is_real = false;
682 number = new StringBuilder ();
687 if (Char.IsDigit ((char)c)){
693 // We need to handle the case of
694 // "1.1" vs "1.ToString()" (LITERAL_SINGLE vs NUMBER DOT IDENTIFIER)
697 if (decimal_digits (getChar())){
703 val = System.Int64.Parse(number.ToString());
704 return integer_type_suffix('.');
708 if (c == 'e' || c == 'E'){
715 number.Append ((char) c);
718 } else if (c == '-'){
719 number.Append ((char) c);
727 type = real_type_suffix (c);
728 if (type == Token.NONE && !is_real){
729 val = System.Int64.Parse(number.ToString());
730 return integer_type_suffix(c);
733 return adjust_real (type);
738 if (putback_char != -1){
739 int x = putback_char;
744 return reader.Read ();
749 if (putback_char != -1)
751 return reader.Peek ();
756 if (putback_char != -1)
757 throw new Exception ("This should not happen putback on putback");
761 public bool advance ()
763 return current_token != Token.EOF ;
766 public Object Value {
772 public Object value ()
777 private bool IsEOL(int currentChar)
781 if (currentChar == 0x0D) {
782 if (peekChar() == 0x0A) // if it is a CR-LF pair consume LF also
788 retVal = (currentChar == -1 || currentChar == 0x0A || currentChar == 0x2028 || currentChar == 0x2029);
798 private int DropComments()
801 while (!IsEOL(d = getChar ()))
809 int lastToken = current_token;
812 current_token = xtoken ();
813 if (current_token == 0)
815 if (current_token == Token.REM)
816 current_token = DropComments();
817 } while (lastToken == Token.EOL && current_token == Token.EOL);
819 // Console.WriteLine ("Token = " + val);
821 return current_token;
824 private string GetIdentifier()
827 if (is_identifier_start_character ((char) c))
828 return GetIdentifier(c);
833 private string GetIdentifier(int c)
835 StringBuilder id = new StringBuilder ();
837 id.Append ((char) c);
839 while ((c = peekChar ()) != -1)
841 if (is_identifier_part_character ((char) c))
843 id.Append ((char)getChar ());
850 cant_have_a_type_character = false;
852 return id.ToString();
855 private bool is_doublequote(int currentChar)
857 return (currentChar == '"' ||
858 currentChar == 0x201C || // unicode left double-quote character
859 currentChar == 0x201D); // unicode right double-quote character
862 private bool is_whitespace(int c)
864 return (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0);
867 private bool tokens_seen = false;
869 private void nextLine()
871 cant_have_a_type_character = true;
885 for (;(c = getChar ()) != -1; col++) {
887 // Handle line continuation character
891 if (!is_identifier_part_character((char)d)) {
892 while ((c = getChar ()) != -1 && !IsEOL(c)) {}
898 if (is_whitespace(c)) {
899 // expand tabs for location
901 col = (((col + ExpandedTabsSize) / ExpandedTabsSize) * ExpandedTabsSize) - 1;
902 cant_have_a_type_character = true;
906 // Handle line comments.
913 if (current_token == Token.EOL) // if last token was also EOL keep skipping
918 // Handle escaped identifiers
921 if ((val = GetIdentifier()) == null)
923 if ((c = getChar()) != ']')
926 return Token.IDENTIFIER;
929 // Handle unescaped identifiers
930 if (is_identifier_start_character ((char) c))
933 if ((id = GetIdentifier(c)) == null)
937 if (is_keyword(id) && (current_token != Token.DOT))
938 return getKeyword(id);
939 return Token.IDENTIFIER;
942 // Treat string literals
943 if (is_doublequote(c)) {
944 cant_have_a_type_character = true;
945 return ExtractStringOrCharLiteral(c);
948 // handle numeric literals
951 cant_have_a_type_character = true;
953 if (Char.IsDigit ((char) peekChar ()))
954 return is_number (c);
958 if (Char.IsDigit ((char) c))
960 cant_have_a_type_character = true;
962 return is_number (c);
965 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR) {
966 cant_have_a_type_character = true;
979 error_details = ((char)c).ToString ();
983 if (current_token != Token.EOL) // if last token wasn't EOL send it before EOF
989 private int ExtractDateTimeLiteral()
993 StringBuilder sb = new StringBuilder();
994 for (;(c = getChar ()) != -1; col++)
997 val = ParseDateLiteral(sb);
998 return Token.LITERAL_DATE;
1010 private int ExtractStringOrCharLiteral(int c)
1012 StringBuilder s = new StringBuilder ();
1016 while ((c = getChar ()) != -1){
1017 if (is_doublequote(c)){
1018 if (is_doublequote(peekChar()))
1021 //handle Char Literals
1022 if (peekChar() == 'C' || peekChar() == 'c') {
1024 if (s.Length == 1) {
1026 return Token.LITERAL_CHARACTER;
1028 val = "Incorrect length for a character literal";
1032 val = s.ToString ();
1033 return Token.LITERAL_STRING;
1042 s.Append ((char) c);
1048 static IFormatProvider enUSculture = new CultureInfo("en-US", true);
1050 private DateTime ParseDateLiteral(StringBuilder value)
1054 return DateTime.Parse(value.ToString(),
1056 DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowWhiteSpaces);
1058 catch (FormatException ex)
1060 //TODO: What is the correct error number and message?
1061 Report.Error (1, Location, string.Format("Invalid date literal '{0}'", value.ToString())
1062 + Environment.NewLine + ex.ToString());
1066 Report.Error (1, Location, "Error parsing date literal"); //TODO: What is the correct error number and message?
1068 return new DateTime();
1071 public void PositionCursorAtNextPreProcessorDirective()
1075 for(t = token(); t != Token.HASH && t != Token.EOF; t = token());
1078 throw new ApplicationException("Unexpected EOF while looking for a pre-processor directive");
1080 if(t == Token.HASH) {
1081 tokens_seen = false;
1086 public void cleanup ()
1091 public static void Cleanup ()