2 // Mono.MonoBASIC.Tokenizer.cs: The Tokenizer for the MonoBASIC compiler
4 // Author: A Rafael D Teixeira (rafaelteixeirabr@hotmail.com)
5 // : Manjula GHM (mmanjula@novell.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;
82 // Details about the error encoutered by the tokenizer
93 public string Source {
101 Location.SetCurrentSource(file_name);
105 public string EffectiveSource {
111 Location.SetCurrentSource(ref_name);
121 public int EffectiveLine {
136 static void initTokens ()
138 keywords = new Hashtable ();
140 keywords.Add ("addhandler", Token.ADDHANDLER);
141 keywords.Add ("addressof", Token.ADDRESSOF);
142 keywords.Add ("alias", Token.ALIAS);
143 keywords.Add ("and", Token.AND);
144 keywords.Add ("andalso", Token.ANDALSO);
145 keywords.Add ("ansi", Token.ANSI);
146 keywords.Add ("as", Token.AS);
147 keywords.Add ("assembly", Token.ASSEMBLY);
148 keywords.Add ("auto", Token.AUTO);
149 keywords.Add ("binary", Token.BINARY); // Not a VB.NET Keyword
150 keywords.Add ("boolean", Token.BOOLEAN);
151 keywords.Add ("byref", Token.BYREF);
152 keywords.Add ("byte", Token.BYTE);
153 keywords.Add ("byval", Token.BYVAL);
154 keywords.Add ("call", Token.CALL);
155 keywords.Add ("case", Token.CASE);
156 keywords.Add ("catch", Token.CATCH);
157 keywords.Add ("cbool", Token.CBOOL);
158 keywords.Add ("cbyte", Token.CBYTE);
159 keywords.Add ("cchar", Token.CCHAR);
160 keywords.Add ("cdate", Token.CDATE);
161 keywords.Add ("cdec", Token.CDEC);
162 keywords.Add ("cdbl", Token.CDBL);
163 keywords.Add ("char", Token.CHAR);
164 keywords.Add ("cint", Token.CINT);
165 keywords.Add ("class", Token.CLASS);
166 keywords.Add ("clng", Token.CLNG);
167 keywords.Add ("cobj", Token.COBJ);
168 keywords.Add ("compare", Token.COMPARE); // Not a VB.NET Keyword
169 keywords.Add ("const", Token.CONST);
170 keywords.Add ("cshort", Token.CSHORT);
171 keywords.Add ("csng", Token.CSNG);
172 keywords.Add ("cstr", Token.CSTR);
173 keywords.Add ("ctype", Token.CTYPE);
174 keywords.Add ("date", Token.DATE);
175 keywords.Add ("decimal", Token.DECIMAL);
176 keywords.Add ("declare", Token.DECLARE);
177 keywords.Add ("default", Token.DEFAULT);
178 keywords.Add ("delegate", Token.DELEGATE);
179 keywords.Add ("dim", Token.DIM);
180 keywords.Add ("directcast", Token.DIRECTCAST);
181 keywords.Add ("do", Token.DO);
182 keywords.Add ("double", Token.DOUBLE);
183 keywords.Add ("each", Token.EACH);
184 keywords.Add ("else", Token.ELSE);
185 keywords.Add ("elseif", Token.ELSEIF);
186 keywords.Add ("end", Token.END);
187 keywords.Add ("endif", Token.ENDIF); // An unused VB.NET keyword
188 keywords.Add ("enum", Token.ENUM);
189 keywords.Add ("erase", Token.ERASE);
190 keywords.Add ("error", Token.ERROR);
191 keywords.Add ("event", Token.EVENT);
192 keywords.Add ("exit", Token.EXIT);
193 keywords.Add ("explicit", Token.EXPLICIT); // Not a VB.NET keyword
194 keywords.Add ("false", Token.FALSE);
195 keywords.Add ("finally", Token.FINALLY);
196 keywords.Add ("for", Token.FOR);
197 keywords.Add ("friend", Token.FRIEND);
198 keywords.Add ("function", Token.FUNCTION);
199 keywords.Add ("get", Token.GET);
200 keywords.Add ("gettype", Token.GETTYPE);
201 keywords.Add ("gosub", Token.GOSUB); // An unused VB.NET keyword
202 keywords.Add ("goto", Token.GOTO);
203 keywords.Add ("handles", Token.HANDLES);
204 keywords.Add ("if", Token.IF);
205 keywords.Add ("implements", Token.IMPLEMENTS);
206 keywords.Add ("imports", Token.IMPORTS);
207 keywords.Add ("in", Token.IN);
208 keywords.Add ("inherits", Token.INHERITS);
209 keywords.Add ("integer", Token.INTEGER);
210 keywords.Add ("interface", Token.INTERFACE);
211 keywords.Add ("is", Token.IS);
212 keywords.Add ("let ", Token.LET ); // An unused VB.NET keyword
213 keywords.Add ("lib ", Token.LIB );
214 keywords.Add ("like", Token.LIKE );
215 keywords.Add ("long", Token.LONG);
216 keywords.Add ("loop", Token.LOOP);
217 keywords.Add ("me", Token.ME);
218 keywords.Add ("mod", Token.MOD);
219 keywords.Add ("module", Token.MODULE);
220 keywords.Add ("mustinherit", Token.MUSTINHERIT);
221 keywords.Add ("mustoverride", Token.MUSTOVERRIDE);
222 keywords.Add ("mybase", Token.MYBASE);
223 keywords.Add ("myclass", Token.MYCLASS);
224 keywords.Add ("namespace", Token.NAMESPACE);
225 keywords.Add ("new", Token.NEW);
226 keywords.Add ("next", Token.NEXT);
227 keywords.Add ("not", Token.NOT);
228 keywords.Add ("nothing", Token.NOTHING);
229 keywords.Add ("notinheritable", Token.NOTINHERITABLE);
230 keywords.Add ("notoverridable", Token.NOTOVERRIDABLE);
231 keywords.Add ("object", Token.OBJECT);
232 keywords.Add ("off", Token.OFF); // Not a VB.NET Keyword
233 keywords.Add ("on", Token.ON);
234 keywords.Add ("option", Token.OPTION);
235 keywords.Add ("optional", Token.OPTIONAL);
236 keywords.Add ("or", Token.OR);
237 keywords.Add ("orelse", Token.ORELSE);
238 keywords.Add ("overloads", Token.OVERLOADS);
239 keywords.Add ("overridable", Token.OVERRIDABLE);
240 keywords.Add ("overrides", Token.OVERRIDES);
241 keywords.Add ("paramarray", Token.PARAM_ARRAY);
242 keywords.Add ("preserve", Token.PRESERVE);
243 keywords.Add ("private", Token.PRIVATE);
244 keywords.Add ("property", Token.PROPERTY);
245 keywords.Add ("protected", Token.PROTECTED);
246 keywords.Add ("public", Token.PUBLIC);
247 keywords.Add ("raiseevent", Token.RAISEEVENT);
248 keywords.Add ("readonly", Token.READONLY);
249 keywords.Add ("redim", Token.REDIM);
250 keywords.Add ("rem", Token.REM);
251 keywords.Add ("removehandler", Token.REMOVEHANDLER);
252 keywords.Add ("resume", Token.RESUME);
253 keywords.Add ("return", Token.RETURN);
254 keywords.Add ("select", Token.SELECT);
255 keywords.Add ("set", Token.SET);
256 keywords.Add ("shadows", Token.SHADOWS);
257 keywords.Add ("shared", Token.SHARED);
258 keywords.Add ("short", Token.SHORT);
259 keywords.Add ("single", Token.SINGLE);
260 keywords.Add ("sizeof", Token.SIZEOF); // Not a VB.NET Keyword
261 keywords.Add ("static", Token.STATIC);
262 keywords.Add ("step", Token.STEP);
263 keywords.Add ("stop", Token.STOP);
264 keywords.Add ("strict", Token.STRICT); // Not a VB.NET Keyword
265 keywords.Add ("string", Token.STRING);
266 keywords.Add ("structure", Token.STRUCTURE);
267 keywords.Add ("sub", Token.SUB);
268 keywords.Add ("synclock", Token.SYNCLOCK);
269 keywords.Add ("text", Token.TEXT); // Not a VB.NET Keyword
270 keywords.Add ("then", Token.THEN);
271 keywords.Add ("throw", Token.THROW);
272 keywords.Add ("to", Token.TO);
273 keywords.Add ("true", Token.TRUE);
274 keywords.Add ("try", Token.TRY);
275 keywords.Add ("typeof", Token.TYPEOF);
276 keywords.Add ("unicode", Token.UNICODE);
277 keywords.Add ("until", Token.UNTIL);
278 keywords.Add ("variant", Token.VARIANT); // An unused VB.NET keyword
279 keywords.Add ("wend", Token.WEND); // An unused VB.NET keyword
280 keywords.Add ("when", Token.WHEN);
281 keywords.Add ("while", Token.WHILE);
282 keywords.Add ("with", Token.WITH);
283 keywords.Add ("withevents", Token.WITHEVENTS);
284 keywords.Add ("writeonly", Token.WRITEONLY);
285 keywords.Add ("xor", Token.XOR);
287 if (Parser.UseExtendedSyntax){
288 keywords.Add ("yield", Token.YIELD);
296 csharp_format_info = new NumberFormatInfo ();
297 csharp_format_info.CurrencyDecimalSeparator = ".";
298 styles = NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint;
301 public Tokenizer (System.IO.TextReader input, string fname, ArrayList defines)
307 // putback an EOL at the beginning of a stream. This is a convenience that
308 // allows pre-processor directives to be added to the beginning of a vb file.
312 bool is_keyword (string name)
315 name = name.ToLower();
317 res = keywords.Contains(name);
318 if ((name == "GET" || name == "SET") && handle_get_set == false)
323 int getKeyword (string name)
325 return (int) (keywords [name.ToLower()]);
328 public Location Location {
330 return new Location (ref_line, col);
334 public bool PropertyParsing {
336 return handle_get_set;
340 handle_get_set = value;
344 bool is_identifier_start_character (char c)
346 return Char.IsLetter (c) || c == '_' ;
349 bool is_identifier_part_character (char c)
351 return (Char.IsLetter (c) || Char.IsDigit (c) || c == '_');
354 int is_punct (char c, ref bool doread)
361 error_details = c.ToString();
367 return Token.OPEN_BRACKET;
369 return Token.CLOSE_BRACKET;
371 return Token.OPEN_BRACE;
373 return Token.CLOSE_BRACE;
375 return Token.OPEN_PARENS;
377 return Token.CLOSE_PARENS;
383 if (is_identifier_start_character((char)d) || cant_have_a_type_character)
384 return Token.EXCLAMATION;
385 return Token.SINGLETYPECHAR;
387 if (cant_have_a_type_character)
389 return Token.DOLAR_SIGN;
391 if (cant_have_a_type_character)
393 return Token.AT_SIGN;
395 if (cant_have_a_type_character)
397 return Token.PERCENT;
401 if (cant_have_a_type_character)
402 return ExtractDateTimeLiteral();
404 return Token.NUMBER_SIGN;
412 if (!cant_have_a_type_character)
413 return Token.LONGTYPECHAR;
414 t = handle_integer_literal_in_other_bases(d);
415 if (t == Token.NONE) {
446 return Token.OP_IDIV;
466 return Token.OP_SHIFT_LEFT;
479 return Token.OP_SHIFT_RIGHT;
487 return Token.ATTR_ASSIGN;
495 bool decimal_digits (int c)
498 bool seen_digits = false;
501 number.Append ((char) c);
502 while ((d = peekChar ()) != -1){
503 if (Char.IsDigit ((char)d)){
504 number.Append ((char) d);
514 int real_type_suffix (int c)
520 t = Token.LITERAL_SINGLE;
523 t = Token.LITERAL_DOUBLE;
526 t= Token.LITERAL_DECIMAL;
535 int integer_type_suffix (int c)
543 t = Token.LITERAL_INTEGER; // SHORT ?
545 // hexadecimal literals - like &H8000S is "-32768"
546 // and not an overflow exception
547 // Check for other literals ???
553 val = ((IConvertible)val).ToInt16(null);
556 t = Token.LITERAL_INTEGER;
557 val = ((IConvertible)val).ToInt32(null);
560 t= Token.LITERAL_INTEGER; // LONG ?
561 val = ((IConvertible)val).ToInt64(null);
564 if ((long)val <= System.Int32.MaxValue &&
565 (long)val >= System.Int32.MinValue) {
566 val = ((IConvertible)val).ToInt32(null);
567 return Token.LITERAL_INTEGER;
569 val = ((IConvertible)val).ToInt64(null);
570 return Token.LITERAL_INTEGER; // LONG ?
575 } catch (Exception e) {
581 int adjust_real (int t)
583 string s = number.ToString ();
586 case Token.LITERAL_DECIMAL:
587 val = new System.Decimal ();
588 val = System.Decimal.Parse (
589 s, styles, csharp_format_info);
591 case Token.LITERAL_DOUBLE:
592 val = new System.Double ();
593 val = System.Double.Parse (
594 s, styles, csharp_format_info);
596 case Token.LITERAL_SINGLE:
597 val = new System.Double ();
598 val = (float) System.Double.Parse (
599 s, styles, csharp_format_info);
603 val = new System.Double ();
604 val = System.Double.Parse (
605 s, styles, csharp_format_info);
606 t = Token.LITERAL_DOUBLE;
614 StringBuilder hexNumber = new StringBuilder ();
618 while ((d = peekChar ()) != -1){
619 char e = Char.ToUpper ((char) d);
621 if (Char.IsDigit (e) || (e >= 'A' && e <= 'F')){
622 hexNumber.Append (e);
627 lon = System.Int64.Parse (hexNumber.ToString(), NumberStyles.HexNumber);
633 long valueToReturn = 0;
637 while ((d = peekChar ()) != -1){
639 if (Char.IsDigit (e) && (e < '8')){
641 valueToReturn += (d - (int)'0');
647 return valueToReturn;
650 int handle_integer_literal_in_other_bases(int peek)
652 if (peek == 'h' || peek == 'H'){
655 return integer_type_suffix (peekChar ());
658 if (peek == 'o' || peek == 'O'){
660 val = octal_digits ();
661 return integer_type_suffix (peekChar ());
668 // Invoked if we know we have .digits or digits
670 int is_number (int c)
672 bool is_real = false;
673 number = new StringBuilder ();
675 bool non_prefixdecimal = false; //To capture decimals like .50
679 if (Char.IsDigit ((char)c)){
682 non_prefixdecimal = true;
686 // We need to handle the case of
687 // "1.1" vs "1.ToString()" (LITERAL_SINGLE vs NUMBER DOT IDENTIFIER)
690 if (non_prefixdecimal == false)
692 if (decimal_digits (getChar())){
698 val = System.Int64.Parse(number.ToString());
699 return integer_type_suffix('.');
703 if (c == 'e' || c == 'E'){
710 number.Append ((char) c);
713 } else if (c == '-'){
714 number.Append ((char) c);
722 type = real_type_suffix (c);
723 if (type == Token.NONE && !is_real){
724 val = System.Int64.Parse(number.ToString());
725 return integer_type_suffix(c);
728 return adjust_real (type);
733 if (putback_char != -1){
734 int x = putback_char;
739 return reader.Read ();
744 if (putback_char != -1)
746 return reader.Peek ();
752 if (putback_char != -1)
753 throw new Exception ("This should not happen putback on putback");
757 public bool advance ()
759 return current_token != Token.EOF ;
762 public Object Value {
768 public Object value ()
773 private bool IsEOL(int currentChar)
777 if (currentChar == 0x0D) {
778 if (peekChar() == 0x0A) // if it is a CR-LF pair consume LF also
784 retVal = (currentChar == -1 || currentChar == 0x0A || currentChar == 0x2028 || currentChar == 0x2029);
794 private int DropComments()
797 while (!IsEOL(/*d =*/ getChar ()))
803 public bool putbacktoken = false;
804 public bool flag = false;
809 int lastToken = current_token;
812 current_token = xtoken ();
813 if(current_token == Token.END) {
814 next_token = xtoken();
816 if (next_token == Token.EOL)
817 return Token.END_EOL;
821 if (current_token == 0)
823 if (current_token == Token.REM)
824 current_token = DropComments();
825 } while (lastToken == Token.EOL && current_token == Token.EOL);
827 return current_token;
830 private string GetIdentifier()
833 if (is_identifier_start_character ((char) c))
834 return GetIdentifier(c);
839 private string GetIdentifier(int c)
841 StringBuilder id = new StringBuilder ();
843 id.Append ((char) c);
845 while ((c = peekChar ()) != -1)
847 if (is_identifier_part_character ((char) c))
849 id.Append ((char)getChar ());
856 cant_have_a_type_character = false;
858 return id.ToString();
861 private bool is_doublequote(int currentChar)
863 return (currentChar == '"' ||
864 currentChar == 0x201C || // unicode left double-quote character
865 currentChar == 0x201D); // unicode right double-quote character
868 private bool is_whitespace(int c)
870 return (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0);
873 private bool tokens_seen = false;
875 private void nextLine()
877 cant_have_a_type_character = true;
890 if (putbacktoken == true) {
891 putbacktoken = false;
896 for (;(c = getChar ()) != -1; col++) {
898 // Handle line continuation character
902 if (!is_identifier_part_character((char)d)) {
903 while ((c = getChar ()) != -1 && !IsEOL(c)) {}
910 if (is_whitespace(c)) {
911 // expand tabs for location
913 col = (((col + ExpandedTabsSize) / ExpandedTabsSize) * ExpandedTabsSize) - 1;
914 cant_have_a_type_character = true;
918 // Handle line comments.
925 if (current_token == Token.EOL) // if last token was also EOL keep skipping
930 // Handle escaped identifiers
933 if ((val = GetIdentifier()) == null)
935 if ((c = getChar()) != ']')
938 return Token.IDENTIFIER;
941 // Handle unescaped identifiers
942 if (is_identifier_start_character ((char) c))
945 if ((id = GetIdentifier(c)) == null)
949 if (is_keyword(id) && (current_token != Token.DOT))
950 return getKeyword(id);
951 return Token.IDENTIFIER;
954 // Treat string literals
955 if (is_doublequote(c)) {
956 cant_have_a_type_character = true;
957 return ExtractStringOrCharLiteral(c);
960 // handle numeric literals
962 if (Char.IsDigit ((char) c))
964 cant_have_a_type_character = true;
966 return is_number (c);
971 cant_have_a_type_character = true;
973 if (Char.IsDigit ((char) peekChar ()))
974 return is_number (c);
977 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR) {
978 cant_have_a_type_character = true;
991 error_details = ((char)c).ToString ();
995 if (current_token != Token.EOL) // if last token wasn't EOL send it before EOF
1001 private int ExtractDateTimeLiteral()
1005 StringBuilder sb = new StringBuilder();
1006 for (;(c = getChar ()) != -1; col++)
1009 val = ParseDateLiteral(sb);
1010 return Token.LITERAL_DATE;
1022 private int ExtractStringOrCharLiteral(int c)
1024 StringBuilder s = new StringBuilder ();
1028 while ((c = getChar ()) != -1){
1029 if (is_doublequote(c)){
1030 if (is_doublequote(peekChar()))
1033 //handle Char Literals
1034 if (peekChar() == 'C' || peekChar() == 'c') {
1036 if (s.Length == 1) {
1038 return Token.LITERAL_CHARACTER;
1040 val = "Incorrect length for a character literal";
1044 val = s.ToString ();
1045 return Token.LITERAL_STRING;
1054 s.Append ((char) c);
1060 static IFormatProvider enUSculture = new CultureInfo("en-US", true);
1062 private DateTime ParseDateLiteral(StringBuilder value)
1066 return DateTime.Parse(value.ToString(),
1068 DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowWhiteSpaces);
1070 catch (FormatException ex)
1072 //TODO: What is the correct error number and message?
1073 Report.Error (1, Location, string.Format("Invalid date literal '{0}'", value.ToString())
1074 + Environment.NewLine + ex.ToString());
1078 Report.Error (1, Location, "Error parsing date literal"); //TODO: What is the correct error number and message?
1080 return new DateTime();
1083 public void PositionCursorAtNextPreProcessorDirective()
1087 for(t = token(); t != Token.HASH && t != Token.EOF ; t = token());
1090 throw new ApplicationException("Unexpected EOF while looking for a pre-processor directive");
1092 if(t == Token.HASH) {
1093 tokens_seen = false;