Fixed subtle bug in expr().
[rmac] / expr.c
1 //
2 // RMAC - Reboot's Macro Assembler for the Atari Jaguar Console System
3 // EXPR.C - Expression Analyzer
4 // Copyright (C) 199x Landon Dyer, 2011 Reboot and Friends
5 // RMAC derived from MADMAC v1.07 Written by Landon Dyer, 1986
6 // Source Utilised with the Kind Permission of Landon Dyer
7 //
8
9 #include "expr.h"
10 #include "direct.h"
11 #include "error.h"
12 #include "listing.h"
13 #include "mach.h"
14 #include "procln.h"
15 #include "riscasm.h"
16 #include "sect.h"
17 #include "symbol.h"
18 #include "token.h"
19
20 #define DEF_KW                                                  // Declare keyword values 
21 #include "kwtab.h"                                              // Incl generated keyword tables & defs
22
23 static char tokenClass[128];                                    // Generated table of token classes
24 static VALUE evstk[EVSTACKSIZE];                // Evaluator value stack
25 static WORD evattr[EVSTACKSIZE];                // Evaluator attribute stack
26
27 // Token-class initialization list
28 char itokcl[] = {
29         0,                                                                      // END
30         CONST, SYMBOL, 0,                                       // ID 
31         '(', '[', '{', 0,                                       // OPAR
32         ')', ']', '}', 0,                                       // CPAR 
33         CR_DEFINED, CR_REFERENCED,                      // SUNARY (special unary)
34         CR_STREQ, CR_MACDEF,
35         CR_DATE, CR_TIME, 0,
36         '!', '~', UNMINUS, 0,                           // UNARY
37         '*', '/', '%', 0,                                       // MULT 
38         '+', '-', 0,                                            // ADD 
39         SHL, SHR, 0,                                            // SHIFT 
40         LE, GE, '<', '>', NE, '=', 0,           // REL 
41         '&', 0,                                                         // AND 
42         '^', 0,                                                         // XOR 
43         '|', 0,                                                         // OR 
44         1                                                                       // (the end) 
45 };
46
47 const char missym_error[] = "missing symbol";
48 const char str_error[] = "missing symbol or string";
49
50 // Convert expression to postfix
51 static TOKEN * evalTokenBuffer;                 // Deposit tokens here (this is really a
52                                                                                 // pointer to exprbuf from direct.c)
53                                                                                 // (Can also be from others, like riscasm.c)
54 static symbolNum;                                               // Pointer to the entry in symbolPtr[]
55
56
57 //
58 // Obtain a String Value
59 //
60 static VALUE str_value(char * p)
61 {
62         VALUE v;
63
64         for(v=0; *p; p++)
65                 v = (v << 8) | (*p & 0xFF);
66
67         return v;
68 }
69
70
71 //
72 // Initialize Expression Analyzer
73 //
74 void InitExpression(void)
75 {
76         int i;                                                                  // Iterator
77         char * p;                                                               // Token pointer
78
79         // Initialize token-class table (all set to END)
80         for(i=0; i<128; i++)
81                 tokenClass[i] = END;
82
83         for(i=0, p=itokcl; *p!=1; p++)
84         {
85                 if (*p == 0)
86                         i++;
87                 else 
88                         tokenClass[(int)(*p)] = (char)i;
89         }
90
91         symbolNum = 0;
92 }
93
94
95 //
96 // Binary operators (all the same precedence)
97 //
98 int expr0(void)
99 {
100         TOKEN t;
101
102         if (expr1() != OK)
103                 return ERROR;
104         
105         while (tokenClass[*tok] >= MULT)
106         {
107                 t = *tok++;
108
109                 if (expr1() != OK)
110                         return ERROR;
111
112                 *evalTokenBuffer++ = t;
113         }
114
115         return OK;
116 }
117
118
119 //
120 // Unary operators (detect unary '-')
121 //
122 int expr1(void)
123 {
124         int class;
125         TOKEN t;
126         SYM * sy;
127         char * p, * p2;
128         WORD w;
129         int j;
130
131         class = tokenClass[*tok];
132
133         if (*tok == '-' || class == UNARY)
134         {
135                 t = *tok++;
136
137                 if (expr2() != OK)
138                         return ERROR;
139
140                 if (t == '-')
141                         t = UNMINUS;
142
143                 *evalTokenBuffer++ = t;
144         }
145         else if (class == SUNARY)
146         {
147                 switch ((int)*tok++)
148                 {
149                 case CR_TIME:
150                         *evalTokenBuffer++ = CONST;
151                         *evalTokenBuffer++ = dos_time();
152                         break;
153                 case CR_DATE:
154                         *evalTokenBuffer++ = CONST;
155                         *evalTokenBuffer++ = dos_date();
156                         break;
157                 case CR_MACDEF:                                    // ^^macdef <macro-name>
158                         if (*tok++ != SYMBOL)
159                                 return error(missym_error);
160
161                         p = string[*tok++];
162                         w = (lookup(p, MACRO, 0) == NULL ? 0 : 1);
163                         *evalTokenBuffer++ = CONST;
164                         *evalTokenBuffer++ = (TOKEN)w;
165                         break;
166                 case CR_DEFINED:
167                         w = DEFINED;
168                         goto getsym;
169                 case CR_REFERENCED:
170                         w = REFERENCED;
171 getsym:
172                         if (*tok++ != SYMBOL)
173                                 return error(missym_error);
174
175                         p = string[*tok++];
176                         j = (*p == '.' ? curenv : 0);
177                         w = ((sy = lookup(p, LABEL, j)) != NULL && (sy->sattr & w) ? 1 : 0);
178                         *evalTokenBuffer++ = CONST;
179                         *evalTokenBuffer++ = (TOKEN)w;
180                         break;
181                 case CR_STREQ:
182                         if (*tok != SYMBOL && *tok != STRING)
183                                 return error(str_error);
184
185                         p = string[tok[1]];
186                         tok +=2;
187
188                         if (*tok++ != ',')
189                                 return error(comma_error);
190
191                         if (*tok != SYMBOL && *tok != STRING)
192                                 return error(str_error);
193
194                         p = string[tok[1]];
195                         tok += 2;
196
197                         w = (WORD)(!strcmp(p, p2));
198                         *evalTokenBuffer++ = CONST;
199                         *evalTokenBuffer++ = (TOKEN)w;
200                         break;
201                 }
202         }
203         else 
204                 return expr2();
205
206         return OK;
207 }
208
209
210 //
211 // Terminals (CONSTs) and parenthesis grouping
212 //
213 int expr2(void)
214 {
215         char * p;
216         SYM * sy;
217         int j;
218
219         switch ((int)*tok++)
220         {
221         case CONST:
222                 *evalTokenBuffer++ = CONST;
223                 *evalTokenBuffer++ = *tok++;
224                 break;
225         case SYMBOL:
226                 p = string[*tok++];
227                 j = (*p == '.' ? curenv : 0);
228                 sy = lookup(p, LABEL, j);
229
230                 if (sy == NULL)
231                         sy = NewSymbol(p, LABEL, j);
232
233                 // Check register bank usage
234                 if (sy->sattre & EQUATEDREG)
235                 {
236                         if ((regbank == BANK_0) && (sy->sattre & BANK_1) && !altbankok)   
237                                 warns("equated symbol \'%s\' cannot be used in register bank 0", sy->sname);
238
239                         if ((regbank == BANK_1) && (sy->sattre & BANK_0) && !altbankok)
240                                 warns("equated symbol \'%s\' cannot be used in register bank 1", sy->sname);
241                 }
242
243                 *evalTokenBuffer++ = SYMBOL;
244                 *evalTokenBuffer++ = symbolNum;
245                 symbolPtr[symbolNum] = sy;
246                 symbolNum++;
247                 break;
248         case STRING:
249                 *evalTokenBuffer++ = CONST;
250                 *evalTokenBuffer++ = str_value(string[*tok++]);
251                 break;
252         case '(':
253                 if (expr0() != OK)
254                         return ERROR;
255
256                 if (*tok++ != ')')
257                         return error("missing close parenthesis ')'");
258
259                 break;
260         case '[':
261                 if (expr0() != OK)
262                         return ERROR;
263
264                 if (*tok++ != ']')
265                         return error("missing close parenthesis ']'");
266
267                 break;
268         case '$':
269                 *evalTokenBuffer++ = ACONST;                            // Attributed const
270                 *evalTokenBuffer++ = sloc;                                      // Current location
271                 *evalTokenBuffer++ = cursect | DEFINED;         // Store attribs
272                 break;
273         case '*':
274                 *evalTokenBuffer++ = ACONST;                            // Attributed const
275
276 #if 0
277                 if (orgactive)
278                         *evalTokenBuffer++ = orgaddr;
279                 else
280                         *evalTokenBuffer++ = pcloc;                             // Location at start of line
281 #else
282                 // pcloc == location at start of line
283                 *evalTokenBuffer++ = (orgactive ? orgaddr : pcloc);
284 #endif
285
286                 *evalTokenBuffer++ = ABS | DEFINED;                     // Store attribs
287                 break;
288         default:
289                 return error("bad expression");
290         }
291
292         return OK;
293 }
294
295
296 //
297 // Recursive-descent expression analyzer (with some simple speed hacks)
298 //
299 int expr(TOKEN * otk, VALUE * a_value, WORD * a_attr, SYM ** a_esym)
300 {
301         // Passed in values (once derefenced, that is) can all be zero. They are
302         // there so that the expression analyzer can fill them in as needed. The
303         // expression analyzer gets its input from the global token pointer "tok",
304         // and not from anything passed in by the user.
305         SYM * symbol;
306         char * p;
307         int j;
308
309         evalTokenBuffer = otk;  // Set token pointer to 'exprbuf' (direct.c)
310                                                         // Also set in various other places too (riscasm.c, e.g.)
311
312 //printf("expr(): tokens 0-2: %i %i %i (%c %c %c); tc[2] = %i\n", tok[0], tok[1], tok[2], tok[0], tok[1], tok[2], tokenClass[tok[2]]);
313         // Optimize for single constant or single symbol.
314         // Shamus: Subtle bug here. EOL token is 101; if you have a constant token
315         //         followed by the value 101, it will trigger a bad evaluation here.
316         //         This is probably a really bad assumption to be making here...!
317         //         (assuming tok[1] == EOL is a single token that is)
318 //      if ((tok[1] == EOL)
319         if ((tok[1] == EOL && tok[0] != CONST)
320                 || (((*tok == CONST || *tok == SYMBOL) || (*tok >= KW_R0 && *tok <= KW_R31))
321                 && (tokenClass[tok[2]] < UNARY)))
322         {
323                 if (*tok >= KW_R0 && *tok <= KW_R31)
324                 {
325                         *evalTokenBuffer++ = CONST;
326                         *evalTokenBuffer++ = *a_value = (*tok - KW_R0);
327                         *a_attr = ABS | DEFINED;
328
329                         if (a_esym != NULL)
330                                 *a_esym = NULL;
331
332                         tok++;
333                 }
334                 else if (*tok == CONST)
335                 {
336                         *evalTokenBuffer++ = CONST;
337                         *evalTokenBuffer++ = *a_value = tok[1];
338                         *a_attr = ABS | DEFINED;
339
340                         if (a_esym != NULL)
341                                 *a_esym = NULL;
342
343                         tok += 2;
344 //printf("Quick eval in expr(): CONST = %i, tokenClass[tok[2]] = %i\n", *a_value, tokenClass[*tok]);
345                 }
346                 else if (*tok == '*')
347                 {
348                         *evalTokenBuffer++ = CONST;
349
350                         if (orgactive)
351                                 *evalTokenBuffer++ = *a_value = orgaddr;
352                         else
353                                 *evalTokenBuffer++ = *a_value = pcloc;
354
355                         *a_attr = ABS | DEFINED;
356
357                         if (a_esym != NULL)
358                                 *a_esym = NULL;
359
360                         tok++;
361                 }
362                 else if (*tok == STRING || *tok == SYMBOL)
363                 {
364                         p = string[tok[1]];
365                         j = (*p == '.' ? curenv : 0);
366                         symbol = lookup(p, LABEL, j);
367
368                         if (symbol == NULL)
369                                 symbol = NewSymbol(p, LABEL, j);
370
371                         symbol->sattr |= REFERENCED;
372
373                         // Check for undefined register equates
374                         if (symbol->sattre & UNDEF_EQUR)
375                         {
376                                 errors("undefined register equate '%s'", symbol->sname);
377 //if we return right away, it returns some spurious errors...
378 //                              return ERROR;
379                         }
380
381                         // Check register bank usage
382                         if (symbol->sattre & EQUATEDREG)
383                         {
384                                 if ((regbank == BANK_0) && (symbol->sattre & BANK_1) && !altbankok)   
385                                         warns("equated symbol '%s' cannot be used in register bank 0", symbol->sname);
386
387                                 if ((regbank == BANK_1) && (symbol->sattre & BANK_0) && !altbankok)
388                                         warns("equated symbol '%s' cannot be used in register bank 1", symbol->sname);
389                         }
390
391                         *evalTokenBuffer++ = SYMBOL;
392 #if 0
393                         *evalTokenBuffer++ = (TOKEN)symbol;
394 #else
395 /*
396 While this approach works, it's wasteful. It would be better to use something
397 that's already available, like the symbol "order defined" table (which needs to
398 be converted from a linked list into an array).
399 */
400                         *evalTokenBuffer++ = symbolNum;
401                         symbolPtr[symbolNum] = symbol;
402                         symbolNum++;
403 #endif
404
405                         if (symbol->sattr & DEFINED)
406                                 *a_value = symbol->svalue;
407                         else
408                                 *a_value = 0;
409
410 /*
411 All that extra crap that was put into the svalue when doing the equr stuff is
412 thrown away right here. What the hell is it for?
413 */
414                         if (symbol->sattre & EQUATEDREG) 
415                                 *a_value &= 0x1F;
416
417                         *a_attr = (WORD)(symbol->sattr & ~GLOBAL);
418
419                         if ((symbol->sattr & (GLOBAL | DEFINED)) == GLOBAL && a_esym != NULL)
420                                 *a_esym = symbol;
421
422                         tok += 2;
423                 }
424                 else
425                 {
426                         // Unknown type here... Alert the user!
427                         error("undefined RISC register in expression");
428                         // Prevent spurious error reporting...
429                         tok++;
430                         return ERROR;
431                 }
432
433                 *evalTokenBuffer++ = ENDEXPR;
434                 return OK;
435         }
436
437         if (expr0() != OK)
438                 return ERROR;
439
440         *evalTokenBuffer++ = ENDEXPR;
441         return evexpr(otk, a_value, a_attr, a_esym);
442 }
443
444
445 //
446 // Evaluate expression.
447 // If the expression involves only ONE external symbol, the expression is
448 // UNDEFINED, but it's value includes everything but the symbol value, and
449 // `a_esym' is set to the external symbol.
450 //
451 int evexpr(TOKEN * tk, VALUE * a_value, WORD * a_attr, SYM ** a_esym)
452 {
453         WORD * sattr;
454         VALUE * sval;
455         WORD attr;
456         SYM * sy;
457         SYM * esym;
458         WORD sym_seg;
459
460         sval = evstk;                                                   // (Empty) initial stack
461         sattr = evattr;
462         esym = NULL;                                                    // No external symbol involved
463         sym_seg = 0;
464
465         while (*tk != ENDEXPR)
466         {
467                 switch ((int)*tk++)
468                 {
469                 case SYMBOL:
470 //printf("evexpr(): SYMBOL\n");
471                         sy = symbolPtr[*tk++];
472                         sy->sattr |= REFERENCED;                // Set "referenced" bit 
473
474                         if (!(sy->sattr & DEFINED))
475                         {
476                                 // Reference to undefined symbol
477                                 if (!(sy->sattr & GLOBAL))
478                                 {
479                                         *a_attr = 0;
480                                         *a_value = 0;
481                                         return OK;
482                                 }
483
484                                 if (esym != NULL)                       // Check for multiple externals
485                                         return error(seg_error);
486
487                                 esym = sy;
488                         }
489
490                         if (sy->sattr & DEFINED)
491                         {
492                                 *++sval = sy->svalue;           // Push symbol's value
493                         }
494                         else
495                         {
496                                 *++sval = 0;                            // 0 for undefined symbols 
497                         }
498
499                         *++sattr = (WORD)(sy->sattr & ~GLOBAL); // Push attribs
500                         sym_seg = (WORD)(sy->sattr & (TEXT | DATA | BSS));
501                         break;
502                 case CONST:
503 //printf("evexpr(): CONST = %i\n", *tk);
504                         *++sval = *tk++;                                // Push value
505                         *++sattr = ABS | DEFINED;               // Push simple attribs
506                         break;
507                 case ACONST:
508 //printf("evexpr(): ACONST = %i\n", *tk);
509                         *++sval = *tk++;                                // Push value
510                         *++sattr = (WORD)*tk++;                 // Push attribs
511                         break;
512
513                         // Binary "+" and "-" matrix:
514                         // 
515                         //                ABS    Sect     Other
516                         //     ----------------------------
517                         //   ABS     |  ABS   |  Sect  |  Other |
518                         //   Sect    |  Sect  |  [1]   |  Error |
519                         //   Other   |  Other |  Error |  [1]   |
520                         //      ----------------------------
521                         // 
522                         //   [1] + : Error
523                         //       - : ABS
524                 case '+':
525 //printf("evexpr(): +\n");
526                         --sval;                                                 // Pop value
527                         --sattr;                                                // Pop attrib 
528                         *sval += sval[1];                               // Compute value
529
530                         if (!(*sattr & (TEXT | DATA | BSS)))
531                                 *sattr = sattr[1];
532                         else if (sattr[1] & (TEXT | DATA | BSS))
533                                 return error(seg_error);
534
535                         break;
536                 case '-':
537 //printf("evexpr(): -\n");
538                         --sval;                                                 // Pop value
539                         --sattr;                                                // Pop attrib 
540                         *sval -= sval[1];                               // Compute value
541
542                         attr = (WORD)(*sattr & (TEXT | DATA | BSS));
543
544                         if (!attr)
545                                 *sattr = sattr[1];
546                         else if (sattr[1] & (TEXT | DATA | BSS))
547                         {
548                                 if (!(attr & sattr[1]))
549                                         return error(seg_error);
550                                 else
551                                         *sattr &= ~(TEXT | DATA | BSS);
552                         }
553
554                         break;
555                 // Unary operators only work on ABS items
556                 case UNMINUS:
557 //printf("evexpr(): UNMINUS\n");
558                         if (*sattr & (TEXT | DATA | BSS))
559                                 error(seg_error);
560
561                         *sval = -(int)*sval;
562                         *sattr = ABS | DEFINED;                 // Expr becomes absolute
563                         break;
564                 case '!':
565 //printf("evexpr(): !\n");
566                         if (*sattr & (TEXT | DATA | BSS))
567                                 error(seg_error);
568
569                         *sval = !*sval;
570                         *sattr = ABS | DEFINED;                 // Expr becomes absolute
571                         break;
572                 case '~':
573 //printf("evexpr(): ~\n");
574                         if (*sattr & (TEXT | DATA | BSS))
575                                 error(seg_error);
576
577                         *sval = ~*sval;
578                         *sattr = ABS | DEFINED;                 // Expr becomes absolute
579                         break;
580                 // Comparison operators must have two values that
581                 // are in the same segment, but that's the only requirement.
582                 case LE:
583 //printf("evexpr(): LE\n");
584                         --sattr;
585                         --sval;
586
587                         if ((*sattr & TDB) != (sattr[1] & TDB))
588                                 error(seg_error);
589
590                         *sattr = ABS | DEFINED;
591                         *sval = *sval <= sval[1];
592                         break;
593                 case GE:
594 //printf("evexpr(): GE\n");
595                         --sattr;
596                         --sval;
597
598                         if ((*sattr & TDB) != (sattr[1] & TDB))
599                                 error(seg_error);
600
601                         *sattr = ABS | DEFINED;
602                         *sval = *sval >= sval[1];
603                         break;
604                 case '>':
605 //printf("evexpr(): >\n");
606                         --sattr;
607                         --sval;
608
609                         if ((*sattr & TDB) != (sattr[1] & TDB))
610                                 error(seg_error);
611
612                         *sattr = ABS | DEFINED;
613                         *sval = *sval > sval[1];
614                         break;
615                 case '<':
616 //printf("evexpr(): <\n");
617                         --sattr;
618                         --sval;
619
620                         if ((*sattr & TDB) != (sattr[1] & TDB))
621                                 error(seg_error);
622
623                         *sattr = ABS | DEFINED;
624                         *sval = *sval < sval[1];
625                         break;
626                 case NE:
627 //printf("evexpr(): NE\n");
628                         --sattr;
629                         --sval;
630
631                         if ((*sattr & TDB) != (sattr[1] & TDB))
632                                 error(seg_error);
633
634                         *sattr = ABS | DEFINED;
635                         *sval = *sval != sval[1];
636                         break;
637                 case '=':
638 //printf("evexpr(): =\n");
639                         --sattr;
640                         --sval;
641
642                         if ((*sattr & TDB) != (sattr[1] & TDB))
643                                 error(seg_error);
644
645                         *sattr = ABS | DEFINED;
646                         *sval = *sval == sval[1];
647                         break;
648                 // All other binary operators must have two ABS items
649                 // to work with.  They all produce an ABS value.
650                 default:
651 //printf("evexpr(): default\n");
652                         // GH - Removed for v1.0.15 as part of the fix for indexed loads.
653                         //if ((*sattr & (TEXT|DATA|BSS)) || (*--sattr & (TEXT|DATA|BSS)))
654                         //error(seg_error);
655                         *sattr = ABS | DEFINED;                 // Expr becomes absolute
656
657                         switch ((int)tk[-1])
658                         {
659                         case '*':
660                                 --sval;
661                                 --sattr;                                        // Pop attrib 
662                                 *sval *= sval[1];
663                                 break;
664                         case '/':
665                                 --sval;
666                                 --sattr;                                        // Pop attrib 
667
668                                 if (sval[1] == 0)
669                                         return error("divide by zero");
670
671                                 *sval /= sval[1];
672                                 break;
673                         case '%':
674                                 --sval;
675                                 --sattr;                                        // Pop attrib 
676
677                                 if (sval[1] == 0)
678                                         return error("mod (%) by zero");
679
680                                 *sval %= sval[1];
681                                 break;
682                         case SHL:
683                                 --sval;
684                                 --sattr;                                        // Pop attrib 
685                                 *sval <<= sval[1];
686                                 break;
687                         case SHR:
688                                 --sval;
689                                 --sattr;                                        // Pop attrib 
690                                 *sval >>= sval[1];
691                                 break;
692                         case '&':
693                                 --sval;
694                                 --sattr;                                        // Pop attrib 
695                                 *sval &= sval[1];
696                                 break;
697                         case '^':
698                                 --sval;
699                                 --sattr;                                        // Pop attrib 
700                                 *sval ^= sval[1];
701                                 break;
702                         case '|':
703                                 --sval;
704                                 --sattr;                                        // Pop attrib 
705                                 *sval |= sval[1];
706                                 break;
707                         default:
708                                 interror(5);                            // Bad operator in expression stream
709                         }
710                 }
711         }
712
713         if (esym != NULL)
714                 *sattr &= ~DEFINED;
715
716         if (a_esym != NULL)
717                 *a_esym = esym;
718
719         // sym_seg added in 1.0.16 to solve a problem with forward symbols in
720         // expressions where absolute values also existed. The absolutes were
721         // overiding the symbol segments and not being included :(
722         //*a_attr = *sattr | sym_seg;                                        // Copy value + attrib
723
724         *a_attr = *sattr;                                               // Copy value + attrib
725         *a_value = *sval;
726
727         return OK;
728 }