]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
dc2252c7dd53466cd869e8c599b2e05e53a45743
[cc65] / src / cc65 / expr.c
1 /*
2  * expr.c
3  *
4  * Ullrich von Bassewitz, 21.06.1998
5  */
6
7
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12
13 /* common */
14 #include "check.h"
15 #include "xmalloc.h"
16
17 /* cc65 */
18 #include "asmcode.h"
19 #include "asmlabel.h"
20 #include "codegen.h"
21 #include "datatype.h"
22 #include "declare.h"
23 #include "error.h"
24 #include "funcdesc.h"
25 #include "function.h"
26 #include "global.h"
27 #include "litpool.h"
28 #include "macrotab.h"
29 #include "preproc.h"
30 #include "scanner.h"
31 #include "stdfunc.h"
32 #include "symtab.h"
33 #include "typecmp.h"
34 #include "expr.h"
35
36
37
38 /*****************************************************************************/
39 /*                                   Data                                    */
40 /*****************************************************************************/
41
42
43
44 /* Generator attributes */
45 #define GEN_NOPUSH      0x01            /* Don't push lhs */
46
47 /* Map a generator function and its attributes to a token */
48 typedef struct {
49     unsigned char Tok;                  /* Token to map to */
50     unsigned char Flags;                /* Flags for generator function */
51     void          (*Func) (unsigned, unsigned long);    /* Generator func */
52 } GenDesc;
53
54 /* Descriptors for the operations */
55 static GenDesc GenMUL    = { TOK_STAR,          GEN_NOPUSH,     g_mul };
56 static GenDesc GenDIV    = { TOK_DIV,           GEN_NOPUSH,     g_div };
57 static GenDesc GenMOD    = { TOK_MOD,           GEN_NOPUSH,     g_mod };
58 static GenDesc GenASL    = { TOK_SHL,           GEN_NOPUSH,     g_asl };
59 static GenDesc GenASR    = { TOK_SHR,           GEN_NOPUSH,     g_asr };
60 static GenDesc GenLT     = { TOK_LT,            GEN_NOPUSH,     g_lt  };
61 static GenDesc GenLE     = { TOK_LE,            GEN_NOPUSH,     g_le  };
62 static GenDesc GenGE     = { TOK_GE,            GEN_NOPUSH,     g_ge  };
63 static GenDesc GenGT     = { TOK_GT,            GEN_NOPUSH,     g_gt  };
64 static GenDesc GenEQ     = { TOK_EQ,            GEN_NOPUSH,     g_eq  };
65 static GenDesc GenNE     = { TOK_NE,            GEN_NOPUSH,     g_ne  };
66 static GenDesc GenAND    = { TOK_AND,           GEN_NOPUSH,     g_and };
67 static GenDesc GenXOR    = { TOK_XOR,           GEN_NOPUSH,     g_xor };
68 static GenDesc GenOR     = { TOK_OR,            GEN_NOPUSH,     g_or  };
69 static GenDesc GenPASGN  = { TOK_PLUS_ASSIGN,   GEN_NOPUSH,     g_add };
70 static GenDesc GenSASGN  = { TOK_MINUS_ASSIGN,  GEN_NOPUSH,     g_sub };
71 static GenDesc GenMASGN  = { TOK_MUL_ASSIGN,    GEN_NOPUSH,     g_mul };
72 static GenDesc GenDASGN  = { TOK_DIV_ASSIGN,    GEN_NOPUSH,     g_div };
73 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN,    GEN_NOPUSH,     g_mod };
74 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN,    GEN_NOPUSH,     g_asl };
75 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN,    GEN_NOPUSH,     g_asr };
76 static GenDesc GenAASGN  = { TOK_AND_ASSIGN,    GEN_NOPUSH,     g_and };
77 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN,    GEN_NOPUSH,     g_xor };
78 static GenDesc GenOASGN  = { TOK_OR_ASSIGN,     GEN_NOPUSH,     g_or  };
79
80
81
82 /*****************************************************************************/
83 /*                             Function forwards                             */
84 /*****************************************************************************/
85
86
87
88 static int hie10 (struct expent* lval);
89 /* Handle ++, --, !, unary - etc. */
90
91
92
93 /*****************************************************************************/
94 /*                             Helper functions                              */
95 /*****************************************************************************/
96
97
98
99 static unsigned GlobalModeFlags (unsigned flags)
100 /* Return the addressing mode flags for the variable with the given flags */
101 {
102     flags &= E_MCTYPE;
103     if (flags == E_TGLAB) {
104         /* External linkage */
105         return CF_EXTERNAL;
106     } else if (flags == E_TREGISTER) {
107         /* Register variable */
108         return CF_REGVAR;
109     } else {
110         /* Static */
111         return CF_STATIC;
112     }
113 }
114
115
116
117 static int IsNullPtr (struct expent* lval)
118 /* Return true if this is the NULL pointer constant */
119 {
120     return (IsClassInt (lval->e_tptr) &&        /* Is it an int? */
121             lval->e_flags == E_MCONST &&        /* Is it constant? */
122             lval->e_const == 0);                /* And is it's value zero? */
123 }
124
125
126
127 static type* promoteint (type* lhst, type* rhst)
128 /* In an expression with two ints, return the type of the result */
129 {
130     /* Rules for integer types:
131      *   - If one of the values is a long, the result is long.
132      *   - If one of the values is unsigned, the result is also unsigned.
133      *   - Otherwise the result is an int.
134      */
135     if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
136         if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
137             return type_ulong;
138         } else {
139             return type_long;
140         }
141     } else {
142         if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
143             return type_uint;
144         } else {
145             return type_int;
146         }
147     }
148 }
149
150
151
152 static unsigned typeadjust (struct expent* lhs, struct expent* rhs, int NoPush)
153 /* Adjust the two values for a binary operation. lhs is expected on stack or
154  * to be constant, rhs is expected to be in the primary register or constant.
155  * The function will put the type of the result into lhs and return the
156  * code generator flags for the operation.
157  * If NoPush is given, it is assumed that the operation does not expect the lhs
158  * to be on stack, and that lhs is in a register instead.
159  * Beware: The function does only accept int types.
160  */
161 {
162     unsigned ltype, rtype;
163     unsigned flags;
164
165     /* Get the type strings */
166     type* lhst = lhs->e_tptr;
167     type* rhst = rhs->e_tptr;
168
169     /* Generate type adjustment code if needed */
170     ltype = TypeOf (lhst);
171     if (lhs->e_flags == E_MCONST) {
172         ltype |= CF_CONST;
173     }
174     if (NoPush) {
175         /* Value is in primary register*/
176         ltype |= CF_REG;
177     }
178     rtype = TypeOf (rhst);
179     if (rhs->e_flags == E_MCONST) {
180         rtype |= CF_CONST;
181     }
182     flags = g_typeadjust (ltype, rtype);
183
184     /* Set the type of the result */
185     lhs->e_tptr = promoteint (lhst, rhst);
186
187     /* Return the code generator flags */
188     return flags;
189 }
190
191
192
193 unsigned assignadjust (type* lhst, struct expent* rhs)
194 /* Adjust the type of the right hand expression so that it can be assigned to
195  * the type on the left hand side. This function is used for assignment and
196  * for converting parameters in a function call. It returns the code generator
197  * flags for the operation. The type string of the right hand side will be
198  * set to the type of the left hand side.
199  */
200 {
201     /* Get the type of the right hand side */
202     type* rhst = rhs->e_tptr;
203
204     /* After calling this function, rhs will have the type of the lhs */
205     rhs->e_tptr = lhst;
206
207     /* First, do some type checking */
208     if (IsTypeVoid (lhst) || IsTypeVoid (rhst)) {
209         /* If one of the sides are of type void, output a more apropriate
210          * error message.
211          */
212         Error (ERR_ILLEGAL_TYPE);
213     } else if (IsClassInt (lhst)) {
214         if (IsClassPtr (rhst)) {
215             /* Pointer -> int conversion */
216             Warning (WARN_PTR_TO_INT_CONV);
217         } else if (!IsClassInt (rhst)) {
218             Error (ERR_INCOMPATIBLE_TYPES);
219         } else {
220             /* Adjust the int types. To avoid manipulation of TOS mark lhs
221              * as const.
222              */
223             unsigned flags = TypeOf (rhst);
224             if (rhs->e_flags & E_MCONST) {
225                 flags |= CF_CONST;
226             }
227             return g_typeadjust (TypeOf (lhst) | CF_CONST, flags);
228         }
229     } else if (IsClassPtr (lhst)) {
230         if (IsClassPtr (rhst)) {
231             /* Pointer to pointer assignment is valid, if:
232              *   - both point to the same types, or
233              *   - the rhs pointer is a void pointer, or
234              *   - the lhs pointer is a void pointer.
235              */
236             if (!IsTypeVoid (Indirect (lhst)) && !IsTypeVoid (Indirect (rhst))) {
237                 /* Compare the types */
238                 switch (TypeCmp (lhst, rhst)) {
239
240                     case TC_INCOMPATIBLE:
241                         Error (ERR_INCOMPATIBLE_POINTERS);
242                         break;
243
244                     case TC_QUAL_DIFF:
245                         Error (ERR_QUAL_DIFF);
246                         break;
247
248                     default:
249                         /* Ok */
250                         break;
251                 }
252             }
253         } else if (IsClassInt (rhst)) {
254             /* Int to pointer assignment is valid only for constant zero */
255             if ((rhs->e_flags & E_MCONST) == 0 || rhs->e_const != 0) {
256                 Warning (WARN_INT_TO_PTR_CONV);
257             }
258         } else if (IsTypeFuncPtr (lhst) && IsTypeFunc(rhst)) {
259             /* Assignment of function to function pointer is allowed, provided
260              * that both functions have the same parameter list.
261              */
262             if (TypeCmp (Indirect (lhst), rhst) < TC_EQUAL) {
263                 Error (ERR_INCOMPATIBLE_TYPES);
264             }
265         } else {
266             Error (ERR_INCOMPATIBLE_TYPES);
267         }
268     } else {
269         Error (ERR_INCOMPATIBLE_TYPES);
270     }
271
272     /* Return an int value in all cases where the operands are not both ints */
273     return CF_INT;
274 }
275
276
277
278 void DefineData (struct expent* lval)
279 /* Output a data definition for the given expression */
280 {
281     unsigned flags = lval->e_flags;
282
283     switch (flags & E_MCTYPE) {
284
285         case E_TCONST:
286             /* Number */
287             g_defdata (TypeOf (lval->e_tptr) | CF_CONST, lval->e_const, 0);
288             break;
289
290         case E_TREGISTER:
291             /* Register variable. Taking the address is usually not
292              * allowed.
293              */
294             if (!AllowRegVarAddr) {
295                 Error (ERR_CANNOT_TAKE_ADDR_OF_REG);
296             }
297             /* FALLTHROUGH */
298
299         case E_TGLAB:
300         case E_TLLAB:
301             /* Local or global symbol */
302             g_defdata (GlobalModeFlags (flags), lval->e_name, lval->e_const);
303             break;
304
305         case E_TLIT:
306             /* a literal of some kind */
307             g_defdata (CF_STATIC, LiteralLabel, lval->e_const);
308             break;
309
310         default:
311             Internal ("Unknown constant type: %04X", flags);
312     }
313 }
314
315
316
317 static void lconst (unsigned flags, struct expent* lval)
318 /* Load primary reg with some constant value. */
319 {
320     switch (lval->e_flags & E_MCTYPE) {
321
322         case E_TLOFFS:
323             g_leasp (lval->e_const);
324             break;
325
326         case E_TCONST:
327             /* Number constant */
328             g_getimmed (flags | TypeOf (lval->e_tptr) | CF_CONST, lval->e_const, 0);
329             break;
330
331         case E_TREGISTER:
332             /* Register variable. Taking the address is usually not
333              * allowed.
334              */
335             if (!AllowRegVarAddr) {
336                 Error (ERR_CANNOT_TAKE_ADDR_OF_REG);
337             }
338             /* FALLTHROUGH */
339
340         case E_TGLAB:
341         case E_TLLAB:
342             /* Local or global symbol, load address */
343             flags |= GlobalModeFlags (lval->e_flags);
344             flags &= ~CF_CONST;
345             g_getimmed (flags, lval->e_name, lval->e_const);
346             break;
347
348         case E_TLIT:
349             /* Literal string */
350             g_getimmed (CF_STATIC, LiteralLabel, lval->e_const);
351             break;
352
353         default:
354             Internal ("Unknown constant type: %04X", lval->e_flags);
355     }
356 }
357
358
359
360 static int kcalc (int tok, long val1, long val2)
361 /* Calculate an operation with left and right operand constant. */
362 {
363     switch (tok) {
364         case TOK_EQ:
365             return (val1 == val2);
366         case TOK_NE:
367             return (val1 != val2);
368         case TOK_LT:
369             return (val1 < val2);
370         case TOK_LE:
371             return (val1 <= val2);
372         case TOK_GE:
373             return (val1 >= val2);
374         case TOK_GT:
375             return (val1 > val2);
376         case TOK_OR:
377             return (val1 | val2);
378         case TOK_XOR:
379             return (val1 ^ val2);
380         case TOK_AND:
381             return (val1 & val2);
382         case TOK_SHR:
383             return (val1 >> val2);
384         case TOK_SHL:
385             return (val1 << val2);
386         case TOK_STAR:
387             return (val1 * val2);
388         case TOK_DIV:
389             if (val2 == 0) {
390                 Error (ERR_DIV_BY_ZERO);
391                 return 0x7FFFFFFF;
392             }
393             return (val1 / val2);
394         case TOK_MOD:
395             if (val2 == 0) {
396                 Error (ERR_MOD_BY_ZERO);
397                 return 0;
398             }
399             return (val1 % val2);
400         default:
401             Internal ("kcalc: got token 0x%X\n", tok);
402             return 0;
403     }
404 }
405
406
407
408 static GenDesc* FindGen (int Tok, GenDesc** Table)
409 {
410     GenDesc* G;
411     while ((G = *Table) != 0) {
412         if (G->Tok == Tok) {
413             return G;
414         }
415         ++Table;
416     }
417     return 0;
418 }
419
420
421
422 static int istypeexpr (void)
423 /* Return true if some sort of variable or type is waiting (helper for cast
424  * and sizeof() in hie10).
425  */
426 {
427     SymEntry* Entry;
428
429     return curtok == TOK_LPAREN && (
430             (nxttok >= TOK_FIRSTTYPE && nxttok <= TOK_LASTTYPE) ||
431             (nxttok == TOK_CONST)                               ||
432             (nxttok  == TOK_IDENT                               &&
433             (Entry = FindSym (NextTok.Ident)) != 0              &&
434             IsTypeDef (Entry))
435            );
436 }
437
438
439
440 static void PushAddr (struct expent* lval)
441 /* If the expression contains an address that was somehow evaluated,
442  * push this address on the stack. This is a helper function for all
443  * sorts of implicit or explicit assignment functions where the lvalue
444  * must be saved if it's not constant, before evaluating the rhs.
445  */
446 {
447     /* Get the address on stack if needed */
448     if (lval->e_flags != E_MREG && (lval->e_flags & E_MEXPR)) {
449         /* Push the address (always a pointer) */
450         g_push (CF_PTR, 0);
451     }
452 }
453
454
455
456 /*****************************************************************************/
457 /*                                   code                                    */
458 /*****************************************************************************/
459
460
461
462 void exprhs (unsigned flags, int k, struct expent *lval)
463 /* Put the result of an expression into the primary register */
464 {
465     int f;
466
467     f = lval->e_flags;
468     if (k) {
469         /* Dereferenced lvalue */
470         flags |= TypeOf (lval->e_tptr);
471         if (lval->e_test & E_FORCETEST) {
472             flags |= CF_TEST;
473             lval->e_test &= ~E_FORCETEST;
474         }
475         if (f & E_MGLOBAL) {    /* ref to globalvar */
476             /* Generate code */
477             flags |= GlobalModeFlags (f);
478             g_getstatic (flags, lval->e_name, lval->e_const);
479         } else if (f & E_MLOCAL) {
480             /* ref to localvar */
481             g_getlocal (flags, lval->e_const);
482         } else if (f & E_MCONST) {
483             /* ref to absolute address */
484             g_getstatic (flags | CF_ABSOLUTE, lval->e_const, 0);
485         } else if (f == E_MEOFFS) {
486             g_getind (flags, lval->e_const);
487         } else if (f != E_MREG) {
488             g_getind (flags, 0);
489         }
490     } else if (f == E_MEOFFS) {
491         /* reference not storable */
492         flags |= TypeOf (lval->e_tptr);
493         g_inc (flags | CF_CONST, lval->e_const);
494     } else if ((f & E_MEXPR) == 0) {
495         /* Constant of some sort, load it into the primary */
496         lconst (flags, lval);
497     }
498     if (lval->e_test & E_FORCETEST) {   /* we testing this value? */
499         /* debug... */
500         AddCodeHint ("forcetest");
501         flags |= TypeOf (lval->e_tptr);
502         g_test (flags);                 /* yes, force a test */
503         lval->e_test &= ~E_FORCETEST;
504     }
505 }
506
507
508 static void callfunction (struct expent* lval)
509 /* Perform a function call.  Called from hie11, this routine will
510  * either call the named function, or if the supplied ptr is zero,
511  * will call the contents of P.
512  */
513 {
514     struct expent lval2;
515     FuncDesc*     Func;         /* Function descriptor */
516     int           Ellipsis;     /* True if we have an open param list */
517     SymEntry*     Param;        /* Current formal parameter */
518     unsigned      ParamCount;   /* Actual parameter count */
519     unsigned      ParamSize;    /* Number of parameter bytes */
520     unsigned      Flags;
521     unsigned      CFlags;
522     CodeMark      Mark;
523
524
525     /* Get a pointer to the function descriptor from the type string */
526     Func = GetFuncDesc (lval->e_tptr);
527
528     /* Initialize vars to keep gcc silent */
529     Param = 0;
530     Mark  = 0;
531
532     /* Check if this is a function pointer. If so, save it. If not, check for
533      * special known library functions that may be inlined.
534      */
535     if (lval->e_flags & E_MEXPR) {
536         /* Function pointer is in primary register, save it */
537         Mark = GetCodePos ();
538         g_save (CF_PTR);
539     } else if (InlineStdFuncs && IsStdFunc ((const char*) lval->e_name)) {
540         /* Inline this function */
541         HandleStdFunc (lval);
542         return;
543     }
544
545     /* Parse the actual parameter list */
546     ParamSize  = 0;
547     ParamCount = 0;
548     Ellipsis   = 0;
549     while (curtok != TOK_RPAREN) {
550
551         /* Add a hint for the optimizer */
552         AddCodeHint ("param:start");
553
554         /* Count arguments */
555         ++ParamCount;
556
557         /* Fetch the pointer to the next argument, check for too many args */
558         if (ParamCount <= Func->ParamCount) {
559             if (ParamCount == 1) {
560                 /* First argument */
561                 Param = Func->SymTab->SymHead;
562             } else {
563                 /* Next argument */
564                 Param = Param->NextSym;
565                 CHECK ((Param->Flags & SC_PARAM) != 0);
566             }
567         } else if (!Ellipsis) {
568             /* Too many arguments. Do we have an open param list? */
569             if ((Func->Flags & FD_ELLIPSIS) == 0) {
570                 /* End of param list reached, no ellipsis */
571                 Error (ERR_TOO_MANY_FUNC_ARGS);
572             }
573             /* Assume an ellipsis even in case of errors to avoid an error
574              * message for each other argument.
575              */
576             Ellipsis = 1;
577         }
578
579         /* Do some optimization: If we have a constant value to push,
580          * use a special function that may optimize.
581          */
582         CFlags = CF_NONE;
583         if (!Ellipsis && SizeOf (Param->Type) == 1) {
584             CFlags = CF_FORCECHAR;
585         }
586         Flags = 0;
587         if (evalexpr (CFlags, hie1, &lval2) == 0) {
588             /* A constant value */
589             Flags |= CF_CONST;
590         }
591
592         /* If we don't have an argument spec, accept anything, otherwise
593          * convert the actual argument to the type needed.
594          */
595         if (!Ellipsis) {
596             /* Promote the argument if needed */
597             assignadjust (Param->Type, &lval2);
598
599             /* If we have a prototype, chars may be pushed as chars */
600             Flags |= CF_FORCECHAR;
601         }
602
603         /* Use the type of the argument for the push */
604         Flags |= TypeOf (lval2.e_tptr);
605
606         /* If this is a fastcall function, don't push the last argument */
607         if (ParamCount == Func->ParamCount && (Func->Flags & FD_FASTCALL) != 0) {
608             /* Just load the argument into the primary. This is only needed if
609              * we have a constant argument, otherwise the value is already in
610              * the primary.
611              */
612             if (Flags & CF_CONST) {
613                 exprhs (CF_FORCECHAR, 0, &lval2);
614             }
615         } else {
616             /* Push the argument, count the argument size */
617             g_push (Flags, lval2.e_const);
618             ParamSize += sizeofarg (Flags);
619         }
620
621         /* Add an optimizer hint */
622         AddCodeHint ("param:end");
623
624         /* Check for end of argument list */
625         if (curtok != TOK_COMMA) {
626             break;
627         }
628         NextToken ();
629     }
630
631     /* We need the closing bracket here */
632     ConsumeRParen ();
633
634     /* Check if we had enough parameters */
635     if (ParamCount < Func->ParamCount) {
636         Error (ERR_TOO_FEW_FUNC_ARGS);
637     }
638
639     /* */
640     if (lval->e_flags & E_MEXPR) {
641         /* Function called via pointer: Restore it and call function */
642         if (ParamSize != 0) {
643             g_restore (CF_PTR);
644         } else {
645             /* We had no parameters - remove save code */
646             RemoveCode (Mark);
647         }
648         g_callind (TypeOf (lval->e_tptr), ParamSize);
649     } else {
650         g_call (TypeOf (lval->e_tptr), (char*) lval->e_name, ParamSize);
651     }
652 }
653
654
655
656 void doasm (void)
657 /* This function parses ASM statements. The syntax of the ASM directive
658  * looks like the one defined for C++ (C has no ASM directive), that is,
659  * a string literal in parenthesis.
660  */
661 {
662     /* Skip the ASM */
663     NextToken ();
664
665     /* Need left parenthesis */
666     ConsumeLParen ();
667
668     /* String literal */
669     if (curtok != TOK_SCONST) {
670         Error (ERR_STRLIT_EXPECTED);
671     } else {
672         /* Write the string directly into the output, followed by a newline */
673         AddCodeLine (GetLiteral (curval));
674
675         /* Reset the string pointer, effectivly clearing the string from the
676          * string table. Since we're working with one token lookahead, this
677          * will fail if the next token is also a string token, but that's a
678          * syntax error anyway, because we expect a right paren.
679          */
680         ResetLiteralOffs (curval);
681     }
682
683     /* Skip the string token */
684     NextToken ();
685
686     /* Closing paren needed */
687     ConsumeRParen ();
688 }
689
690
691
692 static int primary (struct expent* lval)
693 /* This is the lowest level of the expression parser. */
694 {
695     int k;
696
697     /* not a test at all, yet */
698     lval->e_test = 0;
699
700     /* Character and integer constants. */
701     if (curtok == TOK_ICONST || curtok == TOK_CCONST) {
702         lval->e_flags = E_MCONST | E_TCONST;
703         lval->e_tptr  = curtype;
704         lval->e_const = curval;
705         NextToken ();
706         return 0;
707     }
708
709     /* Process parenthesized subexpression by calling the whole parser
710      * recursively.
711      */
712     if (curtok == TOK_LPAREN) {
713         NextToken ();
714         memset (lval, 0, sizeof (*lval));       /* Remove any attributes */
715         k = hie0 (lval);
716         ConsumeRParen ();
717         return k;
718     }
719
720     /* All others may only be used if the expression evaluation is not called
721      * recursively by the preprocessor.
722      */
723     if (Preprocessing) {
724         /* Illegal expression in PP mode */
725         Error (ERR_CPP_EXPR_EXPECTED);
726         lval->e_flags = E_MCONST;
727         lval->e_tptr = type_int;
728         return 0;
729     }
730
731     /* Identifier? */
732     if (curtok == TOK_IDENT) {
733
734         SymEntry* Sym;
735         ident Ident;
736
737         /* Get a pointer to the symbol table entry */
738         Sym = FindSym (CurTok.Ident);
739
740         /* Is the symbol known? */
741         if (Sym) {
742
743             /* We found the symbol - skip the name token */
744             NextToken ();
745
746             /* The expression type is the symbol type */
747             lval->e_tptr = Sym->Type;
748
749             /* Check for illegal symbol types */
750             if ((Sym->Flags & SC_LABEL) == SC_LABEL) {
751                 /* Cannot use labels in expressions */
752                 Error (ERR_SYMBOL_KIND);
753                 return 1;
754             } else if (Sym->Flags & SC_TYPE) {
755                 /* Cannot use type symbols */
756                 Error (ERR_VAR_IDENT_EXPECTED);
757                 /* Assume an int type to make lval valid */
758                 lval->e_flags = E_MLOCAL | E_TLOFFS;
759                 lval->e_tptr = type_int;
760                 lval->e_const = 0;
761                 return 0;
762             }
763
764             /* Check for legal symbol types */
765             if ((Sym->Flags & SC_ENUM) == SC_ENUM) {
766                 lval->e_flags = E_MCONST;
767                 lval->e_const = Sym->V.EnumVal;
768                 return 0;
769             } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
770                 /* Function */
771                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
772                 lval->e_name = (unsigned long) Sym->Name;
773                 lval->e_const = 0;
774             } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
775                 /* Local variable */
776                 lval->e_flags = E_MLOCAL | E_TLOFFS;
777                 lval->e_const = Sym->V.Offs;
778             } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
779                 /* Static variable */
780                 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
781                     lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
782                     lval->e_name = (unsigned long) Sym->Name;
783                 } else {
784                     lval->e_flags = E_MGLOBAL | E_MCONST | E_TLLAB;
785                     lval->e_name = Sym->V.Label;
786                 }
787                 lval->e_const = 0;
788             } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
789                 /* Register variable, zero page based */
790                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TREGISTER;
791                 lval->e_name  = Sym->V.Offs;
792                 lval->e_const = 0;
793             } else {
794                 /* Local static variable */
795                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TLLAB;
796                 lval->e_name  = Sym->V.Offs;
797                 lval->e_const = 0;
798             }
799
800             /* The symbol is referenced now */
801             Sym->Flags |= SC_REF;
802             if (IsTypeFunc (lval->e_tptr) || IsTypeArray (lval->e_tptr)) {
803                 return 0;
804             }
805             return 1;
806         }
807
808         /* We did not find the symbol. Remember the name, then skip it */
809         strcpy (Ident, CurTok.Ident);
810         NextToken ();
811
812         /* IDENT is either an auto-declared function or an undefined variable. */
813         if (curtok == TOK_LPAREN) {
814             /* Declare a function returning int. For that purpose, prepare a
815              * function signature for a function having an empty param list
816              * and returning int.
817              */
818             Warning (WARN_FUNC_WITHOUT_PROTO);
819             Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
820             lval->e_tptr  = Sym->Type;
821             lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
822             lval->e_name  = (unsigned long) Sym->Name;
823             lval->e_const = 0;
824             return 0;
825
826         } else {
827
828             /* Undeclared Variable */
829             Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
830             lval->e_flags = E_MLOCAL | E_TLOFFS;
831             lval->e_tptr = type_int;
832             lval->e_const = 0;
833             Error (ERR_UNDEFINED_SYMBOL, Ident);
834             return 1;
835
836         }
837     }
838
839     /* String literal? */
840     if (curtok == TOK_SCONST) {
841         lval->e_flags = E_MCONST | E_TLIT;
842         lval->e_const = curval;
843         lval->e_tptr  = GetCharArrayType (strlen (GetLiteral (curval)));
844         NextToken ();
845         return 0;
846     }
847
848     /* ASM statement? */
849     if (curtok == TOK_ASM) {
850         doasm ();
851         lval->e_tptr  = type_void;
852         lval->e_flags = E_MEXPR;
853         lval->e_const = 0;
854         return 0;
855     }
856
857     /* __AX__ and __EAX__ pseudo values? */
858     if (curtok == TOK_AX || curtok == TOK_EAX) {
859         lval->e_tptr  = (curtok == TOK_AX)? type_uint : type_ulong;
860         lval->e_flags = E_MREG;
861         lval->e_test &= ~E_CC;
862         lval->e_const = 0;
863         NextToken ();
864         return 1;               /* May be used as lvalue */
865     }
866
867     /* Illegal primary. */
868     Error (ERR_EXPR_EXPECTED);
869     lval->e_flags = E_MCONST;
870     lval->e_tptr = type_int;
871     return 0;
872 }
873
874
875
876 static int arrayref (int k, struct expent* lval)
877 /* Handle an array reference */
878 {
879     unsigned lflags;
880     unsigned rflags;
881     int ConstBaseAddr;
882     int ConstSubAddr;
883     int l;
884     struct expent lval2;
885     CodeMark Mark1;
886     CodeMark Mark2;
887     type* tptr1;
888     type* tptr2;
889
890
891     /* Skip the bracket */
892     NextToken ();
893
894     /* Get the type of left side */
895     tptr1 = lval->e_tptr;
896
897     /* We can apply a special treatment for arrays that have a const base
898      * address. This is true for most arrays and will produce a lot better
899      * code. Check if this is a const base address.
900      */
901     lflags = lval->e_flags & ~E_MCTYPE;
902     ConstBaseAddr = (lflags == E_MCONST)       || /* Constant numeric address */
903                      (lflags & E_MGLOBAL) != 0 || /* Static array, or ... */
904                      lflags == E_MLOCAL;          /* Local array */
905
906     /* If we have a constant base, we delay the address fetch */
907     Mark1 = GetCodePos ();
908     Mark2 = 0;          /* Silence gcc */
909     if (!ConstBaseAddr) {
910         /* Get a pointer to the array into the primary */
911         exprhs (CF_NONE, k, lval);
912
913         /* Get the array pointer on stack. Do not push more than 16
914          * bit, even if this value is greater, since we cannot handle
915          * other than 16bit stuff when doing indexing.
916          */
917         Mark2 = GetCodePos ();
918         g_push (CF_PTR, 0);
919     }
920
921     /* TOS now contains ptr to array elements. Get the subscript. */
922     l = hie0 (&lval2);
923     if (l == 0 && lval2.e_flags == E_MCONST) {
924
925         /* The array subscript is a constant - remove value from stack */
926         if (!ConstBaseAddr) {
927             RemoveCode (Mark2);
928             pop (CF_PTR);
929         } else {
930             /* Get an array pointer into the primary */
931             exprhs (CF_NONE, k, lval);
932         }
933
934         if (IsClassPtr (tptr1)) {
935
936             /* Scale the subscript value according to element size */
937             lval2.e_const *= PSizeOf (tptr1);
938
939             /* Remove code for lhs load */
940             RemoveCode (Mark1);
941
942             /* Handle constant base array on stack. Be sure NOT to
943              * handle pointers the same way, this won't work.
944              */
945             if (IsTypeArray (tptr1) &&
946                 ((lval->e_flags & ~E_MCTYPE) == E_MCONST ||
947                 (lval->e_flags & ~E_MCTYPE) == E_MLOCAL ||
948                 (lval->e_flags & E_MGLOBAL) != 0 ||
949                 (lval->e_flags == E_MEOFFS))) {
950                 lval->e_const += lval2.e_const;
951
952             } else {
953                 /* Pointer - load into primary and remember offset */
954                 if ((lval->e_flags & E_MEXPR) == 0 || k != 0) {
955                     exprhs (CF_NONE, k, lval);
956                 }
957                 lval->e_const = lval2.e_const;
958                 lval->e_flags = E_MEOFFS;
959             }
960
961             /* Result is of element type */
962             lval->e_tptr = Indirect (tptr1);
963
964             /* Done */
965             goto end_array;
966
967         } else if (IsClassPtr (tptr2 = lval2.e_tptr)) {
968             /* Subscript is pointer, get element type */
969             lval2.e_tptr = Indirect (tptr2);
970
971             /* Scale the rhs value in the primary register */
972             g_scale (TypeOf (tptr1), SizeOf (lval2.e_tptr));
973             /* */
974             lval->e_tptr = lval2.e_tptr;
975         } else {
976             Error (ERR_CANNOT_SUBSCRIPT);
977         }
978
979         /* Add the subscript. Since arrays are indexed by integers,
980          * we will ignore the true type of the subscript here and
981          * use always an int.
982          */
983         g_inc (CF_INT | CF_CONST, lval2.e_const);
984
985     } else {
986
987         /* Array subscript is not constant. Load it into the primary */
988         Mark2 = GetCodePos ();
989         exprhs (CF_NONE, l, &lval2);
990
991         tptr2 = lval2.e_tptr;
992         if (IsClassPtr (tptr1)) {
993
994             /* Get the element type */
995             lval->e_tptr = Indirect (tptr1);
996
997             /* Indexing is based on int's, so we will just use the integer
998              * portion of the index (which is in (e)ax, so there's no further
999              * action required).
1000              */
1001             g_scale (CF_INT, SizeOf (lval->e_tptr));
1002
1003         } else if (IsClassPtr (tptr2)) {
1004
1005             /* Get the element type */
1006             lval2.e_tptr = Indirect (tptr2);
1007
1008             /* Get the int value on top. If we go here, we're sure,
1009              * both values are 16 bit (the first one was truncated
1010              * if necessary and the second one is a pointer).
1011              * Note: If ConstBaseAddr is true, we don't have a value on
1012              * stack, so to "swap" both, just push the subscript.
1013              */
1014             if (ConstBaseAddr) {
1015                 g_push (CF_INT, 0);
1016                 exprhs (CF_NONE, k, lval);
1017                 ConstBaseAddr = 0;
1018             } else {
1019                 g_swap (CF_INT);
1020             }
1021
1022             /* Scale it */
1023             g_scale (TypeOf (tptr1), SizeOf (lval2.e_tptr));
1024             lval->e_tptr = lval2.e_tptr;
1025         } else {
1026             Error (ERR_CANNOT_SUBSCRIPT);
1027         }
1028
1029         /* The offset is now in the primary register. It didn't have a
1030          * constant base address for the lhs, the lhs address is already
1031          * on stack, and we must add the offset. If the base address was
1032          * constant, we call special functions to add the address to the
1033          * offset value.
1034          */
1035         if (!ConstBaseAddr) {
1036             /* Add the subscript. Both values are int sized. */
1037             g_add (CF_INT, 0);
1038         } else {
1039
1040             /* If the subscript has itself a constant address, it is often
1041              * a better idea to reverse again the order of the evaluation.
1042              * This will generate better code if the subscript is a byte
1043              * sized variable. But beware: This is only possible if the
1044              * subscript was not scaled, that is, if this was a byte array
1045              * or pointer.
1046              */
1047             rflags = lval2.e_flags & ~E_MCTYPE;
1048             ConstSubAddr = (rflags == E_MCONST)       || /* Constant numeric address */
1049                             (rflags & E_MGLOBAL) != 0 || /* Static array, or ... */
1050                             rflags == E_MLOCAL;          /* Local array */
1051
1052             if (ConstSubAddr && SizeOf (lval->e_tptr) == 1) {
1053
1054                 type* SavedType;
1055
1056                 /* Reverse the order of evaluation */
1057                 unsigned flags = (SizeOf (lval2.e_tptr) == 1)? CF_CHAR : CF_INT;
1058                 RemoveCode (Mark2);
1059
1060                 /* Get a pointer to the array into the primary. We have changed
1061                  * e_tptr above but we need the original type to load the
1062                  * address, so restore it temporarily.
1063                  */
1064                 SavedType = lval->e_tptr;
1065                 lval->e_tptr = tptr1;
1066                 exprhs (CF_NONE, k, lval);
1067                 lval->e_tptr = SavedType;
1068
1069                 /* Add the variable */
1070                 if (rflags == E_MLOCAL) {
1071                     g_addlocal (flags, lval2.e_const);
1072                 } else {
1073                     flags |= GlobalModeFlags (lval2.e_flags);
1074                     g_addstatic (flags, lval2.e_name, lval2.e_const);
1075                 }
1076             } else {
1077                 if (lflags == E_MCONST) {
1078                     /* Constant numeric address. Just add it */
1079                     g_inc (CF_INT | CF_UNSIGNED, lval->e_const);
1080                 } else if (lflags == E_MLOCAL) {
1081                     /* Base address is a local variable address */
1082                     if (IsTypeArray (tptr1)) {
1083                         g_addaddr_local (CF_INT, lval->e_const);
1084                     } else {
1085                         g_addlocal (CF_PTR, lval->e_const);
1086                     }
1087                 } else {
1088                     /* Base address is a static variable address */
1089                     unsigned flags = CF_INT;
1090                     flags |= GlobalModeFlags (lval->e_flags);
1091                     if (IsTypeArray (tptr1)) {
1092                         g_addaddr_static (flags, lval->e_name, lval->e_const);
1093                     } else {
1094                         g_addstatic (flags, lval->e_name, lval->e_const);
1095                     }
1096                 }
1097             }
1098         }
1099     }
1100     lval->e_flags = E_MEXPR;
1101 end_array:
1102     ConsumeRBrack ();
1103     return !IsTypeArray (lval->e_tptr);
1104
1105 }
1106
1107
1108
1109 static int structref (int k, struct expent* lval)
1110 /* Process struct field after . or ->. */
1111 {
1112     ident Ident;
1113     SymEntry* Field;
1114     int flags;
1115
1116     /* Skip the token and check for an identifier */
1117     NextToken ();
1118     if (curtok != TOK_IDENT) {
1119         Error (ERR_IDENT_EXPECTED);
1120         lval->e_tptr = type_int;
1121         return 0;
1122     }
1123
1124     /* Get the symbol table entry and check for a struct field */
1125     strcpy (Ident, CurTok.Ident);
1126     NextToken ();
1127     Field = FindStructField (lval->e_tptr, Ident);
1128     if (Field == 0) {
1129         Error (ERR_STRUCT_FIELD_MISMATCH, Ident);
1130         lval->e_tptr = type_int;
1131         return 0;
1132     }
1133
1134     /* If we have constant input data, the result is also constant */
1135     flags = lval->e_flags & ~E_MCTYPE;
1136     if (flags == E_MCONST ||
1137         (k == 0 && (flags == E_MLOCAL ||
1138                     (flags & E_MGLOBAL) != 0 ||
1139                     lval->e_flags  == E_MEOFFS))) {
1140         lval->e_const += Field->V.Offs;
1141     } else {
1142         if ((flags & E_MEXPR) == 0 || k != 0) {
1143             exprhs (CF_NONE, k, lval);
1144         }
1145         lval->e_const = Field->V.Offs;
1146         lval->e_flags = E_MEOFFS;
1147     }
1148     lval->e_tptr = Field->Type;
1149     return !IsTypeArray (Field->Type);
1150 }
1151
1152
1153
1154 static int hie11 (struct expent *lval)
1155 /* Handle compound types (structs and arrays) */
1156 {
1157     int k;
1158     type* tptr;
1159
1160
1161     k = primary (lval);
1162     if (curtok < TOK_LBRACK || curtok > TOK_PTR_REF) {
1163         /* Not for us */
1164         return k;
1165     }
1166
1167     while (1) {
1168
1169         if (curtok == TOK_LBRACK) {
1170
1171             /* Array reference */
1172             k = arrayref (k, lval);
1173
1174         } else if (curtok == TOK_LPAREN) {
1175
1176             /* Function call. Skip the opening parenthesis */
1177             NextToken ();
1178             tptr = lval->e_tptr;
1179             if (IsTypeFunc (tptr) || IsTypeFuncPtr (tptr)) {
1180                 if (IsTypeFuncPtr (tptr)) {
1181                     /* Pointer to function. Handle transparently */
1182                     exprhs (CF_NONE, k, lval);  /* Function pointer to A/X */
1183                     ++lval->e_tptr;             /* Skip T_PTR */
1184                     lval->e_flags |= E_MEXPR;
1185                 }
1186                 callfunction (lval);
1187                 lval->e_flags = E_MEXPR;
1188                 lval->e_tptr += DECODE_SIZE + 1;        /* Set to result */
1189             } else {
1190                 Error (ERR_ILLEGAL_FUNC_CALL);
1191             }
1192             k = 0;
1193
1194         } else if (curtok == TOK_DOT) {
1195
1196             if (!IsClassStruct (lval->e_tptr)) {
1197                 Error (ERR_STRUCT_EXPECTED);
1198             }
1199             k = structref (0, lval);
1200
1201         } else if (curtok == TOK_PTR_REF) {
1202
1203             tptr = lval->e_tptr;
1204             if (tptr[0] != T_PTR || (tptr[1] & T_STRUCT) == 0) {
1205                 Error (ERR_STRUCT_PTR_EXPECTED);
1206             }
1207             k = structref (k, lval);
1208
1209         } else {
1210             return k;
1211         }
1212     }
1213 }
1214
1215
1216
1217 static void store (struct expent* lval)
1218 /* Store primary reg into this reference */
1219 {
1220     int f;
1221     unsigned flags;
1222
1223     f = lval->e_flags;
1224     flags = TypeOf (lval->e_tptr);
1225     if (f & E_MGLOBAL) {
1226         flags |= GlobalModeFlags (f);
1227         if (lval->e_test) {
1228             /* Just testing */
1229             flags |= CF_TEST;
1230         }
1231
1232         /* Generate code */
1233         g_putstatic (flags, lval->e_name, lval->e_const);
1234
1235     } else if (f & E_MLOCAL) {
1236         g_putlocal (flags, lval->e_const);
1237     } else if (f == E_MEOFFS) {
1238         g_putind (flags, lval->e_const);
1239     } else if (f != E_MREG) {
1240         if (f & E_MEXPR) {
1241             g_putind (flags, 0);
1242         } else {
1243             /* Store into absolute address */
1244             g_putstatic (flags | CF_ABSOLUTE, lval->e_const, 0);
1245         }
1246     }
1247
1248     /* Assume that each one of the stores will invalidate CC */
1249     lval->e_test &= ~E_CC;
1250 }
1251
1252
1253
1254 static void pre_incdec (struct expent* lval, void (*inc) (unsigned, unsigned long))
1255 /* Handle --i and ++i */
1256 {
1257     int k;
1258     unsigned flags;
1259     unsigned long val;
1260
1261     NextToken ();
1262     if ((k = hie10 (lval)) == 0) {
1263         Error (ERR_LVALUE_EXPECTED);
1264         return;
1265     }
1266
1267     /* Get the data type */
1268     flags = TypeOf (lval->e_tptr) | CF_FORCECHAR | CF_CONST;
1269
1270     /* Get the increment value in bytes */
1271     val = (lval->e_tptr [0] == T_PTR)? PSizeOf (lval->e_tptr) : 1;
1272
1273     /* We're currently only able to handle some adressing modes */
1274     if ((lval->e_flags & E_MGLOBAL) == 0 &&     /* Global address? */
1275         (lval->e_flags & E_MLOCAL) == 0  &&     /* Local address? */
1276         (lval->e_flags & E_MCONST) == 0  &&     /* Constant address? */
1277         (lval->e_flags & E_MEXPR) == 0) {       /* Address in a/x? */
1278
1279         /* Use generic code. Push the address if needed */
1280         PushAddr (lval);
1281
1282         /* Fetch the value */
1283         exprhs (CF_NONE, k, lval);
1284
1285         /* Increment value in primary */
1286         inc (flags, val);
1287
1288         /* Store the result back */
1289         store (lval);
1290
1291     } else {
1292
1293         /* Special code for some addressing modes - use the special += ops */
1294         if (lval->e_flags & E_MGLOBAL) {
1295             flags |= GlobalModeFlags (lval->e_flags);
1296             if (inc == g_inc) {
1297                 g_addeqstatic (flags, lval->e_name, lval->e_const, val);
1298             } else {
1299                 g_subeqstatic (flags, lval->e_name, lval->e_const, val);
1300             }
1301         } else if (lval->e_flags & E_MLOCAL) {
1302             /* ref to localvar */
1303             if (inc == g_inc) {
1304                 g_addeqlocal (flags, lval->e_const, val);
1305             } else {
1306                 g_subeqlocal (flags, lval->e_const, val);
1307             }
1308         } else if (lval->e_flags & E_MCONST) {
1309             /* ref to absolute address */
1310             flags |= CF_ABSOLUTE;
1311             if (inc == g_inc) {
1312                 g_addeqstatic (flags, lval->e_const, 0, val);
1313             } else {
1314                 g_subeqstatic (flags, lval->e_const, 0, val);
1315             }
1316         } else if (lval->e_flags & E_MEXPR) {
1317             /* Address in a/x. */
1318             if (inc == g_inc) {
1319                 g_addeqind (flags, lval->e_const, val);
1320             } else {
1321                 g_subeqind (flags, lval->e_const, val);
1322             }
1323         } else {
1324             Internal ("Invalid addressing mode");
1325         }
1326
1327     }
1328
1329     /* Result is an expression */
1330     lval->e_flags = E_MEXPR;
1331 }
1332
1333
1334
1335 static void post_incdec (struct expent *lval, int k, void (*inc) (unsigned, unsigned long))
1336 /* Handle i-- and i++ */
1337 {
1338     unsigned flags;
1339
1340     NextToken ();
1341     if (k == 0) {
1342         Error (ERR_LVALUE_EXPECTED);
1343         return;
1344     }
1345
1346     /* Get the data type */
1347     flags = TypeOf (lval->e_tptr);
1348
1349     /* Push the address if needed */
1350     PushAddr (lval);
1351
1352     /* Fetch the value and save it (since it's the result of the expression) */
1353     exprhs (CF_NONE, 1, lval);
1354     g_save (flags | CF_FORCECHAR);
1355
1356     /* If we have a pointer expression, increment by the size of the type */
1357     if (lval->e_tptr[0] == T_PTR) {
1358         inc (flags | CF_CONST | CF_FORCECHAR, SizeOf (lval->e_tptr + 1));
1359     } else {
1360         inc (flags | CF_CONST | CF_FORCECHAR, 1);
1361     }
1362
1363     /* Store the result back */
1364     store (lval);
1365
1366     /* Restore the original value */
1367     g_restore (flags | CF_FORCECHAR);
1368     lval->e_flags = E_MEXPR;
1369 }
1370
1371
1372
1373 static void unaryop (int tok, struct expent* lval)
1374 /* Handle unary -/+ and ~ */
1375 {
1376     int k;
1377     unsigned flags;
1378
1379     NextToken ();
1380     k = hie10 (lval);
1381     if (k == 0 && lval->e_flags & E_MCONST) {
1382         /* Value is constant */
1383         switch (tok) {
1384             case TOK_MINUS: lval->e_const =     -lval->e_const; break;
1385             case TOK_PLUS:                                      break;
1386             case TOK_COMP:  lval->e_const = ~lval->e_const;     break;
1387             default:        Internal ("Unexpected token: %d", tok);
1388         }
1389     } else {
1390         /* Value is not constant */
1391         exprhs (CF_NONE, k, lval);
1392
1393         /* Get the type of the expression */
1394         flags = TypeOf (lval->e_tptr);
1395
1396         /* Handle the operation */
1397         switch (tok) {
1398             case TOK_MINUS: g_neg (flags);  break;
1399             case TOK_PLUS:                  break;
1400             case TOK_COMP:  g_com (flags);  break;
1401             default:    Internal ("Unexpected token: %d", tok);
1402         }
1403         lval->e_flags = E_MEXPR;
1404     }
1405 }
1406
1407
1408
1409 static int typecast (struct expent* lval)
1410 /* Handle an explicit cast */
1411 {
1412     int k;
1413     type Type[MAXTYPELEN];
1414     unsigned rflags;
1415
1416     /* Skip the left paren */
1417     NextToken ();
1418
1419     /* Read the type */
1420     ParseType (Type);
1421
1422     /* Closing paren */
1423     ConsumeRParen ();
1424
1425     /* Read the expression we have to cast */
1426     k = hie10 (lval);
1427
1428     /* Get the type of the expression and honor constant values */
1429     rflags = TypeOf (lval->e_tptr);
1430     if (lval->e_flags & E_MCONST) {
1431         rflags |= CF_CONST;
1432     }
1433
1434     /* Do the actual cast. Special handling for void casts */
1435     if (!IsTypeVoid (Type)) {
1436         /* Mark the lhs as const to avoid a manipulation of TOS */
1437         g_typecast (TypeOf (Type) | CF_CONST, rflags);
1438     }
1439
1440     /* Use the new type */
1441     lval->e_tptr = TypeDup (Type);
1442
1443     /* Done */
1444     return k;
1445 }
1446
1447
1448
1449 static int hie10 (struct expent* lval)
1450 /* Handle ++, --, !, unary - etc. */
1451 {
1452     int k;
1453     type* t;
1454
1455     switch (curtok) {
1456
1457         case TOK_INC:
1458             pre_incdec (lval, g_inc);
1459             return 0;
1460
1461         case TOK_DEC:
1462             pre_incdec (lval, g_dec);
1463             return 0;
1464
1465         case TOK_PLUS:
1466         case TOK_MINUS:
1467         case TOK_COMP:
1468             unaryop (curtok, lval);
1469             return 0;
1470
1471         case TOK_BOOL_NOT:
1472             NextToken ();
1473             if (evalexpr (CF_NONE, hie10, lval) == 0) {
1474                 /* Constant expression */
1475                 lval->e_const = !lval->e_const;
1476             } else {
1477                 g_bneg (TypeOf (lval->e_tptr));
1478                 lval->e_test |= E_CC;                   /* bneg will set cc */
1479                 lval->e_flags = E_MEXPR;                /* say it's an expr */
1480             }
1481             return 0;                           /* expr not storable */
1482
1483         case TOK_STAR:
1484             NextToken ();
1485             if (evalexpr (CF_NONE, hie10, lval) != 0) {
1486                 /* Expression is not const, indirect value loaded into primary */
1487                 lval->e_flags = E_MEXPR;
1488                 lval->e_const = 0;              /* Offset is zero now */
1489             }
1490             t = lval->e_tptr;
1491             if (IsClassPtr (t)) {
1492                 lval->e_tptr = Indirect (t);
1493             } else {
1494                 Error (ERR_ILLEGAL_INDIRECT);
1495             }
1496             return 1;
1497
1498         case TOK_AND:
1499             NextToken ();
1500             k = hie10 (lval);
1501             if (k == 0) {
1502                 /* Allow the & operator with an array */
1503                 if (!IsTypeArray (lval->e_tptr)) {
1504                     Error (ERR_ILLEGAL_ADDRESS);
1505                 }
1506             } else {
1507                 t = TypeAlloc (TypeLen (lval->e_tptr) + 2);
1508                 t [0] = T_PTR;
1509                 TypeCpy (t + 1, lval->e_tptr);
1510                 lval->e_tptr = t;
1511             }
1512             return 0;
1513
1514         case TOK_SIZEOF:
1515             NextToken ();
1516             if (istypeexpr ()) {
1517                 type Type[MAXTYPELEN];
1518                 NextToken ();
1519                 lval->e_const = SizeOf (ParseType (Type));
1520                 ConsumeRParen ();
1521             } else {
1522                 /* Remember the output queue pointer */
1523                 CodeMark Mark = GetCodePos ();
1524                 hie10 (lval);
1525                 lval->e_const = SizeOf (lval->e_tptr);
1526                 /* Remove any generated code */
1527                 RemoveCode (Mark);
1528             }
1529             lval->e_flags = E_MCONST | E_TCONST;
1530             lval->e_tptr = type_uint;
1531             lval->e_test &= ~E_CC;
1532             return 0;
1533
1534         default:
1535             if (istypeexpr ()) {
1536                 /* A cast */
1537                 return typecast (lval);
1538             }
1539     }
1540
1541     k = hie11 (lval);
1542     switch (curtok) {
1543         case TOK_INC:
1544             post_incdec (lval, k, g_inc);
1545             return 0;
1546
1547         case TOK_DEC:
1548             post_incdec (lval, k, g_dec);
1549             return 0;
1550
1551         default:
1552             return k;
1553     }
1554 }
1555
1556
1557
1558 static int hie_internal (GenDesc** ops,         /* List of generators */
1559                          struct expent* lval,   /* parent expr's lval */
1560                          int (*hienext) (struct expent*),
1561                          int* UsedGen)          /* next higher level */
1562 /* Helper function */
1563 {
1564     int k;
1565     struct expent lval2;
1566     CodeMark Mark1;
1567     CodeMark Mark2;
1568     GenDesc* Gen;
1569     token_t tok;                        /* The operator token */
1570     unsigned ltype, type;
1571     int rconst;                         /* Operand is a constant */
1572
1573
1574     k = hienext (lval);
1575
1576     *UsedGen = 0;
1577     while ((Gen = FindGen (curtok, ops)) != 0) {
1578
1579         /* Tell the caller that we handled it's ops */
1580         *UsedGen = 1;
1581
1582         /* All operators that call this function expect an int on the lhs */
1583         if (!IsClassInt (lval->e_tptr)) {
1584             Error (ERR_INT_EXPR_EXPECTED);
1585         }
1586
1587         /* Remember the operator token, then skip it */
1588         tok = curtok;
1589         NextToken ();
1590
1591         /* Get the lhs on stack */
1592         Mark1 = GetCodePos ();
1593         ltype = TypeOf (lval->e_tptr);
1594         if (k == 0 && lval->e_flags == E_MCONST) {
1595             /* Constant value */
1596             Mark2 = GetCodePos ();
1597             g_push (ltype | CF_CONST, lval->e_const);
1598         } else {
1599             /* Value not constant */
1600             exprhs (CF_NONE, k, lval);
1601             Mark2 = GetCodePos ();
1602             g_push (ltype, 0);
1603         }
1604
1605         /* Get the right hand side */
1606         rconst = (evalexpr (CF_NONE, hienext, &lval2) == 0);
1607
1608         /* Check the type of the rhs */
1609         if (!IsClassInt (lval2.e_tptr)) {
1610             Error (ERR_INT_EXPR_EXPECTED);
1611         }
1612
1613         /* Check for const operands */
1614         if (k == 0 && lval->e_flags == E_MCONST && rconst) {
1615
1616             /* Both operands are constant, remove the generated code */
1617             RemoveCode (Mark1);
1618             pop (ltype);
1619
1620             /* Evaluate the result */
1621             lval->e_const = kcalc (tok, lval->e_const, lval2.e_const);
1622
1623             /* Get the type of the result */
1624             lval->e_tptr = promoteint (lval->e_tptr, lval2.e_tptr);
1625
1626         } else {
1627
1628             /* If the right hand side is constant, and the generator function
1629              * expects the lhs in the primary, remove the push of the primary
1630              * now.
1631              */
1632             unsigned rtype = TypeOf (lval2.e_tptr);
1633             type = 0;
1634             if (rconst) {
1635                 /* Second value is constant - check for div */
1636                 type |= CF_CONST;
1637                 rtype |= CF_CONST;
1638                 if (tok == TOK_DIV && lval2.e_const == 0) {
1639                     Error (ERR_DIV_BY_ZERO);
1640                 } else if (tok == TOK_MOD && lval2.e_const == 0) {
1641                     Error (ERR_MOD_BY_ZERO);
1642                 }
1643                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1644                     RemoveCode (Mark2);
1645                     pop (ltype);
1646                     ltype |= CF_REG;    /* Value is in register */
1647                 }
1648             }
1649
1650             /* Determine the type of the operation result. */
1651             type |= g_typeadjust (ltype, rtype);
1652             lval->e_tptr = promoteint (lval->e_tptr, lval2.e_tptr);
1653
1654             /* Generate code */
1655             Gen->Func (type, lval2.e_const);
1656             lval->e_flags = E_MEXPR;
1657         }
1658
1659         /* We have a rvalue now */
1660         k = 0;
1661     }
1662
1663     return k;
1664 }
1665
1666
1667
1668 static int hie_compare (GenDesc** ops,          /* List of generators */
1669                         struct expent* lval,    /* parent expr's lval */
1670                         int (*hienext) (struct expent*))
1671 /* Helper function for the compare operators */
1672 {
1673     int k;
1674     struct expent lval2;
1675     CodeMark Mark1;
1676     CodeMark Mark2;
1677     GenDesc* Gen;
1678     token_t tok;                        /* The operator token */
1679     unsigned ltype;
1680     int rconst;                         /* Operand is a constant */
1681
1682
1683     k = hienext (lval);
1684
1685     while ((Gen = FindGen (curtok, ops)) != 0) {
1686
1687         /* Remember the operator token, then skip it */
1688         tok = curtok;
1689         NextToken ();
1690
1691         /* Get the lhs on stack */
1692         Mark1 = GetCodePos ();
1693         ltype = TypeOf (lval->e_tptr);
1694         if (k == 0 && lval->e_flags == E_MCONST) {
1695             /* Constant value */
1696             Mark2 = GetCodePos ();
1697             g_push (ltype | CF_CONST, lval->e_const);
1698         } else {
1699             /* Value not constant */
1700             exprhs (CF_NONE, k, lval);
1701             Mark2 = GetCodePos ();
1702             g_push (ltype, 0);
1703         }
1704
1705         /* Get the right hand side */
1706         rconst = (evalexpr (CF_NONE, hienext, &lval2) == 0);
1707
1708         /* Make sure, the types are compatible */
1709         if (IsClassInt (lval->e_tptr)) {
1710             if (!IsClassInt (lval2.e_tptr) && !(IsClassPtr(lval2.e_tptr) && IsNullPtr(lval))) {
1711                 Error (ERR_INCOMPATIBLE_TYPES);
1712             }
1713         } else if (IsClassPtr (lval->e_tptr)) {
1714             if (IsClassPtr (lval2.e_tptr)) {
1715                 /* Both pointers are allowed in comparison if they point to
1716                  * the same type, or if one of them is a void pointer.
1717                  */
1718                 type* left  = Indirect (lval->e_tptr);
1719                 type* right = Indirect (lval2.e_tptr);
1720                 if (TypeCmp (left, right) < TC_EQUAL && *left != T_VOID && *right != T_VOID) {
1721                     /* Incomatible pointers */
1722                     Error (ERR_INCOMPATIBLE_TYPES);
1723                 }
1724             } else if (!IsNullPtr (&lval2)) {
1725                 Error (ERR_INCOMPATIBLE_TYPES);
1726             }
1727         }
1728
1729         /* Check for const operands */
1730         if (k == 0 && lval->e_flags == E_MCONST && rconst) {
1731
1732             /* Both operands are constant, remove the generated code */
1733             RemoveCode (Mark1);
1734             pop (ltype);
1735
1736             /* Evaluate the result */
1737             lval->e_const = kcalc (tok, lval->e_const, lval2.e_const);
1738
1739         } else {
1740
1741             /* If the right hand side is constant, and the generator function
1742              * expects the lhs in the primary, remove the push of the primary
1743              * now.
1744              */
1745             unsigned flags = 0;
1746             if (rconst) {
1747                 flags |= CF_CONST;
1748                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1749                     RemoveCode (Mark2);
1750                     pop (ltype);
1751                     ltype |= CF_REG;    /* Value is in register */
1752                 }
1753             }
1754
1755             /* Determine the type of the operation result. If the left
1756              * operand is of type char and the right is a constant, or
1757              * if both operands are of type char, we will encode the
1758              * operation as char operation. Otherwise the default
1759              * promotions are used.
1760              */
1761             if (IsTypeChar (lval->e_tptr) && (IsTypeChar (lval2.e_tptr) || rconst)) {
1762                 flags |= CF_CHAR;
1763                 if (IsSignUnsigned (lval->e_tptr) || IsSignUnsigned (lval2.e_tptr)) {
1764                     flags |= CF_UNSIGNED;
1765                 }
1766                 if (rconst) {
1767                     flags |= CF_FORCECHAR;
1768                 }
1769             } else {
1770                 unsigned rtype = TypeOf (lval2.e_tptr) | (flags & CF_CONST);
1771                 flags |= g_typeadjust (ltype, rtype);
1772             }
1773
1774             /* Generate code */
1775             Gen->Func (flags, lval2.e_const);
1776             lval->e_flags = E_MEXPR;
1777         }
1778
1779         /* Result type is always int */
1780         lval->e_tptr = type_int;
1781
1782         /* We have a rvalue now, condition codes are set */
1783         k = 0;
1784         lval->e_test |= E_CC;
1785     }
1786
1787     return k;
1788 }
1789
1790
1791
1792 static int hie9 (struct expent *lval)
1793 /* Process * and / operators. */
1794 {
1795     static GenDesc* hie9_ops [] = {
1796         &GenMUL, &GenDIV, &GenMOD, 0
1797     };
1798     int UsedGen;
1799
1800     return hie_internal (hie9_ops, lval, hie10, &UsedGen);
1801 }
1802
1803
1804
1805 static void parseadd (int k, struct expent* lval)
1806 /* Parse an expression with the binary plus operator. lval contains the
1807  * unprocessed left hand side of the expression and will contain the
1808  * result of the expression on return.
1809  */
1810 {
1811     struct expent lval2;
1812     unsigned flags;             /* Operation flags */
1813     CodeMark Mark;              /* Remember code position */
1814     type* lhst;                 /* Type of left hand side */
1815     type* rhst;                 /* Type of right hand side */
1816
1817
1818     /* Skip the PLUS token */
1819     NextToken ();
1820
1821     /* Get the left hand side type, initialize operation flags */
1822     lhst = lval->e_tptr;
1823     flags = 0;
1824
1825     /* Check for constness on both sides */
1826     if (k == 0 && lval->e_flags == E_MCONST) {
1827
1828         /* The left hand side is a constant. Good. Get rhs */
1829         if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
1830
1831             /* Right hand side is also constant. Get the rhs type */
1832             rhst = lval2.e_tptr;
1833
1834             /* Both expressions are constants. Check for pointer arithmetic */
1835             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1836                 /* Left is pointer, right is int, must scale rhs */
1837                 lval->e_const = lval->e_const + lval2.e_const * PSizeOf (lhst);
1838                 /* Result type is a pointer */
1839             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1840                 /* Left is int, right is pointer, must scale lhs */
1841                 lval->e_const = lval->e_const * PSizeOf (rhst) + lval2.e_const;
1842                 /* Result type is a pointer */
1843                 lval->e_tptr = lval2.e_tptr;
1844             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1845                 /* Integer addition */
1846                 lval->e_const += lval2.e_const;
1847                 typeadjust (lval, &lval2, 1);
1848             } else {
1849                 /* OOPS */
1850                 Error (ERR_OP_NOT_ALLOWED);
1851             }
1852
1853             /* Result is constant, condition codes not set */
1854             lval->e_test = E_MCONST;
1855
1856         } else {
1857
1858             /* lhs is constant, rhs is not. Get the rhs type. */
1859             rhst = lval2.e_tptr;
1860
1861             /* Check for pointer arithmetic */
1862             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1863                 /* Left is pointer, right is int, must scale rhs */
1864                 g_scale (CF_INT, PSizeOf (lhst));
1865                 /* Operate on pointers, result type is a pointer */
1866                 flags = CF_PTR;
1867             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1868                 /* Left is int, right is pointer, must scale lhs */
1869                 lval->e_const *= PSizeOf (rhst);
1870                 /* Operate on pointers, result type is a pointer */
1871                 flags = CF_PTR;
1872                 lval->e_tptr = lval2.e_tptr;
1873             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1874                 /* Integer addition */
1875                 flags = typeadjust (lval, &lval2, 1);
1876             } else {
1877                 /* OOPS */
1878                 Error (ERR_OP_NOT_ALLOWED);
1879             }
1880
1881             /* Generate code for the add */
1882             g_inc (flags | CF_CONST, lval->e_const);
1883
1884             /* Result is in primary register */
1885             lval->e_flags = E_MEXPR;
1886             lval->e_test &= ~E_CC;
1887
1888         }
1889
1890     } else {
1891
1892         /* Left hand side is not constant. Get the value onto the stack. */
1893         exprhs (CF_NONE, k, lval);              /* --> primary register */
1894         Mark = GetCodePos ();
1895         g_push (TypeOf (lval->e_tptr), 0);      /* --> stack */
1896
1897         /* Evaluate the rhs */
1898         if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
1899
1900             /* Right hand side is a constant. Get the rhs type */
1901             rhst = lval2.e_tptr;
1902
1903             /* Remove pushed value from stack */
1904             RemoveCode (Mark);
1905             pop (TypeOf (lval->e_tptr));
1906
1907             /* Check for pointer arithmetic */
1908             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1909                 /* Left is pointer, right is int, must scale rhs */
1910                 lval2.e_const *= PSizeOf (lhst);
1911                 /* Operate on pointers, result type is a pointer */
1912                 flags = CF_PTR;
1913             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1914                 /* Left is int, right is pointer, must scale lhs (ptr only) */
1915                 g_scale (CF_INT | CF_CONST, PSizeOf (rhst));
1916                 /* Operate on pointers, result type is a pointer */
1917                 flags = CF_PTR;
1918                 lval->e_tptr = lval2.e_tptr;
1919             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1920                 /* Integer addition */
1921                 flags = typeadjust (lval, &lval2, 1);
1922             } else {
1923                 /* OOPS */
1924                 Error (ERR_OP_NOT_ALLOWED);
1925             }
1926
1927             /* Generate code for the add */
1928             g_inc (flags | CF_CONST, lval2.e_const);
1929
1930             /* Result is in primary register */
1931             lval->e_flags = E_MEXPR;
1932             lval->e_test &= ~E_CC;
1933
1934         } else {
1935
1936             /* lhs and rhs are not constant. Get the rhs type. */
1937             rhst = lval2.e_tptr;
1938
1939             /* Check for pointer arithmetic */
1940             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1941                 /* Left is pointer, right is int, must scale rhs */
1942                 g_scale (CF_INT, PSizeOf (lhst));
1943                 /* Operate on pointers, result type is a pointer */
1944                 flags = CF_PTR;
1945             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1946                 /* Left is int, right is pointer, must scale lhs */
1947                 g_tosint (TypeOf (rhst));       /* Make sure, TOS is int */
1948                 g_swap (CF_INT);                /* Swap TOS and primary */
1949                 g_scale (CF_INT, PSizeOf (rhst));
1950                 /* Operate on pointers, result type is a pointer */
1951                 flags = CF_PTR;
1952                 lval->e_tptr = lval2.e_tptr;
1953             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1954                 /* Integer addition */
1955                 flags = typeadjust (lval, &lval2, 0);
1956             } else {
1957                 /* OOPS */
1958                 Error (ERR_OP_NOT_ALLOWED);
1959             }
1960
1961             /* Generate code for the add */
1962             g_add (flags, 0);
1963
1964             /* Result is in primary register */
1965             lval->e_flags = E_MEXPR;
1966             lval->e_test &= ~E_CC;
1967
1968         }
1969
1970     }
1971 }
1972
1973
1974
1975 static void parsesub (int k, struct expent* lval)
1976 /* Parse an expression with the binary minus operator. lval contains the
1977  * unprocessed left hand side of the expression and will contain the
1978  * result of the expression on return.
1979  */
1980 {
1981     struct expent lval2;
1982     unsigned flags;             /* Operation flags */
1983     type* lhst;                 /* Type of left hand side */
1984     type* rhst;                 /* Type of right hand side */
1985     CodeMark Mark1;             /* Save position of output queue */
1986     CodeMark Mark2;             /* Another position in the queue */
1987     int rscale;                 /* Scale factor for the result */
1988
1989
1990     /* Skip the MINUS token */
1991     NextToken ();
1992
1993     /* Get the left hand side type, initialize operation flags */
1994     lhst = lval->e_tptr;
1995     flags = 0;
1996     rscale = 1;                 /* Scale by 1, that is, don't scale */
1997
1998     /* Remember the output queue position, then bring the value onto the stack */
1999     Mark1 = GetCodePos ();
2000     exprhs (CF_NONE, k, lval);  /* --> primary register */
2001     Mark2 = GetCodePos ();
2002     g_push (TypeOf (lhst), 0);  /* --> stack */
2003
2004     /* Parse the right hand side */
2005     if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
2006
2007         /* The right hand side is constant. Get the rhs type. */
2008         rhst = lval2.e_tptr;
2009
2010         /* Check left hand side */
2011         if (k == 0 && lval->e_flags & E_MCONST) {
2012
2013             /* Both sides are constant, remove generated code */
2014             RemoveCode (Mark1);
2015             pop (TypeOf (lhst));        /* Clean up the stack */
2016
2017             /* Check for pointer arithmetic */
2018             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2019                 /* Left is pointer, right is int, must scale rhs */
2020                 lval->e_const -= lval2.e_const * PSizeOf (lhst);
2021                 /* Operate on pointers, result type is a pointer */
2022             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2023                 /* Left is pointer, right is pointer, must scale result */
2024                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2025                     Error (ERR_INCOMPATIBLE_POINTERS);
2026                 } else {
2027                     lval->e_const = (lval->e_const - lval2.e_const) / PSizeOf (lhst);
2028                 }
2029                 /* Operate on pointers, result type is an integer */
2030                 lval->e_tptr = type_int;
2031             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2032                 /* Integer subtraction */
2033                 typeadjust (lval, &lval2, 1);
2034                 lval->e_const -= lval2.e_const;
2035             } else {
2036                 /* OOPS */
2037                 Error (ERR_OP_NOT_ALLOWED);
2038             }
2039
2040             /* Result is constant, condition codes not set */
2041             lval->e_flags = E_MCONST;
2042             lval->e_test &= ~E_CC;
2043
2044         } else {
2045
2046             /* Left hand side is not constant, right hand side is.
2047              * Remove pushed value from stack.
2048              */
2049             RemoveCode (Mark2);
2050             pop (TypeOf (lhst));
2051
2052             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2053                 /* Left is pointer, right is int, must scale rhs */
2054                 lval2.e_const *= PSizeOf (lhst);
2055                 /* Operate on pointers, result type is a pointer */
2056                 flags = CF_PTR;
2057             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2058                 /* Left is pointer, right is pointer, must scale result */
2059                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2060                     Error (ERR_INCOMPATIBLE_POINTERS);
2061                 } else {
2062                     rscale = PSizeOf (lhst);
2063                 }
2064                 /* Operate on pointers, result type is an integer */
2065                 flags = CF_PTR;
2066                 lval->e_tptr = type_int;
2067             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2068                 /* Integer subtraction */
2069                 flags = typeadjust (lval, &lval2, 1);
2070             } else {
2071                 /* OOPS */
2072                 Error (ERR_OP_NOT_ALLOWED);
2073             }
2074
2075             /* Do the subtraction */
2076             g_dec (flags | CF_CONST, lval2.e_const);
2077
2078             /* If this was a pointer subtraction, we must scale the result */
2079             if (rscale != 1) {
2080                 g_scale (flags, -rscale);
2081             }
2082
2083             /* Result is in primary register */
2084             lval->e_flags = E_MEXPR;
2085             lval->e_test &= ~E_CC;
2086
2087         }
2088
2089     } else {
2090
2091         /* Right hand side is not constant. Get the rhs type. */
2092         rhst = lval2.e_tptr;
2093
2094         /* Check for pointer arithmetic */
2095         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2096             /* Left is pointer, right is int, must scale rhs */
2097             g_scale (CF_INT, PSizeOf (lhst));
2098             /* Operate on pointers, result type is a pointer */
2099             flags = CF_PTR;
2100         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2101             /* Left is pointer, right is pointer, must scale result */
2102             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2103                 Error (ERR_INCOMPATIBLE_POINTERS);
2104             } else {
2105                 rscale = PSizeOf (lhst);
2106             }
2107             /* Operate on pointers, result type is an integer */
2108             flags = CF_PTR;
2109             lval->e_tptr = type_int;
2110         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2111             /* Integer subtraction. If the left hand side descriptor says that
2112              * the lhs is const, we have to remove this mark, since this is no
2113              * longer true, lhs is on stack instead.
2114              */
2115             if (lval->e_flags == E_MCONST) {
2116                 lval->e_flags = E_MEXPR;
2117             }
2118             /* Adjust operand types */
2119             flags = typeadjust (lval, &lval2, 0);
2120         } else {
2121             /* OOPS */
2122             Error (ERR_OP_NOT_ALLOWED);
2123         }
2124
2125         /* Generate code for the sub (the & is a hack here) */
2126         g_sub (flags & ~CF_CONST, 0);
2127
2128         /* If this was a pointer subtraction, we must scale the result */
2129         if (rscale != 1) {
2130             g_scale (flags, -rscale);
2131         }
2132
2133         /* Result is in primary register */
2134         lval->e_flags = E_MEXPR;
2135         lval->e_test &= ~E_CC;
2136     }
2137 }
2138
2139
2140
2141 static int hie8 (struct expent* lval)
2142 /* Process + and - binary operators. */
2143 {
2144     int k = hie9 (lval);
2145     while (curtok == TOK_PLUS || curtok == TOK_MINUS) {
2146
2147         if (curtok == TOK_PLUS) {
2148             parseadd (k, lval);
2149         } else {
2150             parsesub (k, lval);
2151         }
2152         k = 0;
2153     }
2154     return k;
2155 }
2156
2157
2158
2159
2160 static int hie7 (struct expent *lval)
2161 /* Parse << and >>. */
2162 {
2163     static GenDesc* hie7_ops [] = {
2164         &GenASL, &GenASR, 0
2165     };
2166     int UsedGen;
2167
2168     return hie_internal (hie7_ops, lval, hie8, &UsedGen);
2169 }
2170
2171
2172
2173 static int hie6 (struct expent *lval)
2174 /* process greater-than type comparators */
2175 {
2176     static GenDesc* hie6_ops [] = {
2177         &GenLT, &GenLE, &GenGE, &GenGT, 0
2178     };
2179     return hie_compare (hie6_ops, lval, hie7);
2180 }
2181
2182
2183
2184 static int hie5 (struct expent *lval)
2185 {
2186     static GenDesc* hie5_ops[] = {
2187         &GenEQ, &GenNE, 0
2188     };
2189     return hie_compare (hie5_ops, lval, hie6);
2190 }
2191
2192
2193
2194 static int hie4 (struct expent* lval)
2195 /* Handle & (bitwise and) */
2196 {
2197     static GenDesc* hie4_ops [] = {
2198         &GenAND, 0
2199     };
2200     int UsedGen;
2201
2202     return hie_internal (hie4_ops, lval, hie5, &UsedGen);
2203 }
2204
2205
2206
2207 static int hie3 (struct expent *lval)
2208 /* Handle ^ (bitwise exclusive or) */
2209 {
2210     static GenDesc* hie3_ops [] = {
2211         &GenXOR, 0
2212     };
2213     int UsedGen;
2214
2215     return hie_internal (hie3_ops, lval, hie4, &UsedGen);
2216 }
2217
2218
2219
2220 static int hie2 (struct expent *lval)
2221 /* Handle | (bitwise or) */
2222 {
2223     static GenDesc* hie2_ops [] = {
2224         &GenOR, 0
2225     };
2226     int UsedGen;
2227
2228     return hie_internal (hie2_ops, lval, hie3, &UsedGen);
2229 }
2230
2231
2232
2233 static int hieAnd (struct expent* lval, unsigned TrueLab, int* BoolOp)
2234 /* Process "exp && exp" */
2235 {
2236     int k;
2237     int lab;
2238     struct expent lval2;
2239
2240     k = hie2 (lval);
2241     if (curtok == TOK_BOOL_AND) {
2242
2243         /* Tell our caller that we're evaluating a boolean */
2244         *BoolOp = 1;
2245
2246         /* Get a label that we will use for false expressions */
2247         lab = GetLabel ();
2248
2249         /* If the expr hasn't set condition codes, set the force-test flag */
2250         if ((lval->e_test & E_CC) == 0) {
2251             lval->e_test |= E_FORCETEST;
2252         }
2253
2254         /* Load the value */
2255         exprhs (CF_FORCECHAR, k, lval);
2256
2257         /* Generate the jump */
2258         g_falsejump (CF_NONE, lab);
2259
2260         /* Parse more boolean and's */
2261         while (curtok == TOK_BOOL_AND) {
2262
2263             /* Skip the && */
2264             NextToken ();
2265
2266             /* Get rhs */
2267             k = hie2 (&lval2);
2268             if ((lval2.e_test & E_CC) == 0) {
2269                 lval2.e_test |= E_FORCETEST;
2270             }
2271             exprhs (CF_FORCECHAR, k, &lval2);
2272
2273             /* Do short circuit evaluation */
2274             if (curtok == TOK_BOOL_AND) {
2275                 g_falsejump (CF_NONE, lab);
2276             } else {
2277                 /* Last expression - will evaluate to true */
2278                 g_truejump (CF_NONE, TrueLab);
2279             }
2280         }
2281
2282         /* Define the false jump label here */
2283         g_defloclabel (lab);
2284
2285         /* Define the label */
2286         lval->e_flags = E_MEXPR;
2287         lval->e_test |= E_CC;   /* Condition codes are set */
2288         k = 0;
2289     }
2290     return k;
2291 }
2292
2293
2294
2295 static int hieOr (struct expent *lval)
2296 /* Process "exp || exp". */
2297 {
2298     int k;
2299     struct expent lval2;
2300     int BoolOp = 0;             /* Did we have a boolean op? */
2301     int AndOp;                  /* Did we have a && operation? */
2302     unsigned TrueLab;           /* Jump to this label if true */
2303     unsigned DoneLab;
2304
2305     /* Get a label */
2306     TrueLab = GetLabel ();
2307
2308     /* Call the next level parser */
2309     k = hieAnd (lval, TrueLab, &BoolOp);
2310
2311     /* Any boolean or's? */
2312     if (curtok == TOK_BOOL_OR) {
2313
2314         /* If the expr hasn't set condition codes, set the force-test flag */
2315         if ((lval->e_test & E_CC) == 0) {
2316             lval->e_test |= E_FORCETEST;
2317         }
2318
2319         /* Get first expr */
2320         exprhs (CF_FORCECHAR, k, lval);
2321
2322         /* For each expression jump to TrueLab if true. Beware: If we
2323          * had && operators, the jump is already in place!
2324          */
2325         if (!BoolOp) {
2326             g_truejump (CF_NONE, TrueLab);
2327         }
2328
2329         /* Remember that we had a boolean op */
2330         BoolOp = 1;
2331
2332         /* while there's more expr */
2333         while (curtok == TOK_BOOL_OR) {
2334
2335             /* skip the || */
2336             NextToken ();
2337
2338             /* Get a subexpr */
2339             AndOp = 0;
2340             k = hieAnd (&lval2, TrueLab, &AndOp);
2341             if ((lval2.e_test & E_CC) == 0) {
2342                 lval2.e_test |= E_FORCETEST;
2343             }
2344             exprhs (CF_FORCECHAR, k, &lval2);
2345
2346             /* If there is more to come, add shortcut boolean eval.
2347              * Beware: If we had && operators, the jump is already
2348              * in place!
2349              */
2350 #if     0
2351 /* Seems this sometimes generates wrong code */
2352             if (curtok == TOK_BOOL_OR && !AndOp) {
2353                 g_truejump (CF_NONE, TrueLab);
2354             }
2355 #else
2356             g_truejump (CF_NONE, TrueLab);
2357 #endif
2358         }
2359         lval->e_flags = E_MEXPR;
2360         lval->e_test |= E_CC;                   /* Condition codes are set */
2361         k = 0;
2362     }
2363
2364     /* If we really had boolean ops, generate the end sequence */
2365     if (BoolOp) {
2366         DoneLab = GetLabel ();
2367         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
2368         g_falsejump (CF_NONE, DoneLab);
2369         g_defloclabel (TrueLab);
2370         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
2371         g_defloclabel (DoneLab);
2372     }
2373     return k;
2374 }
2375
2376
2377
2378 static int hieQuest (struct expent *lval)
2379 /* Parse "lvalue ? exp : exp" */
2380 {
2381     int k;
2382     int labf;
2383     int labt;
2384     struct expent lval2;        /* Expression 2 */
2385     struct expent lval3;        /* Expression 3 */
2386     type* type2;                /* Type of expression 2 */
2387     type* type3;                /* Type of expression 3 */
2388     type* rtype;                /* Type of result */
2389     CodeMark Mark1;             /* Save position in output code */
2390     CodeMark Mark2;             /* Save position in output code */
2391
2392
2393
2394     k = hieOr (lval);
2395     if (curtok == TOK_QUEST) {
2396         NextToken ();
2397         if ((lval->e_test & E_CC) == 0) {
2398             /* Condition codes not set, force a test */
2399             lval->e_test |= E_FORCETEST;
2400         }
2401         exprhs (CF_NONE, k, lval);
2402         labf = GetLabel ();
2403         g_falsejump (CF_NONE, labf);
2404
2405         /* Parse second and third expression */
2406         expression1 (&lval2);
2407         labt = GetLabel ();
2408         ConsumeColon ();
2409         g_jump (labt);
2410         g_defloclabel (labf);
2411         expression1 (&lval3);
2412
2413         /* Check if any conversions are needed, if so, do them.
2414          * Conversion rules for ?: expression are:
2415          *   - if both expressions are int expressions, default promotion
2416          *     rules for ints apply.
2417          *   - if both expressions are pointers of the same type, the
2418          *     result of the expression is of this type.
2419          *   - if one of the expressions is a pointer and the other is
2420          *     a zero constant, the resulting type is that of the pointer
2421          *     type.
2422          *   - all other cases are flagged by an error.
2423          */
2424         type2 = lval2.e_tptr;
2425         type3 = lval3.e_tptr;
2426         if (IsClassInt (type2) && IsClassInt (type3)) {
2427
2428             /* Get common type */
2429             rtype = promoteint (type2, type3);
2430
2431             /* Convert the third expression to this type if needed */
2432             g_typecast (TypeOf (rtype), TypeOf (type3));
2433
2434             /* Setup a new label so that the expr3 code will jump around
2435              * the type cast code for expr2.
2436              */
2437             labf = GetLabel ();         /* Get new label */
2438             Mark1 = GetCodePos ();      /* Remember current position */
2439             g_jump (labf);              /* Jump around code */
2440
2441             /* The jump for expr2 goes here */
2442             g_defloclabel (labt);
2443
2444             /* Create the typecast code for expr2 */
2445             Mark2 = GetCodePos ();      /* Remember position */
2446             g_typecast (TypeOf (rtype), TypeOf (type2));
2447
2448             /* If the typecast did not produce code, remove the jump,
2449              * otherwise output the label.
2450              */
2451             if (GetCodePos() == Mark2) {
2452                 RemoveCode (Mark1);     /* Remove code */
2453             } else {
2454                 /* We have typecast code, output label */
2455                 g_defloclabel (labf);
2456                 labt = 0;               /* Mark other label as invalid */
2457             }
2458
2459         } else if (IsClassPtr (type2) && IsClassPtr (type3)) {
2460             /* Must point to same type */
2461             if (TypeCmp (Indirect (type2), Indirect (type3)) < TC_EQUAL) {
2462                 Error (ERR_INCOMPATIBLE_TYPES);
2463             }
2464             /* Result has the common type */
2465             rtype = lval2.e_tptr;
2466         } else if (IsClassPtr (type2) && IsNullPtr (&lval3)) {
2467             /* Result type is pointer, no cast needed */
2468             rtype = lval2.e_tptr;
2469         } else if (IsNullPtr (&lval2) && IsClassPtr (type3)) {
2470             /* Result type is pointer, no cast needed */
2471             rtype = lval3.e_tptr;
2472         } else {
2473             Error (ERR_INCOMPATIBLE_TYPES);
2474             rtype = lval2.e_tptr;               /* Doesn't matter here */
2475         }
2476
2477         /* If we don't have the label defined until now, do it */
2478         if (labt) {
2479             g_defloclabel (labt);
2480         }
2481
2482         /* Setup the target expression */
2483         lval->e_flags = E_MEXPR;
2484         lval->e_tptr = rtype;
2485         k = 0;
2486     }
2487     return k;
2488 }
2489
2490
2491
2492 static void opeq (GenDesc* Gen, struct expent *lval, int k)
2493 /* Process "op=" operators. */
2494 {
2495     struct expent lval2;
2496     unsigned flags;
2497     CodeMark Mark;
2498     int MustScale;
2499
2500     NextToken ();
2501     if (k == 0) {
2502         Error (ERR_LVALUE_EXPECTED);
2503         return;
2504     }
2505
2506     /* Determine the type of the lhs */
2507     flags = TypeOf (lval->e_tptr);
2508     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) &&
2509                 lval->e_tptr [0] == T_PTR;
2510
2511     /* Get the lhs address on stack (if needed) */
2512     PushAddr (lval);
2513
2514     /* Fetch the lhs into the primary register if needed */
2515     exprhs (CF_NONE, k, lval);
2516
2517     /* Bring the lhs on stack */
2518     Mark = GetCodePos ();
2519     g_push (flags, 0);
2520
2521     /* Evaluate the rhs */
2522     if (evalexpr (CF_NONE, hie1, &lval2) == 0) {
2523         /* The resulting value is a constant. If the generator has the NOPUSH
2524          * flag set, don't push the lhs.
2525          */
2526         if (Gen->Flags & GEN_NOPUSH) {
2527             RemoveCode (Mark);
2528             pop (flags);
2529         }
2530         if (MustScale) {
2531             /* lhs is a pointer, scale rhs */
2532             lval2.e_const *= SizeOf (lval->e_tptr+1);
2533         }
2534
2535         /* If the lhs is character sized, the operation may be later done
2536          * with characters.
2537          */
2538         if (SizeOf (lval->e_tptr) == 1) {
2539             flags |= CF_FORCECHAR;
2540         }
2541
2542         /* Special handling for add and sub - some sort of a hack, but short code */
2543         if (Gen->Func == g_add) {
2544             g_inc (flags | CF_CONST, lval2.e_const);
2545         } else if (Gen->Func == g_sub) {
2546             g_dec (flags | CF_CONST, lval2.e_const);
2547         } else {
2548             Gen->Func (flags | CF_CONST, lval2.e_const);
2549         }
2550     } else {
2551         /* rhs is not constant and already in the primary register */
2552         if (MustScale) {
2553             /* lhs is a pointer, scale rhs */
2554             g_scale (TypeOf (lval2.e_tptr), SizeOf (lval->e_tptr+1));
2555         }
2556
2557         /* If the lhs is character sized, the operation may be later done
2558          * with characters.
2559          */
2560         if (SizeOf (lval->e_tptr) == 1) {
2561             flags |= CF_FORCECHAR;
2562         }
2563
2564         /* Adjust the types of the operands if needed */
2565         Gen->Func (g_typeadjust (flags, TypeOf (lval2.e_tptr)), 0);
2566     }
2567     store (lval);
2568     lval->e_flags = E_MEXPR;
2569 }
2570
2571
2572
2573 static void addsubeq (GenDesc* Gen, struct expent *lval, int k)
2574 /* Process the += and -= operators */
2575 {
2576     struct expent lval2;
2577     unsigned flags;
2578     int MustScale;
2579
2580
2581     if (k == 0) {
2582         Error (ERR_LVALUE_EXPECTED);
2583         return;
2584     }
2585
2586
2587     /* We're currently only able to handle some adressing modes */
2588     if ((lval->e_flags & E_MGLOBAL) == 0 &&     /* Global address? */
2589         (lval->e_flags & E_MLOCAL) == 0  &&     /* Local address? */
2590         (lval->e_flags & E_MCONST) == 0) {      /* Constant address? */
2591         /* Use generic routine */
2592         opeq (Gen, lval, k);
2593         return;
2594     }
2595
2596     /* Skip the operator */
2597     NextToken ();
2598
2599     /* Check if we have a pointer expression and must scale rhs */
2600     MustScale = (lval->e_tptr [0] == T_PTR);
2601
2602     /* Determine the code generator flags */
2603     flags = TypeOf (lval->e_tptr) | CF_FORCECHAR;
2604
2605     /* Evaluate the rhs */
2606     if (evalexpr (CF_NONE, hie1, &lval2) == 0) {
2607         /* The resulting value is a constant. */
2608         if (MustScale) {
2609             /* lhs is a pointer, scale rhs */
2610             lval2.e_const *= SizeOf (lval->e_tptr+1);
2611         }
2612         flags |= CF_CONST;
2613     } else {
2614         /* rhs is not constant and already in the primary register */
2615         if (MustScale) {
2616             /* lhs is a pointer, scale rhs */
2617             g_scale (TypeOf (lval2.e_tptr), SizeOf (lval->e_tptr+1));
2618         }
2619     }
2620
2621     /* Adjust the rhs to the lhs */
2622     g_typeadjust (flags, TypeOf (lval2.e_tptr));
2623
2624     /* Output apropriate code */
2625     if (lval->e_flags & E_MGLOBAL) {
2626         /* Static variable */
2627         flags |= GlobalModeFlags (lval->e_flags);
2628         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2629             g_addeqstatic (flags, lval->e_name, lval->e_const, lval2.e_const);
2630         } else {
2631             g_subeqstatic (flags, lval->e_name, lval->e_const, lval2.e_const);
2632         }
2633     } else if (lval->e_flags & E_MLOCAL) {
2634         /* ref to localvar */
2635         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2636             g_addeqlocal (flags, lval->e_const, lval2.e_const);
2637         } else {
2638             g_subeqlocal (flags, lval->e_const, lval2.e_const);
2639         }
2640     } else if (lval->e_flags & E_MCONST) {
2641         /* ref to absolute address */
2642         flags |= CF_ABSOLUTE;
2643         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2644             g_addeqstatic (flags, lval->e_const, 0, lval2.e_const);
2645         } else {
2646             g_subeqstatic (flags, lval->e_const, 0, lval2.e_const);
2647         }
2648     } else if (lval->e_flags & E_MEXPR) {
2649         /* Address in a/x. */
2650         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2651             g_addeqind (flags, lval->e_const, lval2.e_const);
2652         } else {
2653             g_subeqind (flags, lval->e_const, lval2.e_const);
2654         }
2655     } else {
2656         Internal ("Invalid addressing mode");
2657     }
2658
2659     /* Expression is in the primary now */
2660     lval->e_flags = E_MEXPR;
2661 }
2662
2663
2664
2665 static void Assignment (struct expent* lval)
2666 /* Parse an assignment */
2667 {
2668     int k;
2669     struct expent lval2;
2670     unsigned flags;
2671     type* ltype = lval->e_tptr;
2672
2673     /* Check for assignment to const */
2674     if (IsQualConst (ltype)) {
2675         Error (ERR_CONST_ASSIGN);
2676     }
2677
2678     /* cc65 does not have full support for handling structs by value. Since
2679      * assigning structs is one of the more useful operations from this
2680      * familiy, allow it here.
2681      */
2682     if (IsClassStruct (ltype)) {
2683
2684         /* Bring the address of the lhs into the primary and push it */
2685         exprhs (0, 0, lval);
2686         g_push (CF_PTR | CF_UNSIGNED, 0);
2687
2688         /* Get the expression on the right of the '=' into the primary */
2689         k = hie1 (&lval2);
2690         if (k) {
2691             /* Get the address */
2692             exprhs (0, 0, &lval2);
2693         } else {
2694             /* We need an lvalue */
2695             Error (ERR_LVALUE_EXPECTED);
2696         }
2697
2698         /* Push the address (or whatever is in ax in case of errors) */
2699         g_push (CF_PTR | CF_UNSIGNED, 0);
2700
2701         /* Check for equality of the structs */
2702         if (TypeCmp (ltype, lval2.e_tptr) < TC_EQUAL) {
2703             Error (ERR_INCOMPATIBLE_TYPES);
2704         }
2705
2706         /* Load the size of the struct into the primary */
2707         g_getimmed (CF_INT | CF_UNSIGNED | CF_CONST, SizeOf (ltype), 0);
2708
2709         /* Call the memcpy function */
2710         g_call (CF_FIXARGC, "memcpy", 4);
2711
2712     } else {
2713
2714         /* Get the address on stack if needed */
2715         PushAddr (lval);
2716
2717         /* No struct, setup flags for the load */
2718         flags = SizeOf (ltype) == 1? CF_FORCECHAR : CF_NONE;
2719
2720         /* Get the expression on the right of the '=' into the primary */
2721         if (evalexpr (flags, hie1, &lval2) == 0) {
2722             /* Constant expression. Adjust the types */
2723             assignadjust (ltype, &lval2);
2724             /* Put the value into the primary register */
2725             lconst (flags, &lval2);
2726         } else {
2727             /* Expression is not constant and already in the primary */
2728             assignadjust (ltype, &lval2);
2729         }
2730
2731         /* Generate a store instruction */
2732         store (lval);
2733
2734     }
2735
2736     /* Value is still in primary */
2737     lval->e_flags = E_MEXPR;
2738 }
2739
2740
2741
2742 int hie1 (struct expent* lval)
2743 /* Parse first level of expression hierarchy. */
2744 {
2745     int k;
2746
2747     k = hieQuest (lval);
2748     switch (curtok) {
2749
2750         case TOK_RPAREN:
2751         case TOK_SEMI:
2752             return k;
2753
2754         case TOK_ASSIGN:
2755             NextToken ();
2756             if (k == 0) {
2757                 Error (ERR_LVALUE_EXPECTED);
2758             } else {
2759                 Assignment (lval);
2760             }
2761             break;
2762
2763         case TOK_PLUS_ASSIGN:
2764             addsubeq (&GenPASGN, lval, k);
2765             break;
2766
2767         case TOK_MINUS_ASSIGN:
2768             addsubeq (&GenSASGN, lval, k);
2769             break;
2770
2771         case TOK_MUL_ASSIGN:
2772             opeq (&GenMASGN, lval, k);
2773             break;
2774
2775         case TOK_DIV_ASSIGN:
2776             opeq (&GenDASGN, lval, k);
2777             break;
2778
2779         case TOK_MOD_ASSIGN:
2780             opeq (&GenMOASGN, lval, k);
2781             break;
2782
2783         case TOK_SHL_ASSIGN:
2784             opeq (&GenSLASGN, lval, k);
2785             break;
2786
2787         case TOK_SHR_ASSIGN:
2788             opeq (&GenSRASGN, lval, k);
2789             break;
2790
2791         case TOK_AND_ASSIGN:
2792             opeq (&GenAASGN, lval, k);
2793             break;
2794
2795         case TOK_XOR_ASSIGN:
2796             opeq (&GenXOASGN, lval, k);
2797             break;
2798
2799         case TOK_OR_ASSIGN:
2800             opeq (&GenOASGN, lval, k);
2801             break;
2802
2803         default:
2804             return k;
2805     }
2806     return 0;
2807 }
2808
2809
2810
2811 int hie0 (struct expent *lval)
2812 /* Parse comma operator. */
2813 {
2814     int k;
2815
2816     k = hie1 (lval);
2817     while (curtok == TOK_COMMA) {
2818         NextToken ();
2819         k = hie1 (lval);
2820     }
2821     return k;
2822 }
2823
2824
2825
2826 int evalexpr (unsigned flags, int (*f) (struct expent*), struct expent* lval)
2827 /* Will evaluate an expression via the given function. If the result is a
2828  * constant, 0 is returned and the value is put in the lval struct. If the
2829  * result is not constant, exprhs is called to bring the value into the
2830  * primary register and 1 is returned.
2831  */
2832 {
2833     int k;
2834
2835     /* Evaluate */
2836     k = f (lval);
2837     if (k == 0 && lval->e_flags == E_MCONST) {
2838         /* Constant expression */
2839         return 0;
2840     } else {
2841         /* Not constant, load into the primary */
2842         exprhs (flags, k, lval);
2843         return 1;
2844     }
2845 }
2846
2847
2848
2849 int expr (int (*func) (), struct expent *lval)
2850 /* Expression parser; func is either hie0 or hie1. */
2851 {
2852     int k;
2853     int savsp;
2854
2855     savsp = oursp;
2856
2857     k = (*func) (lval);
2858
2859     /* Do some checks if code generation is still constistent */
2860     if (savsp != oursp) {
2861         if (Debug) {
2862             fprintf (stderr, "oursp != savesp (%d != %d)\n", oursp, savsp);
2863         } else {
2864             Internal ("oursp != savsp (%d != %d)", oursp, savsp);
2865         }
2866     }
2867     return k;
2868 }
2869
2870
2871
2872 void expression1 (struct expent* lval)
2873 /* Evaluate an expression on level 1 (no comma operator) and put it into
2874  * the primary register
2875  */
2876 {
2877     memset (lval, 0, sizeof (*lval));
2878     exprhs (CF_NONE, expr (hie1, lval), lval);
2879 }
2880
2881
2882
2883 void expression (struct expent* lval)
2884 /* Evaluate an expression and put it into the primary register */
2885 {
2886     memset (lval, 0, sizeof (*lval));
2887     exprhs (CF_NONE, expr (hie0, lval), lval);
2888 }
2889
2890
2891
2892 void constexpr (struct expent* lval)
2893 /* Get a constant value */
2894 {
2895     memset (lval, 0, sizeof (*lval));
2896     if (expr (hie1, lval) != 0 || (lval->e_flags & E_MCONST) == 0) {
2897         Error (ERR_CONST_EXPR_EXPECTED);
2898         /* To avoid any compiler errors, make the expression a valid const */
2899         lval->e_flags = E_MCONST;
2900         lval->e_tptr = type_int;
2901         lval->e_const = 0;
2902     }
2903 }
2904
2905
2906
2907 void intexpr (struct expent* lval)
2908 /* Get an integer expression */
2909 {
2910     expression (lval);
2911     if (!IsClassInt (lval->e_tptr)) {
2912         Error (ERR_INT_EXPR_EXPECTED);
2913         /* To avoid any compiler errors, make the expression a valid int */
2914         lval->e_flags = E_MCONST;
2915         lval->e_tptr = type_int;
2916         lval->e_const = 0;
2917     }
2918 }
2919
2920
2921
2922 void boolexpr (struct expent* lval)
2923 /* Get a boolean expression */
2924 {
2925     /* Read an expression */
2926     expression (lval);
2927
2928     /* If it's an integer, it's ok. If it's not an integer, but a pointer,
2929      * the pointer used in a boolean context is also ok (Ootherwise check if it's a pointer
2930      * expression.
2931      */
2932     if (!IsClassInt (lval->e_tptr) && !IsClassPtr (lval->e_tptr)) {
2933         Error (ERR_INT_EXPR_EXPECTED);
2934         /* To avoid any compiler errors, make the expression a valid int */
2935         lval->e_flags = E_MCONST;
2936         lval->e_tptr = type_int;
2937         lval->e_const = 0;
2938     }
2939 }
2940
2941
2942
2943 void test (unsigned label, int cond)
2944 /* Generate code to perform test and jump if false. */
2945 {
2946     int k;
2947     struct expent lval;
2948
2949     /* Eat the parenthesis */
2950     ConsumeLParen ();
2951
2952     /* Prepare the expression, setup labels */
2953     memset (&lval, 0, sizeof (lval));
2954     lval.e_test = E_TEST;
2955
2956     /* Generate code to eval the expr */
2957     k = expr (hie0, &lval);
2958     if (k == 0 && lval.e_flags == E_MCONST) {
2959         /* Constant rvalue */
2960         if (cond == 0 && lval.e_const == 0) {
2961             g_jump (label);
2962             Warning (WARN_UNREACHABLE_CODE);
2963         } else if (cond && lval.e_const) {
2964             g_jump (label);
2965         }
2966         ConsumeRParen ();
2967         return;
2968     }
2969
2970     /* If the expr hasn't set condition codes, set the force-test flag */
2971     if ((lval.e_test & E_CC) == 0) {
2972         lval.e_test |= E_FORCETEST;
2973     }
2974
2975     /* Load the value into the primary register */
2976     exprhs (CF_FORCECHAR, k, &lval);
2977
2978     /* Check for the closing brace */
2979     ConsumeRParen ();
2980
2981     /* Generate the jump */
2982     if (cond) {
2983         g_truejump (CF_NONE, label);
2984     } else {
2985         /* Special case (putting this here is a small hack - but hey, the
2986          * compiler itself is one big hack...): If a semicolon follows, we
2987          * don't have a statement and may omit the jump.
2988          */
2989         if (curtok != TOK_SEMI) {
2990             g_falsejump (CF_NONE, label);
2991         }
2992     }
2993 }
2994
2995
2996
2997