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
13 namespace Mono.MonoBASIC
17 using System.Collections;
19 using System.Globalization;
24 /// Tokenizer for MonoBASIC source code.
27 public class Tokenizer : yyParser.yyInput
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
92 public string Source {
100 Location.SetCurrentSource(file_name);
104 public string EffectiveSource {
110 Location.SetCurrentSource(ref_name);
120 public int EffectiveLine {
135 static void initTokens ()
137 keywords = new Hashtable ();
139 keywords.Add ("addhandler", Token.ADDHANDLER);
140 keywords.Add ("addressof", Token.ADDRESSOF);
141 keywords.Add ("alias", Token.ALIAS);
142 keywords.Add ("and", Token.AND);
143 keywords.Add ("andalso", Token.ANDALSO);
144 keywords.Add ("ansi", Token.ANSI);
145 keywords.Add ("as", Token.AS);
146 keywords.Add ("assembly", Token.ASSEMBLY);
147 keywords.Add ("auto", Token.AUTO);
148 keywords.Add ("binary", Token.BINARY);
149 keywords.Add ("boolean", Token.BOOLEAN);
150 keywords.Add ("byref", Token.BYREF);
151 keywords.Add ("byte", Token.BYTE);
152 keywords.Add ("byval", Token.BYVAL);
153 keywords.Add ("call", Token.CALL);
154 keywords.Add ("case", Token.CASE);
155 keywords.Add ("catch", Token.CATCH);
156 keywords.Add ("cbool", Token.CBOOL);
157 keywords.Add ("cbyte", Token.CBYTE);
158 keywords.Add ("cchar", Token.CCHAR);
159 keywords.Add ("cdate", Token.CDATE);
160 keywords.Add ("cdec", Token.CDEC);
161 keywords.Add ("cdbl", Token.CDBL);
162 keywords.Add ("char", Token.CHAR);
163 keywords.Add ("cint", Token.CINT);
164 keywords.Add ("class", Token.CLASS);
165 keywords.Add ("clng", Token.CLNG);
166 keywords.Add ("cobj", Token.COBJ);
167 keywords.Add ("compare", Token.COMPARE);
168 keywords.Add ("const", Token.CONST);
169 keywords.Add ("cshort", Token.CSHORT);
170 keywords.Add ("csng", Token.CSNG);
171 keywords.Add ("cstr", Token.CSTR);
172 keywords.Add ("ctype", Token.CTYPE);
173 keywords.Add ("date", Token.DATE);
174 keywords.Add ("decimal", Token.DECIMAL);
175 keywords.Add ("declare", Token.DECLARE);
176 keywords.Add ("default", Token.DEFAULT);
177 keywords.Add ("delegate", Token.DELEGATE);
178 keywords.Add ("dim", Token.DIM);
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 ("enum", Token.ENUM);
186 keywords.Add ("erase", Token.ERASE);
187 keywords.Add ("error", Token.ERROR);
188 keywords.Add ("event", Token.EVENT);
189 keywords.Add ("exit", Token.EXIT);
190 keywords.Add ("explicit", Token.EXPLICIT);
191 keywords.Add ("false", Token.FALSE);
192 keywords.Add ("finally", Token.FINALLY);
193 keywords.Add ("for", Token.FOR);
194 keywords.Add ("friend", Token.FRIEND);
195 keywords.Add ("function", Token.FUNCTION);
196 keywords.Add ("get", Token.GET);
197 //keywords.Add ("gettype", Token.GETTYPE);
198 keywords.Add ("goto", Token.GOTO);
199 keywords.Add ("handles", Token.HANDLES);
200 keywords.Add ("if", Token.IF);
201 keywords.Add ("implements", Token.IMPLEMENTS);
202 keywords.Add ("imports", Token.IMPORTS);
203 keywords.Add ("in", Token.IN);
204 keywords.Add ("inherits", Token.INHERITS);
205 keywords.Add ("integer", Token.INTEGER);
206 keywords.Add ("interface", Token.INTERFACE);
207 keywords.Add ("is", Token.IS);
208 keywords.Add ("let ", Token.LET );
209 keywords.Add ("lib ", Token.LIB );
210 keywords.Add ("like ", Token.LIKE );
211 keywords.Add ("long", Token.LONG);
212 keywords.Add ("loop", Token.LOOP);
213 keywords.Add ("me", Token.ME);
214 keywords.Add ("mod", Token.MOD);
215 keywords.Add ("module", Token.MODULE);
216 keywords.Add ("mustinherit", Token.MUSTINHERIT);
217 keywords.Add ("mustoverride", Token.MUSTOVERRIDE);
218 keywords.Add ("mybase", Token.MYBASE);
219 keywords.Add ("myclass", Token.MYCLASS);
220 keywords.Add ("namespace", Token.NAMESPACE);
221 keywords.Add ("new", Token.NEW);
222 keywords.Add ("next", Token.NEXT);
223 keywords.Add ("not", Token.NOT);
224 keywords.Add ("nothing", Token.NOTHING);
225 keywords.Add ("notinheritable", Token.NOTINHERITABLE);
226 keywords.Add ("notoverridable", Token.NOTOVERRIDABLE);
227 keywords.Add ("object", Token.OBJECT);
228 keywords.Add ("off", Token.OFF);
229 keywords.Add ("on", Token.ON);
230 keywords.Add ("option", Token.OPTION);
231 keywords.Add ("optional", Token.OPTIONAL);
232 keywords.Add ("or", Token.OR);
233 keywords.Add ("orelse", Token.ORELSE);
234 keywords.Add ("overloads", Token.OVERLOADS);
235 keywords.Add ("overridable", Token.OVERRIDABLE);
236 keywords.Add ("overrides", Token.OVERRIDES);
237 keywords.Add ("paramarray", Token.PARAM_ARRAY);
238 keywords.Add ("preserve", Token.PRESERVE);
239 keywords.Add ("private", Token.PRIVATE);
240 keywords.Add ("property", Token.PROPERTY);
241 keywords.Add ("protected", Token.PROTECTED);
242 keywords.Add ("public", Token.PUBLIC);
243 keywords.Add ("raiseevent", Token.RAISEEVENT);
244 keywords.Add ("readonly", Token.READONLY);
245 keywords.Add ("redim", Token.REDIM);
246 keywords.Add ("rem", Token.REM);
247 keywords.Add ("removehandler", Token.REMOVEHANDLER);
248 keywords.Add ("resume", Token.RESUME);
249 keywords.Add ("return", Token.RETURN);
250 keywords.Add ("select", Token.SELECT);
251 keywords.Add ("set", Token.SET);
252 keywords.Add ("shadows", Token.SHADOWS);
253 keywords.Add ("shared", Token.SHARED);
254 keywords.Add ("short", Token.SHORT);
255 keywords.Add ("single", Token.SINGLE);
256 keywords.Add ("sizeof", Token.SIZEOF);
257 keywords.Add ("static", Token.STATIC);
258 keywords.Add ("step", Token.STEP);
259 keywords.Add ("stop", Token.STOP);
260 keywords.Add ("strict", Token.STRICT);
261 keywords.Add ("string", Token.STRING);
262 keywords.Add ("structure", Token.STRUCTURE);
263 keywords.Add ("sub", Token.SUB);
264 keywords.Add ("synclock", Token.SYNCLOCK);
265 keywords.Add ("text", Token.TEXT);
266 keywords.Add ("then", Token.THEN);
267 keywords.Add ("throw", Token.THROW);
268 keywords.Add ("to", Token.TO);
269 keywords.Add ("true", Token.TRUE);
270 keywords.Add ("try", Token.TRY);
271 keywords.Add ("typeof", Token.TYPEOF);
272 keywords.Add ("unicode", Token.UNICODE);
273 keywords.Add ("until", Token.UNTIL);
274 keywords.Add ("variant", Token.VARIANT);
275 keywords.Add ("when", Token.WHEN);
276 keywords.Add ("while", Token.WHILE);
277 keywords.Add ("with", Token.WITH);
278 keywords.Add ("withevents", Token.WITHEVENTS);
279 keywords.Add ("writeonly", Token.WRITEONLY);
280 keywords.Add ("xor", Token.XOR);
282 if (Parser.UseExtendedSyntax){
283 keywords.Add ("yield", Token.YIELD);
291 csharp_format_info = new NumberFormatInfo ();
292 csharp_format_info.CurrencyDecimalSeparator = ".";
293 styles = NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint;
296 public Tokenizer (System.IO.TextReader input, string fname, ArrayList defines)
302 // putback an EOL at the beginning of a stream. This is a convenience that
303 // allows pre-processor directives to be added to the beginning of a vb file.
307 bool is_keyword (string name)
310 name = name.ToLower();
312 res = keywords.Contains(name);
313 if ((name == "GET" || name == "SET") && handle_get_set == false)
318 int getKeyword (string name)
320 return (int) (keywords [name.ToLower()]);
323 public Location Location {
325 return new Location (ref_line, col);
329 public bool PropertyParsing {
331 return handle_get_set;
335 handle_get_set = value;
339 bool is_identifier_start_character (char c)
341 return Char.IsLetter (c) || c == '_' ;
344 bool is_identifier_part_character (char c)
346 return (Char.IsLetter (c) || Char.IsDigit (c) || c == '_');
349 int is_punct (char c, ref bool doread)
356 error_details = c.ToString();
362 return Token.OPEN_BRACKET;
364 return Token.CLOSE_BRACKET;
366 return Token.OPEN_BRACE;
368 return Token.CLOSE_BRACE;
370 return Token.OPEN_PARENS;
372 return Token.CLOSE_PARENS;
378 if (is_identifier_start_character((char)d) || cant_have_a_type_character)
379 return Token.EXCLAMATION;
380 return Token.SINGLETYPECHAR;
382 if (cant_have_a_type_character)
384 return Token.DOLAR_SIGN;
386 if (cant_have_a_type_character)
388 return Token.AT_SIGN;
390 if (cant_have_a_type_character)
392 return Token.PERCENT;
396 if (cant_have_a_type_character)
397 return ExtractDateTimeLiteral();
399 return Token.NUMBER_SIGN;
407 if (!cant_have_a_type_character)
408 return Token.LONGTYPECHAR;
409 t = handle_integer_literal_in_other_bases(d);
410 if (t == Token.NONE) {
413 t = Token.OP_CONCAT_ASSIGN;
424 t = Token.OP_ADD_ASSIGN;
432 t = Token.OP_SUB_ASSIGN;
446 return Token.OP_MULT_ASSIGN;
454 return Token.OP_DIV_ASSIGN;
462 return Token.OP_IDIV_ASSIGN;
464 return Token.OP_IDIV;
470 return Token.OP_EXP_ASSIGN;
488 return Token.OP_SHIFT_LEFT;
501 return Token.OP_SHIFT_RIGHT;
509 return Token.ATTR_ASSIGN;
517 bool decimal_digits (int c)
520 bool seen_digits = false;
523 number.Append ((char) c);
525 while ((d = peekChar ()) != -1){
526 if (Char.IsDigit ((char)d)){
527 number.Append ((char) d);
537 int real_type_suffix (int c)
543 t = Token.LITERAL_SINGLE;
546 t = Token.LITERAL_DOUBLE;
549 t= Token.LITERAL_DECIMAL;
558 int integer_type_suffix (int c)
566 t = Token.LITERAL_INTEGER; // SHORT ?
567 val = ((IConvertible)val).ToInt16(null);
570 t = Token.LITERAL_INTEGER;
571 val = ((IConvertible)val).ToInt32(null);
574 t= Token.LITERAL_INTEGER; // LONG ?
575 val = ((IConvertible)val).ToInt64(null);
578 if ((long)val <= System.Int32.MaxValue &&
579 (long)val >= System.Int32.MinValue) {
580 val = ((IConvertible)val).ToInt32(null);
581 return Token.LITERAL_INTEGER;
583 val = ((IConvertible)val).ToInt64(null);
584 return Token.LITERAL_INTEGER; // LONG ?
589 } catch (Exception e) {
595 int adjust_real (int t)
597 string s = number.ToString ();
600 case Token.LITERAL_DECIMAL:
601 val = new System.Decimal ();
602 val = System.Decimal.Parse (
603 s, styles, csharp_format_info);
605 case Token.LITERAL_DOUBLE:
606 val = new System.Double ();
607 val = System.Double.Parse (
608 s, styles, csharp_format_info);
610 case Token.LITERAL_SINGLE:
611 val = new System.Double ();
612 val = (float) System.Double.Parse (
613 s, styles, csharp_format_info);
617 val = new System.Double ();
618 val = System.Double.Parse (
619 s, styles, csharp_format_info);
620 t = Token.LITERAL_DOUBLE;
628 StringBuilder hexNumber = new StringBuilder ();
632 while ((d = peekChar ()) != -1){
633 char e = Char.ToUpper ((char) d);
635 if (Char.IsDigit (e) || (e >= 'A' && e <= 'F')){
636 hexNumber.Append (e);
641 return System.Int64.Parse (hexNumber.ToString(), NumberStyles.HexNumber);
646 long valueToReturn = 0;
650 while ((d = peekChar ()) != -1){
652 if (Char.IsDigit (e) && (e < '8')){
654 valueToReturn += (d - (int)'0');
660 return valueToReturn;
663 int handle_integer_literal_in_other_bases(int peek)
665 if (peek == 'h' || peek == 'H'){
668 return integer_type_suffix (peekChar ());
671 if (peek == 'o' || peek == 'O'){
673 val = octal_digits ();
674 return integer_type_suffix (peekChar ());
681 // Invoked if we know we have .digits or digits
683 int is_number (int c)
685 bool is_real = false;
686 number = new StringBuilder ();
691 if (Char.IsDigit ((char)c)){
697 // We need to handle the case of
698 // "1.1" vs "1.ToString()" (LITERAL_SINGLE vs NUMBER DOT IDENTIFIER)
701 if (decimal_digits (getChar())){
707 val = System.Int64.Parse(number.ToString());
708 return integer_type_suffix('.');
712 if (c == 'e' || c == 'E'){
719 number.Append ((char) c);
722 } else if (c == '-'){
723 number.Append ((char) c);
731 type = real_type_suffix (c);
732 if (type == Token.NONE && !is_real){
733 val = System.Int64.Parse(number.ToString());
734 return integer_type_suffix(c);
737 return adjust_real (type);
742 if (putback_char != -1){
743 int x = putback_char;
748 return reader.Read ();
753 if (putback_char != -1)
755 return reader.Peek ();
760 if (putback_char != -1)
761 throw new Exception ("This should not happen putback on putback");
765 public bool advance ()
767 return current_token != Token.EOF ;
770 public Object Value {
776 public Object value ()
781 private bool IsEOL(int currentChar)
785 if (currentChar == 0x0D) {
786 if (peekChar() == 0x0A) // if it is a CR-LF pair consume LF also
792 retVal = (currentChar == -1 || currentChar == 0x0A || currentChar == 0x2028 || currentChar == 0x2029);
802 private int DropComments()
805 while (!IsEOL(d = getChar ()))
813 int lastToken = current_token;
816 current_token = xtoken ();
817 if (current_token == 0)
819 if (current_token == Token.REM)
820 current_token = DropComments();
821 } while (lastToken == Token.EOL && current_token == Token.EOL);
823 return current_token;
826 private string GetIdentifier()
829 if (is_identifier_start_character ((char) c))
830 return GetIdentifier(c);
835 private string GetIdentifier(int c)
837 StringBuilder id = new StringBuilder ();
839 id.Append ((char) c);
841 while ((c = peekChar ()) != -1)
843 if (is_identifier_part_character ((char) c))
845 id.Append ((char)getChar ());
852 cant_have_a_type_character = false;
854 return id.ToString();
857 private bool is_doublequote(int currentChar)
859 return (currentChar == '"' ||
860 currentChar == 0x201C || // unicode left double-quote character
861 currentChar == 0x201D); // unicode right double-quote character
864 private bool is_whitespace(int c)
866 return (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0);
869 private bool tokens_seen = false;
871 private void nextLine()
873 cant_have_a_type_character = true;
887 for (;(c = getChar ()) != -1; col++) {
889 // Handle line continuation character
893 if (!is_identifier_part_character((char)d)) {
894 while ((c = getChar ()) != -1 && !IsEOL(c)) {}
900 if (is_whitespace(c)) {
901 // expand tabs for location
903 col = (((col + ExpandedTabsSize) / ExpandedTabsSize) * ExpandedTabsSize) - 1;
904 cant_have_a_type_character = true;
908 // Handle line comments.
915 if (current_token == Token.EOL) // if last token was also EOL keep skipping
920 // Handle escaped identifiers
923 if ((val = GetIdentifier()) == null)
925 if ((c = getChar()) != ']')
928 return Token.IDENTIFIER;
931 // Handle unescaped identifiers
932 if (is_identifier_start_character ((char) c))
935 if ((id = GetIdentifier(c)) == null)
939 if (is_keyword(id) && (current_token != Token.DOT))
940 return getKeyword(id);
941 return Token.IDENTIFIER;
944 // Treat string literals
945 if (is_doublequote(c)) {
946 cant_have_a_type_character = true;
947 return ExtractStringOrCharLiteral(c);
950 // handle numeric literals
953 cant_have_a_type_character = true;
955 if (Char.IsDigit ((char) peekChar ()))
956 return is_number (c);
960 if (Char.IsDigit ((char) c))
962 cant_have_a_type_character = true;
964 return is_number (c);
967 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR) {
968 cant_have_a_type_character = true;
981 error_details = ((char)c).ToString ();
985 if (current_token != Token.EOL) // if last token wasn't EOL send it before EOF
991 private int ExtractDateTimeLiteral()
995 StringBuilder sb = new StringBuilder();
996 for (;(c = getChar ()) != -1; col++)
999 val = ParseDateLiteral(sb);
1000 return Token.LITERAL_DATE;
1012 private int ExtractStringOrCharLiteral(int c)
1014 StringBuilder s = new StringBuilder ();
1018 while ((c = getChar ()) != -1){
1019 if (is_doublequote(c)){
1020 if (is_doublequote(peekChar()))
1023 //handle Char Literals
1024 if (peekChar() == 'C' || peekChar() == 'c') {
1026 if (s.Length == 1) {
1028 return Token.LITERAL_CHARACTER;
1030 val = "Incorrect length for a character literal";
1034 val = s.ToString ();
1035 return Token.LITERAL_STRING;
1044 s.Append ((char) c);
1050 static IFormatProvider enUSculture = new CultureInfo("en-US", true);
1052 private DateTime ParseDateLiteral(StringBuilder value)
1056 return DateTime.Parse(value.ToString(),
1058 DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowWhiteSpaces);
1060 catch (FormatException ex)
1062 //TODO: What is the correct error number and message?
1063 Report.Error (1, Location, string.Format("Invalid date literal '{0}'", value.ToString())
1064 + Environment.NewLine + ex.ToString());
1068 Report.Error (1, Location, "Error parsing date literal"); //TODO: What is the correct error number and message?
1070 return new DateTime();
1073 public void PositionCursorAtNextPreProcessorDirective()
1077 for(t = token(); t != Token.HASH && t != Token.EOF; t = token());
1080 throw new ApplicationException("Unexpected EOF while looking for a pre-processor directive");
1082 if(t == Token.HASH) {
1083 tokens_seen = false;