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
30 // TODO: public SourceFile file_name;
31 public string file_name;
32 public string ref_name;
33 public int ref_line = 1;
36 public int current_token = Token.EOL;
37 bool handle_get_set = false;
38 bool cant_have_a_type_character = false;
40 public int ExpandedTabsSize = 4;
42 public string location {
46 if (current_token == Token.ERROR)
47 det = "detail: " + error_details;
51 return "Line: "+line+" Col: "+col + "\n" +
52 "VirtLine: "+ref_line +
53 " Token: "+current_token + " " + det;
57 public bool properties {
59 return handle_get_set;
63 handle_get_set = value;
70 static Hashtable keywords;
71 static NumberStyles styles;
72 static NumberFormatInfo csharp_format_info;
80 const int TAKEN_BEFORE = 2;
81 const int ELSE_SEEN = 4;
82 const int PARENT_TAKING = 8;
83 const int REGION = 16;
86 // pre-processor if stack state:
91 // Values for the associated token returned
98 // Details about the error encoutered by the tokenizer
100 string error_details;
102 public string error {
104 return error_details;
120 static void initTokens ()
122 keywords = new Hashtable ();
124 keywords.Add ("addhandler", Token.ADDHANDLER);
125 keywords.Add ("addressof", Token.ADDRESSOF);
126 keywords.Add ("alias", Token.ALIAS);
127 keywords.Add ("and", Token.AND);
128 keywords.Add ("andalso", Token.ANDALSO);
129 keywords.Add ("ansi", Token.ANSI);
130 keywords.Add ("as", Token.AS);
131 keywords.Add ("assembly", Token.ASSEMBLY);
132 keywords.Add ("auto", Token.AUTO);
133 keywords.Add ("binary", Token.BINARY);
134 keywords.Add ("boolean", Token.BOOLEAN);
135 keywords.Add ("byref", Token.BYREF);
136 keywords.Add ("byte", Token.BYTE);
137 keywords.Add ("byval", Token.BYVAL);
138 keywords.Add ("call", Token.CALL);
139 keywords.Add ("case", Token.CASE);
140 keywords.Add ("catch", Token.CATCH);
141 keywords.Add ("cbool", Token.CBOOL);
142 keywords.Add ("cbyte", Token.CBYTE);
143 keywords.Add ("cchar", Token.CCHAR);
144 keywords.Add ("cdate", Token.CDATE);
145 keywords.Add ("cdec", Token.CDEC);
146 keywords.Add ("cdbl", Token.CDBL);
147 keywords.Add ("char", Token.CHAR);
148 keywords.Add ("cint", Token.CINT);
149 keywords.Add ("class", Token.CLASS);
150 keywords.Add ("clng", Token.CLNG);
151 keywords.Add ("cobj", Token.COBJ);
152 keywords.Add ("compare", Token.COMPARE);
153 keywords.Add ("const", Token.CONST);
154 keywords.Add ("cshort", Token.CSHORT);
155 keywords.Add ("csng", Token.CSNG);
156 keywords.Add ("cstr", Token.CSTR);
157 keywords.Add ("ctype", Token.CTYPE);
158 keywords.Add ("date", Token.DATE);
159 keywords.Add ("decimal", Token.DECIMAL);
160 keywords.Add ("declare", Token.DECLARE);
161 keywords.Add ("default", Token.DEFAULT);
162 keywords.Add ("delegate", Token.DELEGATE);
163 keywords.Add ("dim", Token.DIM);
164 keywords.Add ("do", Token.DO);
165 keywords.Add ("double", Token.DOUBLE);
166 keywords.Add ("each", Token.EACH);
167 keywords.Add ("else", Token.ELSE);
168 keywords.Add ("elseif", Token.ELSEIF);
169 keywords.Add ("end", Token.END);
170 keywords.Add ("enum", Token.ENUM);
171 keywords.Add ("erase", Token.ERASE);
172 keywords.Add ("error", Token.ERROR);
173 keywords.Add ("event", Token.EVENT);
174 keywords.Add ("exit", Token.EXIT);
175 keywords.Add ("explicit", Token.EXPLICIT);
176 keywords.Add ("false", Token.FALSE);
177 keywords.Add ("finally", Token.FINALLY);
178 keywords.Add ("for", Token.FOR);
179 keywords.Add ("friend", Token.FRIEND);
180 keywords.Add ("function", Token.FUNCTION);
181 keywords.Add ("get", Token.GET);
182 //keywords.Add ("gettype", Token.GETTYPE);
183 keywords.Add ("goto", Token.GOTO);
184 keywords.Add ("handles", Token.HANDLES);
185 keywords.Add ("if", Token.IF);
186 keywords.Add ("implements", Token.IMPLEMENTS);
187 keywords.Add ("imports", Token.IMPORTS);
188 keywords.Add ("in", Token.IN);
189 keywords.Add ("inherits", Token.INHERITS);
190 keywords.Add ("integer", Token.INTEGER);
191 keywords.Add ("interface", Token.INTERFACE);
192 keywords.Add ("is", Token.IS);
193 keywords.Add ("let ", Token.LET );
194 keywords.Add ("lib ", Token.LIB );
195 keywords.Add ("like ", Token.LIKE );
196 keywords.Add ("long", Token.LONG);
197 keywords.Add ("loop", Token.LOOP);
198 keywords.Add ("me", Token.ME);
199 keywords.Add ("mod", Token.MOD);
200 keywords.Add ("module", Token.MODULE);
201 keywords.Add ("mustinherit", Token.MUSTINHERIT);
202 keywords.Add ("mustoverride", Token.MUSTOVERRIDE);
203 keywords.Add ("mybase", Token.MYBASE);
204 keywords.Add ("myclass", Token.MYCLASS);
205 keywords.Add ("namespace", Token.NAMESPACE);
206 keywords.Add ("new", Token.NEW);
207 keywords.Add ("next", Token.NEXT);
208 keywords.Add ("not", Token.NOT);
209 keywords.Add ("nothing", Token.NOTHING);
210 keywords.Add ("notinheritable", Token.NOTINHERITABLE);
211 keywords.Add ("notoverridable", Token.NOTOVERRIDABLE);
212 keywords.Add ("object", Token.OBJECT);
213 keywords.Add ("off", Token.OFF);
214 keywords.Add ("on", Token.ON);
215 keywords.Add ("option", Token.OPTION);
216 keywords.Add ("optional", Token.OPTIONAL);
217 keywords.Add ("or", Token.OR);
218 keywords.Add ("orelse", Token.ORELSE);
219 keywords.Add ("overloads", Token.OVERLOADS);
220 keywords.Add ("overridable", Token.OVERRIDABLE);
221 keywords.Add ("overrides", Token.OVERRIDES);
222 keywords.Add ("paramarray", Token.PARAM_ARRAY);
223 keywords.Add ("preserve", Token.PRESERVE);
224 keywords.Add ("private", Token.PRIVATE);
225 keywords.Add ("property", Token.PROPERTY);
226 keywords.Add ("protected", Token.PROTECTED);
227 keywords.Add ("public", Token.PUBLIC);
228 keywords.Add ("raiseevent", Token.RAISEEVENT);
229 keywords.Add ("readonly", Token.READONLY);
230 keywords.Add ("redim", Token.REDIM);
231 keywords.Add ("rem", Token.REM);
232 keywords.Add ("removehandler", Token.REMOVEHANDLER);
233 keywords.Add ("resume", Token.RESUME);
234 keywords.Add ("return", Token.RETURN);
235 keywords.Add ("select", Token.SELECT);
236 keywords.Add ("set", Token.SET);
237 keywords.Add ("shadows", Token.SHADOWS);
238 keywords.Add ("shared", Token.SHARED);
239 keywords.Add ("short", Token.SHORT);
240 keywords.Add ("single", Token.SINGLE);
241 keywords.Add ("sizeof", Token.SIZEOF);
242 keywords.Add ("static", Token.STATIC);
243 keywords.Add ("step", Token.STEP);
244 keywords.Add ("stop", Token.STOP);
245 keywords.Add ("strict", Token.STRICT);
246 keywords.Add ("string", Token.STRING);
247 keywords.Add ("structure", Token.STRUCTURE);
248 keywords.Add ("sub", Token.SUB);
249 keywords.Add ("synclock", Token.SYNCLOCK);
250 keywords.Add ("text", Token.TEXT);
251 keywords.Add ("then", Token.THEN);
252 keywords.Add ("throw", Token.THROW);
253 keywords.Add ("to", Token.TO);
254 keywords.Add ("true", Token.TRUE);
255 keywords.Add ("try", Token.TRY);
256 keywords.Add ("typeof", Token.TYPEOF);
257 keywords.Add ("unicode", Token.UNICODE);
258 keywords.Add ("until", Token.UNTIL);
259 keywords.Add ("variant", Token.VARIANT);
260 keywords.Add ("when", Token.WHEN);
261 keywords.Add ("while", Token.WHILE);
262 keywords.Add ("with", Token.WITH);
263 keywords.Add ("withevents", Token.WITHEVENTS);
264 keywords.Add ("writeonly", Token.WRITEONLY);
265 keywords.Add ("xor", Token.XOR);
267 if (Parser.UseExtendedSyntax){
268 keywords.Add ("yield", Token.YIELD);
279 csharp_format_info = new NumberFormatInfo ();
280 csharp_format_info.CurrencyDecimalSeparator = ".";
281 styles = NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint;
284 bool is_keyword (string name)
288 res = keywords.Contains(name.ToLower());
289 if ((name == "get" || name == "set") && handle_get_set == false)
294 int getKeyword (string name)
296 return (int) (keywords [name.ToLower()]);
299 public Location Location {
301 return new Location (ref_line, col);
305 void define (string def)
307 if (!RootContext.AllDefines.Contains(def)){
308 RootContext.AllDefines [def] = true;
310 if (defines.Contains (def))
312 defines [def] = true;
315 public bool PropertyParsing {
317 return handle_get_set;
321 handle_get_set = value;
325 bool is_identifier_start_character (char c)
327 return Char.IsLetter (c) || c == '_' ;
330 bool is_identifier_part_character (char c)
332 return (Char.IsLetter (c) || Char.IsDigit (c) || c == '_');
335 int is_punct (char c, ref bool doread)
342 error_details = c.ToString();
348 return Token.OPEN_BRACKET;
350 return Token.CLOSE_BRACKET;
352 return Token.OPEN_BRACE;
354 return Token.CLOSE_BRACE;
356 return Token.OPEN_PARENS;
358 return Token.CLOSE_PARENS;
364 if (is_identifier_start_character((char)d) || cant_have_a_type_character)
365 return Token.EXCLAMATION;
366 return Token.SINGLETYPECHAR;
368 if (cant_have_a_type_character)
370 return Token.DOLAR_SIGN;
372 if (cant_have_a_type_character)
374 return Token.AT_SIGN;
376 if (cant_have_a_type_character)
378 return Token.PERCENT;
382 workout_preprocessing_directive();
385 if (cant_have_a_type_character)
386 return ExtractDateTimeLiteral();
387 return Token.NUMBER_SIGN;
389 if (!cant_have_a_type_character)
390 return Token.LONGTYPECHAR;
391 t = handle_integer_literal_in_other_bases(d);
392 if (t == Token.NONE) {
395 t = Token.OP_CONCAT_ASSIGN;
406 t = Token.OP_ADD_ASSIGN;
414 t = Token.OP_SUB_ASSIGN;
428 return Token.OP_MULT_ASSIGN;
436 return Token.OP_DIV_ASSIGN;
444 return Token.OP_IDIV_ASSIGN;
446 return Token.OP_IDIV;
452 return Token.OP_EXP_ASSIGN;
470 return Token.OP_SHIFT_LEFT;
483 return Token.OP_SHIFT_RIGHT;
491 return Token.ATTR_ASSIGN;
499 bool decimal_digits (int c)
502 bool seen_digits = false;
505 number.Append ((char) c);
507 while ((d = peekChar ()) != -1){
508 if (Char.IsDigit ((char)d)){
509 number.Append ((char) d);
519 int real_type_suffix (int c)
525 t = Token.LITERAL_SINGLE;
528 t = Token.LITERAL_DOUBLE;
531 t= Token.LITERAL_DECIMAL;
540 int integer_type_suffix (int c)
548 t = Token.LITERAL_INTEGER; // SHORT ?
549 val = ((IConvertible)val).ToInt16(null);
552 t = Token.LITERAL_INTEGER;
553 val = ((IConvertible)val).ToInt32(null);
556 t= Token.LITERAL_INTEGER; // LONG ?
557 val = ((IConvertible)val).ToInt64(null);
560 if ((long)val <= System.Int32.MaxValue &&
561 (long)val >= System.Int32.MinValue) {
562 val = ((IConvertible)val).ToInt32(null);
563 return Token.LITERAL_INTEGER;
565 val = ((IConvertible)val).ToInt64(null);
566 return Token.LITERAL_INTEGER; // LONG ?
571 } catch (Exception e) {
577 int adjust_real (int t)
579 string s = number.ToString ();
582 case Token.LITERAL_DECIMAL:
583 val = new System.Decimal ();
584 val = System.Decimal.Parse (
585 s, styles, csharp_format_info);
587 case Token.LITERAL_DOUBLE:
588 val = new System.Double ();
589 val = System.Double.Parse (
590 s, styles, csharp_format_info);
592 case Token.LITERAL_SINGLE:
593 val = new System.Double ();
594 val = (float) System.Double.Parse (
595 s, styles, csharp_format_info);
599 val = new System.Double ();
600 val = System.Double.Parse (
601 s, styles, csharp_format_info);
602 t = Token.LITERAL_DOUBLE;
610 StringBuilder hexNumber = new StringBuilder ();
614 while ((d = peekChar ()) != -1){
615 char e = Char.ToUpper ((char) d);
617 if (Char.IsDigit (e) || (e >= 'A' && e <= 'F')){
618 hexNumber.Append (e);
623 return System.Int64.Parse (hexNumber.ToString(), NumberStyles.HexNumber);
628 long valueToReturn = 0;
632 while ((d = peekChar ()) != -1){
634 if (Char.IsDigit (e) && (e < '8')){
636 valueToReturn += (d - (int)'0');
642 return valueToReturn;
645 int handle_integer_literal_in_other_bases(int peek)
647 if (peek == 'h' || peek == 'H'){
650 return integer_type_suffix (peekChar ());
653 if (peek == 'o' || peek == 'O'){
655 val = octal_digits ();
656 return integer_type_suffix (peekChar ());
663 // Invoked if we know we have .digits or digits
665 int is_number (int c)
667 bool is_real = false;
668 number = new StringBuilder ();
673 if (Char.IsDigit ((char)c)){
679 // We need to handle the case of
680 // "1.1" vs "1.ToString()" (LITERAL_SINGLE vs NUMBER DOT IDENTIFIER)
683 if (decimal_digits (getChar())){
689 val = System.Int64.Parse(number.ToString());
690 return integer_type_suffix('.');
694 if (c == 'e' || c == 'E'){
701 number.Append ((char) c);
704 } else if (c == '-'){
705 number.Append ((char) c);
713 type = real_type_suffix (c);
714 if (type == Token.NONE && !is_real){
715 val = System.Int64.Parse(number.ToString());
716 return integer_type_suffix(c);
719 return adjust_real (type);
724 if (putback_char != -1){
725 int x = putback_char;
730 return reader.Read ();
735 if (putback_char != -1)
737 return reader.Peek ();
742 if (putback_char != -1)
743 throw new Exception ("This should not happen putback on putback");
747 public bool advance ()
749 return current_token != Token.EOF ;
752 public Object Value {
758 public Object value ()
763 private bool IsEOL(int currentChar)
765 if (currentChar == 0x0D)
767 if (peekChar() == 0x0A) // if it is a CR-LF pair consume LF also
772 return (currentChar == -1 || currentChar == 0x0A || currentChar == 0x2028 || currentChar == 0x2029);
775 private int DropComments()
778 while (!IsEOL(d = getChar ()))
789 int lastToken = current_token;
792 current_token = xtoken ();
793 if (current_token == 0)
795 if (current_token == Token.REM)
796 current_token = DropComments();
797 } while (lastToken == Token.EOL && current_token == Token.EOL);
799 return current_token;
802 private string GetIdentifier()
805 if (is_identifier_start_character ((char) c))
806 return GetIdentifier(c);
811 private string GetIdentifier(int c)
813 StringBuilder id = new StringBuilder ();
815 id.Append ((char) c);
817 while ((c = peekChar ()) != -1)
819 if (is_identifier_part_character ((char) c))
821 id.Append ((char)getChar ());
828 cant_have_a_type_character = false;
830 return id.ToString ();
833 private bool is_doublequote(int currentChar)
835 return (currentChar == '"' ||
836 currentChar == 0x201C || // unicode left double-quote character
837 currentChar == 0x201D); // unicode right double-quote character
840 private bool is_whitespace(int c)
842 return (c == ' ' || c == '\t' || c == '\v' || c == '\r' || c == 0xa0);
845 private bool tokens_seen = false;
854 for (;(c = getChar ()) != -1; col++) {
856 // Handle line continuation character
860 if (!is_identifier_part_character((char)d)) {
861 while ((c = getChar ()) != -1 && !IsEOL(c)) {}
867 if (is_whitespace(c)) {
868 // expand tabs for location
870 col = (((col + ExpandedTabsSize) / ExpandedTabsSize) * ExpandedTabsSize) - 1;
871 cant_have_a_type_character = true;
875 // Handle line comments.
882 cant_have_a_type_character = true;
887 if (current_token == Token.EOL) // if last token was also EOL keep skipping
892 // Handle escaped identifiers
895 if ((val = GetIdentifier()) == null)
897 if ((c = getChar()) != ']')
900 return Token.IDENTIFIER;
903 // Handle unescaped identifiers
904 if (is_identifier_start_character ((char) c))
907 if ((id = GetIdentifier(c)) == null)
911 if (is_keyword(id) && (current_token != Token.DOT))
912 return getKeyword(id);
913 return Token.IDENTIFIER;
916 // Treat string literals
917 if (is_doublequote(c)) {
918 cant_have_a_type_character = true;
919 return ExtractStringOrCharLiteral(c);
922 // handle numeric literals
925 cant_have_a_type_character = true;
927 if (Char.IsDigit ((char) peekChar ()))
928 return is_number (c);
932 if (Char.IsDigit ((char) c))
934 cant_have_a_type_character = true;
936 return is_number (c);
939 if ((t = is_punct ((char)c, ref doread)) != Token.ERROR) {
940 cant_have_a_type_character = true;
953 error_details = ((char)c).ToString ();
957 if (current_token != Token.EOL) // if last token wasn't EOL send it before EOF
963 private int ExtractDateTimeLiteral()
967 StringBuilder sb = new StringBuilder();
968 for (;(c = getChar ()) != -1; col++)
971 val = ParseDateLiteral(sb);
972 return Token.LITERAL_DATE;
985 private int ExtractStringOrCharLiteral(int c)
987 StringBuilder s = new StringBuilder ();
991 while ((c = getChar ()) != -1){
992 if (is_doublequote(c)){
993 if (is_doublequote(peekChar()))
996 //handle Char Literals
997 if (peekChar() == 'C' || peekChar() == 'c') {
1001 return Token.LITERAL_CHARACTER;
1003 val = "Incorrect length for a character literal";
1007 val = s.ToString ();
1008 return Token.LITERAL_STRING;
1016 s.Append ((char) c);
1022 private void workout_preprocessing_directive()
1029 cont = handle_preprocessing_directive (cont);
1037 bool skipping = false;
1038 for (;(c = getChar ()) != -1; col++) {
1039 if (is_whitespace(c))
1052 if (c == '#' && !skipping)
1055 tokens_seen = false;
1057 Report.Error (1027, Location, "#endif/#endregion expected");
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)
1072 Report.Error (1, Location, "Invalid date literal"); //TODO: What is the correct error number and message?
1076 Report.Error (1, Location, "Error parsing date literal"); //TODO: What is the correct error number and message?
1078 return new DateTime();
1082 public void cleanup ()
1084 /* borrowed from mcs - have to work it to have preprocessing in mbas
1086 if (ifstack != null && ifstack.Count >= 1) {
1087 int state = (int) ifstack.Pop ();
1088 if ((state & REGION) != 0)
1089 Report.Error (1038, "#endregion directive expected");
1091 Report.Error (1027, "#endif directive expected");
1096 public Tokenizer (System.IO.TextReader input, string fname, ArrayList defines)
1098 this.ref_name = fname;
1102 Location.Push (fname);
1105 static StringBuilder static_cmd_arg = new StringBuilder ();
1107 void get_cmd_arg (out string cmd, out string arg)
1111 tokens_seen = false;
1113 static_cmd_arg.Length = 0;
1115 while ((c = getChar ()) != -1 && (c != '\n') && (c != ' ') && (c != '\t') && (c != '\r')){
1116 static_cmd_arg.Append ((char) c);
1119 cmd = static_cmd_arg.ToString().ToLower();
1125 } else if (c == '\r')
1128 // skip over white space
1129 while ((c = getChar ()) != -1 && (c != '\n') && ((c == '\r') || (c == ' ') || (c == '\t')))
1136 } else if (c == '\r'){
1141 static_cmd_arg.Length = 0;
1142 static_cmd_arg.Append ((char) c);
1144 while ((c = getChar ()) != -1 && (c != '\n') && (c != '\r')){
1145 static_cmd_arg.Append ((char) c);
1151 } else if (c == '\r')
1153 arg = static_cmd_arg.ToString ().Trim ();
1155 if (cmd == "end" && arg.ToLower() == "region") {
1159 if (cmd == "end" && arg.ToLower() == "if") {
1167 // Handles the #line directive
1169 bool PreProcessLine (string arg)
1174 if (arg == "default"){
1176 ref_name = file_name;
1177 Location.Push (ref_name);
1184 if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
1185 ref_line = System.Int32.Parse (arg.Substring (0, pos));
1188 char [] quotes = { '\"' };
1190 string name = arg.Substring (pos). Trim (quotes);
1191 ref_name = name; // TODO: Synchronize with mcs: Location.LookupFile (name);
1192 Location.Push (ref_name);
1194 ref_line = System.Int32.Parse (arg);
1204 // Handles #define and #undef
1206 void PreProcessDefinition (bool is_define, string arg)
1208 if (arg == "" || arg == "true" || arg == "false"){
1209 Report.Error (1001, Location, "Missing identifer to pre-processor directive");
1213 char[] whitespace = { ' ', '\t' };
1214 if (arg.IndexOfAny (whitespace) != -1){
1215 Report.Error (1025, Location, "Single-line comment or end-of-line expected");
1219 foreach (char c in arg){
1220 if (!Char.IsLetter (c) && (c != '_')){
1221 Report.Error (1001, Location, "Identifier expected");
1227 if (defines == null)
1228 defines = new Hashtable ();
1231 if (defines == null)
1233 if (defines.Contains (arg))
1234 defines.Remove (arg);
1238 bool eval_val (string s)
1245 if (defines == null)
1247 if (defines.Contains (s))
1253 bool pp_primary (ref string s)
1262 s = s.Substring (1);
1263 bool val = pp_expr (ref s);
1264 if (s.Length > 0 && s [0] == ')'){
1265 s = s.Substring (1);
1268 Error_InvalidDirective ();
1272 if (is_identifier_start_character (c)){
1278 if (is_identifier_part_character (c)){
1282 bool v = eval_val (s.Substring (0, j));
1283 s = s.Substring (j);
1286 bool vv = eval_val (s);
1291 Error_InvalidDirective ();
1295 bool pp_unary (ref string s)
1302 if (len > 1 && s [1] == '='){
1303 Error_InvalidDirective ();
1306 s = s.Substring (1);
1307 return ! pp_primary (ref s);
1309 return pp_primary (ref s);
1311 Error_InvalidDirective ();
1316 bool pp_eq (ref string s)
1318 bool va = pp_unary (ref s);
1324 if (len > 2 && s [1] == '='){
1325 s = s.Substring (2);
1326 return va == pp_unary (ref s);
1328 Error_InvalidDirective ();
1331 } else if (s [0] == '!' && len > 1 && s [1] == '='){
1332 s = s.Substring (2);
1334 return va != pp_unary (ref s);
1343 bool pp_and (ref string s)
1345 bool va = pp_eq (ref s);
1351 if (len > 2 && s [1] == '&'){
1352 s = s.Substring (2);
1353 return (va & pp_eq (ref s));
1355 Error_InvalidDirective ();
1364 // Evaluates an expression for `#if' or `#elif'
1366 bool pp_expr (ref string s)
1368 bool va = pp_and (ref s);
1375 if (len > 2 && s [1] == '|'){
1376 s = s.Substring (2);
1377 return va | pp_expr (ref s);
1379 Error_InvalidDirective ();
1388 bool eval (string s)
1390 bool v = pp_expr (ref s);
1393 Error_InvalidDirective ();
1400 void Error_InvalidDirective ()
1402 Report.Error (1517, Location, "Invalid pre-processor directive");
1405 void Error_UnexpectedDirective (string extra)
1409 "Unexpected processor directive (" + extra + ")");
1412 void Error_TokensSeen ()
1416 "Cannot define or undefine pre-processor symbols after a token in the file");
1420 // if true, then the code continues processing the code
1421 // if false, the code stays in a loop until another directive is
1424 bool handle_preprocessing_directive (bool caller_is_taking)
1426 char [] blank = { ' ', '\t' };
1428 bool region_directive = false;
1430 get_cmd_arg (out cmd, out arg);
1431 // Eat any trailing whitespaces and single-line comments
1432 if (arg.IndexOf ("//") != -1)
1433 arg = arg.Substring (0, arg.IndexOf ("//"));
1434 arg = arg.TrimEnd (' ', '\t');
1437 // The first group of pre-processing instructions is always processed
1439 switch (cmd.ToLower()){
1441 if (!PreProcessLine (arg))
1444 "Argument to #line directive is missing or invalid");
1448 region_directive = true;
1453 region_directive = true;
1458 Error_InvalidDirective ();
1461 bool taking = false;
1462 if (ifstack == null)
1463 ifstack = new Stack ();
1465 if (ifstack.Count == 0){
1468 int state = (int) ifstack.Peek ();
1469 if ((state & TAKING) != 0)
1473 if (eval (arg) && taking){
1474 int push = TAKING | TAKEN_BEFORE | PARENT_TAKING;
1475 if (region_directive)
1477 ifstack.Push (push);
1480 int push = (taking ? PARENT_TAKING : 0);
1481 if (region_directive)
1483 ifstack.Push (push);
1488 if (ifstack == null || ifstack.Count == 0){
1489 Error_UnexpectedDirective ("no #if for this #end if");
1492 int pop = (int) ifstack.Pop ();
1494 if (region_directive && ((pop & REGION) == 0))
1495 Report.Error (1027, Location, "#end if directive expected");
1496 else if (!region_directive && ((pop & REGION) != 0))
1497 Report.Error (1038, Location, "#end region directive expected");
1499 if (ifstack.Count == 0)
1502 int state = (int) ifstack.Peek ();
1504 if ((state & TAKING) != 0)
1512 if (ifstack == null || ifstack.Count == 0){
1513 Error_UnexpectedDirective ("no #if for this #elif");
1516 int state = (int) ifstack.Peek ();
1518 if ((state & REGION) != 0) {
1519 Report.Error (1038, Location, "#end region directive expected");
1523 if ((state & ELSE_SEEN) != 0){
1524 Error_UnexpectedDirective ("#elif not valid after #else");
1528 if ((state & (TAKEN_BEFORE | TAKING)) != 0)
1531 if (eval (arg) && ((state & PARENT_TAKING) != 0)){
1532 state = (int) ifstack.Pop ();
1533 ifstack.Push (state | TAKING | TAKEN_BEFORE);
1540 if (ifstack == null || ifstack.Count == 0){
1543 "Unexpected processor directive (no #if for this #else)");
1546 int state = (int) ifstack.Peek ();
1548 if ((state & REGION) != 0) {
1549 Report.Error (1038, Location, "#end region directive expected");
1553 if ((state & ELSE_SEEN) != 0){
1554 Error_UnexpectedDirective ("#else within #else");
1561 if ((state & TAKEN_BEFORE) == 0){
1562 ret = ((state & PARENT_TAKING) != 0);
1571 ifstack.Push (state | ELSE_SEEN);
1578 // These are only processed if we are in a `taking' block
1580 if (!caller_is_taking)
1583 switch (cmd.ToLower()){
1585 /* if (any_token_seen){
1586 Error_TokensSeen ();
1589 PreProcessDefinition (true, arg);
1593 /* if (any_token_seen){
1594 Error_TokensSeen ();
1597 PreProcessDefinition (false, arg);
1601 Report.Error (1029, Location, "#error: '" + arg + "'");
1605 Report.Warning (1030, Location, "#warning: '" + arg + "'");
1609 Report.Error (1024, Location, "Preprocessor directive expected (got: " + cmd + ")");