Rename
[xonotic/gmqcc.git] / parser.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Wolfgang Bumiller
4  *     Dale Weiler
5  * 
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include <stdio.h>
25 #include <stdarg.h>
26
27 #include "gmqcc.h"
28 #include "lexer.h"
29 #include "ast.h"
30
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS  2
33
34 #define PARSER_HT_SIZE    128
35 #define TYPEDEF_HT_SIZE   16
36
37 typedef struct {
38     lex_file *lex;
39     int      tok;
40
41     ast_expression **globals;
42     ast_expression **fields;
43     ast_function **functions;
44     ast_value    **imm_float;
45     ast_value    **imm_string;
46     ast_value    **imm_vector;
47     size_t         translated;
48
49     /* must be deleted first, they reference immediates and values */
50     ast_value    **accessors;
51
52     ast_value *imm_float_zero;
53     ast_value *imm_float_one;
54     ast_value *imm_vector_zero;
55     ast_value *nil;
56     ast_value *reserved_version;
57
58     size_t crc_globals;
59     size_t crc_fields;
60
61     ast_function *function;
62
63     /* All the labels the function defined...
64      * Should they be in ast_function instead?
65      */
66     ast_label  **labels;
67     ast_goto   **gotos;
68     const char **breaks;
69     const char **continues;
70
71     /* A list of hashtables for each scope */
72     ht *variables;
73     ht htfields;
74     ht htglobals;
75     ht *typedefs;
76
77     /* same as above but for the spelling corrector */
78     correct_trie_t  **correct_variables;
79     size_t         ***correct_variables_score;  /* vector of vector of size_t* */
80
81     /* not to be used directly, we use the hash table */
82     ast_expression **_locals;
83     size_t          *_blocklocals;
84     ast_value      **_typedefs;
85     size_t          *_blocktypedefs;
86     lex_ctx         *_block_ctx;
87
88     /* we store the '=' operator info */
89     const oper_info *assign_op;
90
91     /* magic values */
92     ast_value *const_vec[3];
93
94     /* pragma flags */
95     bool noref;
96
97     /* collected information */
98     size_t     max_param_count;
99 } parser_t;
100
101 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
102
103 static void parser_enterblock(parser_t *parser);
104 static bool parser_leaveblock(parser_t *parser);
105 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
106 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
107 static bool parse_typedef(parser_t *parser);
108 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
109 static ast_block* parse_block(parser_t *parser);
110 static bool parse_block_into(parser_t *parser, ast_block *block);
111 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
112 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
113 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
114 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
115 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
116 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
117 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
118
119 static void parseerror(parser_t *parser, const char *fmt, ...)
120 {
121     va_list ap;
122     va_start(ap, fmt);
123     vcompile_error(parser->lex->tok.ctx, fmt, ap);
124     va_end(ap);
125 }
126
127 /* returns true if it counts as an error */
128 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
129 {
130     bool    r;
131     va_list ap;
132     va_start(ap, fmt);
133     r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
134     va_end(ap);
135     return r;
136 }
137
138 /**********************************************************************
139  * some maths used for constant folding
140  */
141
142 vector vec3_add(vector a, vector b)
143 {
144     vector out;
145     out.x = a.x + b.x;
146     out.y = a.y + b.y;
147     out.z = a.z + b.z;
148     return out;
149 }
150
151 vector vec3_sub(vector a, vector b)
152 {
153     vector out;
154     out.x = a.x - b.x;
155     out.y = a.y - b.y;
156     out.z = a.z - b.z;
157     return out;
158 }
159
160 qcfloat vec3_mulvv(vector a, vector b)
161 {
162     return (a.x * b.x + a.y * b.y + a.z * b.z);
163 }
164
165 vector vec3_mulvf(vector a, float b)
166 {
167     vector out;
168     out.x = a.x * b;
169     out.y = a.y * b;
170     out.z = a.z * b;
171     return out;
172 }
173
174 /**********************************************************************
175  * parsing
176  */
177
178 bool parser_next(parser_t *parser)
179 {
180     /* lex_do kills the previous token */
181     parser->tok = lex_do(parser->lex);
182     if (parser->tok == TOKEN_EOF)
183         return true;
184     if (parser->tok >= TOKEN_ERROR) {
185         parseerror(parser, "lex error");
186         return false;
187     }
188     return true;
189 }
190
191 #define parser_tokval(p) ((p)->lex->tok.value)
192 #define parser_token(p)  (&((p)->lex->tok))
193 #define parser_ctx(p)    ((p)->lex->tok.ctx)
194
195 static ast_value* parser_const_float(parser_t *parser, double d)
196 {
197     size_t i;
198     ast_value *out;
199     lex_ctx ctx;
200     for (i = 0; i < vec_size(parser->imm_float); ++i) {
201         const double compare = parser->imm_float[i]->constval.vfloat;
202         if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
203             return parser->imm_float[i];
204     }
205     if (parser->lex)
206         ctx = parser_ctx(parser);
207     else {
208         memset(&ctx, 0, sizeof(ctx));
209     }
210     out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
211     out->cvq      = CV_CONST;
212     out->hasvalue = true;
213     out->constval.vfloat = d;
214     vec_push(parser->imm_float, out);
215     return out;
216 }
217
218 static ast_value* parser_const_float_0(parser_t *parser)
219 {
220     if (!parser->imm_float_zero)
221         parser->imm_float_zero = parser_const_float(parser, 0);
222     return parser->imm_float_zero;
223 }
224
225 static ast_value* parser_const_float_1(parser_t *parser)
226 {
227     if (!parser->imm_float_one)
228         parser->imm_float_one = parser_const_float(parser, 1);
229     return parser->imm_float_one;
230 }
231
232 static char *parser_strdup(const char *str)
233 {
234     if (str && !*str) {
235         /* actually dup empty strings */
236         char *out = (char*)mem_a(1);
237         *out = 0;
238         return out;
239     }
240     return util_strdup(str);
241 }
242
243 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
244 {
245     size_t i;
246     ast_value *out;
247     for (i = 0; i < vec_size(parser->imm_string); ++i) {
248         if (!strcmp(parser->imm_string[i]->constval.vstring, str))
249             return parser->imm_string[i];
250     }
251     if (dotranslate) {
252         char name[32];
253         snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
254         out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
255     } else
256         out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
257     out->cvq      = CV_CONST;
258     out->hasvalue = true;
259     out->constval.vstring = parser_strdup(str);
260     vec_push(parser->imm_string, out);
261     return out;
262 }
263
264 static ast_value* parser_const_vector(parser_t *parser, vector v)
265 {
266     size_t i;
267     ast_value *out;
268     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
269         if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
270             return parser->imm_vector[i];
271     }
272     out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
273     out->cvq      = CV_CONST;
274     out->hasvalue = true;
275     out->constval.vvec = v;
276     vec_push(parser->imm_vector, out);
277     return out;
278 }
279
280 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
281 {
282     vector v;
283     v.x = x;
284     v.y = y;
285     v.z = z;
286     return parser_const_vector(parser, v);
287 }
288
289 static ast_value* parser_const_vector_0(parser_t *parser)
290 {
291     if (!parser->imm_vector_zero)
292         parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
293     return parser->imm_vector_zero;
294 }
295
296 static ast_expression* parser_find_field(parser_t *parser, const char *name)
297 {
298     return ( ast_expression*)util_htget(parser->htfields, name);
299 }
300
301 static ast_expression* parser_find_label(parser_t *parser, const char *name)
302 {
303     size_t i;
304     for(i = 0; i < vec_size(parser->labels); i++)
305         if (!strcmp(parser->labels[i]->name, name))
306             return (ast_expression*)parser->labels[i];
307     return NULL;
308 }
309
310 static ast_expression* parser_find_global(parser_t *parser, const char *name)
311 {
312     return (ast_expression*)util_htget(parser->htglobals, name);
313 }
314
315 static ast_expression* parser_find_param(parser_t *parser, const char *name)
316 {
317     size_t i;
318     ast_value *fun;
319     if (!parser->function)
320         return NULL;
321     fun = parser->function->vtype;
322     for (i = 0; i < vec_size(fun->expression.params); ++i) {
323         if (!strcmp(fun->expression.params[i]->name, name))
324             return (ast_expression*)(fun->expression.params[i]);
325     }
326     return NULL;
327 }
328
329 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
330 {
331     size_t          i, hash;
332     ast_expression *e;
333
334     hash = util_hthash(parser->htglobals, name);
335
336     *isparam = false;
337     for (i = vec_size(parser->variables); i > upto;) {
338         --i;
339         if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
340             return e;
341     }
342     *isparam = true;
343     return parser_find_param(parser, name);
344 }
345
346 static ast_expression* parser_find_var(parser_t *parser, const char *name)
347 {
348     bool dummy;
349     ast_expression *v;
350     v         = parser_find_local(parser, name, 0, &dummy);
351     if (!v) v = parser_find_global(parser, name);
352     return v;
353 }
354
355 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
356 {
357     size_t     i, hash;
358     ast_value *e;
359     hash = util_hthash(parser->typedefs[0], name);
360
361     for (i = vec_size(parser->typedefs); i > upto;) {
362         --i;
363         if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
364             return e;
365     }
366     return NULL;
367 }
368
369 typedef struct
370 {
371     size_t etype; /* 0 = expression, others are operators */
372     bool            isparen;
373     size_t          off;
374     ast_expression *out;
375     ast_block      *block; /* for commas and function calls */
376     lex_ctx ctx;
377 } sy_elem;
378
379 enum {
380     PAREN_EXPR,
381     PAREN_FUNC,
382     PAREN_INDEX,
383     PAREN_TERNARY1,
384     PAREN_TERNARY2
385 };
386 typedef struct
387 {
388     sy_elem        *out;
389     sy_elem        *ops;
390     size_t         *argc;
391     unsigned int   *paren;
392 } shunt;
393
394 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
395     sy_elem e;
396     e.etype = 0;
397     e.off   = 0;
398     e.out   = v;
399     e.block = NULL;
400     e.ctx   = ctx;
401     e.isparen = false;
402     return e;
403 }
404
405 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
406     sy_elem e;
407     e.etype = 0;
408     e.off   = 0;
409     e.out   = (ast_expression*)v;
410     e.block = v;
411     e.ctx   = ctx;
412     e.isparen = false;
413     return e;
414 }
415
416 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
417     sy_elem e;
418     e.etype = 1 + (op - operators);
419     e.off   = 0;
420     e.out   = NULL;
421     e.block = NULL;
422     e.ctx   = ctx;
423     e.isparen = false;
424     return e;
425 }
426
427 static sy_elem syparen(lex_ctx ctx, size_t off) {
428     sy_elem e;
429     e.etype = 0;
430     e.off   = off;
431     e.out   = NULL;
432     e.block = NULL;
433     e.ctx   = ctx;
434     e.isparen = true;
435     return e;
436 }
437
438 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
439  * so we need to rotate it to become ent.(foo[n]).
440  */
441 static bool rotate_entfield_array_index_nodes(ast_expression **out)
442 {
443     ast_array_index *index;
444     ast_entfield    *entfield;
445
446     ast_value       *field;
447     ast_expression  *sub;
448     ast_expression  *entity;
449
450     lex_ctx ctx = ast_ctx(*out);
451
452     if (!ast_istype(*out, ast_array_index))
453         return false;
454     index = (ast_array_index*)*out;
455
456     if (!ast_istype(index->array, ast_entfield))
457         return false;
458     entfield = (ast_entfield*)index->array;
459
460     if (!ast_istype(entfield->field, ast_value))
461         return false;
462     field = (ast_value*)entfield->field;
463
464     sub    = index->index;
465     entity = entfield->entity;
466
467     ast_delete(index);
468
469     index = ast_array_index_new(ctx, (ast_expression*)field, sub);
470     entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
471     *out = (ast_expression*)entfield;
472
473     return true;
474 }
475
476 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
477 {
478     switch (v->expression.vtype) {
479         case TYPE_FLOAT:
480             return !!v->constval.vfloat;
481         case TYPE_INTEGER:
482             return !!v->constval.vint;
483         case TYPE_VECTOR:
484             if (OPTS_FLAG(CORRECT_LOGIC))
485                 return v->constval.vvec.x &&
486                        v->constval.vvec.y &&
487                        v->constval.vvec.z;
488             else
489                 return !!(v->constval.vvec.x);
490         case TYPE_STRING:
491             if (!v->constval.vstring)
492                 return false;
493             if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
494                 return true;
495             return !!v->constval.vstring[0];
496         default:
497             compile_error(ctx, "internal error: immediate_is_true on invalid type");
498             return !!v->constval.vfunc;
499     }
500 }
501
502 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
503 {
504     const oper_info *op;
505     lex_ctx ctx;
506     ast_expression *out = NULL;
507     ast_expression *exprs[3];
508     ast_block      *blocks[3];
509     ast_value      *asvalue[3];
510     ast_binstore   *asbinstore;
511     size_t i, assignop, addop, subop;
512     qcint  generated_op = 0;
513
514     char ty1[1024];
515     char ty2[1024];
516
517     if (!vec_size(sy->ops)) {
518         parseerror(parser, "internal error: missing operator");
519         return false;
520     }
521
522     if (vec_last(sy->ops).isparen) {
523         parseerror(parser, "unmatched parenthesis");
524         return false;
525     }
526
527     op = &operators[vec_last(sy->ops).etype - 1];
528     ctx = vec_last(sy->ops).ctx;
529
530     if (vec_size(sy->out) < op->operands) {
531         compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
532                       op->op, (int)op->id);
533         return false;
534     }
535
536     vec_shrinkby(sy->ops, 1);
537
538     /* op(:?) has no input and no output */
539     if (!op->operands)
540         return true;
541
542     vec_shrinkby(sy->out, op->operands);
543     for (i = 0; i < op->operands; ++i) {
544         exprs[i]  = sy->out[vec_size(sy->out)+i].out;
545         blocks[i] = sy->out[vec_size(sy->out)+i].block;
546         asvalue[i] = (ast_value*)exprs[i];
547
548         if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
549             !(i != 0 && op->id == opid2('?',':')) &&
550             !(i == 1 && op->id == opid1('.')))
551         {
552             if (ast_istype(exprs[i], ast_label))
553                 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
554             else
555                 compile_error(ast_ctx(exprs[i]), "not an expression");
556             (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
557         }
558     }
559
560     if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
561         compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
562         return false;
563     }
564
565 #define NotSameType(T) \
566              (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
567               exprs[0]->expression.vtype != T)
568 #define CanConstFold1(A) \
569              (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
570               (A)->expression.vtype != TYPE_FUNCTION)
571 #define CanConstFold(A, B) \
572              (CanConstFold1(A) && CanConstFold1(B))
573 #define ConstV(i) (asvalue[(i)]->constval.vvec)
574 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
575 #define ConstS(i) (asvalue[(i)]->constval.vstring)
576     switch (op->id)
577     {
578         default:
579             compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
580             return false;
581
582         case opid1('.'):
583             if (exprs[0]->expression.vtype == TYPE_VECTOR &&
584                 exprs[1]->expression.vtype == TYPE_NOEXPR)
585             {
586                 if      (exprs[1] == (ast_expression*)parser->const_vec[0])
587                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
588                 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
589                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
590                 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
591                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
592                 else {
593                     compile_error(ctx, "access to invalid vector component");
594                     return false;
595                 }
596             }
597             else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
598                 if (exprs[1]->expression.vtype != TYPE_FIELD) {
599                     compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
600                     return false;
601                 }
602                 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
603             }
604             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
605                 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
606                 return false;
607             }
608             else {
609                 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
610                 return false;
611             }
612             break;
613
614         case opid1('['):
615             if (exprs[0]->expression.vtype != TYPE_ARRAY &&
616                 !(exprs[0]->expression.vtype == TYPE_FIELD &&
617                   exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
618             {
619                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
620                 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
621                 return false;
622             }
623             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
624                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
625                 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
626                 return false;
627             }
628             out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
629             if (rotate_entfield_array_index_nodes(&out))
630             {
631 #if 0
632                 /* This is not broken in fteqcc anymore */
633                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
634                     /* this error doesn't need to make us bail out */
635                     (void)!parsewarning(parser, WARN_EXTENSIONS,
636                                         "accessing array-field members of an entity without parenthesis\n"
637                                         " -> this is an extension from -std=gmqcc");
638                 }
639 #endif
640             }
641             break;
642
643         case opid1(','):
644             if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
645                 vec_push(sy->out, syexp(ctx, exprs[0]));
646                 vec_push(sy->out, syexp(ctx, exprs[1]));
647                 vec_last(sy->argc)++;
648                 return true;
649             }
650             if (blocks[0]) {
651                 if (!ast_block_add_expr(blocks[0], exprs[1]))
652                     return false;
653             } else {
654                 blocks[0] = ast_block_new(ctx);
655                 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
656                     !ast_block_add_expr(blocks[0], exprs[1]))
657                 {
658                     return false;
659                 }
660             }
661             if (!ast_block_set_type(blocks[0], exprs[1]))
662                 return false;
663
664             vec_push(sy->out, syblock(ctx, blocks[0]));
665             return true;
666
667         case opid2('+','P'):
668             out = exprs[0];
669             break;
670         case opid2('-','P'):
671             switch (exprs[0]->expression.vtype) {
672                 case TYPE_FLOAT:
673                     if (CanConstFold1(exprs[0]))
674                         out = (ast_expression*)parser_const_float(parser, -ConstF(0));
675                     else
676                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
677                                                               (ast_expression*)parser_const_float_0(parser),
678                                                               exprs[0]);
679                     break;
680                 case TYPE_VECTOR:
681                     if (CanConstFold1(exprs[0]))
682                         out = (ast_expression*)parser_const_vector_f(parser,
683                             -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
684                     else
685                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
686                                                               (ast_expression*)parser_const_vector_0(parser),
687                                                               exprs[0]);
688                     break;
689                 default:
690                 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
691                               type_name[exprs[0]->expression.vtype]);
692                 return false;
693             }
694             break;
695
696         case opid2('!','P'):
697             switch (exprs[0]->expression.vtype) {
698                 case TYPE_FLOAT:
699                     if (CanConstFold1(exprs[0]))
700                         out = (ast_expression*)parser_const_float(parser, !ConstF(0));
701                     else
702                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
703                     break;
704                 case TYPE_VECTOR:
705                     if (CanConstFold1(exprs[0]))
706                         out = (ast_expression*)parser_const_float(parser,
707                             (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
708                     else
709                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
710                     break;
711                 case TYPE_STRING:
712                     if (CanConstFold1(exprs[0])) {
713                         if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
714                             out = (ast_expression*)parser_const_float(parser, !ConstS(0));
715                         else
716                             out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
717                     } else {
718                         if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
719                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
720                         else
721                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
722                     }
723                     break;
724                 /* we don't constant-fold NOT for these types */
725                 case TYPE_ENTITY:
726                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
727                     break;
728                 case TYPE_FUNCTION:
729                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
730                     break;
731                 default:
732                 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
733                               type_name[exprs[0]->expression.vtype]);
734                 return false;
735             }
736             break;
737
738         case opid1('+'):
739             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
740                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
741             {
742                 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
743                               type_name[exprs[0]->expression.vtype],
744                               type_name[exprs[1]->expression.vtype]);
745                 return false;
746             }
747             switch (exprs[0]->expression.vtype) {
748                 case TYPE_FLOAT:
749                     if (CanConstFold(exprs[0], exprs[1]))
750                     {
751                         out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
752                     }
753                     else
754                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
755                     break;
756                 case TYPE_VECTOR:
757                     if (CanConstFold(exprs[0], exprs[1]))
758                         out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
759                     else
760                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
761                     break;
762                 default:
763                     compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
764                                   type_name[exprs[0]->expression.vtype],
765                                   type_name[exprs[1]->expression.vtype]);
766                     return false;
767             };
768             break;
769         case opid1('-'):
770             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
771                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
772             {
773                 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
774                               type_name[exprs[1]->expression.vtype],
775                               type_name[exprs[0]->expression.vtype]);
776                 return false;
777             }
778             switch (exprs[0]->expression.vtype) {
779                 case TYPE_FLOAT:
780                     if (CanConstFold(exprs[0], exprs[1]))
781                         out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
782                     else
783                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
784                     break;
785                 case TYPE_VECTOR:
786                     if (CanConstFold(exprs[0], exprs[1]))
787                         out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
788                     else
789                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
790                     break;
791                 default:
792                     compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
793                                   type_name[exprs[1]->expression.vtype],
794                                   type_name[exprs[0]->expression.vtype]);
795                     return false;
796             };
797             break;
798         case opid1('*'):
799             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
800                 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
801                   exprs[1]->expression.vtype == TYPE_FLOAT) &&
802                 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
803                   exprs[0]->expression.vtype == TYPE_FLOAT)
804                 )
805             {
806                 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
807                               type_name[exprs[1]->expression.vtype],
808                               type_name[exprs[0]->expression.vtype]);
809                 return false;
810             }
811             switch (exprs[0]->expression.vtype) {
812                 case TYPE_FLOAT:
813                     if (exprs[1]->expression.vtype == TYPE_VECTOR)
814                     {
815                         if (CanConstFold(exprs[0], exprs[1]))
816                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
817                         else
818                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
819                     }
820                     else
821                     {
822                         if (CanConstFold(exprs[0], exprs[1]))
823                             out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
824                         else
825                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
826                     }
827                     break;
828                 case TYPE_VECTOR:
829                     if (exprs[1]->expression.vtype == TYPE_FLOAT)
830                     {
831                         if (CanConstFold(exprs[0], exprs[1]))
832                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
833                         else
834                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
835                     }
836                     else
837                     {
838                         if (CanConstFold(exprs[0], exprs[1]))
839                             out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
840                         else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
841                             vector vec = ConstV(0);
842                             if (!vec.y && !vec.z) { /* 'n 0 0' * v */
843                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
844                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
845                                 out->expression.node.keep = false;
846                                 ((ast_member*)out)->rvalue = true;
847                                 if (vec.x != 1)
848                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
849                             }
850                             else if (!vec.x && !vec.z) { /* '0 n 0' * v */
851                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
852                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
853                                 out->expression.node.keep = false;
854                                 ((ast_member*)out)->rvalue = true;
855                                 if (vec.y != 1)
856                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
857                             }
858                             else if (!vec.x && !vec.y) { /* '0 n 0' * v */
859                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
860                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
861                                 out->expression.node.keep = false;
862                                 ((ast_member*)out)->rvalue = true;
863                                 if (vec.z != 1)
864                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
865                             }
866                             else
867                                 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
868                         }
869                         else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
870                             vector vec = ConstV(1);
871                             if (!vec.y && !vec.z) { /* v * 'n 0 0' */
872                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
873                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
874                                 out->expression.node.keep = false;
875                                 ((ast_member*)out)->rvalue = true;
876                                 if (vec.x != 1)
877                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
878                             }
879                             else if (!vec.x && !vec.z) { /* v * '0 n 0' */
880                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
881                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
882                                 out->expression.node.keep = false;
883                                 ((ast_member*)out)->rvalue = true;
884                                 if (vec.y != 1)
885                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
886                             }
887                             else if (!vec.x && !vec.y) { /* v * '0 n 0' */
888                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
889                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
890                                 out->expression.node.keep = false;
891                                 ((ast_member*)out)->rvalue = true;
892                                 if (vec.z != 1)
893                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
894                             }
895                             else
896                                 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
897                         }
898                         else
899                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
900                     }
901                     break;
902                 default:
903                     compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
904                                   type_name[exprs[1]->expression.vtype],
905                                   type_name[exprs[0]->expression.vtype]);
906                     return false;
907             };
908             break;
909         case opid1('/'):
910             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
911                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
912                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
913                 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
914                 return false;
915             }
916             if (exprs[0]->expression.vtype == TYPE_FLOAT) {
917                 if (CanConstFold(exprs[0], exprs[1]))
918                     out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
919                 else
920                     out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
921             }
922             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
923                 if (CanConstFold(exprs[0], exprs[1]))
924                     out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
925                 else {
926                     if (CanConstFold1(exprs[1])) {
927                         out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
928                     } else {
929                         out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
930                                                               (ast_expression*)parser_const_float_1(parser),
931                                                               exprs[1]);
932                     }
933                     if (!out) {
934                         compile_error(ctx, "internal error: failed to generate division");
935                         return false;
936                     }
937                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
938                 }
939             }
940             else
941             {
942                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
943                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
944                 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
945                 return false;
946             }
947             break;
948         case opid1('%'):
949         case opid2('%','='):
950             compile_error(ctx, "qc does not have a modulo operator");
951             return false;
952         case opid1('|'):
953         case opid1('&'):
954             if (NotSameType(TYPE_FLOAT)) {
955                 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
956                               type_name[exprs[0]->expression.vtype],
957                               type_name[exprs[1]->expression.vtype]);
958                 return false;
959             }
960             if (CanConstFold(exprs[0], exprs[1]))
961                 out = (ast_expression*)parser_const_float(parser,
962                     (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
963                                             (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
964             else
965                 out = (ast_expression*)ast_binary_new(ctx,
966                     (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
967                     exprs[0], exprs[1]);
968             break;
969         case opid1('^'):
970             compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
971             return false;
972
973         case opid2('<','<'):
974         case opid2('>','>'):
975             if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
976                 if (op->id == opid2('<','<'))
977                     out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
978                 else
979                     out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
980                 break;
981             }
982         case opid3('<','<','='):
983         case opid3('>','>','='):
984             compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
985             return false;
986
987         case opid2('|','|'):
988             generated_op += 1; /* INSTR_OR */
989         case opid2('&','&'):
990             generated_op += INSTR_AND;
991             if (CanConstFold(exprs[0], exprs[1]))
992             {
993                 if (OPTS_FLAG(PERL_LOGIC)) {
994                     if (immediate_is_true(ctx, asvalue[0]))
995                         out = exprs[1];
996                 }
997                 else
998                     out = (ast_expression*)parser_const_float(parser,
999                           ( (generated_op == INSTR_OR)
1000                             ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1001                             : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1002                           ? 1 : 0);
1003             }
1004             else
1005             {
1006                 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1007                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1008                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1009                     compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1010                     return false;
1011                 }
1012                 for (i = 0; i < 2; ++i) {
1013                     if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1014                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1015                         if (!out) break;
1016                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1017                         if (!out) break;
1018                         exprs[i] = out; out = NULL;
1019                         if (OPTS_FLAG(PERL_LOGIC)) {
1020                             /* here we want to keep the right expressions' type */
1021                             break;
1022                         }
1023                     }
1024                     else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1025                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1026                         if (!out) break;
1027                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1028                         if (!out) break;
1029                         exprs[i] = out; out = NULL;
1030                         if (OPTS_FLAG(PERL_LOGIC)) {
1031                             /* here we want to keep the right expressions' type */
1032                             break;
1033                         }
1034                     }
1035                 }
1036                 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1037             }
1038             break;
1039
1040         case opid2('?',':'):
1041             if (vec_last(sy->paren) != PAREN_TERNARY2) {
1042                 compile_error(ctx, "mismatched parenthesis/ternary");
1043                 return false;
1044             }
1045             vec_pop(sy->paren);
1046             if (!ast_compare_type(exprs[1], exprs[2])) {
1047                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1048                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1049                 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1050                 return false;
1051             }
1052             if (CanConstFold1(exprs[0]))
1053                 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1054             else
1055                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1056             break;
1057
1058         case opid1('>'):
1059             generated_op += 1; /* INSTR_GT */
1060         case opid1('<'):
1061             generated_op += 1; /* INSTR_LT */
1062         case opid2('>', '='):
1063             generated_op += 1; /* INSTR_GE */
1064         case opid2('<', '='):
1065             generated_op += INSTR_LE;
1066             if (NotSameType(TYPE_FLOAT)) {
1067                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1068                               type_name[exprs[0]->expression.vtype],
1069                               type_name[exprs[1]->expression.vtype]);
1070                 return false;
1071             }
1072             out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1073             break;
1074         case opid2('!', '='):
1075             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1076                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1077                               type_name[exprs[0]->expression.vtype],
1078                               type_name[exprs[1]->expression.vtype]);
1079                 return false;
1080             }
1081             out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1082             break;
1083         case opid2('=', '='):
1084             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1085                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1086                               type_name[exprs[0]->expression.vtype],
1087                               type_name[exprs[1]->expression.vtype]);
1088                 return false;
1089             }
1090             out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1091             break;
1092
1093         case opid1('='):
1094             if (ast_istype(exprs[0], ast_entfield)) {
1095                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1096                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1097                     exprs[0]->expression.vtype == TYPE_FIELD &&
1098                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1099                 {
1100                     assignop = type_storep_instr[TYPE_VECTOR];
1101                 }
1102                 else
1103                     assignop = type_storep_instr[exprs[0]->expression.vtype];
1104                 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1105                 {
1106                     ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1107                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1108                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1109                         field->expression.next->expression.vtype == TYPE_FUNCTION &&
1110                         exprs[1]->expression.vtype == TYPE_FUNCTION)
1111                     {
1112                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1113                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1114                     }
1115                     else
1116                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1117                 }
1118             }
1119             else
1120             {
1121                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1122                     exprs[0]->expression.vtype == TYPE_FIELD &&
1123                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1124                 {
1125                     assignop = type_store_instr[TYPE_VECTOR];
1126                 }
1127                 else {
1128                     assignop = type_store_instr[exprs[0]->expression.vtype];
1129                 }
1130
1131                 if (assignop == AINSTR_END) {
1132                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1133                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1134                     compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1135                 }
1136                 else if (!ast_compare_type(exprs[0], exprs[1]))
1137                 {
1138                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1139                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1140                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1141                         exprs[0]->expression.vtype == TYPE_FUNCTION &&
1142                         exprs[1]->expression.vtype == TYPE_FUNCTION)
1143                     {
1144                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1145                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1146                     }
1147                     else
1148                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1149                 }
1150             }
1151             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1152                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1153             }
1154             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1155             break;
1156         case opid3('+','+','P'):
1157         case opid3('-','-','P'):
1158             /* prefix ++ */
1159             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1160                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1161                 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1162                 return false;
1163             }
1164             if (op->id == opid3('+','+','P'))
1165                 addop = INSTR_ADD_F;
1166             else
1167                 addop = INSTR_SUB_F;
1168             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1169                 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1170             }
1171             if (ast_istype(exprs[0], ast_entfield)) {
1172                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1173                                                         exprs[0],
1174                                                         (ast_expression*)parser_const_float_1(parser));
1175             } else {
1176                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1177                                                         exprs[0],
1178                                                         (ast_expression*)parser_const_float_1(parser));
1179             }
1180             break;
1181         case opid3('S','+','+'):
1182         case opid3('S','-','-'):
1183             /* prefix ++ */
1184             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1185                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1186                 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1187                 return false;
1188             }
1189             if (op->id == opid3('S','+','+')) {
1190                 addop = INSTR_ADD_F;
1191                 subop = INSTR_SUB_F;
1192             } else {
1193                 addop = INSTR_SUB_F;
1194                 subop = INSTR_ADD_F;
1195             }
1196             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1197                 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1198             }
1199             if (ast_istype(exprs[0], ast_entfield)) {
1200                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1201                                                         exprs[0],
1202                                                         (ast_expression*)parser_const_float_1(parser));
1203             } else {
1204                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1205                                                         exprs[0],
1206                                                         (ast_expression*)parser_const_float_1(parser));
1207             }
1208             if (!out)
1209                 return false;
1210             out = (ast_expression*)ast_binary_new(ctx, subop,
1211                                                   out,
1212                                                   (ast_expression*)parser_const_float_1(parser));
1213             break;
1214         case opid2('+','='):
1215         case opid2('-','='):
1216             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1217                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1218             {
1219                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1220                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1221                 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1222                               ty1, ty2);
1223                 return false;
1224             }
1225             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1226                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1227             }
1228             if (ast_istype(exprs[0], ast_entfield))
1229                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1230             else
1231                 assignop = type_store_instr[exprs[0]->expression.vtype];
1232             switch (exprs[0]->expression.vtype) {
1233                 case TYPE_FLOAT:
1234                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1235                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1236                                                             exprs[0], exprs[1]);
1237                     break;
1238                 case TYPE_VECTOR:
1239                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1240                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1241                                                             exprs[0], exprs[1]);
1242                     break;
1243                 default:
1244                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1245                                   type_name[exprs[0]->expression.vtype],
1246                                   type_name[exprs[1]->expression.vtype]);
1247                     return false;
1248             };
1249             break;
1250         case opid2('*','='):
1251         case opid2('/','='):
1252             if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1253                 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1254                   exprs[0]->expression.vtype == TYPE_VECTOR))
1255             {
1256                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1257                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1258                 compile_error(ctx, "invalid types used in expression: %s and %s",
1259                               ty1, ty2);
1260                 return false;
1261             }
1262             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1263                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1264             }
1265             if (ast_istype(exprs[0], ast_entfield))
1266                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1267             else
1268                 assignop = type_store_instr[exprs[0]->expression.vtype];
1269             switch (exprs[0]->expression.vtype) {
1270                 case TYPE_FLOAT:
1271                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1272                                                             (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1273                                                             exprs[0], exprs[1]);
1274                     break;
1275                 case TYPE_VECTOR:
1276                     if (op->id == opid2('*','=')) {
1277                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1278                                                                 exprs[0], exprs[1]);
1279                     } else {
1280                         /* there's no DIV_VF */
1281                         if (CanConstFold1(exprs[1])) {
1282                             out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1283                         } else {
1284                             out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1285                                                                   (ast_expression*)parser_const_float_1(parser),
1286                                                                   exprs[1]);
1287                         }
1288                         if (!out) {
1289                             compile_error(ctx, "internal error: failed to generate division");
1290                             return false;
1291                         }
1292                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1293                                                                 exprs[0], out);
1294                     }
1295                     break;
1296                 default:
1297                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1298                                   type_name[exprs[0]->expression.vtype],
1299                                   type_name[exprs[1]->expression.vtype]);
1300                     return false;
1301             };
1302             break;
1303         case opid2('&','='):
1304         case opid2('|','='):
1305             if (NotSameType(TYPE_FLOAT)) {
1306                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1307                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1308                 compile_error(ctx, "invalid types used in expression: %s and %s",
1309                               ty1, ty2);
1310                 return false;
1311             }
1312             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1313                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1314             }
1315             if (ast_istype(exprs[0], ast_entfield))
1316                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1317             else
1318                 assignop = type_store_instr[exprs[0]->expression.vtype];
1319             out = (ast_expression*)ast_binstore_new(ctx, assignop,
1320                                                     (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1321                                                     exprs[0], exprs[1]);
1322             break;
1323         case opid3('&','~','='):
1324             /* This is like: a &= ~(b);
1325              * But QC has no bitwise-not, so we implement it as
1326              * a -= a & (b);
1327              */
1328             if (NotSameType(TYPE_FLOAT)) {
1329                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1330                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1331                 compile_error(ctx, "invalid types used in expression: %s and %s",
1332                               ty1, ty2);
1333                 return false;
1334             }
1335             if (ast_istype(exprs[0], ast_entfield))
1336                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1337             else
1338                 assignop = type_store_instr[exprs[0]->expression.vtype];
1339             out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1340             if (!out)
1341                 return false;
1342             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1343                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1344             }
1345             asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1346             asbinstore->keep_dest = true;
1347             out = (ast_expression*)asbinstore;
1348             break;
1349     }
1350 #undef NotSameType
1351
1352     if (!out) {
1353         compile_error(ctx, "failed to apply operator %s", op->op);
1354         return false;
1355     }
1356
1357     vec_push(sy->out, syexp(ctx, out));
1358     return true;
1359 }
1360
1361 static bool parser_close_call(parser_t *parser, shunt *sy)
1362 {
1363     /* was a function call */
1364     ast_expression *fun;
1365     ast_value      *funval = NULL;
1366     ast_call       *call;
1367
1368     size_t          fid;
1369     size_t          paramcount, i;
1370
1371     fid = vec_last(sy->ops).off;
1372     vec_shrinkby(sy->ops, 1);
1373
1374     /* out[fid] is the function
1375      * everything above is parameters...
1376      */
1377     if (!vec_size(sy->argc)) {
1378         parseerror(parser, "internal error: no argument counter available");
1379         return false;
1380     }
1381
1382     paramcount = vec_last(sy->argc);
1383     vec_pop(sy->argc);
1384
1385     if (vec_size(sy->out) < fid) {
1386         parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1387                    (unsigned long)vec_size(sy->out),
1388                    (unsigned long)fid,
1389                    (unsigned long)paramcount);
1390         return false;
1391     }
1392
1393     fun = sy->out[fid].out;
1394
1395     if (fun == intrinsic_debug_typestring) {
1396         char ty[1024];
1397         if (fid+2 != vec_size(sy->out) ||
1398             vec_last(sy->out).block)
1399         {
1400             parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1401             return false;
1402         }
1403         ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1404         ast_unref(vec_last(sy->out).out);
1405         sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1406                              (ast_expression*)parser_const_string(parser, ty, false));
1407         vec_shrinkby(sy->out, 1);
1408         return true;
1409     }
1410
1411     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1412     if (!call)
1413         return false;
1414
1415     if (fid+1 < vec_size(sy->out))
1416         ++paramcount;
1417
1418     if (fid+1 + paramcount != vec_size(sy->out)) {
1419         parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1420                    (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1421         return false;
1422     }
1423
1424     for (i = 0; i < paramcount; ++i)
1425         vec_push(call->params, sy->out[fid+1 + i].out);
1426     vec_shrinkby(sy->out, paramcount);
1427     (void)!ast_call_check_types(call);
1428     if (parser->max_param_count < paramcount)
1429         parser->max_param_count = paramcount;
1430
1431     if (ast_istype(fun, ast_value)) {
1432         funval = (ast_value*)fun;
1433         if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1434             !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1435         {
1436             call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1437         }
1438     }
1439
1440     /* overwrite fid, the function, with a call */
1441     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1442
1443     if (fun->expression.vtype != TYPE_FUNCTION) {
1444         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1445         return false;
1446     }
1447
1448     if (!fun->expression.next) {
1449         parseerror(parser, "could not determine function return type");
1450         return false;
1451     } else {
1452         ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1453
1454         if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1455             if (!fval) {
1456                 return !parsewarning(parser, WARN_DEPRECATED,
1457                         "call to function (which is marked deprecated)\n",
1458                         "-> it has been declared here: %s:%i",
1459                         ast_ctx(fun).file, ast_ctx(fun).line);
1460             }
1461             if (!fval->desc) {
1462                 return !parsewarning(parser, WARN_DEPRECATED,
1463                         "call to `%s` (which is marked deprecated)\n"
1464                         "-> `%s` declared here: %s:%i",
1465                         fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1466             }
1467             return !parsewarning(parser, WARN_DEPRECATED,
1468                     "call to `%s` (deprecated: %s)\n"
1469                     "-> `%s` declared here: %s:%i",
1470                     fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1471                     ast_ctx(fun).line);
1472         }
1473
1474         if (vec_size(fun->expression.params) != paramcount &&
1475             !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1476               vec_size(fun->expression.params) < paramcount))
1477         {
1478             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1479             if (fval)
1480                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1481                                      "too %s parameters for call to %s: expected %i, got %i\n"
1482                                      " -> `%s` has been declared here: %s:%i",
1483                                      fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1484                                      fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1485             else
1486                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1487                                      "too %s parameters for function call: expected %i, got %i\n"
1488                                      " -> it has been declared here: %s:%i",
1489                                      fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1490                                      ast_ctx(fun).file, (int)ast_ctx(fun).line);
1491         }
1492     }
1493
1494     return true;
1495 }
1496
1497 static bool parser_close_paren(parser_t *parser, shunt *sy)
1498 {
1499     if (!vec_size(sy->ops)) {
1500         parseerror(parser, "unmatched closing paren");
1501         return false;
1502     }
1503
1504     while (vec_size(sy->ops)) {
1505         if (vec_last(sy->ops).isparen) {
1506             if (vec_last(sy->paren) == PAREN_FUNC) {
1507                 vec_pop(sy->paren);
1508                 if (!parser_close_call(parser, sy))
1509                     return false;
1510                 break;
1511             }
1512             if (vec_last(sy->paren) == PAREN_EXPR) {
1513                 vec_pop(sy->paren);
1514                 if (!vec_size(sy->out)) {
1515                     compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1516                     vec_shrinkby(sy->ops, 1);
1517                     return false;
1518                 }
1519                 vec_shrinkby(sy->ops, 1);
1520                 break;
1521             }
1522             if (vec_last(sy->paren) == PAREN_INDEX) {
1523                 vec_pop(sy->paren);
1524                 /* pop off the parenthesis */
1525                 vec_shrinkby(sy->ops, 1);
1526                 /* then apply the index operator */
1527                 if (!parser_sy_apply_operator(parser, sy))
1528                     return false;
1529                 break;
1530             }
1531             if (vec_last(sy->paren) == PAREN_TERNARY1) {
1532                 vec_last(sy->paren) = PAREN_TERNARY2;
1533                 /* pop off the parenthesis */
1534                 vec_shrinkby(sy->ops, 1);
1535                 break;
1536             }
1537             compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1538             return false;
1539         }
1540         if (!parser_sy_apply_operator(parser, sy))
1541             return false;
1542     }
1543     return true;
1544 }
1545
1546 static void parser_reclassify_token(parser_t *parser)
1547 {
1548     size_t i;
1549     for (i = 0; i < operator_count; ++i) {
1550         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1551             parser->tok = TOKEN_OPERATOR;
1552             return;
1553         }
1554     }
1555 }
1556
1557 static ast_expression* parse_vararg_do(parser_t *parser)
1558 {
1559     ast_expression *idx, *out;
1560     ast_value      *typevar;
1561     ast_value      *funtype = parser->function->vtype;
1562
1563     lex_ctx ctx = parser_ctx(parser);
1564
1565     if (!parser_next(parser) || parser->tok != '(') {
1566         parseerror(parser, "expected parameter index and type in parenthesis");
1567         return NULL;
1568     }
1569     if (!parser_next(parser)) {
1570         parseerror(parser, "error parsing parameter index");
1571         return NULL;
1572     }
1573
1574     idx = parse_expression_leave(parser, true, false, false);
1575     if (!idx)
1576         return NULL;
1577
1578     if (parser->tok != ',') {
1579         ast_unref(idx);
1580         parseerror(parser, "expected comma after parameter index");
1581         return NULL;
1582     }
1583
1584     if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1585         ast_unref(idx);
1586         parseerror(parser, "expected typename for vararg");
1587         return NULL;
1588     }
1589
1590     typevar = parse_typename(parser, NULL, NULL);
1591     if (!typevar) {
1592         ast_unref(idx);
1593         return NULL;
1594     }
1595
1596     if (parser->tok != ')') {
1597         ast_unref(idx);
1598         ast_delete(typevar);
1599         parseerror(parser, "expected closing paren");
1600         return NULL;
1601     }
1602
1603 #if 0
1604     if (!parser_next(parser)) {
1605         ast_unref(idx);
1606         ast_delete(typevar);
1607         parseerror(parser, "parse error after vararg");
1608         return NULL;
1609     }
1610 #endif
1611
1612     if (!parser->function->varargs) {
1613         ast_unref(idx);
1614         ast_delete(typevar);
1615         parseerror(parser, "function has no variable argument list");
1616         return NULL;
1617     }
1618
1619     if (funtype->expression.varparam &&
1620         !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1621     {
1622         char ty1[1024];
1623         char ty2[1024];
1624         ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1625         ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1626         compile_error(ast_ctx(typevar),
1627                       "function was declared to take varargs of type `%s`, requested type is: %s",
1628                       ty2, ty1);
1629     }
1630
1631     out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1632     ast_type_adopt(out, typevar);
1633     ast_delete(typevar);
1634     return out;
1635 }
1636
1637 static ast_expression* parse_vararg(parser_t *parser)
1638 {
1639     bool           old_noops = parser->lex->flags.noops;
1640
1641     ast_expression *out;
1642
1643     parser->lex->flags.noops = true;
1644     out = parse_vararg_do(parser);
1645
1646     parser->lex->flags.noops = old_noops;
1647     return out;
1648 }
1649
1650 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1651 {
1652     if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1653         parser->tok == TOKEN_IDENT &&
1654         !strcmp(parser_tokval(parser), "_"))
1655     {
1656         /* a translatable string */
1657         ast_value *val;
1658
1659         parser->lex->flags.noops = true;
1660         if (!parser_next(parser) || parser->tok != '(') {
1661             parseerror(parser, "use _(\"string\") to create a translatable string constant");
1662             return false;
1663         }
1664         parser->lex->flags.noops = false;
1665         if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1666             parseerror(parser, "expected a constant string in translatable-string extension");
1667             return false;
1668         }
1669         val = parser_const_string(parser, parser_tokval(parser), true);
1670         if (!val)
1671             return false;
1672         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1673
1674         if (!parser_next(parser) || parser->tok != ')') {
1675             parseerror(parser, "expected closing paren after translatable string");
1676             return false;
1677         }
1678         return true;
1679     }
1680     else if (parser->tok == TOKEN_DOTS)
1681     {
1682         ast_expression *va;
1683         if (!OPTS_FLAG(VARIADIC_ARGS)) {
1684             parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1685             return false;
1686         }
1687         va = parse_vararg(parser);
1688         if (!va)
1689             return false;
1690         vec_push(sy->out, syexp(parser_ctx(parser), va));
1691         return true;
1692     }
1693     else if (parser->tok == TOKEN_FLOATCONST) {
1694         ast_value *val;
1695         val = parser_const_float(parser, (parser_token(parser)->constval.f));
1696         if (!val)
1697             return false;
1698         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1699         return true;
1700     }
1701     else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1702         ast_value *val;
1703         val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1704         if (!val)
1705             return false;
1706         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1707         return true;
1708     }
1709     else if (parser->tok == TOKEN_STRINGCONST) {
1710         ast_value *val;
1711         val = parser_const_string(parser, parser_tokval(parser), false);
1712         if (!val)
1713             return false;
1714         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1715         return true;
1716     }
1717     else if (parser->tok == TOKEN_VECTORCONST) {
1718         ast_value *val;
1719         val = parser_const_vector(parser, parser_token(parser)->constval.v);
1720         if (!val)
1721             return false;
1722         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1723         return true;
1724     }
1725     else if (parser->tok == TOKEN_IDENT)
1726     {
1727         const char     *ctoken = parser_tokval(parser);
1728         ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1729         ast_expression *var;
1730         /* a_vector.{x,y,z} */
1731         if (!vec_size(sy->ops) ||
1732             !vec_last(sy->ops).etype ||
1733             operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1734             (prev >= intrinsic_debug_typestring &&
1735              prev <= intrinsic_debug_typestring))
1736         {
1737             /* When adding more intrinsics, fix the above condition */
1738             prev = NULL;
1739         }
1740         if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1741         {
1742             var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1743         } else {
1744             var = parser_find_var(parser, parser_tokval(parser));
1745             if (!var)
1746                 var = parser_find_field(parser, parser_tokval(parser));
1747         }
1748         if (!var && with_labels) {
1749             var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1750             if (!with_labels) {
1751                 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1752                 var = (ast_expression*)lbl;
1753                 vec_push(parser->labels, lbl);
1754             }
1755         }
1756         if (!var) {
1757             /* intrinsics */
1758             if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1759                 var = (ast_expression*)intrinsic_debug_typestring;
1760             }
1761             else
1762             {
1763                 char *correct = NULL;
1764                 size_t i;
1765
1766                 /*
1767                  * sometimes people use preprocessing predefs without enabling them
1768                  * i've done this thousands of times already myself.  Lets check for
1769                  * it in the predef table.  And diagnose it better :)
1770                  */
1771                 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1772                     for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1773                         if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1774                             parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1775                             return false;
1776                         }
1777                     }
1778                 }
1779
1780                 /*
1781                  * TODO: determine the best score for the identifier: be it
1782                  * a variable, a field.
1783                  *
1784                  * We should also consider adding correction tables for
1785                  * other things as well.
1786                  */
1787                 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1788                     correction_t corr;
1789                     correct_init(&corr);
1790
1791                     for (i = 0; i < vec_size(parser->correct_variables); i++) {
1792                         correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1793                         if (strcmp(correct, parser_tokval(parser))) {
1794                             break;
1795                         } else if (correct) {
1796                             mem_d(correct);
1797                             correct = NULL;
1798                         }
1799                     }
1800                     correct_free(&corr);
1801
1802                     if (correct) {
1803                         parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1804                         mem_d(correct);
1805                         return false;
1806                     }
1807                 }
1808                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1809                 return false;
1810             }
1811         }
1812         else
1813         {
1814             if (ast_istype(var, ast_value)) {
1815                 ((ast_value*)var)->uses++;
1816             }
1817             else if (ast_istype(var, ast_member)) {
1818                 ast_member *mem = (ast_member*)var;
1819                 if (ast_istype(mem->owner, ast_value))
1820                     ((ast_value*)(mem->owner))->uses++;
1821             }
1822         }
1823         vec_push(sy->out, syexp(parser_ctx(parser), var));
1824         return true;
1825     }
1826     parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1827     return false;
1828 }
1829
1830 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1831 {
1832     ast_expression *expr = NULL;
1833     shunt sy;
1834     size_t i;
1835     bool wantop = false;
1836     /* only warn once about an assignment in a truth value because the current code
1837      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1838      */
1839     bool warn_truthvalue = true;
1840
1841     /* count the parens because an if starts with one, so the
1842      * end of a condition is an unmatched closing paren
1843      */
1844     int ternaries = 0;
1845
1846     memset(&sy, 0, sizeof(sy));
1847
1848     parser->lex->flags.noops = false;
1849
1850     parser_reclassify_token(parser);
1851
1852     while (true)
1853     {
1854         if (parser->tok == TOKEN_TYPENAME) {
1855             parseerror(parser, "unexpected typename");
1856             goto onerr;
1857         }
1858
1859         if (parser->tok == TOKEN_OPERATOR)
1860         {
1861             /* classify the operator */
1862             const oper_info *op;
1863             const oper_info *olast = NULL;
1864             size_t o;
1865             for (o = 0; o < operator_count; ++o) {
1866                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1867                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1868                     !strcmp(parser_tokval(parser), operators[o].op))
1869                 {
1870                     break;
1871                 }
1872             }
1873             if (o == operator_count) {
1874                 /* no operator found... must be the end of the statement */
1875                 break;
1876             }
1877             /* found an operator */
1878             op = &operators[o];
1879
1880             /* when declaring variables, a comma starts a new variable */
1881             if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1882                 /* fixup the token */
1883                 parser->tok = ',';
1884                 break;
1885             }
1886
1887             /* a colon without a pervious question mark cannot be a ternary */
1888             if (!ternaries && op->id == opid2(':','?')) {
1889                 parser->tok = ':';
1890                 break;
1891             }
1892
1893             if (op->id == opid1(',')) {
1894                 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1895                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1896                 }
1897             }
1898
1899             if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1900                 olast = &operators[vec_last(sy.ops).etype-1];
1901
1902 #define IsAssignOp(x) (\
1903                 (x) == opid1('=') || \
1904                 (x) == opid2('+','=') || \
1905                 (x) == opid2('-','=') || \
1906                 (x) == opid2('*','=') || \
1907                 (x) == opid2('/','=') || \
1908                 (x) == opid2('%','=') || \
1909                 (x) == opid2('&','=') || \
1910                 (x) == opid2('|','=') || \
1911                 (x) == opid3('&','~','=') \
1912                 )
1913             if (warn_truthvalue) {
1914                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1915                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1916                      (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1917                    )
1918                 {
1919                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1920                     warn_truthvalue = false;
1921                 }
1922             }
1923
1924             while (olast && (
1925                     (op->prec < olast->prec) ||
1926                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1927             {
1928                 if (!parser_sy_apply_operator(parser, &sy))
1929                     goto onerr;
1930                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1931                     olast = &operators[vec_last(sy.ops).etype-1];
1932                 else
1933                     olast = NULL;
1934             }
1935
1936             if (op->id == opid1('(')) {
1937                 if (wantop) {
1938                     size_t sycount = vec_size(sy.out);
1939                     /* we expected an operator, this is the function-call operator */
1940                     vec_push(sy.paren, PAREN_FUNC);
1941                     vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1942                     vec_push(sy.argc, 0);
1943                 } else {
1944                     vec_push(sy.paren, PAREN_EXPR);
1945                     vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1946                 }
1947                 wantop = false;
1948             } else if (op->id == opid1('[')) {
1949                 if (!wantop) {
1950                     parseerror(parser, "unexpected array subscript");
1951                     goto onerr;
1952                 }
1953                 vec_push(sy.paren, PAREN_INDEX);
1954                 /* push both the operator and the paren, this makes life easier */
1955                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1956                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1957                 wantop = false;
1958             } else if (op->id == opid2('?',':')) {
1959                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1960                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1961                 wantop = false;
1962                 ++ternaries;
1963                 vec_push(sy.paren, PAREN_TERNARY1);
1964             } else if (op->id == opid2(':','?')) {
1965                 if (!vec_size(sy.paren)) {
1966                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1967                     goto onerr;
1968                 }
1969                 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1970                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1971                     goto onerr;
1972                 }
1973                 if (!parser_close_paren(parser, &sy))
1974                     goto onerr;
1975                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1976                 wantop = false;
1977                 --ternaries;
1978             } else {
1979                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1980                 wantop = !!(op->flags & OP_SUFFIX);
1981             }
1982         }
1983         else if (parser->tok == ')') {
1984             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1985                 if (!parser_sy_apply_operator(parser, &sy))
1986                     goto onerr;
1987             }
1988             if (!vec_size(sy.paren))
1989                 break;
1990             if (wantop) {
1991                 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1992                     parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1993                     goto onerr;
1994                 }
1995                 if (!parser_close_paren(parser, &sy))
1996                     goto onerr;
1997             } else {
1998                 /* must be a function call without parameters */
1999                 if (vec_last(sy.paren) != PAREN_FUNC) {
2000                     parseerror(parser, "closing paren in invalid position");
2001                     goto onerr;
2002                 }
2003                 if (!parser_close_paren(parser, &sy))
2004                     goto onerr;
2005             }
2006             wantop = true;
2007         }
2008         else if (parser->tok == '(') {
2009             parseerror(parser, "internal error: '(' should be classified as operator");
2010             goto onerr;
2011         }
2012         else if (parser->tok == '[') {
2013             parseerror(parser, "internal error: '[' should be classified as operator");
2014             goto onerr;
2015         }
2016         else if (parser->tok == ']') {
2017             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2018                 if (!parser_sy_apply_operator(parser, &sy))
2019                     goto onerr;
2020             }
2021             if (!vec_size(sy.paren))
2022                 break;
2023             if (vec_last(sy.paren) != PAREN_INDEX) {
2024                 parseerror(parser, "mismatched parentheses, unexpected ']'");
2025                 goto onerr;
2026             }
2027             if (!parser_close_paren(parser, &sy))
2028                 goto onerr;
2029             wantop = true;
2030         }
2031         else if (!wantop) {
2032             if (!parse_sya_operand(parser, &sy, with_labels))
2033                 goto onerr;
2034 #if 0
2035             if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2036                 vec_last(sy.argc)++;
2037 #endif
2038             wantop = true;
2039         }
2040         else {
2041             parseerror(parser, "expected operator or end of statement");
2042             goto onerr;
2043         }
2044
2045         if (!parser_next(parser)) {
2046             goto onerr;
2047         }
2048         if (parser->tok == ';' ||
2049             ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2050             (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2051         {
2052             break;
2053         }
2054     }
2055
2056     while (vec_size(sy.ops)) {
2057         if (!parser_sy_apply_operator(parser, &sy))
2058             goto onerr;
2059     }
2060
2061     parser->lex->flags.noops = true;
2062     if (!vec_size(sy.out)) {
2063         parseerror(parser, "empty expression");
2064         expr = NULL;
2065     } else
2066         expr = sy.out[0].out;
2067     vec_free(sy.out);
2068     vec_free(sy.ops);
2069     if (vec_size(sy.paren)) {
2070         parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2071         return NULL;
2072     }
2073     vec_free(sy.paren);
2074     vec_free(sy.argc);
2075     return expr;
2076
2077 onerr:
2078     parser->lex->flags.noops = true;
2079     for (i = 0; i < vec_size(sy.out); ++i) {
2080         if (sy.out[i].out)
2081             ast_unref(sy.out[i].out);
2082     }
2083     vec_free(sy.out);
2084     vec_free(sy.ops);
2085     vec_free(sy.paren);
2086     vec_free(sy.argc);
2087     return NULL;
2088 }
2089
2090 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2091 {
2092     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2093     if (!e)
2094         return NULL;
2095     if (parser->tok != ';') {
2096         parseerror(parser, "semicolon expected after expression");
2097         ast_unref(e);
2098         return NULL;
2099     }
2100     if (!parser_next(parser)) {
2101         ast_unref(e);
2102         return NULL;
2103     }
2104     return e;
2105 }
2106
2107 static void parser_enterblock(parser_t *parser)
2108 {
2109     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2110     vec_push(parser->_blocklocals, vec_size(parser->_locals));
2111     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2112     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2113     vec_push(parser->_block_ctx, parser_ctx(parser));
2114
2115     /* corrector */
2116     vec_push(parser->correct_variables, correct_trie_new());
2117     vec_push(parser->correct_variables_score, NULL);
2118 }
2119
2120 static bool parser_leaveblock(parser_t *parser)
2121 {
2122     bool   rv = true;
2123     size_t locals, typedefs;
2124
2125     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2126         parseerror(parser, "internal error: parser_leaveblock with no block");
2127         return false;
2128     }
2129
2130     util_htdel(vec_last(parser->variables));
2131     correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2132
2133     vec_pop(parser->variables);
2134     vec_pop(parser->correct_variables);
2135     vec_pop(parser->correct_variables_score);
2136     if (!vec_size(parser->_blocklocals)) {
2137         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2138         return false;
2139     }
2140
2141     locals = vec_last(parser->_blocklocals);
2142     vec_pop(parser->_blocklocals);
2143     while (vec_size(parser->_locals) != locals) {
2144         ast_expression *e = vec_last(parser->_locals);
2145         ast_value      *v = (ast_value*)e;
2146         vec_pop(parser->_locals);
2147         if (ast_istype(e, ast_value) && !v->uses) {
2148             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2149                 rv = false;
2150         }
2151     }
2152
2153     typedefs = vec_last(parser->_blocktypedefs);
2154     while (vec_size(parser->_typedefs) != typedefs) {
2155         ast_delete(vec_last(parser->_typedefs));
2156         vec_pop(parser->_typedefs);
2157     }
2158     util_htdel(vec_last(parser->typedefs));
2159     vec_pop(parser->typedefs);
2160
2161     vec_pop(parser->_block_ctx);
2162
2163     return rv;
2164 }
2165
2166 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2167 {
2168     vec_push(parser->_locals, e);
2169     util_htset(vec_last(parser->variables), name, (void*)e);
2170
2171     /* corrector */
2172     correct_add (
2173          vec_last(parser->correct_variables),
2174         &vec_last(parser->correct_variables_score),
2175         name
2176     );
2177 }
2178
2179 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2180 {
2181     vec_push(parser->globals, e);
2182     util_htset(parser->htglobals, name, e);
2183
2184     /* corrector */
2185     correct_add (
2186          parser->correct_variables[0],
2187         &parser->correct_variables_score[0],
2188         name
2189     );
2190 }
2191
2192 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2193 {
2194     bool       ifnot = false;
2195     ast_unary *unary;
2196     ast_expression *prev;
2197
2198     if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2199         char ty[1024];
2200         ast_type_to_string(cond, ty, sizeof(ty));
2201         compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2202     }
2203
2204     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2205     {
2206         prev = cond;
2207         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2208         if (!cond) {
2209             ast_unref(prev);
2210             parseerror(parser, "internal error: failed to process condition");
2211             return NULL;
2212         }
2213         ifnot = !ifnot;
2214     }
2215     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2216     {
2217         /* vector types need to be cast to true booleans */
2218         ast_binary *bin = (ast_binary*)cond;
2219         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2220         {
2221             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2222             prev = cond;
2223             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2224             if (!cond) {
2225                 ast_unref(prev);
2226                 parseerror(parser, "internal error: failed to process condition");
2227                 return NULL;
2228             }
2229             ifnot = !ifnot;
2230         }
2231     }
2232
2233     unary = (ast_unary*)cond;
2234     while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2235     {
2236         cond = unary->operand;
2237         unary->operand = NULL;
2238         ast_delete(unary);
2239         ifnot = !ifnot;
2240         unary = (ast_unary*)cond;
2241     }
2242
2243     if (!cond)
2244         parseerror(parser, "internal error: failed to process condition");
2245
2246     if (ifnot) *_ifnot = !*_ifnot;
2247     return cond;
2248 }
2249
2250 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2251 {
2252     ast_ifthen *ifthen;
2253     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2254     bool ifnot = false;
2255
2256     lex_ctx ctx = parser_ctx(parser);
2257
2258     (void)block; /* not touching */
2259
2260     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2261     if (!parser_next(parser)) {
2262         parseerror(parser, "expected condition or 'not'");
2263         return false;
2264     }
2265     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2266         ifnot = true;
2267         if (!parser_next(parser)) {
2268             parseerror(parser, "expected condition in parenthesis");
2269             return false;
2270         }
2271     }
2272     if (parser->tok != '(') {
2273         parseerror(parser, "expected 'if' condition in parenthesis");
2274         return false;
2275     }
2276     /* parse into the expression */
2277     if (!parser_next(parser)) {
2278         parseerror(parser, "expected 'if' condition after opening paren");
2279         return false;
2280     }
2281     /* parse the condition */
2282     cond = parse_expression_leave(parser, false, true, false);
2283     if (!cond)
2284         return false;
2285     /* closing paren */
2286     if (parser->tok != ')') {
2287         parseerror(parser, "expected closing paren after 'if' condition");
2288         ast_delete(cond);
2289         return false;
2290     }
2291     /* parse into the 'then' branch */
2292     if (!parser_next(parser)) {
2293         parseerror(parser, "expected statement for on-true branch of 'if'");
2294         ast_delete(cond);
2295         return false;
2296     }
2297     if (!parse_statement_or_block(parser, &ontrue)) {
2298         ast_delete(cond);
2299         return false;
2300     }
2301     if (!ontrue)
2302         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2303     /* check for an else */
2304     if (!strcmp(parser_tokval(parser), "else")) {
2305         /* parse into the 'else' branch */
2306         if (!parser_next(parser)) {
2307             parseerror(parser, "expected on-false branch after 'else'");
2308             ast_delete(ontrue);
2309             ast_delete(cond);
2310             return false;
2311         }
2312         if (!parse_statement_or_block(parser, &onfalse)) {
2313             ast_delete(ontrue);
2314             ast_delete(cond);
2315             return false;
2316         }
2317     }
2318
2319     cond = process_condition(parser, cond, &ifnot);
2320     if (!cond) {
2321         if (ontrue)  ast_delete(ontrue);
2322         if (onfalse) ast_delete(onfalse);
2323         return false;
2324     }
2325
2326     if (ifnot)
2327         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2328     else
2329         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2330     *out = (ast_expression*)ifthen;
2331     return true;
2332 }
2333
2334 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2335 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2336 {
2337     bool rv;
2338     char *label = NULL;
2339
2340     /* skip the 'while' and get the body */
2341     if (!parser_next(parser)) {
2342         if (OPTS_FLAG(LOOP_LABELS))
2343             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2344         else
2345             parseerror(parser, "expected 'while' condition in parenthesis");
2346         return false;
2347     }
2348
2349     if (parser->tok == ':') {
2350         if (!OPTS_FLAG(LOOP_LABELS))
2351             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2352         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2353             parseerror(parser, "expected loop label");
2354             return false;
2355         }
2356         label = util_strdup(parser_tokval(parser));
2357         if (!parser_next(parser)) {
2358             mem_d(label);
2359             parseerror(parser, "expected 'while' condition in parenthesis");
2360             return false;
2361         }
2362     }
2363
2364     if (parser->tok != '(') {
2365         parseerror(parser, "expected 'while' condition in parenthesis");
2366         return false;
2367     }
2368
2369     vec_push(parser->breaks, label);
2370     vec_push(parser->continues, label);
2371
2372     rv = parse_while_go(parser, block, out);
2373     if (label)
2374         mem_d(label);
2375     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2376         parseerror(parser, "internal error: label stack corrupted");
2377         rv = false;
2378         ast_delete(*out);
2379         *out = NULL;
2380     }
2381     else {
2382         vec_pop(parser->breaks);
2383         vec_pop(parser->continues);
2384     }
2385     return rv;
2386 }
2387
2388 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2389 {
2390     ast_loop *aloop;
2391     ast_expression *cond, *ontrue;
2392
2393     bool ifnot = false;
2394
2395     lex_ctx ctx = parser_ctx(parser);
2396
2397     (void)block; /* not touching */
2398
2399     /* parse into the expression */
2400     if (!parser_next(parser)) {
2401         parseerror(parser, "expected 'while' condition after opening paren");
2402         return false;
2403     }
2404     /* parse the condition */
2405     cond = parse_expression_leave(parser, false, true, false);
2406     if (!cond)
2407         return false;
2408     /* closing paren */
2409     if (parser->tok != ')') {
2410         parseerror(parser, "expected closing paren after 'while' condition");
2411         ast_delete(cond);
2412         return false;
2413     }
2414     /* parse into the 'then' branch */
2415     if (!parser_next(parser)) {
2416         parseerror(parser, "expected while-loop body");
2417         ast_delete(cond);
2418         return false;
2419     }
2420     if (!parse_statement_or_block(parser, &ontrue)) {
2421         ast_delete(cond);
2422         return false;
2423     }
2424
2425     cond = process_condition(parser, cond, &ifnot);
2426     if (!cond) {
2427         ast_delete(ontrue);
2428         return false;
2429     }
2430     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2431     *out = (ast_expression*)aloop;
2432     return true;
2433 }
2434
2435 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2436 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2437 {
2438     bool rv;
2439     char *label = NULL;
2440
2441     /* skip the 'do' and get the body */
2442     if (!parser_next(parser)) {
2443         if (OPTS_FLAG(LOOP_LABELS))
2444             parseerror(parser, "expected loop label or body");
2445         else
2446             parseerror(parser, "expected loop body");
2447         return false;
2448     }
2449
2450     if (parser->tok == ':') {
2451         if (!OPTS_FLAG(LOOP_LABELS))
2452             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2453         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2454             parseerror(parser, "expected loop label");
2455             return false;
2456         }
2457         label = util_strdup(parser_tokval(parser));
2458         if (!parser_next(parser)) {
2459             mem_d(label);
2460             parseerror(parser, "expected loop body");
2461             return false;
2462         }
2463     }
2464
2465     vec_push(parser->breaks, label);
2466     vec_push(parser->continues, label);
2467
2468     rv = parse_dowhile_go(parser, block, out);
2469     if (label)
2470         mem_d(label);
2471     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2472         parseerror(parser, "internal error: label stack corrupted");
2473         rv = false;
2474         ast_delete(*out);
2475         *out = NULL;
2476     }
2477     else {
2478         vec_pop(parser->breaks);
2479         vec_pop(parser->continues);
2480     }
2481     return rv;
2482 }
2483
2484 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2485 {
2486     ast_loop *aloop;
2487     ast_expression *cond, *ontrue;
2488
2489     bool ifnot = false;
2490
2491     lex_ctx ctx = parser_ctx(parser);
2492
2493     (void)block; /* not touching */
2494
2495     if (!parse_statement_or_block(parser, &ontrue))
2496         return false;
2497
2498     /* expect the "while" */
2499     if (parser->tok != TOKEN_KEYWORD ||
2500         strcmp(parser_tokval(parser), "while"))
2501     {
2502         parseerror(parser, "expected 'while' and condition");
2503         ast_delete(ontrue);
2504         return false;
2505     }
2506
2507     /* skip the 'while' and check for opening paren */
2508     if (!parser_next(parser) || parser->tok != '(') {
2509         parseerror(parser, "expected 'while' condition in parenthesis");
2510         ast_delete(ontrue);
2511         return false;
2512     }
2513     /* parse into the expression */
2514     if (!parser_next(parser)) {
2515         parseerror(parser, "expected 'while' condition after opening paren");
2516         ast_delete(ontrue);
2517         return false;
2518     }
2519     /* parse the condition */
2520     cond = parse_expression_leave(parser, false, true, false);
2521     if (!cond)
2522         return false;
2523     /* closing paren */
2524     if (parser->tok != ')') {
2525         parseerror(parser, "expected closing paren after 'while' condition");
2526         ast_delete(ontrue);
2527         ast_delete(cond);
2528         return false;
2529     }
2530     /* parse on */
2531     if (!parser_next(parser) || parser->tok != ';') {
2532         parseerror(parser, "expected semicolon after condition");
2533         ast_delete(ontrue);
2534         ast_delete(cond);
2535         return false;
2536     }
2537
2538     if (!parser_next(parser)) {
2539         parseerror(parser, "parse error");
2540         ast_delete(ontrue);
2541         ast_delete(cond);
2542         return false;
2543     }
2544
2545     cond = process_condition(parser, cond, &ifnot);
2546     if (!cond) {
2547         ast_delete(ontrue);
2548         return false;
2549     }
2550     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2551     *out = (ast_expression*)aloop;
2552     return true;
2553 }
2554
2555 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2556 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2557 {
2558     bool rv;
2559     char *label = NULL;
2560
2561     /* skip the 'for' and check for opening paren */
2562     if (!parser_next(parser)) {
2563         if (OPTS_FLAG(LOOP_LABELS))
2564             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2565         else
2566             parseerror(parser, "expected 'for' expressions in parenthesis");
2567         return false;
2568     }
2569
2570     if (parser->tok == ':') {
2571         if (!OPTS_FLAG(LOOP_LABELS))
2572             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2573         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2574             parseerror(parser, "expected loop label");
2575             return false;
2576         }
2577         label = util_strdup(parser_tokval(parser));
2578         if (!parser_next(parser)) {
2579             mem_d(label);
2580             parseerror(parser, "expected 'for' expressions in parenthesis");
2581             return false;
2582         }
2583     }
2584
2585     if (parser->tok != '(') {
2586         parseerror(parser, "expected 'for' expressions in parenthesis");
2587         return false;
2588     }
2589
2590     vec_push(parser->breaks, label);
2591     vec_push(parser->continues, label);
2592
2593     rv = parse_for_go(parser, block, out);
2594     if (label)
2595         mem_d(label);
2596     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2597         parseerror(parser, "internal error: label stack corrupted");
2598         rv = false;
2599         ast_delete(*out);
2600         *out = NULL;
2601     }
2602     else {
2603         vec_pop(parser->breaks);
2604         vec_pop(parser->continues);
2605     }
2606     return rv;
2607 }
2608 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2609 {
2610     ast_loop       *aloop;
2611     ast_expression *initexpr, *cond, *increment, *ontrue;
2612     ast_value      *typevar;
2613
2614     bool retval = true;
2615     bool ifnot  = false;
2616
2617     lex_ctx ctx = parser_ctx(parser);
2618
2619     parser_enterblock(parser);
2620
2621     initexpr  = NULL;
2622     cond      = NULL;
2623     increment = NULL;
2624     ontrue    = NULL;
2625
2626     /* parse into the expression */
2627     if (!parser_next(parser)) {
2628         parseerror(parser, "expected 'for' initializer after opening paren");
2629         goto onerr;
2630     }
2631
2632     typevar = NULL;
2633     if (parser->tok == TOKEN_IDENT)
2634         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2635
2636     if (typevar || parser->tok == TOKEN_TYPENAME) {
2637 #if 0
2638         if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2639             if (parsewarning(parser, WARN_EXTENSIONS,
2640                              "current standard does not allow variable declarations in for-loop initializers"))
2641                 goto onerr;
2642         }
2643 #endif
2644         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2645             goto onerr;
2646     }
2647     else if (parser->tok != ';')
2648     {
2649         initexpr = parse_expression_leave(parser, false, false, false);
2650         if (!initexpr)
2651             goto onerr;
2652     }
2653
2654     /* move on to condition */
2655     if (parser->tok != ';') {
2656         parseerror(parser, "expected semicolon after for-loop initializer");
2657         goto onerr;
2658     }
2659     if (!parser_next(parser)) {
2660         parseerror(parser, "expected for-loop condition");
2661         goto onerr;
2662     }
2663
2664     /* parse the condition */
2665     if (parser->tok != ';') {
2666         cond = parse_expression_leave(parser, false, true, false);
2667         if (!cond)
2668             goto onerr;
2669     }
2670
2671     /* move on to incrementor */
2672     if (parser->tok != ';') {
2673         parseerror(parser, "expected semicolon after for-loop initializer");
2674         goto onerr;
2675     }
2676     if (!parser_next(parser)) {
2677         parseerror(parser, "expected for-loop condition");
2678         goto onerr;
2679     }
2680
2681     /* parse the incrementor */
2682     if (parser->tok != ')') {
2683         lex_ctx condctx = parser_ctx(parser);
2684         increment = parse_expression_leave(parser, false, false, false);
2685         if (!increment)
2686             goto onerr;
2687         if (!ast_side_effects(increment)) {
2688             if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2689                 goto onerr;
2690         }
2691     }
2692
2693     /* closing paren */
2694     if (parser->tok != ')') {
2695         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2696         goto onerr;
2697     }
2698     /* parse into the 'then' branch */
2699     if (!parser_next(parser)) {
2700         parseerror(parser, "expected for-loop body");
2701         goto onerr;
2702     }
2703     if (!parse_statement_or_block(parser, &ontrue))
2704         goto onerr;
2705
2706     if (cond) {
2707         cond = process_condition(parser, cond, &ifnot);
2708         if (!cond)
2709             goto onerr;
2710     }
2711     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2712     *out = (ast_expression*)aloop;
2713
2714     if (!parser_leaveblock(parser))
2715         retval = false;
2716     return retval;
2717 onerr:
2718     if (initexpr)  ast_delete(initexpr);
2719     if (cond)      ast_delete(cond);
2720     if (increment) ast_delete(increment);
2721     (void)!parser_leaveblock(parser);
2722     return false;
2723 }
2724
2725 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2726 {
2727     ast_expression *exp = NULL;
2728     ast_return     *ret = NULL;
2729     ast_value      *expected = parser->function->vtype;
2730
2731     lex_ctx ctx = parser_ctx(parser);
2732
2733     (void)block; /* not touching */
2734
2735     if (!parser_next(parser)) {
2736         parseerror(parser, "expected return expression");
2737         return false;
2738     }
2739
2740     if (parser->tok != ';') {
2741         exp = parse_expression(parser, false, false);
2742         if (!exp)
2743             return false;
2744
2745         if (exp->expression.vtype != TYPE_NIL &&
2746             exp->expression.vtype != expected->expression.next->expression.vtype)
2747         {
2748             parseerror(parser, "return with invalid expression");
2749         }
2750
2751         ret = ast_return_new(ctx, exp);
2752         if (!ret) {
2753             ast_delete(exp);
2754             return false;
2755         }
2756     } else {
2757         if (!parser_next(parser))
2758             parseerror(parser, "parse error");
2759         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2760             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2761         }
2762         ret = ast_return_new(ctx, NULL);
2763     }
2764     *out = (ast_expression*)ret;
2765     return true;
2766 }
2767
2768 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2769 {
2770     size_t       i;
2771     unsigned int levels = 0;
2772     lex_ctx      ctx = parser_ctx(parser);
2773     const char **loops = (is_continue ? parser->continues : parser->breaks);
2774
2775     (void)block; /* not touching */
2776     if (!parser_next(parser)) {
2777         parseerror(parser, "expected semicolon or loop label");
2778         return false;
2779     }
2780
2781     if (!vec_size(loops)) {
2782         if (is_continue)
2783             parseerror(parser, "`continue` can only be used inside loops");
2784         else
2785             parseerror(parser, "`break` can only be used inside loops or switches");
2786     }
2787
2788     if (parser->tok == TOKEN_IDENT) {
2789         if (!OPTS_FLAG(LOOP_LABELS))
2790             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2791         i = vec_size(loops);
2792         while (i--) {
2793             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2794                 break;
2795             if (!i) {
2796                 parseerror(parser, "no such loop to %s: `%s`",
2797                            (is_continue ? "continue" : "break out of"),
2798                            parser_tokval(parser));
2799                 return false;
2800             }
2801             ++levels;
2802         }
2803         if (!parser_next(parser)) {
2804             parseerror(parser, "expected semicolon");
2805             return false;
2806         }
2807     }
2808
2809     if (parser->tok != ';') {
2810         parseerror(parser, "expected semicolon");
2811         return false;
2812     }
2813
2814     if (!parser_next(parser))
2815         parseerror(parser, "parse error");
2816
2817     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2818     return true;
2819 }
2820
2821 /* returns true when it was a variable qualifier, false otherwise!
2822  * on error, cvq is set to CV_WRONG
2823  */
2824 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2825 {
2826     bool had_const    = false;
2827     bool had_var      = false;
2828     bool had_noref    = false;
2829     bool had_attrib   = false;
2830     bool had_static   = false;
2831     uint32_t flags    = 0;
2832
2833     *cvq = CV_NONE;
2834     for (;;) {
2835         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2836             had_attrib = true;
2837             /* parse an attribute */
2838             if (!parser_next(parser)) {
2839                 parseerror(parser, "expected attribute after `[[`");
2840                 *cvq = CV_WRONG;
2841                 return false;
2842             }
2843             if (!strcmp(parser_tokval(parser), "noreturn")) {
2844                 flags |= AST_FLAG_NORETURN;
2845                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2846                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2847                     *cvq = CV_WRONG;
2848                     return false;
2849                 }
2850             }
2851             else if (!strcmp(parser_tokval(parser), "noref")) {
2852                 had_noref = true;
2853                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2854                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2855                     *cvq = CV_WRONG;
2856                     return false;
2857                 }
2858             }
2859             else if (!strcmp(parser_tokval(parser), "inline")) {
2860                 flags |= AST_FLAG_INLINE;
2861                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2862                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2863                     *cvq = CV_WRONG;
2864                     return false;
2865                 }
2866             }
2867
2868
2869             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2870                 flags   |= AST_FLAG_DEPRECATED;
2871                 *message = NULL;
2872
2873                 if (!parser_next(parser)) {
2874                     parseerror(parser, "parse error in attribute");
2875                     goto argerr;
2876                 }
2877
2878                 if (parser->tok == '(') {
2879                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2880                         parseerror(parser, "`deprecated` attribute missing parameter");
2881                         goto argerr;
2882                     }
2883
2884                     *message = util_strdup(parser_tokval(parser));
2885
2886                     if (!parser_next(parser)) {
2887                         parseerror(parser, "parse error in attribute");
2888                         goto argerr;
2889                     }
2890
2891                     if(parser->tok != ')') {
2892                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2893                         goto argerr;
2894                     }
2895
2896                     if (!parser_next(parser)) {
2897                         parseerror(parser, "parse error in attribute");
2898                         goto argerr;
2899                     }
2900                 }
2901                 /* no message */
2902                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2903                     parseerror(parser, "`deprecated` attribute expected `]]`");
2904
2905                     argerr: /* ugly */
2906                     if (*message) mem_d(*message);
2907                     *message = NULL;
2908                     *cvq     = CV_WRONG;
2909                     return false;
2910                 }
2911             }
2912             else
2913             {
2914                 /* Skip tokens until we hit a ]] */
2915                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2916                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2917                     if (!parser_next(parser)) {
2918                         parseerror(parser, "error inside attribute");
2919                         *cvq = CV_WRONG;
2920                         return false;
2921                     }
2922                 }
2923             }
2924         }
2925         else if (with_local && !strcmp(parser_tokval(parser), "static"))
2926             had_static = true;
2927         else if (!strcmp(parser_tokval(parser), "const"))
2928             had_const = true;
2929         else if (!strcmp(parser_tokval(parser), "var"))
2930             had_var = true;
2931         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2932             had_var = true;
2933         else if (!strcmp(parser_tokval(parser), "noref"))
2934             had_noref = true;
2935         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2936             return false;
2937         }
2938         else
2939             break;
2940         if (!parser_next(parser))
2941             goto onerr;
2942     }
2943     if (had_const)
2944         *cvq = CV_CONST;
2945     else if (had_var)
2946         *cvq = CV_VAR;
2947     else
2948         *cvq = CV_NONE;
2949     *noref     = had_noref;
2950     *is_static = had_static;
2951     *_flags    = flags;
2952     return true;
2953 onerr:
2954     parseerror(parser, "parse error after variable qualifier");
2955     *cvq = CV_WRONG;
2956     return true;
2957 }
2958
2959 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2960 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2961 {
2962     bool rv;
2963     char *label = NULL;
2964
2965     /* skip the 'while' and get the body */
2966     if (!parser_next(parser)) {
2967         if (OPTS_FLAG(LOOP_LABELS))
2968             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2969         else
2970             parseerror(parser, "expected 'switch' operand in parenthesis");
2971         return false;
2972     }
2973
2974     if (parser->tok == ':') {
2975         if (!OPTS_FLAG(LOOP_LABELS))
2976             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2977         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2978             parseerror(parser, "expected loop label");
2979             return false;
2980         }
2981         label = util_strdup(parser_tokval(parser));
2982         if (!parser_next(parser)) {
2983             mem_d(label);
2984             parseerror(parser, "expected 'switch' operand in parenthesis");
2985             return false;
2986         }
2987     }
2988
2989     if (parser->tok != '(') {
2990         parseerror(parser, "expected 'switch' operand in parenthesis");
2991         return false;
2992     }
2993
2994     vec_push(parser->breaks, label);
2995
2996     rv = parse_switch_go(parser, block, out);
2997     if (label)
2998         mem_d(label);
2999     if (vec_last(parser->breaks) != label) {
3000         parseerror(parser, "internal error: label stack corrupted");
3001         rv = false;
3002         ast_delete(*out);
3003         *out = NULL;
3004     }
3005     else {
3006         vec_pop(parser->breaks);
3007     }
3008     return rv;
3009 }
3010
3011 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3012 {
3013     ast_expression *operand;
3014     ast_value      *opval;
3015     ast_value      *typevar;
3016     ast_switch     *switchnode;
3017     ast_switch_case swcase;
3018
3019     int  cvq;
3020     bool noref, is_static;
3021     uint32_t qflags = 0;
3022
3023     lex_ctx ctx = parser_ctx(parser);
3024
3025     (void)block; /* not touching */
3026     (void)opval;
3027
3028     /* parse into the expression */
3029     if (!parser_next(parser)) {
3030         parseerror(parser, "expected switch operand");
3031         return false;
3032     }
3033     /* parse the operand */
3034     operand = parse_expression_leave(parser, false, false, false);
3035     if (!operand)
3036         return false;
3037
3038     switchnode = ast_switch_new(ctx, operand);
3039
3040     /* closing paren */
3041     if (parser->tok != ')') {
3042         ast_delete(switchnode);
3043         parseerror(parser, "expected closing paren after 'switch' operand");
3044         return false;
3045     }
3046
3047     /* parse over the opening paren */
3048     if (!parser_next(parser) || parser->tok != '{') {
3049         ast_delete(switchnode);
3050         parseerror(parser, "expected list of cases");
3051         return false;
3052     }
3053
3054     if (!parser_next(parser)) {
3055         ast_delete(switchnode);
3056         parseerror(parser, "expected 'case' or 'default'");
3057         return false;
3058     }
3059
3060     /* new block; allow some variables to be declared here */
3061     parser_enterblock(parser);
3062     while (true) {
3063         typevar = NULL;
3064         if (parser->tok == TOKEN_IDENT)
3065             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3066         if (typevar || parser->tok == TOKEN_TYPENAME) {
3067             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3068                 ast_delete(switchnode);
3069                 return false;
3070             }
3071             continue;
3072         }
3073         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3074         {
3075             if (cvq == CV_WRONG) {
3076                 ast_delete(switchnode);
3077                 return false;
3078             }
3079             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3080                 ast_delete(switchnode);
3081                 return false;
3082             }
3083             continue;
3084         }
3085         break;
3086     }
3087
3088     /* case list! */
3089     while (parser->tok != '}') {
3090         ast_block *caseblock;
3091
3092         if (!strcmp(parser_tokval(parser), "case")) {
3093             if (!parser_next(parser)) {
3094                 ast_delete(switchnode);
3095                 parseerror(parser, "expected expression for case");
3096                 return false;
3097             }
3098             swcase.value = parse_expression_leave(parser, false, false, false);
3099             if (!swcase.value) {
3100                 ast_delete(switchnode);
3101                 parseerror(parser, "expected expression for case");
3102                 return false;
3103             }
3104             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3105                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3106                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3107                     ast_unref(operand);
3108                     return false;
3109                 }
3110             }
3111         }
3112         else if (!strcmp(parser_tokval(parser), "default")) {
3113             swcase.value = NULL;
3114             if (!parser_next(parser)) {
3115                 ast_delete(switchnode);
3116                 parseerror(parser, "expected colon");
3117                 return false;
3118             }
3119         }
3120         else {
3121             ast_delete(switchnode);
3122             parseerror(parser, "expected 'case' or 'default'");
3123             return false;
3124         }
3125
3126         /* Now the colon and body */
3127         if (parser->tok != ':') {
3128             if (swcase.value) ast_unref(swcase.value);
3129             ast_delete(switchnode);
3130             parseerror(parser, "expected colon");
3131             return false;
3132         }
3133
3134         if (!parser_next(parser)) {
3135             if (swcase.value) ast_unref(swcase.value);
3136             ast_delete(switchnode);
3137             parseerror(parser, "expected statements or case");
3138             return false;
3139         }
3140         caseblock = ast_block_new(parser_ctx(parser));
3141         if (!caseblock) {
3142             if (swcase.value) ast_unref(swcase.value);
3143             ast_delete(switchnode);
3144             return false;
3145         }
3146         swcase.code = (ast_expression*)caseblock;
3147         vec_push(switchnode->cases, swcase);
3148         while (true) {
3149             ast_expression *expr;
3150             if (parser->tok == '}')
3151                 break;
3152             if (parser->tok == TOKEN_KEYWORD) {
3153                 if (!strcmp(parser_tokval(parser), "case") ||
3154                     !strcmp(parser_tokval(parser), "default"))
3155                 {
3156                     break;
3157                 }
3158             }
3159             if (!parse_statement(parser, caseblock, &expr, true)) {
3160                 ast_delete(switchnode);
3161                 return false;
3162             }
3163             if (!expr)
3164                 continue;
3165             if (!ast_block_add_expr(caseblock, expr)) {
3166                 ast_delete(switchnode);
3167                 return false;
3168             }
3169         }
3170     }
3171
3172     parser_leaveblock(parser);
3173
3174     /* closing paren */
3175     if (parser->tok != '}') {
3176         ast_delete(switchnode);
3177         parseerror(parser, "expected closing paren of case list");
3178         return false;
3179     }
3180     if (!parser_next(parser)) {
3181         ast_delete(switchnode);
3182         parseerror(parser, "parse error after switch");
3183         return false;
3184     }
3185     *out = (ast_expression*)switchnode;
3186     return true;
3187 }
3188
3189 /* parse computed goto sides */
3190 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3191     ast_expression *on_true;
3192     ast_expression *on_false;
3193     ast_expression *cond;
3194
3195     if (!*side)
3196         return NULL;
3197
3198     if (ast_istype(*side, ast_ternary)) {
3199         ast_ternary *tern = (ast_ternary*)*side;
3200         on_true  = parse_goto_computed(parser, &tern->on_true);
3201         on_false = parse_goto_computed(parser, &tern->on_false);
3202
3203         if (!on_true || !on_false) {
3204             parseerror(parser, "expected label or expression in ternary");
3205             if (on_true) ast_unref(on_true);
3206             if (on_false) ast_unref(on_false);
3207             return NULL;
3208         }
3209
3210         cond = tern->cond;
3211         tern->cond = NULL;
3212         ast_delete(tern);
3213         *side = NULL;
3214         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3215     } else if (ast_istype(*side, ast_label)) {
3216         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3217         ast_goto_set_label(gt, ((ast_label*)*side));
3218         *side = NULL;
3219         return (ast_expression*)gt;
3220     }
3221     return NULL;
3222 }
3223
3224 static bool parse_goto(parser_t *parser, ast_expression **out)
3225 {
3226     ast_goto       *gt = NULL;
3227     ast_expression *lbl;
3228
3229     if (!parser_next(parser))
3230         return false;
3231
3232     if (parser->tok != TOKEN_IDENT) {
3233         ast_expression *expression;
3234
3235         /* could be an expression i.e computed goto :-) */
3236         if (parser->tok != '(') {
3237             parseerror(parser, "expected label name after `goto`");
3238             return false;
3239         }
3240
3241         /* failed to parse expression for goto */
3242         if (!(expression = parse_expression(parser, false, true)) ||
3243             !(*out = parse_goto_computed(parser, &expression))) {
3244             parseerror(parser, "invalid goto expression");
3245             ast_unref(expression);
3246             return false;
3247         }
3248
3249         return true;
3250     }
3251
3252     /* not computed goto */
3253     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3254     lbl = parser_find_label(parser, gt->name);
3255     if (lbl) {
3256         if (!ast_istype(lbl, ast_label)) {
3257             parseerror(parser, "internal error: label is not an ast_label");
3258             ast_delete(gt);
3259             return false;
3260         }
3261         ast_goto_set_label(gt, (ast_label*)lbl);
3262     }
3263     else
3264         vec_push(parser->gotos, gt);
3265
3266     if (!parser_next(parser) || parser->tok != ';') {
3267         parseerror(parser, "semicolon expected after goto label");
3268         return false;
3269     }
3270     if (!parser_next(parser)) {
3271         parseerror(parser, "parse error after goto");
3272         return false;
3273     }
3274
3275     *out = (ast_expression*)gt;
3276     return true;
3277 }
3278
3279 static bool parse_skipwhite(parser_t *parser)
3280 {
3281     do {
3282         if (!parser_next(parser))
3283             return false;
3284     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3285     return parser->tok < TOKEN_ERROR;
3286 }
3287
3288 static bool parse_eol(parser_t *parser)
3289 {
3290     if (!parse_skipwhite(parser))
3291         return false;
3292     return parser->tok == TOKEN_EOL;
3293 }
3294
3295 /*
3296  * Traditionally you'd implement warning, error, and message
3297  * directives in the preprocessor. However, like #pragma, these
3298  * shouldn't depend on -fftepp to utilize.  So they're instead
3299  * implemented here.
3300  */   
3301 enum {
3302     PARSE_DIRECTIVE_ERROR,
3303     PARSE_DIRECTIVE_MESSAGE,
3304     PARSE_DIRECTIVE_WARNING,
3305     PARSE_DIRECTIVE_COUNT
3306 };
3307
3308 static const char *parser_directives[PARSE_DIRECTIVE_COUNT] = {
3309     "error",
3310     "message",
3311     "warning"
3312 };
3313
3314 static bool parse_pragma_do(parser_t *parser) {
3315     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3316         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3317         return false;
3318     }
3319
3320     if (!strcmp(parser_tokval(parser), "noref")) {
3321         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3322             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3323             return false;
3324         }
3325
3326         parser->noref = !!parser_token(parser)->constval.i;
3327
3328         if (!parse_eol(parser)) {
3329             parseerror(parser, "parse error after `noref` pragma");
3330             return false;
3331         }
3332     } else {
3333         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3334         return false;
3335     }
3336     return true;
3337 }
3338
3339 static bool parse_directive_or_pragma_do(parser_t *parser, bool *pragma) {
3340
3341     size_t type = PARSE_DIRECTIVE_COUNT;
3342
3343     if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3344         parseerror(parser, "expected `pragma, error, message, warning` after `#`, got `%s`",
3345             parser_tokval(parser));
3346
3347         return false;
3348     }
3349
3350     if (!strcmp(parser_tokval(parser), "pragma" )) {
3351         *pragma = true;
3352
3353         return parse_pragma_do(parser);
3354     }
3355
3356     if (!strcmp(parser_tokval(parser), "error"  )) type = PARSE_DIRECTIVE_ERROR;
3357     if (!strcmp(parser_tokval(parser), "message")) type = PARSE_DIRECTIVE_MESSAGE;
3358     if (!strcmp(parser_tokval(parser), "warning")) type = PARSE_DIRECTIVE_WARNING;
3359
3360     switch (type) {
3361         case PARSE_DIRECTIVE_ERROR:
3362         case PARSE_DIRECTIVE_MESSAGE:
3363         case PARSE_DIRECTIVE_WARNING:
3364             *pragma = false;
3365
3366             if (!parse_skipwhite(parser) || parser->tok != TOKEN_STRINGCONST) {
3367                 parseerror(parser, "expected %s, got `%`", parser_directives[type], parser_tokval(parser));
3368                 return false;
3369             }
3370
3371             switch (type) {
3372                 case PARSE_DIRECTIVE_ERROR:
3373                     con_cprintmsg(&parser->lex->tok.ctx, LVL_ERROR, "error", parser_tokval(parser));
3374                     compile_errors ++; /* hack */
3375                     break;
3376                     /*break;*/
3377
3378                 case PARSE_DIRECTIVE_MESSAGE:
3379                     con_cprintmsg(&parser->lex->tok.ctx, LVL_MSG, "message", parser_tokval(parser));
3380                     break;
3381
3382                 case PARSE_DIRECTIVE_WARNING:
3383                     con_cprintmsg(&parser->lex->tok.ctx, LVL_WARNING, "warning", parser_tokval(parser));
3384                     break;
3385             }
3386
3387             if (!parse_eol(parser)) {
3388                 parseerror(parser, "parse error after `%` directive", parser_directives[type]);
3389                 return false;
3390             }
3391
3392             return (type != PARSE_DIRECTIVE_ERROR);
3393     }
3394
3395     parseerror(parser, "invalid directive `%s`", parser_tokval(parser));
3396     return false;
3397 }
3398
3399 static bool parse_directive_or_pragma(parser_t *parser)
3400 {
3401     bool rv;
3402     bool pragma; /* true when parsing pragma */
3403  
3404     parser->lex->flags.preprocessing = true;
3405     parser->lex->flags.mergelines    = true;
3406
3407     rv = parse_directive_or_pragma_do(parser, &pragma);
3408
3409     if (parser->tok != TOKEN_EOL) {
3410         parseerror(parser, "junk after %s", (pragma) ? "pragma" : "directive");
3411         rv = false;
3412     }
3413     parser->lex->flags.preprocessing = false;
3414     parser->lex->flags.mergelines    = false;
3415
3416     if (!parser_next(parser)) {
3417         parseerror(parser, "parse error after %s", (pragma) ? "pragma" : "directive");
3418         rv = false;
3419     }
3420     return rv;
3421 }
3422
3423 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3424 {
3425     bool       noref, is_static;
3426     int        cvq     = CV_NONE;
3427     uint32_t   qflags  = 0;
3428     ast_value *typevar = NULL;
3429     char      *vstring = NULL;
3430
3431     *out = NULL;
3432
3433     if (parser->tok == TOKEN_IDENT)
3434         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3435
3436     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3437     {
3438         /* local variable */
3439         if (!block) {
3440             parseerror(parser, "cannot declare a variable from here");
3441             return false;
3442         }
3443         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3444             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3445                 return false;
3446         }
3447         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3448             return false;
3449         return true;
3450     }
3451     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3452     {
3453         if (cvq == CV_WRONG)
3454             return false;
3455         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3456     }
3457     else if (parser->tok == TOKEN_KEYWORD)
3458     {
3459         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3460         {
3461             char ty[1024];
3462             ast_value *tdef;
3463
3464             if (!parser_next(parser)) {
3465                 parseerror(parser, "parse error after __builtin_debug_printtype");
3466                 return false;
3467             }
3468
3469             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3470             {
3471                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3472                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3473                 if (!parser_next(parser)) {
3474                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3475                     return false;
3476                 }
3477             }
3478             else
3479             {
3480                 if (!parse_statement(parser, block, out, allow_cases))
3481                     return false;
3482                 if (!*out)
3483                     con_out("__builtin_debug_printtype: got no output node\n");
3484                 else
3485                 {
3486                     ast_type_to_string(*out, ty, sizeof(ty));
3487                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3488                 }
3489             }
3490             return true;
3491         }
3492         else if (!strcmp(parser_tokval(parser), "return"))
3493         {
3494             return parse_return(parser, block, out);
3495         }
3496         else if (!strcmp(parser_tokval(parser), "if"))