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