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