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