]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.cpp
Initial movement to std::vector
[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 typedef struct
151 {
152     size_t etype; /* 0 = expression, others are operators */
153     bool            isparen;
154     size_t          off;
155     ast_expression *out;
156     ast_block      *block; /* for commas and function calls */
157     lex_ctx_t ctx;
158 } sy_elem;
159
160 enum {
161     PAREN_EXPR,
162     PAREN_FUNC,
163     PAREN_INDEX,
164     PAREN_TERNARY1,
165     PAREN_TERNARY2
166 };
167 typedef struct
168 {
169     sy_elem        *out;
170     sy_elem        *ops;
171     size_t         *argc;
172     unsigned int   *paren;
173 } shunt;
174
175 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
176     sy_elem e;
177     e.etype = 0;
178     e.off   = 0;
179     e.out   = v;
180     e.block = NULL;
181     e.ctx   = ctx;
182     e.isparen = false;
183     return e;
184 }
185
186 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
187     sy_elem e;
188     e.etype = 0;
189     e.off   = 0;
190     e.out   = (ast_expression*)v;
191     e.block = v;
192     e.ctx   = ctx;
193     e.isparen = false;
194     return e;
195 }
196
197 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
198     sy_elem e;
199     e.etype = 1 + (op - operators);
200     e.off   = 0;
201     e.out   = NULL;
202     e.block = NULL;
203     e.ctx   = ctx;
204     e.isparen = false;
205     return e;
206 }
207
208 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
209     sy_elem e;
210     e.etype = 0;
211     e.off   = off;
212     e.out   = NULL;
213     e.block = NULL;
214     e.ctx   = ctx;
215     e.isparen = true;
216     return e;
217 }
218
219 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
220  * so we need to rotate it to become ent.(foo[n]).
221  */
222 static bool rotate_entfield_array_index_nodes(ast_expression **out)
223 {
224     ast_array_index *index, *oldindex;
225     ast_entfield    *entfield;
226
227     ast_value       *field;
228     ast_expression  *sub;
229     ast_expression  *entity;
230
231     lex_ctx_t ctx = ast_ctx(*out);
232
233     if (!ast_istype(*out, ast_array_index))
234         return false;
235     index = (ast_array_index*)*out;
236
237     if (!ast_istype(index->array, ast_entfield))
238         return false;
239     entfield = (ast_entfield*)index->array;
240
241     if (!ast_istype(entfield->field, ast_value))
242         return false;
243     field = (ast_value*)entfield->field;
244
245     sub    = index->index;
246     entity = entfield->entity;
247
248     oldindex = index;
249
250     index = ast_array_index_new(ctx, (ast_expression*)field, sub);
251     entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
252     *out = (ast_expression*)entfield;
253
254     oldindex->array = NULL;
255     oldindex->index = NULL;
256     ast_delete(oldindex);
257
258     return true;
259 }
260
261 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
262 {
263     if (ast_istype(expr, ast_value)) {
264         ast_value *val = (ast_value*)expr;
265         if (val->cvq == CV_CONST) {
266             if (val->name[0] == '#') {
267                 compile_error(ctx, "invalid assignment to a literal constant");
268                 return false;
269             }
270             /*
271              * To work around quakeworld we must elide the error and make it
272              * a warning instead.
273              */
274             if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
275                 compile_error(ctx, "assignment to constant `%s`", val->name);
276             else
277                 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
278             return false;
279         }
280     }
281     return true;
282 }
283
284 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
285 {
286     const oper_info *op;
287     lex_ctx_t ctx;
288     ast_expression *out = NULL;
289     ast_expression *exprs[3];
290     ast_block      *blocks[3];
291     ast_binstore   *asbinstore;
292     size_t i, assignop, addop, subop;
293     qcint_t  generated_op = 0;
294
295     char ty1[1024];
296     char ty2[1024];
297
298     if (!vec_size(sy->ops)) {
299         parseerror(parser, "internal error: missing operator");
300         return false;
301     }
302
303     if (vec_last(sy->ops).isparen) {
304         parseerror(parser, "unmatched parenthesis");
305         return false;
306     }
307
308     op = &operators[vec_last(sy->ops).etype - 1];
309     ctx = vec_last(sy->ops).ctx;
310
311     if (vec_size(sy->out) < op->operands) {
312         if (op->flags & OP_PREFIX)
313             compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
314         else /* this should have errored previously already */
315             compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
316         return false;
317     }
318
319     vec_shrinkby(sy->ops, 1);
320
321     /* op(:?) has no input and no output */
322     if (!op->operands)
323         return true;
324
325     vec_shrinkby(sy->out, op->operands);
326     for (i = 0; i < op->operands; ++i) {
327         exprs[i]  = sy->out[vec_size(sy->out)+i].out;
328         blocks[i] = sy->out[vec_size(sy->out)+i].block;
329
330         if (exprs[i]->vtype == TYPE_NOEXPR &&
331             !(i != 0 && op->id == opid2('?',':')) &&
332             !(i == 1 && op->id == opid1('.')))
333         {
334             if (ast_istype(exprs[i], ast_label))
335                 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
336             else
337                 compile_error(ast_ctx(exprs[i]), "not an expression");
338             (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
339         }
340     }
341
342     if (blocks[0] && blocks[0]->exprs.empty() && op->id != opid1(',')) {
343         compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
344         return false;
345     }
346
347 #define NotSameType(T) \
348              (exprs[0]->vtype != exprs[1]->vtype || \
349               exprs[0]->vtype != T)
350
351     switch (op->id)
352     {
353         default:
354             compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
355             return false;
356
357         case opid1('.'):
358             if (exprs[0]->vtype == TYPE_VECTOR &&
359                 exprs[1]->vtype == TYPE_NOEXPR)
360             {
361                 if      (exprs[1] == (ast_expression*)parser->const_vec[0])
362                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
363                 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
364                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
365                 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
366                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
367                 else {
368                     compile_error(ctx, "access to invalid vector component");
369                     return false;
370                 }
371             }
372             else if (exprs[0]->vtype == TYPE_ENTITY) {
373                 if (exprs[1]->vtype != TYPE_FIELD) {
374                     compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
375                     return false;
376                 }
377                 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
378             }
379             else if (exprs[0]->vtype == TYPE_VECTOR) {
380                 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
381                 return false;
382             }
383             else {
384                 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
385                 return false;
386             }
387             break;
388
389         case opid1('['):
390             if (exprs[0]->vtype != TYPE_ARRAY &&
391                 !(exprs[0]->vtype == TYPE_FIELD &&
392                   exprs[0]->next->vtype == TYPE_ARRAY))
393             {
394                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
395                 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
396                 return false;
397             }
398             if (exprs[1]->vtype != TYPE_FLOAT) {
399                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
400                 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
401                 return false;
402             }
403             out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
404             rotate_entfield_array_index_nodes(&out);
405             break;
406
407         case opid1(','):
408             if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
409                 vec_push(sy->out, syexp(ctx, exprs[0]));
410                 vec_push(sy->out, syexp(ctx, exprs[1]));
411                 vec_last(sy->argc)++;
412                 return true;
413             }
414             if (blocks[0]) {
415                 if (!ast_block_add_expr(blocks[0], exprs[1]))
416                     return false;
417             } else {
418                 blocks[0] = ast_block_new(ctx);
419                 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
420                     !ast_block_add_expr(blocks[0], exprs[1]))
421                 {
422                     return false;
423                 }
424             }
425             ast_block_set_type(blocks[0], exprs[1]);
426
427             vec_push(sy->out, syblock(ctx, blocks[0]));
428             return true;
429
430         case opid2('+','P'):
431             out = exprs[0];
432             break;
433         case opid2('-','P'):
434             if ((out = fold_op(parser->fold, op, exprs)))
435                 break;
436
437             if (exprs[0]->vtype != TYPE_FLOAT &&
438                 exprs[0]->vtype != TYPE_VECTOR) {
439                     compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
440                                   type_name[exprs[0]->vtype]);
441                 return false;
442             }
443             if (exprs[0]->vtype == TYPE_FLOAT)
444                 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_F, exprs[0]);
445             else
446                 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_V, exprs[0]);
447             break;
448
449         case opid2('!','P'):
450             if (!(out = fold_op(parser->fold, op, exprs))) {
451                 switch (exprs[0]->vtype) {
452                     case TYPE_FLOAT:
453                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
454                         break;
455                     case TYPE_VECTOR:
456                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
457                         break;
458                     case TYPE_STRING:
459                         if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
460                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
461                         else
462                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
463                         break;
464                     /* we don't constant-fold NOT for these types */
465                     case TYPE_ENTITY:
466                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
467                         break;
468                     case TYPE_FUNCTION:
469                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
470                         break;
471                     default:
472                     compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
473                                   type_name[exprs[0]->vtype]);
474                     return false;
475                 }
476             }
477             break;
478
479         case opid1('+'):
480             if (exprs[0]->vtype != exprs[1]->vtype ||
481                (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
482             {
483                 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
484                               type_name[exprs[0]->vtype],
485                               type_name[exprs[1]->vtype]);
486                 return false;
487             }
488             if (!(out = fold_op(parser->fold, op, exprs))) {
489                 switch (exprs[0]->vtype) {
490                     case TYPE_FLOAT:
491                         out = fold_binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
492                         break;
493                     case TYPE_VECTOR:
494                         out = fold_binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
495                         break;
496                     default:
497                         compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
498                                       type_name[exprs[0]->vtype],
499                                       type_name[exprs[1]->vtype]);
500                         return false;
501                 }
502             }
503             break;
504         case opid1('-'):
505             if  (exprs[0]->vtype != exprs[1]->vtype ||
506                 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
507             {
508                 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
509                               type_name[exprs[1]->vtype],
510                               type_name[exprs[0]->vtype]);
511                 return false;
512             }
513             if (!(out = fold_op(parser->fold, op, exprs))) {
514                 switch (exprs[0]->vtype) {
515                     case TYPE_FLOAT:
516                         out = fold_binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
517                         break;
518                     case TYPE_VECTOR:
519                         out = fold_binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
520                         break;
521                     default:
522                         compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
523                                       type_name[exprs[1]->vtype],
524                                       type_name[exprs[0]->vtype]);
525                         return false;
526                 }
527             }
528             break;
529         case opid1('*'):
530             if (exprs[0]->vtype != exprs[1]->vtype &&
531                 !(exprs[0]->vtype == TYPE_VECTOR &&
532                   exprs[1]->vtype == TYPE_FLOAT) &&
533                 !(exprs[1]->vtype == TYPE_VECTOR &&
534                   exprs[0]->vtype == TYPE_FLOAT)
535                 )
536             {
537                 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
538                               type_name[exprs[1]->vtype],
539                               type_name[exprs[0]->vtype]);
540                 return false;
541             }
542             if (!(out = fold_op(parser->fold, op, exprs))) {
543                 switch (exprs[0]->vtype) {
544                     case TYPE_FLOAT:
545                         if (exprs[1]->vtype == TYPE_VECTOR)
546                             out = fold_binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
547                         else
548                             out = fold_binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
549                         break;
550                     case TYPE_VECTOR:
551                         if (exprs[1]->vtype == TYPE_FLOAT)
552                             out = fold_binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
553                         else
554                             out = fold_binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
555                         break;
556                     default:
557                         compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
558                                       type_name[exprs[1]->vtype],
559                                       type_name[exprs[0]->vtype]);
560                         return false;
561                 }
562             }
563             break;
564
565         case opid1('/'):
566             if (exprs[1]->vtype != TYPE_FLOAT) {
567                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
568                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
569                 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
570                 return false;
571             }
572             if (!(out = fold_op(parser->fold, op, exprs))) {
573                 if (exprs[0]->vtype == TYPE_FLOAT)
574                     out = fold_binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
575                 else {
576                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
577                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
578                     compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
579                     return false;
580                 }
581             }
582             break;
583
584         case opid1('%'):
585             if (NotSameType(TYPE_FLOAT)) {
586                 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
587                     type_name[exprs[0]->vtype],
588                     type_name[exprs[1]->vtype]);
589                 return false;
590             } else if (!(out = fold_op(parser->fold, op, exprs))) {
591                 /* generate a call to __builtin_mod */
592                 ast_expression *mod  = intrin_func(parser->intrin, "mod");
593                 ast_call       *call = NULL;
594                 if (!mod) return false; /* can return null for missing floor */
595
596                 call = ast_call_new(parser_ctx(parser), mod);
597                 vec_push(call->params, exprs[0]);
598                 vec_push(call->params, exprs[1]);
599
600                 out = (ast_expression*)call;
601             }
602             break;
603
604         case opid2('%','='):
605             compile_error(ctx, "%= is unimplemented");
606             return false;
607
608         case opid1('|'):
609         case opid1('&'):
610         case opid1('^'):
611             if ( !(exprs[0]->vtype == TYPE_FLOAT  && exprs[1]->vtype == TYPE_FLOAT) &&
612                  !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
613                  !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
614             {
615                 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
616                               type_name[exprs[0]->vtype],
617                               type_name[exprs[1]->vtype]);
618                 return false;
619             }
620
621             if (!(out = fold_op(parser->fold, op, exprs))) {
622                 /*
623                  * IF the first expression is float, the following will be too
624                  * since scalar ^ vector is not allowed.
625                  */
626                 if (exprs[0]->vtype == TYPE_FLOAT) {
627                     out = fold_binary(ctx,
628                         (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
629                         exprs[0], exprs[1]);
630                 } else {
631                     /*
632                      * The first is a vector: vector is allowed to bitop with vector and
633                      * with scalar, branch here for the second operand.
634                      */
635                     if (exprs[1]->vtype == TYPE_VECTOR) {
636                         /*
637                          * Bitop all the values of the vector components against the
638                          * vectors components in question.
639                          */
640                         out = fold_binary(ctx,
641                             (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
642                             exprs[0], exprs[1]);
643                     } else {
644                         out = fold_binary(ctx,
645                             (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
646                             exprs[0], exprs[1]);
647                     }
648                 }
649             }
650             break;
651
652         case opid2('<','<'):
653         case opid2('>','>'):
654             if (NotSameType(TYPE_FLOAT)) {
655                 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
656                     type_name[exprs[0]->vtype],
657                     type_name[exprs[1]->vtype]);
658                 return false;
659             }
660
661             if (!(out = fold_op(parser->fold, op, exprs))) {
662                 ast_expression *shift = intrin_func(parser->intrin, (op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
663                 ast_call       *call  = ast_call_new(parser_ctx(parser), shift);
664                 vec_push(call->params, exprs[0]);
665                 vec_push(call->params, exprs[1]);
666                 out = (ast_expression*)call;
667             }
668             break;
669
670         case opid3('<','<','='):
671         case opid3('>','>','='):
672             if (NotSameType(TYPE_FLOAT)) {
673                 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
674                     type_name[exprs[0]->vtype],
675                     type_name[exprs[1]->vtype]);
676                 return false;
677             }
678
679             if(!(out = fold_op(parser->fold, op, exprs))) {
680                 ast_expression *shift = intrin_func(parser->intrin, (op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
681                 ast_call       *call  = ast_call_new(parser_ctx(parser), shift);
682                 vec_push(call->params, exprs[0]);
683                 vec_push(call->params, exprs[1]);
684                 out = (ast_expression*)ast_store_new(
685                     parser_ctx(parser),
686                     INSTR_STORE_F,
687                     exprs[0],
688                     (ast_expression*)call
689                 );
690             }
691
692             break;
693
694         case opid2('|','|'):
695             generated_op += 1; /* INSTR_OR */
696         case opid2('&','&'):
697             generated_op += INSTR_AND;
698             if (!(out = fold_op(parser->fold, op, exprs))) {
699                 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
700                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
701                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
702                     compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
703                     return false;
704                 }
705                 for (i = 0; i < 2; ++i) {
706                     if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
707                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
708                         if (!out) break;
709                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
710                         if (!out) break;
711                         exprs[i] = out; out = NULL;
712                         if (OPTS_FLAG(PERL_LOGIC)) {
713                             /* here we want to keep the right expressions' type */
714                             break;
715                         }
716                     }
717                     else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
718                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
719                         if (!out) break;
720                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
721                         if (!out) break;
722                         exprs[i] = out; out = NULL;
723                         if (OPTS_FLAG(PERL_LOGIC)) {
724                             /* here we want to keep the right expressions' type */
725                             break;
726                         }
727                     }
728                 }
729                 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
730             }
731             break;
732
733         case opid2('?',':'):
734             if (vec_last(sy->paren) != PAREN_TERNARY2) {
735                 compile_error(ctx, "mismatched parenthesis/ternary");
736                 return false;
737             }
738             vec_pop(sy->paren);
739             if (!ast_compare_type(exprs[1], exprs[2])) {
740                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
741                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
742                 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
743                 return false;
744             }
745             if (!(out = fold_op(parser->fold, op, exprs)))
746                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
747             break;
748
749         case opid2('*', '*'):
750             if (NotSameType(TYPE_FLOAT)) {
751                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
752                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
753                 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
754                     ty1, ty2);
755                 return false;
756             }
757
758             if (!(out = fold_op(parser->fold, op, exprs))) {
759                 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
760                 vec_push(gencall->params, exprs[0]);
761                 vec_push(gencall->params, exprs[1]);
762                 out = (ast_expression*)gencall;
763             }
764             break;
765
766         case opid2('>', '<'):
767             if (NotSameType(TYPE_VECTOR)) {
768                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
769                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
770                 compile_error(ctx, "invalid types used in cross product: %s and %s",
771                     ty1, ty2);
772                 return false;
773             }
774
775             if (!(out = fold_op(parser->fold, op, exprs))) {
776                 out = fold_binary(
777                         parser_ctx(parser),
778                         VINSTR_CROSS,
779                         exprs[0],
780                         exprs[1]
781                 );
782             }
783
784             break;
785
786         case opid3('<','=','>'): /* -1, 0, or 1 */
787             if (NotSameType(TYPE_FLOAT)) {
788                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
789                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
790                 compile_error(ctx, "invalid types used in comparision: %s and %s",
791                     ty1, ty2);
792
793                 return false;
794             }
795
796             if (!(out = fold_op(parser->fold, op, exprs))) {
797                 /* This whole block is NOT fold_binary safe */
798                 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
799
800                 eq->refs = AST_REF_NONE;
801
802                     /* if (lt) { */
803                 out = (ast_expression*)ast_ternary_new(ctx,
804                         (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
805                         /* out = -1 */
806                         (ast_expression*)parser->fold->imm_float[2],
807                     /* } else { */
808                         /* if (eq) { */
809                         (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
810                             /* out = 0 */
811                             (ast_expression*)parser->fold->imm_float[0],
812                         /* } else { */
813                             /* out = 1 */
814                             (ast_expression*)parser->fold->imm_float[1]
815                         /* } */
816                         )
817                     /* } */
818                     );
819
820             }
821             break;
822
823         case opid1('>'):
824             generated_op += 1; /* INSTR_GT */
825         case opid1('<'):
826             generated_op += 1; /* INSTR_LT */
827         case opid2('>', '='):
828             generated_op += 1; /* INSTR_GE */
829         case opid2('<', '='):
830             generated_op += INSTR_LE;
831             if (NotSameType(TYPE_FLOAT)) {
832                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
833                               type_name[exprs[0]->vtype],
834                               type_name[exprs[1]->vtype]);
835                 return false;
836             }
837             if (!(out = fold_op(parser->fold, op, exprs)))
838                 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
839             break;
840         case opid2('!', '='):
841             if (exprs[0]->vtype != exprs[1]->vtype) {
842                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
843                               type_name[exprs[0]->vtype],
844                               type_name[exprs[1]->vtype]);
845                 return false;
846             }
847             if (!(out = fold_op(parser->fold, op, exprs)))
848                 out = fold_binary(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
849             break;
850         case opid2('=', '='):
851             if (exprs[0]->vtype != exprs[1]->vtype) {
852                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
853                               type_name[exprs[0]->vtype],
854                               type_name[exprs[1]->vtype]);
855                 return false;
856             }
857             if (!(out = fold_op(parser->fold, op, exprs)))
858                 out = fold_binary(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
859             break;
860
861         case opid1('='):
862             if (ast_istype(exprs[0], ast_entfield)) {
863                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
864                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
865                     exprs[0]->vtype == TYPE_FIELD &&
866                     exprs[0]->next->vtype == TYPE_VECTOR)
867                 {
868                     assignop = type_storep_instr[TYPE_VECTOR];
869                 }
870                 else
871                     assignop = type_storep_instr[exprs[0]->vtype];
872                 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
873                 {
874                     ast_type_to_string(field->next, ty1, sizeof(ty1));
875                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
876                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
877                         field->next->vtype == TYPE_FUNCTION &&
878                         exprs[1]->vtype == TYPE_FUNCTION)
879                     {
880                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
881                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
882                     }
883                     else
884                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
885                 }
886             }
887             else
888             {
889                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
890                     exprs[0]->vtype == TYPE_FIELD &&
891                     exprs[0]->next->vtype == TYPE_VECTOR)
892                 {
893                     assignop = type_store_instr[TYPE_VECTOR];
894                 }
895                 else {
896                     assignop = type_store_instr[exprs[0]->vtype];
897                 }
898
899                 if (assignop == VINSTR_END) {
900                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
901                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
902                     compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
903                 }
904                 else if (!ast_compare_type(exprs[0], exprs[1]))
905                 {
906                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
907                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
908                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
909                         exprs[0]->vtype == TYPE_FUNCTION &&
910                         exprs[1]->vtype == TYPE_FUNCTION)
911                     {
912                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
913                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
914                     }
915                     else
916                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
917                 }
918             }
919             (void)check_write_to(ctx, exprs[0]);
920             /* When we're a vector of part of an entity field we use STOREP */
921             if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->owner, ast_entfield))
922                 assignop = INSTR_STOREP_F;
923             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
924             break;
925         case opid3('+','+','P'):
926         case opid3('-','-','P'):
927             /* prefix ++ */
928             if (exprs[0]->vtype != TYPE_FLOAT) {
929                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
930                 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
931                 return false;
932             }
933             if (op->id == opid3('+','+','P'))
934                 addop = INSTR_ADD_F;
935             else
936                 addop = INSTR_SUB_F;
937             (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
938             if (ast_istype(exprs[0], ast_entfield)) {
939                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
940                                                         exprs[0],
941                                                         (ast_expression*)parser->fold->imm_float[1]);
942             } else {
943                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
944                                                         exprs[0],
945                                                         (ast_expression*)parser->fold->imm_float[1]);
946             }
947             break;
948         case opid3('S','+','+'):
949         case opid3('S','-','-'):
950             /* prefix ++ */
951             if (exprs[0]->vtype != TYPE_FLOAT) {
952                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
953                 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
954                 return false;
955             }
956             if (op->id == opid3('S','+','+')) {
957                 addop = INSTR_ADD_F;
958                 subop = INSTR_SUB_F;
959             } else {
960                 addop = INSTR_SUB_F;
961                 subop = INSTR_ADD_F;
962             }
963             (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
964             if (ast_istype(exprs[0], ast_entfield)) {
965                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
966                                                         exprs[0],
967                                                         (ast_expression*)parser->fold->imm_float[1]);
968             } else {
969                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
970                                                         exprs[0],
971                                                         (ast_expression*)parser->fold->imm_float[1]);
972             }
973             if (!out)
974                 return false;
975             out = fold_binary(ctx, subop,
976                               out,
977                               (ast_expression*)parser->fold->imm_float[1]);
978
979             break;
980         case opid2('+','='):
981         case opid2('-','='):
982             if (exprs[0]->vtype != exprs[1]->vtype ||
983                 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
984             {
985                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
986                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
987                 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
988                               ty1, ty2);
989                 return false;
990             }
991             (void)check_write_to(ctx, exprs[0]);
992             if (ast_istype(exprs[0], ast_entfield))
993                 assignop = type_storep_instr[exprs[0]->vtype];
994             else
995                 assignop = type_store_instr[exprs[0]->vtype];
996             switch (exprs[0]->vtype) {
997                 case TYPE_FLOAT:
998                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
999                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1000                                                             exprs[0], exprs[1]);
1001                     break;
1002                 case TYPE_VECTOR:
1003                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1004                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1005                                                             exprs[0], exprs[1]);
1006                     break;
1007                 default:
1008                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1009                                   type_name[exprs[0]->vtype],
1010                                   type_name[exprs[1]->vtype]);
1011                     return false;
1012             };
1013             break;
1014         case opid2('*','='):
1015         case opid2('/','='):
1016             if (exprs[1]->vtype != TYPE_FLOAT ||
1017                 !(exprs[0]->vtype == TYPE_FLOAT ||
1018                   exprs[0]->vtype == TYPE_VECTOR))
1019             {
1020                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1021                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1022                 compile_error(ctx, "invalid types used in expression: %s and %s",
1023                               ty1, ty2);
1024                 return false;
1025             }
1026             (void)check_write_to(ctx, exprs[0]);
1027             if (ast_istype(exprs[0], ast_entfield))
1028                 assignop = type_storep_instr[exprs[0]->vtype];
1029             else
1030                 assignop = type_store_instr[exprs[0]->vtype];
1031             switch (exprs[0]->vtype) {
1032                 case TYPE_FLOAT:
1033                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1034                                                             (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1035                                                             exprs[0], exprs[1]);
1036                     break;
1037                 case TYPE_VECTOR:
1038                     if (op->id == opid2('*','=')) {
1039                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1040                                                                 exprs[0], exprs[1]);
1041                     } else {
1042                         out = fold_binary(ctx, INSTR_DIV_F,
1043                                          (ast_expression*)parser->fold->imm_float[1],
1044                                          exprs[1]);
1045                         if (!out) {
1046                             compile_error(ctx, "internal error: failed to generate division");
1047                             return false;
1048                         }
1049                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1050                                                                 exprs[0], out);
1051                     }
1052                     break;
1053                 default:
1054                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1055                                   type_name[exprs[0]->vtype],
1056                                   type_name[exprs[1]->vtype]);
1057                     return false;
1058             };
1059             break;
1060         case opid2('&','='):
1061         case opid2('|','='):
1062         case opid2('^','='):
1063             if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1064                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1065                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1066                 compile_error(ctx, "invalid types used in expression: %s and %s",
1067                               ty1, ty2);
1068                 return false;
1069             }
1070             (void)check_write_to(ctx, exprs[0]);
1071             if (ast_istype(exprs[0], ast_entfield))
1072                 assignop = type_storep_instr[exprs[0]->vtype];
1073             else
1074                 assignop = type_store_instr[exprs[0]->vtype];
1075             if (exprs[0]->vtype == TYPE_FLOAT)
1076                 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1077                                                         (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1078                                                         exprs[0], exprs[1]);
1079             else
1080                 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1081                                                         (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1082                                                         exprs[0], exprs[1]);
1083             break;
1084         case opid3('&','~','='):
1085             /* This is like: a &= ~(b);
1086              * But QC has no bitwise-not, so we implement it as
1087              * a -= a & (b);
1088              */
1089             if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1090                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1091                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1092                 compile_error(ctx, "invalid types used in expression: %s and %s",
1093                               ty1, ty2);
1094                 return false;
1095             }
1096             if (ast_istype(exprs[0], ast_entfield))
1097                 assignop = type_storep_instr[exprs[0]->vtype];
1098             else
1099                 assignop = type_store_instr[exprs[0]->vtype];
1100             if (exprs[0]->vtype == TYPE_FLOAT)
1101                 out = fold_binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1102             else
1103                 out = fold_binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1104             if (!out)
1105                 return false;
1106             (void)check_write_to(ctx, exprs[0]);
1107             if (exprs[0]->vtype == TYPE_FLOAT)
1108                 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1109             else
1110                 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1111             asbinstore->keep_dest = true;
1112             out = (ast_expression*)asbinstore;
1113             break;
1114
1115         case opid3('l', 'e', 'n'):
1116             if (exprs[0]->vtype != TYPE_STRING && exprs[0]->vtype != TYPE_ARRAY) {
1117                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1118                 compile_error(ast_ctx(exprs[0]), "invalid type for length operator: %s", ty1);
1119                 return false;
1120             }
1121             /* strings must be const, arrays are statically sized */
1122             if (exprs[0]->vtype == TYPE_STRING &&
1123                 !(((ast_value*)exprs[0])->hasvalue && ((ast_value*)exprs[0])->cvq == CV_CONST))
1124             {
1125                 compile_error(ast_ctx(exprs[0]), "operand of length operator not a valid constant expression");
1126                 return false;
1127             }
1128             out = fold_op(parser->fold, op, exprs);
1129             break;
1130
1131         case opid2('~', 'P'):
1132             if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1133                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1134                 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1135                 return false;
1136             }
1137             if (!(out = fold_op(parser->fold, op, exprs))) {
1138                 if (exprs[0]->vtype == TYPE_FLOAT) {
1139                     out = fold_binary(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1140                 } else {
1141                     out = fold_binary(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1142                 }
1143             }
1144             break;
1145     }
1146 #undef NotSameType
1147     if (!out) {
1148         compile_error(ctx, "failed to apply operator %s", op->op);
1149         return false;
1150     }
1151
1152     vec_push(sy->out, syexp(ctx, out));
1153     return true;
1154 }
1155
1156 static bool parser_close_call(parser_t *parser, shunt *sy)
1157 {
1158     /* was a function call */
1159     ast_expression *fun;
1160     ast_value      *funval = NULL;
1161     ast_call       *call;
1162
1163     size_t          fid;
1164     size_t          paramcount, i;
1165     bool            fold = true;
1166
1167     fid = vec_last(sy->ops).off;
1168     vec_shrinkby(sy->ops, 1);
1169
1170     /* out[fid] is the function
1171      * everything above is parameters...
1172      */
1173     if (!vec_size(sy->argc)) {
1174         parseerror(parser, "internal error: no argument counter available");
1175         return false;
1176     }
1177
1178     paramcount = vec_last(sy->argc);
1179     vec_pop(sy->argc);
1180
1181     if (vec_size(sy->out) < fid) {
1182         parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1183                    (unsigned long)vec_size(sy->out),
1184                    (unsigned long)fid,
1185                    (unsigned long)paramcount);
1186         return false;
1187     }
1188
1189     /*
1190      * TODO handle this at the intrinsic level with an ast_intrinsic
1191      * node and codegen.
1192      */
1193     if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1194         char ty[1024];
1195         if (fid+2 != vec_size(sy->out) ||
1196             vec_last(sy->out).block)
1197         {
1198             parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1199             return false;
1200         }
1201         ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1202         ast_unref(vec_last(sy->out).out);
1203         sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1204                              (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1205         vec_shrinkby(sy->out, 1);
1206         return true;
1207     }
1208
1209     /*
1210      * Now we need to determine if the function that is being called is
1211      * an intrinsic so we can evaluate if the arguments to it are constant
1212      * and than fruitfully fold them.
1213      */
1214 #define fold_can_1(X)  \
1215     (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1216                 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1217
1218     if (fid + 1 < vec_size(sy->out))
1219         ++paramcount;
1220
1221     for (i = 0; i < paramcount; ++i) {
1222         if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1223             fold = false;
1224             break;
1225         }
1226     }
1227
1228     /*
1229      * All is well which ends well, if we make it into here we can ignore the
1230      * intrinsic call and just evaluate it i.e constant fold it.
1231      */
1232     if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1233         ast_expression **exprs  = NULL;
1234         ast_expression *foldval = NULL;
1235
1236         for (i = 0; i < paramcount; i++)
1237             vec_push(exprs, sy->out[fid+1 + i].out);
1238
1239         if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1240             vec_free(exprs);
1241             goto fold_leave;
1242         }
1243
1244         /*
1245          * Blub: what sorts of unreffing and resizing of
1246          * sy->out should I be doing here?
1247          */
1248         sy->out[fid] = syexp(foldval->node.context, foldval);
1249         vec_shrinkby(sy->out, paramcount);
1250         vec_free(exprs);
1251
1252         return true;
1253     }
1254
1255     fold_leave:
1256     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1257
1258     if (!call)
1259         return false;
1260
1261     if (fid+1 + paramcount != vec_size(sy->out)) {
1262         parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1263                    (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1264         return false;
1265     }
1266
1267     for (i = 0; i < paramcount; ++i)
1268         vec_push(call->params, sy->out[fid+1 + i].out);
1269     vec_shrinkby(sy->out, paramcount);
1270     (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1271     if (parser->max_param_count < paramcount)
1272         parser->max_param_count = paramcount;
1273
1274     if (ast_istype(fun, ast_value)) {
1275         funval = (ast_value*)fun;
1276         if ((fun->flags & AST_FLAG_VARIADIC) &&
1277             !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1278         {
1279             call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount, false);
1280         }
1281     }
1282
1283     /* overwrite fid, the function, with a call */
1284     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1285
1286     if (fun->vtype != TYPE_FUNCTION) {
1287         parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1288         return false;
1289     }
1290
1291     if (!fun->next) {
1292         parseerror(parser, "could not determine function return type");
1293         return false;
1294     } else {
1295         ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1296
1297         if (fun->flags & AST_FLAG_DEPRECATED) {
1298             if (!fval) {
1299                 return !parsewarning(parser, WARN_DEPRECATED,
1300                         "call to function (which is marked deprecated)\n",
1301                         "-> it has been declared here: %s:%i",
1302                         ast_ctx(fun).file, ast_ctx(fun).line);
1303             }
1304             if (!fval->desc) {
1305                 return !parsewarning(parser, WARN_DEPRECATED,
1306                         "call to `%s` (which is marked deprecated)\n"
1307                         "-> `%s` declared here: %s:%i",
1308                         fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1309             }
1310             return !parsewarning(parser, WARN_DEPRECATED,
1311                     "call to `%s` (deprecated: %s)\n"
1312                     "-> `%s` declared here: %s:%i",
1313                     fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1314                     ast_ctx(fun).line);
1315         }
1316
1317         if (fun->params.size() != paramcount &&
1318             !((fun->flags & AST_FLAG_VARIADIC) &&
1319               fun->params.size() < paramcount))
1320         {
1321             const char *fewmany = (fun->params.size() > paramcount) ? "few" : "many";
1322             if (fval)
1323                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1324                                      "too %s parameters for call to %s: expected %i, got %i\n"
1325                                      " -> `%s` has been declared here: %s:%i",
1326                                      fewmany, fval->name, (int)fun->params.size(), (int)paramcount,
1327                                      fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1328             else
1329                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1330                                      "too %s parameters for function call: expected %i, got %i\n"
1331                                      " -> it has been declared here: %s:%i",
1332                                      fewmany, (int)fun->params.size(), (int)paramcount,
1333                                      ast_ctx(fun).file, (int)ast_ctx(fun).line);
1334         }
1335     }
1336
1337     return true;
1338 }
1339
1340 static bool parser_close_paren(parser_t *parser, shunt *sy)
1341 {
1342     if (!vec_size(sy->ops)) {
1343         parseerror(parser, "unmatched closing paren");
1344         return false;
1345     }
1346
1347     while (vec_size(sy->ops)) {
1348         if (vec_last(sy->ops).isparen) {
1349             if (vec_last(sy->paren) == PAREN_FUNC) {
1350                 vec_pop(sy->paren);
1351                 if (!parser_close_call(parser, sy))
1352                     return false;
1353                 break;
1354             }
1355             if (vec_last(sy->paren) == PAREN_EXPR) {
1356                 vec_pop(sy->paren);
1357                 if (!vec_size(sy->out)) {
1358                     compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1359                     vec_shrinkby(sy->ops, 1);
1360                     return false;
1361                 }
1362                 vec_shrinkby(sy->ops, 1);
1363                 break;
1364             }
1365             if (vec_last(sy->paren) == PAREN_INDEX) {
1366                 vec_pop(sy->paren);
1367                 /* pop off the parenthesis */
1368                 vec_shrinkby(sy->ops, 1);
1369                 /* then apply the index operator */
1370                 if (!parser_sy_apply_operator(parser, sy))
1371                     return false;
1372                 break;
1373             }
1374             if (vec_last(sy->paren) == PAREN_TERNARY1) {
1375                 vec_last(sy->paren) = PAREN_TERNARY2;
1376                 /* pop off the parenthesis */
1377                 vec_shrinkby(sy->ops, 1);
1378                 break;
1379             }
1380             compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1381             return false;
1382         }
1383         if (!parser_sy_apply_operator(parser, sy))
1384             return false;
1385     }
1386     return true;
1387 }
1388
1389 static void parser_reclassify_token(parser_t *parser)
1390 {
1391     size_t i;
1392     if (parser->tok >= TOKEN_START)
1393         return;
1394     for (i = 0; i < operator_count; ++i) {
1395         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1396             parser->tok = TOKEN_OPERATOR;
1397             return;
1398         }
1399     }
1400 }
1401
1402 static ast_expression* parse_vararg_do(parser_t *parser)
1403 {
1404     ast_expression *idx, *out;
1405     ast_value      *typevar;
1406     ast_value      *funtype = parser->function->vtype;
1407     lex_ctx_t         ctx     = parser_ctx(parser);
1408
1409     if (!parser->function->varargs) {
1410         parseerror(parser, "function has no variable argument list");
1411         return NULL;
1412     }
1413
1414     if (!parser_next(parser) || parser->tok != '(') {
1415         parseerror(parser, "expected parameter index and type in parenthesis");
1416         return NULL;
1417     }
1418     if (!parser_next(parser)) {
1419         parseerror(parser, "error parsing parameter index");
1420         return NULL;
1421     }
1422
1423     idx = parse_expression_leave(parser, true, false, false);
1424     if (!idx)
1425         return NULL;
1426
1427     if (parser->tok != ',') {
1428         if (parser->tok != ')') {
1429             ast_unref(idx);
1430             parseerror(parser, "expected comma after parameter index");
1431             return NULL;
1432         }
1433         /* vararg piping: ...(start) */
1434         out = (ast_expression*)ast_argpipe_new(ctx, idx);
1435         return out;
1436     }
1437
1438     if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1439         ast_unref(idx);
1440         parseerror(parser, "expected typename for vararg");
1441         return NULL;
1442     }
1443
1444     typevar = parse_typename(parser, NULL, NULL, NULL);
1445     if (!typevar) {
1446         ast_unref(idx);
1447         return NULL;
1448     }
1449
1450     if (parser->tok != ')') {
1451         ast_unref(idx);
1452         ast_delete(typevar);
1453         parseerror(parser, "expected closing paren");
1454         return NULL;
1455     }
1456
1457     if (funtype->expression.varparam &&
1458         !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1459     {
1460         char ty1[1024];
1461         char ty2[1024];
1462         ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1463         ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1464         compile_error(ast_ctx(typevar),
1465                       "function was declared to take varargs of type `%s`, requested type is: %s",
1466                       ty2, ty1);
1467     }
1468
1469     out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1470     ast_type_adopt(out, typevar);
1471     ast_delete(typevar);
1472     return out;
1473 }
1474
1475 static ast_expression* parse_vararg(parser_t *parser)
1476 {
1477     bool           old_noops = parser->lex->flags.noops;
1478
1479     ast_expression *out;
1480
1481     parser->lex->flags.noops = true;
1482     out = parse_vararg_do(parser);
1483
1484     parser->lex->flags.noops = old_noops;
1485     return out;
1486 }
1487
1488 /* not to be exposed */
1489 bool ftepp_predef_exists(const char *name);
1490 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1491 {
1492     if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1493         parser->tok == TOKEN_IDENT &&
1494         !strcmp(parser_tokval(parser), "_"))
1495     {
1496         /* a translatable string */
1497         ast_value *val;
1498
1499         parser->lex->flags.noops = true;
1500         if (!parser_next(parser) || parser->tok != '(') {
1501             parseerror(parser, "use _(\"string\") to create a translatable string constant");
1502             return false;
1503         }
1504         parser->lex->flags.noops = false;
1505         if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1506             parseerror(parser, "expected a constant string in translatable-string extension");
1507             return false;
1508         }
1509         val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1510         if (!val)
1511             return false;
1512         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1513
1514         if (!parser_next(parser) || parser->tok != ')') {
1515             parseerror(parser, "expected closing paren after translatable string");
1516             return false;
1517         }
1518         return true;
1519     }
1520     else if (parser->tok == TOKEN_DOTS)
1521     {
1522         ast_expression *va;
1523         if (!OPTS_FLAG(VARIADIC_ARGS)) {
1524             parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1525             return false;
1526         }
1527         va = parse_vararg(parser);
1528         if (!va)
1529             return false;
1530         vec_push(sy->out, syexp(parser_ctx(parser), va));
1531         return true;
1532     }
1533     else if (parser->tok == TOKEN_FLOATCONST) {
1534         ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f), false);
1535         if (!val)
1536             return false;
1537         vec_push(sy->out, syexp(parser_ctx(parser), val));
1538         return true;
1539     }
1540     else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1541         ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i), false);
1542         if (!val)
1543             return false;
1544         vec_push(sy->out, syexp(parser_ctx(parser), val));
1545         return true;
1546     }
1547     else if (parser->tok == TOKEN_STRINGCONST) {
1548         ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1549         if (!val)
1550             return false;
1551         vec_push(sy->out, syexp(parser_ctx(parser), val));
1552         return true;
1553     }
1554     else if (parser->tok == TOKEN_VECTORCONST) {
1555         ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1556         if (!val)
1557             return false;
1558         vec_push(sy->out, syexp(parser_ctx(parser), val));
1559         return true;
1560     }
1561     else if (parser->tok == TOKEN_IDENT)
1562     {
1563         const char     *ctoken = parser_tokval(parser);
1564         ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1565         ast_expression *var;
1566         /* a_vector.{x,y,z} */
1567         if (!vec_size(sy->ops) ||
1568             !vec_last(sy->ops).etype ||
1569             operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1570         {
1571             /* When adding more intrinsics, fix the above condition */
1572             prev = NULL;
1573         }
1574         if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1575         {
1576             var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1577         } else {
1578             var = parser_find_var(parser, parser_tokval(parser));
1579             if (!var)
1580                 var = parser_find_field(parser, parser_tokval(parser));
1581         }
1582         if (!var && with_labels) {
1583             var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1584             if (!with_labels) {
1585                 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1586                 var = (ast_expression*)lbl;
1587                 parser->labels.push_back(lbl);
1588             }
1589         }
1590         if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1591             var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1592         if (!var) {
1593             /*
1594              * now we try for the real intrinsic hashtable. If the string
1595              * begins with __builtin, we simply skip past it, otherwise we
1596              * use the identifier as is.
1597              */
1598             if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1599                 var = intrin_func(parser->intrin, parser_tokval(parser));
1600             }
1601
1602             /*
1603              * Try it again, intrin_func deals with the alias method as well
1604              * the first one masks for __builtin though, we emit warning here.
1605              */
1606             if (!var) {
1607                 if ((var = intrin_func(parser->intrin, parser_tokval(parser)))) {
1608                     (void)!compile_warning(
1609                         parser_ctx(parser),
1610                         WARN_BUILTINS,
1611                         "using implicitly defined builtin `__builtin_%s' for `%s'",
1612                         parser_tokval(parser),
1613                         parser_tokval(parser)
1614                     );
1615                 }
1616             }
1617
1618
1619             if (!var) {
1620                 /*
1621                  * sometimes people use preprocessing predefs without enabling them
1622                  * i've done this thousands of times already myself.  Lets check for
1623                  * it in the predef table.  And diagnose it better :)
1624                  */
1625                 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1626                     parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1627                     return false;
1628                 }
1629
1630                 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1631                 return false;
1632             }
1633         }
1634         else
1635         {
1636             if (ast_istype(var, ast_value)) {
1637                 ((ast_value*)var)->uses++;
1638             }
1639             else if (ast_istype(var, ast_member)) {
1640                 ast_member *mem = (ast_member*)var;
1641                 if (ast_istype(mem->owner, ast_value))
1642                     ((ast_value*)(mem->owner))->uses++;
1643             }
1644         }
1645         vec_push(sy->out, syexp(parser_ctx(parser), var));
1646         return true;
1647     }
1648     parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1649     return false;
1650 }
1651
1652 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1653 {
1654     ast_expression *expr = NULL;
1655     shunt sy;
1656     size_t i;
1657     bool wantop = false;
1658     /* only warn once about an assignment in a truth value because the current code
1659      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1660      */
1661     bool warn_parenthesis = true;
1662
1663     /* count the parens because an if starts with one, so the
1664      * end of a condition is an unmatched closing paren
1665      */
1666     int ternaries = 0;
1667
1668     memset(&sy, 0, sizeof(sy));
1669
1670     parser->lex->flags.noops = false;
1671
1672     parser_reclassify_token(parser);
1673
1674     while (true)
1675     {
1676         if (parser->tok == TOKEN_TYPENAME) {
1677             parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1678             goto onerr;
1679         }
1680
1681         if (parser->tok == TOKEN_OPERATOR)
1682         {
1683             /* classify the operator */
1684             const oper_info *op;
1685             const oper_info *olast = NULL;
1686             size_t o;
1687             for (o = 0; o < operator_count; ++o) {
1688                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1689                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1690                     !strcmp(parser_tokval(parser), operators[o].op))
1691                 {
1692                     break;
1693                 }
1694             }
1695             if (o == operator_count) {
1696                 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1697                 goto onerr;
1698             }
1699             /* found an operator */
1700             op = &operators[o];
1701
1702             /* when declaring variables, a comma starts a new variable */
1703             if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1704                 /* fixup the token */
1705                 parser->tok = ',';
1706                 break;
1707             }
1708
1709             /* a colon without a pervious question mark cannot be a ternary */
1710             if (!ternaries && op->id == opid2(':','?')) {
1711                 parser->tok = ':';
1712                 break;
1713             }
1714
1715             if (op->id == opid1(',')) {
1716                 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1717                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1718                 }
1719             }
1720
1721             if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1722                 olast = &operators[vec_last(sy.ops).etype-1];
1723
1724             /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1725             while (olast && op->prec < olast->prec)
1726             {
1727                 if (!parser_sy_apply_operator(parser, &sy))
1728                     goto onerr;
1729                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1730                     olast = &operators[vec_last(sy.ops).etype-1];
1731                 else
1732                     olast = NULL;
1733             }
1734
1735 #define IsAssignOp(x) (\
1736                 (x) == opid1('=') || \
1737                 (x) == opid2('+','=') || \
1738                 (x) == opid2('-','=') || \
1739                 (x) == opid2('*','=') || \
1740                 (x) == opid2('/','=') || \
1741                 (x) == opid2('%','=') || \
1742                 (x) == opid2('&','=') || \
1743                 (x) == opid2('|','=') || \
1744                 (x) == opid3('&','~','=') \
1745                 )
1746             if (warn_parenthesis) {
1747                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1748                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1749                      (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1750                    )
1751                 {
1752                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1753                     warn_parenthesis = false;
1754                 }
1755
1756                 if (olast && olast->id != op->id) {
1757                     if ((op->id    == opid1('&') || op->id    == opid1('|') || op->id    == opid1('^')) &&
1758                         (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1759                     {
1760                         (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1761                         warn_parenthesis = false;
1762                     }
1763                     else if ((op->id    == opid2('&','&') || op->id    == opid2('|','|')) &&
1764                              (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1765                     {
1766                         (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1767                         warn_parenthesis = false;
1768                     }
1769                 }
1770             }
1771
1772             while (olast && (
1773                     (op->prec < olast->prec) ||
1774                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1775             {
1776                 if (!parser_sy_apply_operator(parser, &sy))
1777                     goto onerr;
1778                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1779                     olast = &operators[vec_last(sy.ops).etype-1];
1780                 else
1781                     olast = NULL;
1782             }
1783
1784             if (op->id == opid1('(')) {
1785                 if (wantop) {
1786                     size_t sycount = vec_size(sy.out);
1787                     /* we expected an operator, this is the function-call operator */
1788                     vec_push(sy.paren, PAREN_FUNC);
1789                     vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1790                     vec_push(sy.argc, 0);
1791                 } else {
1792                     vec_push(sy.paren, PAREN_EXPR);
1793                     vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1794                 }
1795                 wantop = false;
1796             } else if (op->id == opid1('[')) {
1797                 if (!wantop) {
1798                     parseerror(parser, "unexpected array subscript");
1799                     goto onerr;
1800                 }
1801                 vec_push(sy.paren, PAREN_INDEX);
1802                 /* push both the operator and the paren, this makes life easier */
1803                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1804                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1805                 wantop = false;
1806             } else if (op->id == opid2('?',':')) {
1807                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1808                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1809                 wantop = false;
1810                 ++ternaries;
1811                 vec_push(sy.paren, PAREN_TERNARY1);
1812             } else if (op->id == opid2(':','?')) {
1813                 if (!vec_size(sy.paren)) {
1814                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1815                     goto onerr;
1816                 }
1817                 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1818                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1819                     goto onerr;
1820                 }
1821                 if (!parser_close_paren(parser, &sy))
1822                     goto onerr;
1823                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1824                 wantop = false;
1825                 --ternaries;
1826             } else {
1827                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1828                 wantop = !!(op->flags & OP_SUFFIX);
1829             }
1830         }
1831         else if (parser->tok == ')') {
1832             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1833                 if (!parser_sy_apply_operator(parser, &sy))
1834                     goto onerr;
1835             }
1836             if (!vec_size(sy.paren))
1837                 break;
1838             if (wantop) {
1839                 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1840                     parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1841                     goto onerr;
1842                 }
1843                 if (!parser_close_paren(parser, &sy))
1844                     goto onerr;
1845             } else {
1846                 /* must be a function call without parameters */
1847                 if (vec_last(sy.paren) != PAREN_FUNC) {
1848                     parseerror(parser, "closing paren in invalid position");
1849                     goto onerr;
1850                 }
1851                 if (!parser_close_paren(parser, &sy))
1852                     goto onerr;
1853             }
1854             wantop = true;
1855         }
1856         else if (parser->tok == '(') {
1857             parseerror(parser, "internal error: '(' should be classified as operator");
1858             goto onerr;
1859         }
1860         else if (parser->tok == '[') {
1861             parseerror(parser, "internal error: '[' should be classified as operator");
1862             goto onerr;
1863         }
1864         else if (parser->tok == ']') {
1865             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1866                 if (!parser_sy_apply_operator(parser, &sy))
1867                     goto onerr;
1868             }
1869             if (!vec_size(sy.paren))
1870                 break;
1871             if (vec_last(sy.paren) != PAREN_INDEX) {
1872                 parseerror(parser, "mismatched parentheses, unexpected ']'");
1873                 goto onerr;
1874             }
1875             if (!parser_close_paren(parser, &sy))
1876                 goto onerr;
1877             wantop = true;
1878         }
1879         else if (!wantop) {
1880             if (!parse_sya_operand(parser, &sy, with_labels))
1881                 goto onerr;
1882             wantop = true;
1883         }
1884         else {
1885             /* in this case we might want to allow constant string concatenation */
1886             bool concatenated = false;
1887             if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1888                 ast_expression *lexpr = vec_last(sy.out).out;
1889                 if (ast_istype(lexpr, ast_value)) {
1890                     ast_value *last = (ast_value*)lexpr;
1891                     if (last->isimm == true && last->cvq == CV_CONST &&
1892                         last->hasvalue && last->expression.vtype == TYPE_STRING)
1893                     {
1894                         char *newstr = NULL;
1895                         util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1896                         vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1897                         mem_d(newstr);
1898                         concatenated = true;
1899                     }
1900                 }
1901             }
1902             if (!concatenated) {
1903                 parseerror(parser, "expected operator or end of statement");
1904                 goto onerr;
1905             }
1906         }
1907
1908         if (!parser_next(parser)) {
1909             goto onerr;
1910         }
1911         if (parser->tok == ';' ||
1912             ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1913             (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1914         {
1915             break;
1916         }
1917     }
1918
1919     while (vec_size(sy.ops)) {
1920         if (!parser_sy_apply_operator(parser, &sy))
1921             goto onerr;
1922     }
1923
1924     parser->lex->flags.noops = true;
1925     if (vec_size(sy.out) != 1) {
1926         parseerror(parser, "expression expected");
1927         expr = NULL;
1928     } else
1929         expr = sy.out[0].out;
1930     vec_free(sy.out);
1931     vec_free(sy.ops);
1932     if (vec_size(sy.paren)) {
1933         parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1934         return NULL;
1935     }
1936     vec_free(sy.paren);
1937     vec_free(sy.argc);
1938     return expr;
1939
1940 onerr:
1941     parser->lex->flags.noops = true;
1942     for (i = 0; i < vec_size(sy.out); ++i) {
1943         if (sy.out[i].out)
1944             ast_unref(sy.out[i].out);
1945     }
1946     vec_free(sy.out);
1947     vec_free(sy.ops);
1948     vec_free(sy.paren);
1949     vec_free(sy.argc);
1950     return NULL;
1951 }
1952
1953 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1954 {
1955     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1956     if (!e)
1957         return NULL;
1958     if (parser->tok != ';') {
1959         parseerror(parser, "semicolon expected after expression");
1960         ast_unref(e);
1961         return NULL;
1962     }
1963     if (!parser_next(parser)) {
1964         ast_unref(e);
1965         return NULL;
1966     }
1967     return e;
1968 }
1969
1970 static void parser_enterblock(parser_t *parser)
1971 {
1972     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1973     vec_push(parser->_blocklocals, vec_size(parser->_locals));
1974     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1975     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1976     vec_push(parser->_block_ctx, parser_ctx(parser));
1977 }
1978
1979 static bool parser_leaveblock(parser_t *parser)
1980 {
1981     bool   rv = true;
1982     size_t locals, typedefs;
1983
1984     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1985         parseerror(parser, "internal error: parser_leaveblock with no block");
1986         return false;
1987     }
1988
1989     util_htdel(vec_last(parser->variables));
1990
1991     vec_pop(parser->variables);
1992     if (!vec_size(parser->_blocklocals)) {
1993         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1994         return false;
1995     }
1996
1997     locals = vec_last(parser->_blocklocals);
1998     vec_pop(parser->_blocklocals);
1999     while (vec_size(parser->_locals) != locals) {
2000         ast_expression *e = vec_last(parser->_locals);
2001         ast_value      *v = (ast_value*)e;
2002         vec_pop(parser->_locals);
2003         if (ast_istype(e, ast_value) && !v->uses) {
2004             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2005                 rv = false;
2006         }
2007     }
2008
2009     typedefs = vec_last(parser->_blocktypedefs);
2010     while (vec_size(parser->_typedefs) != typedefs) {
2011         ast_delete(vec_last(parser->_typedefs));
2012         vec_pop(parser->_typedefs);
2013     }
2014     util_htdel(vec_last(parser->typedefs));
2015     vec_pop(parser->typedefs);
2016
2017     vec_pop(parser->_block_ctx);
2018
2019     return rv;
2020 }
2021
2022 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2023 {
2024     vec_push(parser->_locals, e);
2025     util_htset(vec_last(parser->variables), name, (void*)e);
2026 }
2027
2028 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2029 {
2030     vec_push(parser->globals, e);
2031     util_htset(parser->htglobals, name, e);
2032 }
2033
2034 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2035 {
2036     bool       ifnot = false;
2037     ast_unary *unary;
2038     ast_expression *prev;
2039
2040     if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2041         char ty[1024];
2042         ast_type_to_string(cond, ty, sizeof(ty));
2043         compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2044     }
2045
2046     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2047     {
2048         prev = cond;
2049         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2050         if (!cond) {
2051             ast_unref(prev);
2052             parseerror(parser, "internal error: failed to process condition");
2053             return NULL;
2054         }
2055         ifnot = !ifnot;
2056     }
2057     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2058     {
2059         /* vector types need to be cast to true booleans */
2060         ast_binary *bin = (ast_binary*)cond;
2061         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2062         {
2063             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2064             prev = cond;
2065             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2066             if (!cond) {
2067                 ast_unref(prev);
2068                 parseerror(parser, "internal error: failed to process condition");
2069                 return NULL;
2070             }
2071             ifnot = !ifnot;
2072         }
2073     }
2074
2075     unary = (ast_unary*)cond;
2076     /* ast_istype dereferences cond, should test here for safety */
2077     while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2078     {
2079         cond = unary->operand;
2080         unary->operand = NULL;
2081         ast_delete(unary);
2082         ifnot = !ifnot;
2083         unary = (ast_unary*)cond;
2084     }
2085
2086     if (!cond)
2087         parseerror(parser, "internal error: failed to process condition");
2088
2089     if (ifnot) *_ifnot = !*_ifnot;
2090     return cond;
2091 }
2092
2093 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2094 {
2095     ast_ifthen *ifthen;
2096     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2097     bool ifnot = false;
2098
2099     lex_ctx_t ctx = parser_ctx(parser);
2100
2101     (void)block; /* not touching */
2102
2103     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2104     if (!parser_next(parser)) {
2105         parseerror(parser, "expected condition or 'not'");
2106         return false;
2107     }
2108     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2109         ifnot = true;
2110         if (!parser_next(parser)) {
2111             parseerror(parser, "expected condition in parenthesis");
2112             return false;
2113         }
2114     }
2115     if (parser->tok != '(') {
2116         parseerror(parser, "expected 'if' condition in parenthesis");
2117         return false;
2118     }
2119     /* parse into the expression */
2120     if (!parser_next(parser)) {
2121         parseerror(parser, "expected 'if' condition after opening paren");
2122         return false;
2123     }
2124     /* parse the condition */
2125     cond = parse_expression_leave(parser, false, true, false);
2126     if (!cond)
2127         return false;
2128     /* closing paren */
2129     if (parser->tok != ')') {
2130         parseerror(parser, "expected closing paren after 'if' condition");
2131         ast_unref(cond);
2132         return false;
2133     }
2134     /* parse into the 'then' branch */
2135     if (!parser_next(parser)) {
2136         parseerror(parser, "expected statement for on-true branch of 'if'");
2137         ast_unref(cond);
2138         return false;
2139     }
2140     if (!parse_statement_or_block(parser, &ontrue)) {
2141         ast_unref(cond);
2142         return false;
2143     }
2144     if (!ontrue)
2145         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2146     /* check for an else */
2147     if (!strcmp(parser_tokval(parser), "else")) {
2148         /* parse into the 'else' branch */
2149         if (!parser_next(parser)) {
2150             parseerror(parser, "expected on-false branch after 'else'");
2151             ast_delete(ontrue);
2152             ast_unref(cond);
2153             return false;
2154         }
2155         if (!parse_statement_or_block(parser, &onfalse)) {
2156             ast_delete(ontrue);
2157             ast_unref(cond);
2158             return false;
2159         }
2160     }
2161
2162     cond = process_condition(parser, cond, &ifnot);
2163     if (!cond) {
2164         if (ontrue)  ast_delete(ontrue);
2165         if (onfalse) ast_delete(onfalse);
2166         return false;
2167     }
2168
2169     if (ifnot)
2170         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2171     else
2172         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2173     *out = (ast_expression*)ifthen;
2174     return true;
2175 }
2176
2177 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2178 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2179 {
2180     bool rv;
2181     char *label = NULL;
2182
2183     /* skip the 'while' and get the body */
2184     if (!parser_next(parser)) {
2185         if (OPTS_FLAG(LOOP_LABELS))
2186             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2187         else
2188             parseerror(parser, "expected 'while' condition in parenthesis");
2189         return false;
2190     }
2191
2192     if (parser->tok == ':') {
2193         if (!OPTS_FLAG(LOOP_LABELS))
2194             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2195         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2196             parseerror(parser, "expected loop label");
2197             return false;
2198         }
2199         label = util_strdup(parser_tokval(parser));
2200         if (!parser_next(parser)) {
2201             mem_d(label);
2202             parseerror(parser, "expected 'while' condition in parenthesis");
2203             return false;
2204         }
2205     }
2206
2207     if (parser->tok != '(') {
2208         parseerror(parser, "expected 'while' condition in parenthesis");
2209         return false;
2210     }
2211
2212     parser->breaks.push_back(label);
2213     parser->continues.push_back(label);
2214
2215     rv = parse_while_go(parser, block, out);
2216     if (label)
2217         mem_d(label);
2218     if (parser->breaks.back() != label || parser->continues.back() != label) {
2219         parseerror(parser, "internal error: label stack corrupted");
2220         rv = false;
2221         ast_delete(*out);
2222         *out = NULL;
2223     }
2224     else {
2225         parser->breaks.pop_back();
2226         parser->continues.pop_back();
2227     }
2228     return rv;
2229 }
2230
2231 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2232 {
2233     ast_loop *aloop;
2234     ast_expression *cond, *ontrue;
2235
2236     bool ifnot = false;
2237
2238     lex_ctx_t ctx = parser_ctx(parser);
2239
2240     (void)block; /* not touching */
2241
2242     /* parse into the expression */
2243     if (!parser_next(parser)) {
2244         parseerror(parser, "expected 'while' condition after opening paren");
2245         return false;
2246     }
2247     /* parse the condition */
2248     cond = parse_expression_leave(parser, false, true, false);
2249     if (!cond)
2250         return false;
2251     /* closing paren */
2252     if (parser->tok != ')') {
2253         parseerror(parser, "expected closing paren after 'while' condition");
2254         ast_unref(cond);
2255         return false;
2256     }
2257     /* parse into the 'then' branch */
2258     if (!parser_next(parser)) {
2259         parseerror(parser, "expected while-loop body");
2260         ast_unref(cond);
2261         return false;
2262     }
2263     if (!parse_statement_or_block(parser, &ontrue)) {
2264         ast_unref(cond);
2265         return false;
2266     }
2267
2268     cond = process_condition(parser, cond, &ifnot);
2269     if (!cond) {
2270         ast_unref(ontrue);
2271         return false;
2272     }
2273     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2274     *out = (ast_expression*)aloop;
2275     return true;
2276 }
2277
2278 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2279 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2280 {
2281     bool rv;
2282     char *label = NULL;
2283
2284     /* skip the 'do' and get the body */
2285     if (!parser_next(parser)) {
2286         if (OPTS_FLAG(LOOP_LABELS))
2287             parseerror(parser, "expected loop label or body");
2288         else
2289             parseerror(parser, "expected loop body");
2290         return false;
2291     }
2292
2293     if (parser->tok == ':') {
2294         if (!OPTS_FLAG(LOOP_LABELS))
2295             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2296         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2297             parseerror(parser, "expected loop label");
2298             return false;
2299         }
2300         label = util_strdup(parser_tokval(parser));
2301         if (!parser_next(parser)) {
2302             mem_d(label);
2303             parseerror(parser, "expected loop body");
2304             return false;
2305         }
2306     }
2307
2308     parser->breaks.push_back(label);
2309     parser->continues.push_back(label);
2310
2311     rv = parse_dowhile_go(parser, block, out);
2312     if (label)
2313         mem_d(label);
2314     if (parser->breaks.back() != label || parser->continues.back() != label) {
2315         parseerror(parser, "internal error: label stack corrupted");
2316         rv = false;
2317         /*
2318          * Test for NULL otherwise ast_delete dereferences null pointer
2319          * and boom.
2320          */
2321         if (*out)
2322             ast_delete(*out);
2323         *out = NULL;
2324     }
2325     else {
2326         parser->breaks.pop_back();
2327         parser->continues.pop_back();
2328     }
2329     return rv;
2330 }
2331
2332 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2333 {
2334     ast_loop *aloop;
2335     ast_expression *cond, *ontrue;
2336
2337     bool ifnot = false;
2338
2339     lex_ctx_t ctx = parser_ctx(parser);
2340
2341     (void)block; /* not touching */
2342
2343     if (!parse_statement_or_block(parser, &ontrue))
2344         return false;
2345
2346     /* expect the "while" */
2347     if (parser->tok != TOKEN_KEYWORD ||
2348         strcmp(parser_tokval(parser), "while"))
2349     {
2350         parseerror(parser, "expected 'while' and condition");
2351         ast_delete(ontrue);
2352         return false;
2353     }
2354
2355     /* skip the 'while' and check for opening paren */
2356     if (!parser_next(parser) || parser->tok != '(') {
2357         parseerror(parser, "expected 'while' condition in parenthesis");
2358         ast_delete(ontrue);
2359         return false;
2360     }
2361     /* parse into the expression */
2362     if (!parser_next(parser)) {
2363         parseerror(parser, "expected 'while' condition after opening paren");
2364         ast_delete(ontrue);
2365         return false;
2366     }
2367     /* parse the condition */
2368     cond = parse_expression_leave(parser, false, true, false);
2369     if (!cond)
2370         return false;
2371     /* closing paren */
2372     if (parser->tok != ')') {
2373         parseerror(parser, "expected closing paren after 'while' condition");
2374         ast_delete(ontrue);
2375         ast_unref(cond);
2376         return false;
2377     }
2378     /* parse on */
2379     if (!parser_next(parser) || parser->tok != ';') {
2380         parseerror(parser, "expected semicolon after condition");
2381         ast_delete(ontrue);
2382         ast_unref(cond);
2383         return false;
2384     }
2385
2386     if (!parser_next(parser)) {
2387         parseerror(parser, "parse error");
2388         ast_delete(ontrue);
2389         ast_unref(cond);
2390         return false;
2391     }
2392
2393     cond = process_condition(parser, cond, &ifnot);
2394     if (!cond) {
2395         ast_delete(ontrue);
2396         return false;
2397     }
2398     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2399     *out = (ast_expression*)aloop;
2400     return true;
2401 }
2402
2403 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2404 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2405 {
2406     bool rv;
2407     char *label = NULL;
2408
2409     /* skip the 'for' and check for opening paren */
2410     if (!parser_next(parser)) {
2411         if (OPTS_FLAG(LOOP_LABELS))
2412             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2413         else
2414             parseerror(parser, "expected 'for' expressions in parenthesis");
2415         return false;
2416     }
2417
2418     if (parser->tok == ':') {
2419         if (!OPTS_FLAG(LOOP_LABELS))
2420             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2421         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2422             parseerror(parser, "expected loop label");
2423             return false;
2424         }
2425         label = util_strdup(parser_tokval(parser));
2426         if (!parser_next(parser)) {
2427             mem_d(label);
2428             parseerror(parser, "expected 'for' expressions in parenthesis");
2429             return false;
2430         }
2431     }
2432
2433     if (parser->tok != '(') {
2434         parseerror(parser, "expected 'for' expressions in parenthesis");
2435         return false;
2436     }
2437
2438     parser->breaks.push_back(label);
2439     parser->continues.push_back(label);
2440
2441     rv = parse_for_go(parser, block, out);
2442     if (label)
2443         mem_d(label);
2444     if (parser->breaks.back() != label || parser->continues.back() != label) {
2445         parseerror(parser, "internal error: label stack corrupted");
2446         rv = false;
2447         ast_delete(*out);
2448         *out = NULL;
2449     }
2450     else {
2451         parser->breaks.pop_back();
2452         parser->continues.pop_back();
2453     }
2454     return rv;
2455 }
2456 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2457 {
2458     ast_loop       *aloop;
2459     ast_expression *initexpr, *cond, *increment, *ontrue;
2460     ast_value      *typevar;
2461
2462     bool ifnot  = false;
2463
2464     lex_ctx_t ctx = parser_ctx(parser);
2465
2466     parser_enterblock(parser);
2467
2468     initexpr  = NULL;
2469     cond      = NULL;
2470     increment = NULL;
2471     ontrue    = NULL;
2472
2473     /* parse into the expression */
2474     if (!parser_next(parser)) {
2475         parseerror(parser, "expected 'for' initializer after opening paren");
2476         goto onerr;
2477     }
2478
2479     typevar = NULL;
2480     if (parser->tok == TOKEN_IDENT)
2481         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2482
2483     if (typevar || parser->tok == TOKEN_TYPENAME) {
2484         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2485             goto onerr;
2486     }
2487     else if (parser->tok != ';')
2488     {
2489         initexpr = parse_expression_leave(parser, false, false, false);
2490         if (!initexpr)
2491             goto onerr;
2492
2493         /* move on to condition */
2494         if (parser->tok != ';') {
2495             parseerror(parser, "expected semicolon after for-loop initializer");
2496             goto onerr;
2497         }
2498
2499         if (!parser_next(parser)) {
2500             parseerror(parser, "expected for-loop condition");
2501             goto onerr;
2502         }
2503     }
2504
2505     /* parse the condition */
2506     if (parser->tok != ';') {
2507         cond = parse_expression_leave(parser, false, true, false);
2508         if (!cond)
2509             goto onerr;
2510     }
2511
2512     /* move on to incrementor */
2513     if (parser->tok != ';') {
2514         parseerror(parser, "expected semicolon after for-loop initializer");
2515         goto onerr;
2516     }
2517     if (!parser_next(parser)) {
2518         parseerror(parser, "expected for-loop condition");
2519         goto onerr;
2520     }
2521
2522     /* parse the incrementor */
2523     if (parser->tok != ')') {
2524         lex_ctx_t condctx = parser_ctx(parser);
2525         increment = parse_expression_leave(parser, false, false, false);
2526         if (!increment)
2527             goto onerr;
2528         if (!ast_side_effects(increment)) {
2529             if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2530                 goto onerr;
2531         }
2532     }
2533
2534     /* closing paren */
2535     if (parser->tok != ')') {
2536         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2537         goto onerr;
2538     }
2539     /* parse into the 'then' branch */
2540     if (!parser_next(parser)) {
2541         parseerror(parser, "expected for-loop body");
2542         goto onerr;
2543     }
2544     if (!parse_statement_or_block(parser, &ontrue))
2545         goto onerr;
2546
2547     if (cond) {
2548         cond = process_condition(parser, cond, &ifnot);
2549         if (!cond)
2550             goto onerr;
2551     }
2552     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2553     *out = (ast_expression*)aloop;
2554
2555     if (!parser_leaveblock(parser)) {
2556         ast_delete(aloop);
2557         return false;
2558     }
2559     return true;
2560 onerr:
2561     if (initexpr)  ast_unref(initexpr);
2562     if (cond)      ast_unref(cond);
2563     if (increment) ast_unref(increment);
2564     (void)!parser_leaveblock(parser);
2565     return false;
2566 }
2567
2568 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2569 {
2570     ast_expression *exp      = NULL;
2571     ast_expression *var      = NULL;
2572     ast_return     *ret      = NULL;
2573     ast_value      *retval   = parser->function->return_value;
2574     ast_value      *expected = parser->function->vtype;
2575
2576     lex_ctx_t ctx = parser_ctx(parser);
2577
2578     (void)block; /* not touching */
2579
2580     if (!parser_next(parser)) {
2581         parseerror(parser, "expected return expression");
2582         return false;
2583     }
2584
2585     /* return assignments */
2586     if (parser->tok == '=') {
2587         if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2588             parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2589             return false;
2590         }
2591
2592         if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2593             char ty1[1024];
2594             ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2595             parseerror(parser, "invalid return type: `%s'", ty1);
2596             return false;
2597         }
2598
2599         if (!parser_next(parser)) {
2600             parseerror(parser, "expected return assignment expression");
2601             return false;
2602         }
2603
2604         if (!(exp = parse_expression_leave(parser, false, false, false)))
2605             return false;
2606
2607         /* prepare the return value */
2608         if (!retval) {
2609             retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2610             ast_type_adopt(retval, expected->expression.next);
2611             parser->function->return_value = retval;
2612         }
2613
2614         if (!ast_compare_type(exp, (ast_expression*)retval)) {
2615             char ty1[1024], ty2[1024];
2616             ast_type_to_string(exp, ty1, sizeof(ty1));
2617             ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2618             parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2619         }
2620
2621         /* store to 'return' local variable */
2622         var = (ast_expression*)ast_store_new(
2623             ctx,
2624             type_store_instr[expected->expression.next->vtype],
2625             (ast_expression*)retval, exp);
2626
2627         if (!var) {
2628             ast_unref(exp);
2629             return false;
2630         }
2631
2632         if (parser->tok != ';')
2633             parseerror(parser, "missing semicolon after return assignment");
2634         else if (!parser_next(parser))
2635             parseerror(parser, "parse error after return assignment");
2636
2637         *out = var;
2638         return true;
2639     }
2640
2641     if (parser->tok != ';') {
2642         exp = parse_expression(parser, false, false);
2643         if (!exp)
2644             return false;
2645
2646         if (exp->vtype != TYPE_NIL &&
2647             exp->vtype != ((ast_expression*)expected)->next->vtype)
2648         {
2649             parseerror(parser, "return with invalid expression");
2650         }
2651
2652         ret = ast_return_new(ctx, exp);
2653         if (!ret) {
2654             ast_unref(exp);
2655             return false;
2656         }
2657     } else {
2658         if (!parser_next(parser))
2659             parseerror(parser, "parse error");
2660
2661         if (!retval && expected->expression.next->vtype != TYPE_VOID)
2662         {
2663             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2664         }
2665         ret = ast_return_new(ctx, (ast_expression*)retval);
2666     }
2667     *out = (ast_expression*)ret;
2668     return true;
2669 }
2670
2671 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2672 {
2673     size_t i;
2674     unsigned int levels = 0;
2675     lex_ctx_t ctx = parser_ctx(parser);
2676     auto &loops = (is_continue ? parser->continues : parser->breaks);
2677
2678     (void)block; /* not touching */
2679     if (!parser_next(parser)) {
2680         parseerror(parser, "expected semicolon or loop label");
2681         return false;
2682     }
2683
2684     if (loops.empty()) {
2685         if (is_continue)
2686             parseerror(parser, "`continue` can only be used inside loops");
2687         else
2688             parseerror(parser, "`break` can only be used inside loops or switches");
2689     }
2690
2691     if (parser->tok == TOKEN_IDENT) {
2692         if (!OPTS_FLAG(LOOP_LABELS))
2693             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2694         i = loops.size();
2695         while (i--) {
2696             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2697                 break;
2698             if (!i) {
2699                 parseerror(parser, "no such loop to %s: `%s`",
2700                            (is_continue ? "continue" : "break out of"),
2701                            parser_tokval(parser));
2702                 return false;
2703             }
2704             ++levels;
2705         }
2706         if (!parser_next(parser)) {
2707             parseerror(parser, "expected semicolon");
2708             return false;
2709         }
2710     }
2711
2712     if (parser->tok != ';') {
2713         parseerror(parser, "expected semicolon");
2714         return false;
2715     }
2716
2717     if (!parser_next(parser))
2718         parseerror(parser, "parse error");
2719
2720     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2721     return true;
2722 }
2723
2724 /* returns true when it was a variable qualifier, false otherwise!
2725  * on error, cvq is set to CV_WRONG
2726  */
2727 typedef struct {
2728     const char *name;
2729     size_t      flag;
2730 } attribute_t;
2731
2732 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2733 {
2734     bool had_const    = false;
2735     bool had_var      = false;
2736     bool had_noref    = false;
2737     bool had_attrib   = false;
2738     bool had_static   = false;
2739     uint32_t flags    = 0;
2740
2741     static attribute_t attributes[] = {
2742         { "noreturn",   AST_FLAG_NORETURN   },
2743         { "inline",     AST_FLAG_INLINE     },
2744         { "eraseable",  AST_FLAG_ERASEABLE  },
2745         { "accumulate", AST_FLAG_ACCUMULATE },
2746         { "last",       AST_FLAG_FINAL_DECL }
2747     };
2748
2749    *cvq = CV_NONE;
2750
2751     for (;;) {
2752         size_t i;
2753         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2754             had_attrib = true;
2755             /* parse an attribute */
2756             if (!parser_next(parser)) {
2757                 parseerror(parser, "expected attribute after `[[`");
2758                 *cvq = CV_WRONG;
2759                 return false;
2760             }
2761
2762             for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2763                 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2764                     flags |= attributes[i].flag;
2765                     if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2766                         parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2767                             attributes[i].name);
2768                         *cvq = CV_WRONG;
2769                         return false;
2770                     }
2771                     break;
2772                 }
2773             }
2774
2775             if (i != GMQCC_ARRAY_COUNT(attributes))
2776                 goto leave;
2777
2778
2779             if (!strcmp(parser_tokval(parser), "noref")) {
2780                 had_noref = true;
2781                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2782                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2783                     *cvq = CV_WRONG;
2784                     return false;
2785                 }
2786             }
2787             else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2788                 flags   |= AST_FLAG_ALIAS;
2789                 *message = NULL;
2790
2791                 if (!parser_next(parser)) {
2792                     parseerror(parser, "parse error in attribute");
2793                     goto argerr;
2794                 }
2795
2796                 if (parser->tok == '(') {
2797                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2798                         parseerror(parser, "`alias` attribute missing parameter");
2799                         goto argerr;
2800                     }
2801
2802                     *message = util_strdup(parser_tokval(parser));
2803
2804                     if (!parser_next(parser)) {
2805                         parseerror(parser, "parse error in attribute");
2806                         goto argerr;
2807                     }
2808
2809                     if (parser->tok != ')') {
2810                         parseerror(parser, "`alias` attribute expected `)` after parameter");
2811                         goto argerr;
2812                     }
2813
2814                     if (!parser_next(parser)) {
2815                         parseerror(parser, "parse error in attribute");
2816                         goto argerr;
2817                     }
2818                 }
2819
2820                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2821                     parseerror(parser, "`alias` attribute expected `]]`");
2822                     goto argerr;
2823                 }
2824             }
2825             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2826                 flags   |= AST_FLAG_DEPRECATED;
2827                 *message = NULL;
2828
2829                 if (!parser_next(parser)) {
2830                     parseerror(parser, "parse error in attribute");
2831                     goto argerr;
2832                 }
2833
2834                 if (parser->tok == '(') {
2835                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2836                         parseerror(parser, "`deprecated` attribute missing parameter");
2837                         goto argerr;
2838                     }
2839
2840                     *message = util_strdup(parser_tokval(parser));
2841
2842                     if (!parser_next(parser)) {
2843                         parseerror(parser, "parse error in attribute");
2844                         goto argerr;
2845                     }
2846
2847                     if(parser->tok != ')') {
2848                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2849                         goto argerr;
2850                     }
2851
2852                     if (!parser_next(parser)) {
2853                         parseerror(parser, "parse error in attribute");
2854                         goto argerr;
2855                     }
2856                 }
2857                 /* no message */
2858                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2859                     parseerror(parser, "`deprecated` attribute expected `]]`");
2860
2861                     argerr: /* ugly */
2862                     if (*message) mem_d(*message);
2863                     *message = NULL;
2864                     *cvq     = CV_WRONG;
2865                     return false;
2866                 }
2867             }
2868             else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2869                 flags |= AST_FLAG_COVERAGE;
2870                 if (!parser_next(parser)) {
2871                     error_in_coverage:
2872                     parseerror(parser, "parse error in coverage attribute");
2873                     *cvq = CV_WRONG;
2874                     return false;
2875                 }
2876                 if (parser->tok == '(') {
2877                     if (!parser_next(parser)) {
2878                         bad_coverage_arg:
2879                         parseerror(parser, "invalid parameter for coverage() attribute\n"
2880                                            "valid are: block");
2881                         *cvq = CV_WRONG;
2882                         return false;
2883                     }
2884                     if (parser->tok != ')') {
2885                         do {
2886                             if (parser->tok != TOKEN_IDENT)
2887                                 goto bad_coverage_arg;
2888                             if (!strcmp(parser_tokval(parser), "block"))
2889                                 flags |= AST_FLAG_BLOCK_COVERAGE;
2890                             else if (!strcmp(parser_tokval(parser), "none"))
2891                                 flags &= ~(AST_FLAG_COVERAGE_MASK);
2892                             else
2893                                 goto bad_coverage_arg;
2894                             if (!parser_next(parser))
2895                                 goto error_in_coverage;
2896                             if (parser->tok == ',') {
2897                                 if (!parser_next(parser))
2898                                     goto error_in_coverage;
2899                             }
2900                         } while (parser->tok != ')');
2901                     }
2902                     if (parser->tok != ')' || !parser_next(parser))
2903                         goto error_in_coverage;
2904                 } else {
2905                     /* without parameter [[coverage]] equals [[coverage(block)]] */
2906                     flags |= AST_FLAG_BLOCK_COVERAGE;
2907                 }
2908             }
2909             else
2910             {
2911                 /* Skip tokens until we hit a ]] */
2912                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2913                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2914                     if (!parser_next(parser)) {
2915                         parseerror(parser, "error inside attribute");
2916                         *cvq = CV_WRONG;
2917                         return false;
2918                     }
2919                 }
2920             }
2921         }
2922         else if (with_local && !strcmp(parser_tokval(parser), "static"))
2923             had_static = true;
2924         else if (!strcmp(parser_tokval(parser), "const"))
2925             had_const = true;
2926         else if (!strcmp(parser_tokval(parser), "var"))
2927             had_var = true;
2928         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2929             had_var = true;
2930         else if (!strcmp(parser_tokval(parser), "noref"))
2931             had_noref = true;
2932         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2933             return false;
2934         }
2935         else
2936             break;
2937
2938         leave:
2939         if (!parser_next(parser))
2940             goto onerr;
2941     }
2942     if (had_const)
2943         *cvq = CV_CONST;
2944     else if (had_var)
2945         *cvq = CV_VAR;
2946     else
2947         *cvq = CV_NONE;
2948     *noref     = had_noref;
2949     *is_static = had_static;
2950     *_flags    = flags;
2951     return true;
2952 onerr:
2953     parseerror(parser, "parse error after variable qualifier");
2954     *cvq = CV_WRONG;
2955     return true;
2956 }
2957
2958 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2959 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2960 {
2961     bool rv;
2962     char *label = NULL;
2963
2964     /* skip the 'while' and get the body */
2965     if (!parser_next(parser)) {
2966         if (OPTS_FLAG(LOOP_LABELS))
2967             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2968         else
2969             parseerror(parser, "expected 'switch' operand in parenthesis");
2970         return false;
2971     }
2972
2973     if (parser->tok == ':') {
2974         if (!OPTS_FLAG(LOOP_LABELS))
2975             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2976         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2977             parseerror(parser, "expected loop label");
2978             return false;
2979         }
2980         label = util_strdup(parser_tokval(parser));
2981         if (!parser_next(parser)) {
2982             mem_d(label);
2983             parseerror(parser, "expected 'switch' operand in parenthesis");
2984             return false;
2985         }
2986     }
2987
2988     if (parser->tok != '(') {
2989         parseerror(parser, "expected 'switch' operand in parenthesis");
2990         return false;
2991     }
2992
2993     parser->breaks.push_back(label);
2994
2995     rv = parse_switch_go(parser, block, out);
2996     if (label)
2997         mem_d(label);
2998     if (parser->breaks.back() != label) {
2999         parseerror(parser, "internal error: label stack corrupted");
3000         rv = false;
3001         ast_delete(*out);
3002         *out = NULL;
3003     }
3004     else {
3005         parser->breaks.pop_back();
3006     }
3007     return rv;
3008 }
3009
3010 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3011 {
3012     ast_expression *operand;
3013     ast_value      *opval;
3014     ast_value      *typevar;
3015     ast_switch     *switchnode;
3016     ast_switch_case swcase;
3017
3018     int  cvq;
3019     bool noref, is_static;
3020     uint32_t qflags = 0;
3021
3022     lex_ctx_t ctx = parser_ctx(parser);
3023
3024     (void)block; /* not touching */
3025     (void)opval;
3026
3027     /* parse into the expression */
3028     if (!parser_next(parser)) {
3029         parseerror(parser, "expected switch operand");
3030         return false;
3031     }
3032     /* parse the operand */
3033     operand = parse_expression_leave(parser, false, false, false);
3034     if (!operand)
3035         return false;
3036
3037     switchnode = ast_switch_new(ctx, operand);
3038
3039     /* closing paren */
3040     if (parser->tok != ')') {
3041         ast_delete(switchnode);
3042         parseerror(parser, "expected closing paren after 'switch' operand");
3043         return false;
3044     }
3045
3046     /* parse over the opening paren */
3047     if (!parser_next(parser) || parser->tok != '{') {
3048         ast_delete(switchnode);
3049         parseerror(parser, "expected list of cases");
3050         return false;
3051     }
3052
3053     if (!parser_next(parser)) {
3054         ast_delete(switchnode);
3055         parseerror(parser, "expected 'case' or 'default'");
3056         return false;
3057     }
3058
3059     /* new block; allow some variables to be declared here */
3060     parser_enterblock(parser);
3061     while (true) {
3062         typevar = NULL;
3063         if (parser->tok == TOKEN_IDENT)
3064             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3065         if (typevar || parser->tok == TOKEN_TYPENAME) {
3066             if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, NULL)) {
3067                 ast_delete(switchnode);
3068                 return false;
3069             }
3070             continue;
3071         }
3072         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3073         {
3074             if (cvq == CV_WRONG) {
3075                 ast_delete(switchnode);
3076                 return false;
3077             }
3078             if (!parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, NULL)) {
3079                 ast_delete(switchnode);
3080                 return false;
3081             }
3082             continue;
3083         }
3084         break;
3085     }
3086
3087     /* case list! */
3088     while (parser->tok != '}') {
3089         ast_block *caseblock;
3090
3091         if (!strcmp(parser_tokval(parser), "case")) {
3092             if (!parser_next(parser)) {
3093                 ast_delete(switchnode);
3094                 parseerror(parser, "expected expression for case");
3095                 return false;
3096             }
3097             swcase.value = parse_expression_leave(parser, false, false, false);
3098             if (!swcase.value) {
3099                 ast_delete(switchnode);
3100                 parseerror(parser, "expected expression for case");
3101                 return false;
3102             }
3103             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3104                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3105                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3106                     ast_unref(operand);
3107                     return false;
3108                 }
3109             }
3110         }
3111         else if (!strcmp(parser_tokval(parser), "default")) {
3112             swcase.value = NULL;
3113             if (!parser_next(parser)) {
3114                 ast_delete(switchnode);
3115                 parseerror(parser, "expected colon");
3116                 return false;
3117             }
3118         }
3119         else {
3120             ast_delete(switchnode);
3121             parseerror(parser, "expected 'case' or 'default'");
3122             return false;
3123         }
3124
3125         /* Now the colon and body */
3126         if (parser->tok != ':') {
3127             if (swcase.value) ast_unref(swcase.value);
3128             ast_delete(switchnode);
3129             parseerror(parser, "expected colon");
3130             return false;
3131         }
3132
3133         if (!parser_next(parser)) {
3134             if (swcase.value) ast_unref(swcase.value);
3135             ast_delete(switchnode);
3136             parseerror(parser, "expected statements or case");
3137             return false;
3138         }
3139         caseblock = ast_block_new(parser_ctx(parser));
3140         if (!caseblock) {
3141             if (swcase.value) ast_unref(swcase.value);
3142             ast_delete(switchnode);
3143             return false;
3144         }
3145         swcase.code = (ast_expression*)caseblock;
3146         vec_push(switchnode->cases, swcase);
3147         while (true) {
3148             ast_expression *expr;
3149             if (parser->tok == '}')
3150                 break;
3151             if (parser->tok == TOKEN_KEYWORD) {
3152                 if (!strcmp(parser_tokval(parser), "case") ||
3153                     !strcmp(parser_tokval(parser), "default"))
3154                 {
3155                     break;
3156                 }
3157             }
3158             if (!parse_statement(parser, caseblock, &expr, true)) {
3159                 ast_delete(switchnode);
3160                 return false;
3161             }
3162             if (!expr)
3163                 continue;
3164             if (!ast_block_add_expr(caseblock, expr)) {
3165                 ast_delete(switchnode);
3166                 return false;
3167             }
3168         }
3169     }
3170
3171     parser_leaveblock(parser);
3172
3173     /* closing paren */
3174     if (parser->tok != '}') {
3175         ast_delete(switchnode);
3176         parseerror(parser, "expected closing paren of case list");
3177         return false;
3178     }
3179     if (!parser_next(parser)) {
3180         ast_delete(switchnode);
3181         parseerror(parser, "parse error after switch");
3182         return false;
3183     }
3184     *out = (ast_expression*)switchnode;
3185     return true;
3186 }
3187
3188 /* parse computed goto sides */
3189 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3190     ast_expression *on_true;
3191     ast_expression *on_false;
3192     ast_expression *cond;
3193
3194     if (!*side)
3195         return NULL;
3196
3197     if (ast_istype(*side, ast_ternary)) {
3198         ast_ternary *tern = (ast_ternary*)*side;
3199         on_true  = parse_goto_computed(parser, &tern->on_true);
3200         on_false = parse_goto_computed(parser, &tern->on_false);
3201
3202         if (!on_true || !on_false) {
3203             parseerror(parser, "expected label or expression in ternary");
3204             if (on_true) ast_unref(on_true);
3205             if (on_false) ast_unref(on_false);
3206             return NULL;
3207         }
3208
3209         cond = tern->cond;
3210         tern->cond = NULL;
3211         ast_delete(tern);
3212         *side = NULL;
3213         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3214     } else if (ast_istype(*side, ast_label)) {
3215         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3216         ast_goto_set_label(gt, ((ast_label*)*side));
3217         *side = NULL;
3218         return (ast_expression*)gt;
3219     }
3220     return NULL;
3221 }
3222
3223 static bool parse_goto(parser_t *parser, ast_expression **out)
3224 {
3225     ast_goto       *gt = NULL;
3226     ast_expression *lbl;
3227
3228     if (!parser_next(parser))
3229         return false;
3230
3231     if (parser->tok != TOKEN_IDENT) {
3232         ast_expression *expression;
3233
3234         /* could be an expression i.e computed goto :-) */
3235         if (parser->tok != '(') {
3236             parseerror(parser, "expected label name after `goto`");
3237             return false;
3238         }
3239
3240         /* failed to parse expression for goto */
3241         if (!(expression = parse_expression(parser, false, true)) ||
3242             !(*out = parse_goto_computed(parser, &expression))) {
3243             parseerror(parser, "invalid goto expression");
3244             if(expression)
3245                 ast_unref(expression);
3246             return false;
3247         }
3248
3249         return true;
3250     }
3251
3252     /* not computed goto */
3253     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3254     lbl = parser_find_label(parser, gt->name);
3255     if (lbl) {
3256         if (!ast_istype(lbl, ast_label)) {
3257             parseerror(parser, "internal error: label is not an ast_label");
3258             ast_delete(gt);
3259             return false;
3260         }
3261         ast_goto_set_label(gt, (ast_label*)lbl);
3262     }
3263     else
3264         parser->gotos.push_back(gt);
3265
3266     if (!parser_next(parser) || parser->tok != ';') {
3267         parseerror(parser, "semicolon expected after goto label");
3268         return false;
3269     }
3270     if (!parser_next(parser)) {
3271         parseerror(parser, "parse error after goto");
3272         return false;
3273     }
3274
3275     *out = (ast_expression*)gt;
3276     return true;
3277 }
3278
3279 static bool parse_skipwhite(parser_t *parser)
3280 {
3281     do {
3282         if (!parser_next(parser))
3283             return false;
3284     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3285     return parser->tok < TOKEN_ERROR;
3286 }
3287
3288 static bool parse_eol(parser_t *parser)
3289 {
3290     if (!parse_skipwhite(parser))
3291         return false;
3292     return parser->tok == TOKEN_EOL;
3293 }
3294
3295 static bool parse_pragma_do(parser_t *parser)
3296 {
3297     if (!parser_next(parser) ||
3298         parser->tok != TOKEN_IDENT ||
3299         strcmp(parser_tokval(parser), "pragma"))
3300     {
3301         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3302         return false;
3303     }
3304     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3305         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3306         return false;
3307     }
3308
3309     if (!strcmp(parser_tokval(parser), "noref")) {
3310         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3311             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3312             return false;
3313         }
3314         parser->noref = !!parser_token(parser)->constval.i;
3315         if (!parse_eol(parser)) {
3316             parseerror(parser, "parse error after `noref` pragma");
3317             return false;
3318         }
3319     }
3320     else
3321     {
3322         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3323
3324         /* skip to eol */
3325         while (!parse_eol(parser)) {
3326             parser_next(parser);
3327         }
3328
3329         return true;
3330     }
3331
3332     return true;
3333 }
3334
3335 static bool parse_pragma(parser_t *parser)
3336 {
3337     bool rv;
3338     parser->lex->flags.preprocessing = true;
3339     parser->lex->flags.mergelines = true;
3340     rv = parse_pragma_do(parser);
3341     if (parser->tok != TOKEN_EOL) {
3342         parseerror(parser, "junk after pragma");
3343         rv = false;
3344     }
3345     parser->lex->flags.preprocessing = false;
3346     parser->lex->flags.mergelines = false;
3347     if (!parser_next(parser)) {
3348         parseerror(parser, "parse error after pragma");
3349         rv = false;
3350     }
3351     return rv;
3352 }
3353
3354 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3355 {
3356     bool       noref, is_static;
3357     int        cvq     = CV_NONE;
3358     uint32_t   qflags  = 0;
3359     ast_value *typevar = NULL;
3360     char      *vstring = NULL;
3361
3362     *out = NULL;
3363
3364     if (parser->tok == TOKEN_IDENT)
3365         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3366
3367     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3368     {
3369         /* local variable */
3370         if (!block) {
3371             parseerror(parser, "cannot declare a variable from here");
3372             return false;
3373         }
3374         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3375             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3376                 return false;
3377         }
3378         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3379             return false;
3380         return true;
3381     }
3382     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3383     {
3384         if (cvq == CV_WRONG)
3385             return false;
3386         return parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, vstring);
3387     }
3388     else if (parser->tok == TOKEN_KEYWORD)
3389     {
3390         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3391         {
3392             char ty[1024];
3393             ast_value *tdef;
3394
3395             if (!parser_next(parser)) {
3396                 parseerror(parser, "parse error after __builtin_debug_printtype");
3397                 return false;
3398             }
3399
3400             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3401             {
3402                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3403                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3404                 if (!parser_next(parser)) {
3405                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3406                     return false;
3407                 }
3408             }
3409             else
3410             {
3411                 if (!parse_statement(parser, block, out, allow_cases))
3412                     return false;
3413                 if (!*out)
3414                     con_out("__builtin_debug_printtype: got no output node\n");
3415                 else
3416                 {
3417                     ast_type_to_string(*out, ty, sizeof(ty));
3418                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3419                 }
3420             }
3421             return true;
3422         }
3423         else if (!strcmp(parser_tokval(parser), "return"))
3424         {
3425             return parse_return(parser, block, out);
3426         }
3427         else if (!strcmp(parser_tokval(parser), "if"))
3428         {
3429             return parse_if(parser, block, out);
3430         }
3431         else if (!strcmp(parser_tokval(parser), "while"))
3432         {
3433             return parse_while(parser, block, out);
3434         }
3435         else if (!strcmp(parser_tokval(parser), "do"))
3436         {
3437             return parse_dowhile(parser, block, out);
3438         }
3439         else if (!strcmp(parser_tokval(parser), "for"))
3440         {
3441             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3442                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3443                     return false;
3444             }
3445             return parse_for(parser, block, out);
3446         }
3447         else if (!strcmp(parser_tokval(parser), "break"))
3448         {
3449             return parse_break_continue(parser, block, out, false);
3450         }
3451         else if (!strcmp(parser_tokval(parser), "continue"))
3452         {
3453             return parse_break_continue(parser, block, out, true);
3454         }
3455         else if (!strcmp(parser_tokval(parser), "switch"))
3456         {
3457             return parse_switch(parser, block, out);
3458         }
3459         else if (!strcmp(parser_tokval(parser), "case") ||
3460                  !strcmp(parser_tokval(parser), "default"))
3461         {
3462             if (!allow_cases) {
3463                 parseerror(parser, "unexpected 'case' label");
3464                 return false;
3465             }
3466             return true;
3467         }
3468         else if (!strcmp(parser_tokval(parser), "goto"))
3469         {
3470             return parse_goto(parser, out);
3471         }
3472         else if (!strcmp(parser_tokval(parser), "typedef"))
3473         {
3474             if (!parser_next(parser)) {
3475                 parseerror(parser, "expected type definition after 'typedef'");
3476                 return false;
3477             }
3478             return parse_typedef(parser);
3479         }
3480         parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3481         return false;
3482     }
3483     else if (parser->tok == '{')
3484     {
3485         ast_block *inner;
3486         inner = parse_block(parser);
3487         if (!inner)
3488             return false;
3489         *out = (ast_expression*)inner;
3490         return true;
3491     }
3492     else if (parser->tok == ':')
3493     {
3494         size_t i;
3495         ast_label *label;
3496         if (!parser_next(parser)) {
3497             parseerror(parser, "expected label name");
3498             return false;
3499         }
3500         if (parser->tok != TOKEN_IDENT) {
3501             parseerror(parser, "label must be an identifier");
3502             return false;
3503         }
3504         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3505         if (label) {
3506             if (!label->undefined) {
3507                 parseerror(parser, "label `%s` already defined", label->name);
3508                 return false;
3509             }
3510             label->undefined = false;
3511         }
3512         else {
3513             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3514             parser->labels.push_back(label);
3515         }
3516         *out = (ast_expression*)label;
3517         if (!parser_next(parser)) {
3518             parseerror(parser, "parse error after label");
3519             return false;
3520         }
3521         for (i = 0; i < parser->gotos.size(); ++i) {
3522             if (!strcmp(parser->gotos[i]->name, label->name)) {
3523                 ast_goto_set_label(parser->gotos[i], label);
3524                 parser->gotos.erase(parser->gotos.begin() + i);
3525                 --i;
3526             }
3527         }
3528         return true;
3529     }
3530     else if (parser->tok == ';')
3531     {
3532         if (!parser_next(parser)) {
3533             parseerror(parser, "parse error after empty statement");
3534             return false;
3535         }
3536         return true;
3537     }
3538     else
3539     {
3540         lex_ctx_t ctx = parser_ctx(parser);
3541         ast_expression *exp = parse_expression(parser, false, false);
3542         if (!exp)
3543             return false;
3544         *out = exp;
3545         if (!ast_side_effects(exp)) {
3546             if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3547                 return false;
3548         }
3549         return true;
3550     }
3551 }
3552
3553 static bool parse_enum(parser_t *parser)
3554 {
3555     bool        flag = false;
3556     bool        reverse = false;
3557     qcfloat_t     num = 0;
3558     ast_value **values = NULL;
3559     ast_value  *var = NULL;
3560     ast_value  *asvalue;
3561
3562     ast_expression *old;
3563
3564     if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3565         parseerror(parser, "expected `{` or `:` after `enum` keyword");
3566         return false;
3567     }
3568
3569     /* enumeration attributes (can add more later) */
3570     if (parser->tok == ':') {
3571         if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3572             parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3573             return false;
3574         }
3575
3576         /* attributes? */
3577         if (!strcmp(parser_tokval(parser), "flag")) {
3578             num  = 1;
3579             flag = true;
3580         }
3581         else if (!strcmp(parser_tokval(parser), "reverse")) {
3582             reverse = true;
3583         }
3584         else {
3585             parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3586             return false;
3587         }
3588
3589         if (!parser_next(parser) || parser->tok != '{') {
3590             parseerror(parser, "expected `{` after enum attribute ");
3591             return false;
3592         }
3593     }
3594
3595     while (true) {
3596         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3597             if (parser->tok == '}') {
3598                 /* allow an empty enum */
3599                 break;
3600             }
3601             parseerror(parser, "expected identifier or `}`");
3602             goto onerror;
3603         }
3604
3605         old = parser_find_field(parser, parser_tokval(parser));
3606         if (!old)
3607             old = parser_find_global(parser, parser_tokval(parser));
3608         if (old) {
3609             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3610                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3611             goto onerror;
3612         }
3613
3614         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3615         vec_push(values, var);
3616         var->cvq             = CV_CONST;
3617         var->hasvalue        = true;
3618
3619         /* for flagged enumerations increment in POTs of TWO */
3620         var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3621         parser_addglobal(parser, var->name, (ast_expression*)var);
3622
3623         if (!parser_next(parser)) {
3624             parseerror(parser, "expected `=`, `}` or comma after identifier");
3625             goto onerror;
3626         }
3627
3628         if (parser->tok == ',')
3629             continue;
3630         if (parser->tok == '}')
3631             break;
3632         if (parser->tok != '=') {
3633             parseerror(parser, "expected `=`, `}` or comma after identifier");
3634             goto onerror;
3635         }
3636
3637         if (!parser_next(parser)) {
3638             parseerror(parser, "expected expression after `=`");
3639             goto onerror;
3640         }
3641
3642         /* We got a value! */
3643         old = parse_expression_leave(parser, true, false, false);
3644         asvalue = (ast_value*)old;
3645         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3646             compile_error(ast_ctx(var), "constant value or expression expected");
3647             goto onerror;
3648         }
3649         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3650
3651         if (parser->tok == '}')
3652             break;
3653         if (parser->tok != ',') {
3654             parseerror(parser, "expected `}` or comma after expression");
3655             goto onerror;
3656         }
3657     }
3658
3659     /* patch them all (for reversed attribute) */
3660     if (reverse) {
3661         size_t i;
3662         for (i = 0; i < vec_size(values); i++)
3663             values[i]->constval.vfloat = vec_size(values) - i - 1;
3664     }
3665
3666     if (parser->tok != '}') {
3667         parseerror(parser, "internal error: breaking without `}`");
3668         goto onerror;
3669     }
3670
3671     if (!parser_next(parser) || parser->tok != ';') {
3672         parseerror(parser, "expected semicolon after enumeration");
3673         goto onerror;
3674     }
3675
3676     if (!parser_next(parser)) {
3677         parseerror(parser, "parse error after enumeration");
3678         goto onerror;
3679     }
3680
3681     vec_free(values);
3682     return true;
3683
3684 onerror:
3685     vec_free(values);
3686     return false;
3687 }
3688
3689 static bool parse_block_into(parser_t *parser, ast_block *block)
3690 {
3691     bool   retval = true;
3692
3693     parser_enterblock(parser);
3694
3695     if (!parser_next(parser)) { /* skip the '{' */
3696         parseerror(parser, "expected function body");
3697         goto cleanup;
3698     }
3699
3700     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3701     {
3702         ast_expression *expr = NULL;
3703         if (parser->tok == '}')
3704             break;
3705
3706         if (!parse_statement(parser, block, &expr, false)) {
3707             /* parseerror(parser, "parse error"); */
3708             block = NULL;
3709             goto cleanup;
3710         }
3711         if (!expr)
3712             continue;
3713         if (!ast_block_add_expr(block, expr)) {
3714             ast_delete(block);
3715             block = NULL;
3716             goto cleanup;
3717         }
3718     }
3719
3720     if (parser->tok != '}') {
3721         block = NULL;
3722     } else {
3723         (void)parser_next(parser);
3724     }
3725
3726 cleanup:
3727     if (!parser_leaveblock(parser))
3728         retval = false;
3729     return retval && !!block;
3730 }
3731
3732 static ast_block* parse_block(parser_t *parser)
3733 {
3734     ast_block *block;
3735     block = ast_block_new(parser_ctx(parser));
3736     if (!block)
3737         return NULL;
3738     if (!parse_block_into(parser, block)) {
3739         ast_block_delete(block);
3740         return NULL;
3741     }
3742     return block;
3743 }
3744
3745 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3746 {
3747     if (parser->tok == '{') {
3748         *out = (ast_expression*)parse_block(parser);
3749         return !!*out;
3750     }
3751     return parse_statement(parser, NULL, out, false);
3752 }
3753
3754 static bool create_vector_members(ast_value *var, ast_member **me)
3755 {
3756     size_t i;
3757     size_t len = strlen(var->name);
3758
3759     for (i = 0; i < 3; ++i) {
3760         char *name = (char*)mem_a(len+3);
3761         memcpy(name, var->name, len);
3762         name[len+0] = '_';
3763         name[len+1] = 'x'+i;
3764         name[len+2] = 0;
3765         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3766         mem_d(name);
3767         if (!me[i])
3768             break;
3769     }
3770     if (i == 3)
3771         return true;
3772
3773     /* unroll */
3774     do { ast_member_delete(me[--i]); } while(i);
3775     return false;
3776 }
3777
3778 static bool parse_function_body(parser_t *parser, ast_value *var)
3779 {
3780     ast_block *block = NULL;
3781     ast_function *func;
3782     ast_function *old;
3783
3784     ast_expression *framenum  = NULL;
3785     ast_expression *nextthink = NULL;
3786     /* None of the following have to be deleted */
3787     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3788     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3789     bool has_frame_think;
3790
3791     bool retval = true;
3792
3793     has_frame_think = false;
3794     old = parser->function;
3795
3796     if (var->expression.flags & AST_FLAG_ALIAS) {
3797         parseerror(parser, "function aliases cannot have bodies");
3798         return false;
3799     }
3800
3801     if (parser->gotos.size() || parser->labels.size()) {
3802         parseerror(parser, "gotos/labels leaking");
3803         return false;
3804     }
3805
3806     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3807         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3808                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3809         {
3810             return false;
3811         }
3812     }
3813
3814     if (parser->tok == '[') {
3815         /* got a frame definition: [ framenum, nextthink ]
3816          * this translates to:
3817          * self.frame = framenum;
3818          * self.nextthink = time + 0.1;
3819          * self.think = nextthink;
3820          */
3821         nextthink = NULL;
3822
3823         fld_think     = parser_find_field(parser, "think");
3824         fld_nextthink = parser_find_field(parser, "nextthink");
3825         fld_frame     = parser_find_field(parser, "frame");
3826         if (!fld_think || !fld_nextthink || !fld_frame) {
3827             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3828             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3829             return false;
3830         }
3831         gbl_time      = parser_find_global(parser, "time");
3832         gbl_self      = parser_find_global(parser, "self");
3833         if (!gbl_time || !gbl_self) {
3834             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3835             parseerror(parser, "please declare the following globals: `time`, `self`");
3836             return false;
3837         }
3838
3839         if (!parser_next(parser))
3840             return false;
3841
3842         framenum = parse_expression_leave(parser, true, false, false);
3843         if (!framenum) {
3844             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3845             return false;
3846         }
3847         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3848             ast_unref(framenum);
3849             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3850             return false;
3851         }
3852
3853         if (parser->tok != ',') {
3854             ast_unref(framenum);
3855             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3856             parseerror(parser, "Got a %i\n", parser->tok);
3857             return false;
3858         }
3859
3860         if (!parser_next(parser)) {
3861             ast_unref(framenum);
3862             return false;
3863         }
3864
3865         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3866         {
3867             /* qc allows the use of not-yet-declared functions here
3868              * - this automatically creates a prototype */
3869             ast_value      *thinkfunc;
3870             ast_expression *functype = fld_think->next;
3871
3872             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3873             if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3874                 ast_unref(framenum);
3875                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3876                 return false;
3877             }
3878             ast_type_adopt(thinkfunc, functype);
3879
3880             if (!parser_next(parser)) {
3881                 ast_unref(framenum);
3882                 ast_delete(thinkfunc);
3883                 return false;
3884             }
3885
3886             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3887
3888             nextthink = (ast_expression*)thinkfunc;
3889
3890         } else {
3891             nextthink = parse_expression_leave(parser, true, false, false);
3892             if (!nextthink) {
3893                 ast_unref(framenum);
3894                 parseerror(parser, "expected a think-function in [frame,think] notation");
3895                 return false;
3896             }
3897         }
3898
3899         if (!ast_istype(nextthink, ast_value)) {
3900             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3901             retval = false;
3902         }
3903
3904         if (retval && parser->tok != ']') {
3905             parseerror(parser, "expected closing `]` for [frame,think] notation");
3906             retval = false;
3907         }
3908
3909         if (retval && !parser_next(parser)) {
3910             retval = false;
3911         }
3912
3913         if (retval && parser->tok != '{') {
3914             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3915             retval = false;
3916         }
3917
3918         if (!retval) {
3919             ast_unref(nextthink);
3920             ast_unref(framenum);
3921             return false;
3922         }
3923
3924         has_frame_think = true;
3925     }
3926
3927     block = ast_block_new(parser_ctx(parser));
3928     if (!block) {
3929         parseerror(parser, "failed to allocate block");
3930         if (has_frame_think) {
3931             ast_unref(nextthink);
3932             ast_unref(framenum);
3933         }
3934         return false;
3935     }
3936
3937     if (has_frame_think) {
3938         if (!OPTS_FLAG(EMULATE_STATE)) {
3939             ast_state *state_op = ast_state_new(parser_ctx(parser), framenum, nextthink);
3940             if (!ast_block_add_expr(block, (ast_expression*)state_op)) {
3941                 parseerror(parser, "failed to generate state op for [frame,think]");
3942                 ast_unref(nextthink);
3943                 ast_unref(framenum);
3944                 ast_delete(block);
3945                 return false;
3946             }
3947         } else {
3948             /* emulate OP_STATE in code: */
3949             lex_ctx_t ctx;
3950             ast_expression *self_frame;
3951             ast_expression *self_nextthink;
3952             ast_expression *self_think;
3953             ast_expression *time_plus_1;
3954             ast_store *store_frame;
3955             ast_store *store_nextthink;
3956             ast_store *store_think;
3957
3958             float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
3959
3960             ctx = parser_ctx(parser);
3961             self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3962             self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3963             self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3964
3965             time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3966                              gbl_time, (ast_expression*)fold_constgen_float(parser->fold, frame_delta, false));
3967
3968             if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3969                 if (self_frame)     ast_delete(self_frame);
3970                 if (self_nextthink) ast_delete(self_nextthink);
3971                 if (self_think)     ast_delete(self_think);
3972                 if (time_plus_1)    ast_delete(time_plus_1);
3973                 retval = false;
3974             }
3975
3976             if (retval)
3977             {
3978                 store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3979                 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3980                 store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3981
3982                 if (!store_frame) {
3983                     ast_delete(self_frame);
3984                     retval = false;
3985                 }
3986                 if (!store_nextthink) {
3987                     ast_delete(self_nextthink);
3988                     retval = false;
3989                 }
3990                 if (!store_think) {
3991                     ast_delete(self_think);
3992                     retval = false;
3993                 }
3994                 if (!retval) {
3995                     if (store_frame)     ast_delete(store_frame);
3996                     if (store_nextthink) ast_delete(store_nextthink);
3997                     if (store_think)     ast_delete(store_think);
3998                     retval = false;
3999                 }
4000                 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4001                     !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4002                     !ast_block_add_expr(block, (ast_expression*)store_think))
4003                 {
4004                     retval = false;
4005                 }
4006             }
4007
4008             if (!retval) {
4009                 parseerror(parser, "failed to generate code for [frame,think]");
4010                 ast_unref(nextthink);
4011                 ast_unref(framenum);
4012                 ast_delete(block);
4013                 return false;
4014             }
4015         }
4016     }
4017
4018     if (var->hasvalue) {
4019         if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
4020             parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4021             ast_block_delete(block);
4022             goto enderr;
4023         }
4024         func = var->constval.vfunc;
4025
4026         if (!func) {
4027             parseerror(parser, "internal error: NULL function: `%s`", var->name);
4028             ast_block_delete(block);
4029             goto enderr;
4030         }
4031     } else {
4032         func = ast_function_new(ast_ctx(var), var->name, var);
4033
4034         if (!func) {
4035             parseerror(parser, "failed to allocate function for `%s`", var->name);
4036             ast_block_delete(block);
4037             goto enderr;
4038         }
4039         vec_push(parser->functions, func);
4040     }
4041
4042     parser_enterblock(parser);
4043
4044     for (auto &it : var->expression.params) {
4045         size_t e;
4046         ast_member *me[3];
4047
4048         if (it->expression.vtype != TYPE_VECTOR &&
4049             (it->expression.vtype != TYPE_FIELD ||
4050              it->expression.next->vtype != TYPE_VECTOR))
4051         {
4052             continue;
4053         }
4054
4055         if (!create_vector_members(it, me)) {
4056             ast_block_delete(block);
4057             goto enderrfn;
4058         }
4059
4060         for (e = 0; e < 3; ++e) {
4061             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4062             ast_block_collect(block, (ast_expression*)me[e]);
4063         }
4064     }
4065
4066     if (var->argcounter && !func->argc) {
4067         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4068         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4069         func->argc = argc;
4070     }
4071
4072     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4073         char name[1024];
4074         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4075         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4076         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4077         varargs->expression.count = 0;
4078         util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4079         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4080             ast_delete(varargs);
4081             ast_block_delete(block);
4082             goto enderrfn;
4083         }
4084         util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4085         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4086             ast_delete(varargs);
4087             ast_block_delete(block);
4088             goto enderrfn;
4089         }
4090         func->varargs     = varargs;
4091         func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, var->expression.params.size(), false);
4092     }
4093
4094     parser->function = func;
4095     if (!parse_block_into(parser, block)) {
4096         ast_block_delete(block);
4097         goto enderrfn;
4098     }
4099
4100     vec_push(func->blocks, block);
4101
4102     parser->function = old;
4103     if (!parser_leaveblock(parser))
4104         retval = false;
4105     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4106         parseerror(parser, "internal error: local scopes left");
4107         retval = false;
4108     }
4109
4110     if (parser->tok == ';')
4111         return parser_next(parser);
4112     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4113         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4114     return retval;
4115
4116 enderrfn:
4117     (void)!parser_leaveblock(parser);
4118     vec_pop(parser->functions);
4119     ast_function_delete(func);
4120     var->constval.vfunc = NULL;
4121
4122 enderr:
4123     parser->function = old;
4124     return false;
4125 }
4126
4127 static ast_expression *array_accessor_split(
4128     parser_t  *parser,
4129     ast_value *array,
4130     ast_value *index,
4131     size_t     middle,
4132     ast_expression *left,
4133     ast_expression *right
4134     )
4135 {
4136     ast_ifthen *ifthen;
4137     ast_binary *cmp;
4138
4139     lex_ctx_t ctx = ast_ctx(array);
4140
4141     if (!left || !right) {
4142         if (left)  ast_delete(left);
4143         if (right) ast_delete(right);
4144         return NULL;
4145     }
4146
4147     cmp = ast_binary_new(ctx, INSTR_LT,
4148                          (ast_expression*)index,
4149                          (ast_expression*)fold_constgen_float(parser->fold, middle, false));
4150     if (!cmp) {
4151         ast_delete(left);
4152         ast_delete(right);
4153         parseerror(parser, "internal error: failed to create comparison for array setter");
4154         return NULL;
4155     }
4156
4157     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4158     if (!ifthen) {
4159         ast_delete(cmp); /* will delete left and right */
4160         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4161         return NULL;
4162     }
4163
4164     return (ast_expression*)ifthen;
4165 }
4166
4167 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4168 {
4169     lex_ctx_t ctx = ast_ctx(array);
4170
4171     if (from+1 == afterend) {
4172         /* set this value */
4173         ast_block       *block;
4174         ast_return      *ret;
4175         ast_array_index *subscript;
4176         ast_store       *st;
4177         int assignop = type_store_instr[value->expression.vtype];
4178
4179         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4180             assignop = INSTR_STORE_V;
4181
4182         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4183         if (!subscript)
4184             return NULL;
4185
4186         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4187         if (!st) {
4188             ast_delete(subscript);
4189             return NULL;
4190         }
4191
4192         block = ast_block_new(ctx);
4193         if (!block) {
4194             ast_delete(st);
4195             return NULL;
4196         }
4197
4198         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4199             ast_delete(block);
4200             return NULL;
4201         }
4202
4203         ret = ast_return_new(ctx, NULL);
4204         if (!ret) {
4205             ast_delete(block);
4206             return NULL;
4207         }
4208
4209         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4210             ast_delete(block);
4211             return NULL;
4212         }
4213
4214         return (ast_expression*)block;
4215     } else {
4216         ast_expression *left, *right;
4217         size_t diff = afterend - from;
4218         size_t middle = from + diff/2;
4219         left  = array_setter_node(parser, array, index, value, from, middle);
4220         right = array_setter_node(parser, array, index, value, middle, afterend);
4221         return array_accessor_split(parser, array, index, middle, left, right);
4222     }
4223 }
4224
4225 static ast_expression *array_field_setter_node(
4226     parser_t  *parser,
4227     ast_value *array,
4228     ast_value *entity,
4229     ast_value *index,
4230     ast_value *value,
4231     size_t     from,
4232     size_t     afterend)
4233 {
4234     lex_ctx_t ctx = ast_ctx(array);
4235
4236     if (from+1 == afterend) {
4237         /* set this value */
4238         ast_block       *block;
4239         ast_return      *ret;
4240         ast_entfield    *entfield;
4241         ast_array_index *subscript;
4242         ast_store       *st;
4243         int assignop = type_storep_instr[value->expression.vtype];
4244
4245         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4246             assignop = INSTR_STOREP_V;
4247
4248         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4249         if (!subscript)
4250             return NULL;
4251
4252         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4253         subscript->expression.vtype = TYPE_FIELD;
4254
4255         entfield = ast_entfield_new_force(ctx,
4256                                           (ast_expression*)entity,
4257                                           (ast_expression*)subscript,
4258                                           (ast_expression*)subscript);
4259         if (!entfield) {
4260             ast_delete(subscript);
4261             return NULL;
4262         }
4263
4264         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4265         if (!st) {
4266             ast_delete(entfield);
4267             return NULL;
4268         }
4269
4270         block = ast_block_new(ctx);
4271         if (!block) {
4272             ast_delete(st);
4273             return NULL;
4274         }
4275
4276         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4277             ast_delete(block);
4278             return NULL;
4279         }
4280
4281         ret = ast_return_new(ctx, NULL);
4282         if (!ret) {
4283             ast_delete(block);
4284             return NULL;
4285         }
4286
4287         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4288             ast_delete(block);
4289             return NULL;
4290         }
4291
4292         return (ast_expression*)block;
4293     } else {
4294         ast_expression *left, *right;
4295         size_t diff = afterend - from;
4296         size_t middle = from + diff/2;
4297         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4298         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4299         return array_accessor_split(parser, array, index, middle, left, right);
4300     }
4301 }
4302
4303 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4304 {
4305     lex_ctx_t ctx = ast_ctx(array);
4306
4307     if (from+1 == afterend) {
4308         ast_return      *ret;
4309         ast_array_index *subscript;
4310
4311         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4312         if (!subscript)
4313             return NULL;
4314
4315         ret = ast_return_new(ctx, (ast_expression*)subscript);
4316         if (!ret) {
4317             ast_delete(subscript);
4318             return NULL;
4319         }
4320
4321         return (ast_expression*)ret;
4322     } else {
4323         ast_expression *left, *right;
4324         size_t diff = afterend - from;
4325         size_t middle = from + diff/2;
4326         left  = array_getter_node(parser, array, index, from, middle);
4327         right = array_getter_node(parser, array, index, middle, afterend);
4328         return array_accessor_split(parser, array, index, middle, left, right);
4329     }
4330 }
4331
4332 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4333 {
4334     ast_function   *func = NULL;
4335     ast_value      *fval = NULL;
4336     ast_block      *body = NULL;
4337
4338     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4339     if (!fval) {
4340         parseerror(parser, "failed to create accessor function value");
4341         return false;
4342     }
4343     fval->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
4344
4345     func = ast_function_new(ast_ctx(array), funcname, fval);
4346     if (!func) {
4347         ast_delete(fval);
4348         parseerror(parser, "failed to create accessor function node");
4349         return false;
4350     }
4351
4352     body = ast_block_new(ast_ctx(array));
4353     if (!body) {
4354         parseerror(parser, "failed to create block for array accessor");
4355         ast_delete(fval);
4356         ast_delete(func);
4357         return false;
4358     }
4359
4360     vec_push(func->blocks, body);
4361     *out = fval;
4362
4363     vec_push(parser->accessors, fval);
4364
4365     return true;
4366 }
4367
4368 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4369 {
4370     ast_value      *index = NULL;
4371     ast_value      *value = NULL;
4372     ast_function   *func;
4373     ast_value      *fval;
4374
4375     if (!ast_istype(array->expression.next, ast_value)) {
4376         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4377         return NULL;
4378     }
4379
4380     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4381         return NULL;
4382     func = fval->constval.vfunc;
4383     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4384
4385     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4386     value = ast_value_copy((ast_value*)array->expression.next);
4387
4388     if (!index || !value) {
4389         parseerror(parser, "failed to create locals for array accessor");
4390         goto cleanup;
4391     }
4392     (void)!ast_value_set_name(value, "value"); /* not important */
4393     fval->expression.params.push_back(index);
4394     fval->expression.params.push_back(value);
4395
4396     array->setter = fval;
4397     return fval;
4398 cleanup:
4399     if (index) ast_delete(index);
4400     if (value) ast_delete(value);
4401     ast_delete(func);
4402     ast_delete(fval);
4403     return NULL;
4404 }
4405
4406 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4407 {
4408     ast_expression *root = NULL;
4409     root = array_setter_node(parser, array,
4410                              array->setter->expression.params[0],
4411                              array->setter->expression.params[1],
4412                              0, array->expression.count);
4413     if (!root) {
4414         parseerror(parser, "failed to build accessor search tree");
4415         return false;
4416     }
4417     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4418         ast_delete(root);
4419         return false;
4420     }
4421     return true;
4422 }
4423
4424 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4425 {
4426     if (!parser_create_array_setter_proto(parser, array, funcname))
4427         return false;
4428     return parser_create_array_setter_impl(parser, array);
4429 }
4430
4431 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4432 {
4433     ast_expression *root = NULL;
4434     ast_value      *entity = NULL;
4435     ast_value      *index = NULL;
4436     ast_value      *value = NULL;
4437     ast_function   *func;
4438     ast_value      *fval;
4439
4440     if (!ast_istype(array->expression.next, ast_value)) {
4441         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4442         return false;
4443     }
4444
4445     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4446         return false;
4447     func = fval->constval.vfunc;
4448     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4449
4450     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4451     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4452     value  = ast_value_copy((ast_value*)array->expression.next);
4453     if (!entity || !index || !value) {
4454         parseerror(parser, "failed to create locals for array accessor");
4455         goto cleanup;
4456     }
4457     (void)!ast_value_set_name(value, "value"); /* not important */
4458     fval->expression.params.push_back(entity);
4459     fval->expression.params.push_back(index);
4460     fval->expression.params.push_back(value);
4461
4462     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4463     if (!root) {
4464         parseerror(parser, "failed to build accessor search tree");
4465         goto cleanup;
4466     }
4467
4468     array->setter = fval;
4469     return ast_block_add_expr(func->blocks[0], root);
4470 cleanup:
4471     if (entity) ast_delete(entity);
4472     if (index)  ast_delete(index);
4473     if (value)  ast_delete(value);
4474     if (root)   ast_delete(root);
4475     ast_delete(func);
4476     ast_delete(fval);
4477     return false;
4478 }
4479
4480 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4481 {
4482     ast_value      *index = NULL;
4483     ast_value      *fval;
4484     ast_function   *func;
4485
4486     /* NOTE: checking array->expression.next rather than elemtype since
4487      * for fields elemtype is a temporary fieldtype.
4488      */
4489     if (!ast_istype(array->expression.next, ast_value)) {
4490         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4491         return NULL;
4492     }
4493
4494     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4495         return NULL;
4496     func = fval->constval.vfunc;
4497     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4498
4499     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4500
4501     if (!index) {
4502         parseerror(parser, "failed to create locals for array accessor");
4503         goto cleanup;
4504     }
4505     fval->expression.params.push_back(index);
4506
4507     array->getter = fval;
4508     return fval;
4509 cleanup:
4510     if (index) ast_delete(index);
4511     ast_delete(func);
4512     ast_delete(fval);
4513     return NULL;
4514 }
4515
4516 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4517 {
4518     ast_expression *root = NULL;
4519
4520     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4521     if (!root) {
4522         parseerror(parser, "failed to build accessor search tree");
4523         return false;
4524     }
4525     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4526         ast_delete(root);
4527         return false;
4528     }
4529     return true;
4530 }
4531
4532 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4533 {
4534     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4535         return false;
4536     return parser_create_array_getter_impl(parser, array);
4537 }
4538
4539 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4540 {
4541     lex_ctx_t ctx = parser_ctx(parser);
4542     std::vector<ast_value *> params;
4543     ast_value *fval;
4544     bool first = true;
4545     bool variadic = false;
4546     ast_value *varparam = NULL;
4547     char *argcounter = NULL;
4548
4549     /* for the sake of less code we parse-in in this function */
4550     if (!parser_next(parser)) {
4551         ast_delete(var);
4552         parseerror(parser, "expected parameter list");
4553         return NULL;
4554     }
4555
4556     /* parse variables until we hit a closing paren */
4557     while (parser->tok != ')') {
4558         bool is_varargs = false;
4559
4560         if (!first) {
4561             /* there must be commas between them */
4562             if (parser->tok != ',') {
4563                 parseerror(parser, "expected comma or end of parameter list");
4564                 goto on_error;
4565             }
4566             if (!parser_next(parser)) {
4567                 parseerror(parser, "expected parameter");
4568                 goto on_error;
4569             }
4570         }
4571         first = false;
4572
4573         ast_value *param = parse_typename(parser, NULL, NULL, &is_varargs);
4574         if (!param && !is_varargs)
4575             goto on_error;
4576         if (is_varargs) {
4577             /* '...' indicates a varargs function */
4578             variadic = true;
4579             if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4580                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4581                 goto on_error;
4582             }
4583             if (parser->tok == TOKEN_IDENT) {
4584                 argcounter = util_strdup(parser_tokval(parser));
4585                 if (!parser_next(parser) || parser->tok != ')') {
4586                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4587                     goto on_error;
4588                 }
4589             }
4590         } else {
4591             params.push_back(param);
4592             if (param->expression.vtype >= TYPE_VARIANT) {
4593                 char tname[1024]; /* typename is reserved in C++ */
4594                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4595                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4596                 goto on_error;
4597             }
4598             /* type-restricted varargs */
4599             if (parser->tok == TOKEN_DOTS) {
4600                 variadic = true;
4601                 varparam = params.back();
4602                 params.pop_back();
4603                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4604                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4605                     goto on_error;
4606                 }
4607                 if (parser->tok == TOKEN_IDENT) {
4608                     argcounter = util_strdup(parser_tokval(parser));
4609                     ast_value_set_name(param, argcounter);
4610                     if (!parser_next(parser) || parser->tok != ')') {
4611                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4612                         goto on_error;
4613                     }
4614                 }
4615             }
4616             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->name[0] == '<') {
4617                 parseerror(parser, "parameter name omitted");
4618                 goto on_error;
4619             }
4620         }
4621     }
4622
4623     if (params.size() == 1 && params[0]->expression.vtype == TYPE_VOID)
4624         params.clear();
4625
4626     /* sanity check */
4627     if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4628         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4629
4630     /* parse-out */
4631     if (!parser_next(parser)) {
4632         parseerror(parser, "parse error after typename");
4633         goto on_error;
4634     }
4635
4636     /* now turn 'var' into a function type */
4637     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4638     fval->expression.next = (ast_expression*)var;
4639     if (variadic)
4640         fval->expression.flags |= AST_FLAG_VARIADIC;
4641     var = fval;
4642
4643     var->expression.params = params;
4644     var->expression.varparam = (ast_expression*)varparam;
4645     var->argcounter = argcounter;
4646
4647     return var;
4648
4649 on_error:
4650     if (argcounter)
4651         mem_d(argcounter);
4652     if (varparam)
4653         ast_delete(varparam);
4654     ast_delete(var);
4655     for (auto &it : params)
4656         ast_delete(it);
4657     return NULL;
4658 }
4659
4660 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4661 {
4662     ast_expression *cexp;
4663     ast_value      *cval, *tmp;
4664     lex_ctx_t ctx;
4665
4666     ctx = parser_ctx(parser);
4667
4668     if (!parser_next(parser)) {
4669         ast_delete(var);
4670         parseerror(parser, "expected array-size");
4671         return NULL;
4672     }
4673
4674     if (parser->tok != ']') {
4675         cexp = parse_expression_leave(parser, true, false, false);
4676
4677         if (!cexp || !ast_istype(cexp, ast_value)) {
4678             if (cexp)
4679                 ast_unref(cexp);
4680             ast_delete(var);
4681             parseerror(parser, "expected array-size as constant positive integer");
4682             return NULL;
4683         }
4684         cval = (ast_value*)cexp;
4685     }
4686     else {
4687         cexp = NULL;
4688         cval = NULL;
4689     }
4690
4691     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4692     tmp->expression.next = (ast_expression*)var;
4693     var = tmp;
4694
4695     if (cval) {
4696         if (cval->expression.vtype == TYPE_INTEGER)
4697             tmp->expression.count = cval->constval.vint;
4698         else if (cval->expression.vtype == TYPE_FLOAT)
4699             tmp->expression.count = cval->constval.vfloat;
4700         else {
4701             ast_unref(cexp);
4702             ast_delete(var);
4703             parseerror(parser, "array-size must be a positive integer constant");
4704             return NULL;
4705         }
4706
4707         ast_unref(cexp);
4708     } else {
4709         var->expression.count = -1;
4710         var->expression.flags |= AST_FLAG_ARRAY_INIT;
4711     }
4712
4713     if (parser->tok != ']') {
4714         ast_delete(var);
4715         parseerror(parser, "expected ']' after array-size");
4716         return NULL;
4717     }
4718     if (!parser_next(parser)) {
4719         ast_delete(var);
4720         parseerror(parser, "error after parsing array size");
4721         return NULL;
4722     }
4723     return var;
4724 }
4725
4726 /* Parse a complete typename.
4727  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4728  * but when parsing variables separated by comma
4729  * 'storebase' should point to where the base-type should be kept.
4730  * The base type makes up every bit of type information which comes *before* the
4731  * variable name.
4732  *
4733  * NOTE: The value must either be named, have a NULL name, or a name starting
4734  *       with '<'. In the first case, this will be the actual variable or type
4735  *       name, in the other cases it is assumed that the name will appear
4736  *       later, and an error is generated otherwise.
4737  *
4738  * The following will be parsed in its entirety:
4739  *     void() foo()
4740  * The 'basetype' in this case is 'void()'
4741  * and if there's a comma after it, say:
4742  *     void() foo(), bar
4743  * then the type-information 'void()' can be stored in 'storebase'
4744  */
4745 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4746 {
4747     ast_value *var, *tmp;
4748     lex_ctx_t    ctx;
4749
4750     const char *name = NULL;
4751     bool        isfield  = false;
4752     bool        wasarray = false;
4753     size_t      morefields = 0;
4754
4755     bool        vararg = (parser->tok == TOKEN_DOTS);
4756
4757     ctx = parser_ctx(parser);
4758
4759     /* types may start with a dot */
4760     if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4761         isfield = true;
4762         if (parser->tok == TOKEN_DOTS)
4763             morefields += 2;
4764         /* if we parsed a dot we need a typename now */
4765         if (!parser_next(parser)) {
4766             parseerror(parser, "expected typename for field definition");
4767             return NULL;
4768         }
4769
4770         /* Further dots are handled seperately because they won't be part of the
4771          * basetype
4772          */
4773         while (true) {
4774             if (parser->tok == '.')
4775                 ++morefields;
4776             else if (parser->tok == TOKEN_DOTS)
4777                 morefields += 3;
4778             else
4779                 break;
4780             vararg = false;
4781             if (!parser_next(parser)) {
4782                 parseerror(parser, "expected typename for field definition");
4783                 return NULL;
4784             }
4785         }
4786     }
4787     if (parser->tok == TOKEN_IDENT)
4788         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4789     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4790         if (vararg && is_vararg) {
4791             *is_vararg = true;
4792             return NULL;
4793         }
4794         parseerror(parser, "expected typename");
4795         return NULL;
4796     }
4797
4798     /* generate the basic type value */
4799     if (cached_typedef) {
4800         var = ast_value_copy(cached_typedef);
4801         ast_value_set_name(var, "<type(from_def)>");
4802     } else
4803         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4804
4805     for (; morefields; --morefields) {
4806         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4807         tmp->expression.next = (ast_expression*)var;
4808         var = tmp;
4809     }
4810
4811     /* do not yet turn into a field - remember:
4812      * .void() foo; is a field too
4813      * .void()() foo; is a function
4814      */
4815
4816     /* parse on */
4817     if (!parser_next(parser)) {
4818         ast_delete(var);
4819         parseerror(parser, "parse error after typename");
4820         return NULL;
4821     }
4822
4823     /* an opening paren now starts the parameter-list of a function
4824      * this is where original-QC has parameter lists.
4825      * We allow a single parameter list here.
4826      * Much like fteqcc we don't allow `float()() x`
4827      */
4828     if (parser->tok == '(') {
4829         var = parse_parameter_list(parser, var);
4830         if (!var)
4831             return NULL;
4832     }
4833
4834     /* store the base if requested */
4835     if (storebase) {
4836         *storebase = ast_value_copy(var);
4837         if (isfield) {
4838             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4839             tmp->expression.next = (ast_expression*)*storebase;
4840             *storebase = tmp;
4841         }
4842     }
4843
4844     /* there may be a name now */
4845     if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4846         if (!strcmp(parser_tokval(parser), "break"))
4847             (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4848         else if (parser->tok == TOKEN_KEYWORD)
4849             goto leave;
4850
4851         name = util_strdup(parser_tokval(parser));
4852
4853         /* parse on */
4854         if (!parser_next(parser)) {
4855             ast_delete(var);
4856             mem_d(name);
4857             parseerror(parser, "error after variable or field declaration");
4858             return NULL;
4859         }
4860     }
4861
4862     leave:
4863     /* now this may be an array */
4864     if (parser->tok == '[') {
4865         wasarray = true;
4866         var = parse_arraysize(parser, var);
4867         if (!var) {
4868             if (name) mem_d(name);
4869             return NULL;
4870         }
4871     }
4872
4873     /* This is the point where we can turn it into a field */
4874     if (isfield) {
4875         /* turn it into a field if desired */
4876         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4877         tmp->expression.next = (ast_expression*)var;
4878         var = tmp;
4879     }
4880
4881     /* now there may be function parens again */
4882     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4883         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4884     if (parser->tok == '(' && wasarray)
4885         parseerror(parser, "arrays as part of a return type is not supported");
4886     while (parser->tok == '(') {
4887         var = parse_parameter_list(parser, var);
4888         if (!var) {
4889             if (name) mem_d(name);
4890             return NULL;
4891         }
4892     }
4893
4894     /* finally name it */
4895     if (name) {
4896         if (!ast_value_set_name(var, name)) {
4897             ast_delete(var);
4898             mem_d(name);
4899             parseerror(parser, "internal error: failed to set name");
4900             return NULL;
4901         }
4902         /* free the name, ast_value_set_name duplicates */
4903         mem_d(name);
4904     }
4905
4906     return var;
4907 }
4908
4909 static bool parse_typedef(parser_t *parser)
4910 {
4911     ast_value      *typevar, *oldtype;
4912     ast_expression *old;
4913
4914     typevar = parse_typename(parser, NULL, NULL, NULL);
4915
4916     if (!typevar)
4917         return false;
4918
4919     /* while parsing types, the ast_value's get named '<something>' */
4920     if (!typevar->name || typevar->name[0] == '<') {
4921         parseerror(parser, "missing name in typedef");
4922         ast_delete(typevar);
4923         return false;
4924     }
4925
4926     if ( (old = parser_find_var(parser, typevar->name)) ) {
4927         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4928                    " -> `%s` has been declared here: %s:%i",
4929                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4930         ast_delete(typevar);
4931         return false;
4932     }
4933
4934     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4935         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4936                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4937         ast_delete(typevar);
4938         return false;
4939     }
4940
4941     vec_push(parser->_typedefs, typevar);
4942     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4943
4944     if (parser->tok != ';') {
4945         parseerror(parser, "expected semicolon after typedef");
4946         return false;
4947     }
4948     if (!parser_next(parser)) {
4949         parseerror(parser, "parse error after typedef");
4950         return false;
4951     }
4952
4953     return true;
4954 }
4955
4956 static const char *cvq_to_str(int cvq) {
4957     switch (cvq) {
4958         case CV_NONE:  return "none";
4959         case CV_VAR:   return "`var`";
4960         case CV_CONST: return "`const`";
4961         default:       return "<INVALID>";
4962     }
4963 }
4964
4965 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4966 {
4967     bool av, ao;
4968     if (proto->cvq != var->cvq) {
4969         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4970               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4971               parser->tok == '='))
4972         {
4973             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4974                                  "`%s` declared with different qualifiers: %s\n"
4975                                  " -> previous declaration here: %s:%i uses %s",
4976                                  var->name, cvq_to_str(var->cvq),
4977                                  ast_ctx(proto).file, ast_ctx(proto).line,
4978                                  cvq_to_str(proto->cvq));
4979         }
4980     }
4981     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4982     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4983     if (!av != !ao) {
4984         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4985                              "`%s` declared with different attributes%s\n"
4986                              " -> previous declaration here: %s:%i",
4987                              var->name, (av ? ": noreturn" : ""),
4988                              ast_ctx(proto).file, ast_ctx(proto).line,
4989                              (ao ? ": noreturn" : ""));
4990     }
4991     return true;
4992 }
4993
4994 static bool create_array_accessors(parser_t *parser, ast_value *var)
4995 {
4996     char name[1024];
4997     util_snprintf(name, sizeof(name), "%s##SET", var->name);
4998     if (!parser_create_array_setter(parser, var, name))
4999         return false;
5000     util_snprintf(name, sizeof(name), "%s##GET", var->name);
5001     if (!parser_create_array_getter(parser, var, var->expression.next, name))
5002         return false;
5003     return true;
5004 }
5005
5006 static bool parse_array(parser_t *parser, ast_value *array)
5007 {
5008     size_t i;
5009     if (array->initlist) {
5010         parseerror(parser, "array already initialized elsewhere");
5011         return false;
5012     }
5013     if (!parser_next(parser)) {
5014         parseerror(parser, "parse error in array initializer");
5015         return false;
5016     }
5017     i = 0;
5018     while (parser->tok != '}') {
5019         ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5020         if (!v)
5021             return false;
5022         if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5023             ast_unref(v);
5024             parseerror(parser, "initializing element must be a compile time constant");
5025             return false;
5026         }
5027         vec_push(array->initlist, v->constval);
5028         if (v->expression.vtype == TYPE_STRING) {
5029             array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5030             ++i;
5031         }
5032         ast_unref(v);
5033         if (parser->tok == '}')
5034             break;
5035         if (parser->tok != ',' || !parser_next(parser)) {
5036             parseerror(parser, "expected comma or '}' in element list");
5037             return false;
5038         }
5039     }
5040     if (!parser_next(parser) || parser->tok != ';') {
5041         parseerror(parser, "expected semicolon after initializer, got %s");
5042         return false;
5043     }
5044     /*
5045     if (!parser_next(parser)) {
5046         parseerror(parser, "parse error after initializer");
5047         return false;
5048     }
5049     */
5050
5051     if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5052         if (array->expression.count != (size_t)-1) {
5053             parseerror(parser, "array `%s' has already been initialized with %u elements",
5054                        array->name, (unsigned)array->expression.count);
5055         }
5056         array->expression.count = vec_size(array->initlist);
5057         if (!create_array_accessors(parser, array))
5058             return false;
5059     }
5060     return true;
5061 }
5062
5063 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)
5064 {
5065     ast_value *var;
5066     ast_value *proto;
5067     ast_expression *old;
5068     bool       was_end;
5069     size_t     i;
5070
5071     ast_value *basetype = NULL;
5072     bool      retval    = true;
5073     bool      isparam   = false;
5074     bool      isvector  = false;
5075     bool      cleanvar  = true;
5076     bool      wasarray  = false;
5077
5078     ast_member *me[3] = { NULL, NULL, NULL };
5079     ast_member *last_me[3] = { NULL, NULL, NULL };
5080
5081     if (!localblock && is_static)
5082         parseerror(parser, "`static` qualifier is not supported in global scope");
5083
5084     /* get the first complete variable */
5085     var = parse_typename(parser, &basetype, cached_typedef, NULL);
5086     if (!var) {
5087         if (basetype)
5088             ast_delete(basetype);
5089         return false;
5090     }
5091
5092     /* while parsing types, the ast_value's get named '<something>' */
5093     if (!var->name || var->name[0] == '<') {
5094         parseerror(parser, "declaration does not declare anything");
5095         if (basetype)
5096             ast_delete(basetype);
5097         return false;
5098     }
5099
5100     while (true) {
5101         proto = NULL;
5102         wasarray = false;
5103
5104         /* Part 0: finish the type */
5105         if (parser->tok == '(') {
5106             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5107                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5108             var = parse_parameter_list(parser, var);
5109             if (!var) {
5110                 retval = false;
5111                 goto cleanup;
5112             }
5113         }
5114         /* we only allow 1-dimensional arrays */
5115         if (parser->tok == '[') {
5116             wasarray = true;
5117             var = parse_arraysize(parser, var);
5118             if (!var) {
5119                 retval = false;
5120                 goto cleanup;
5121             }
5122         }
5123         if (parser->tok == '(' && wasarray) {
5124             parseerror(parser, "arrays as part of a return type is not supported");
5125             /* we'll still parse the type completely for now */
5126         }
5127         /* for functions returning functions */
5128         while (parser->tok == '(') {
5129             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5130                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5131             var = parse_parameter_list(parser, var);
5132             if (!var) {
5133                 retval = false;
5134                 goto cleanup;
5135             }
5136         }
5137
5138         var->cvq = qualifier;
5139         if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5140             var->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
5141         var->expression.flags |= qflags;
5142
5143         /*
5144          * store the vstring back to var for alias and
5145          * deprecation messages.
5146          */
5147         if (var->expression.flags & AST_FLAG_DEPRECATED ||
5148             var->expression.flags & AST_FLAG_ALIAS)
5149             var->desc = vstring;
5150
5151         if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5152             parseerror(parser, "function aliases cannot be forward declared");
5153             retval = false;
5154             goto cleanup;
5155         }
5156
5157
5158         /* Part 1:
5159          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5160          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5161          * is then filled with the previous definition and the parameter-names replaced.
5162          */
5163         if (!strcmp(var->name, "nil")) {
5164             if (OPTS_FLAG(UNTYPED_NIL)) {
5165                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5166                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5167             } else
5168                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5169         }
5170         if (!localblock) {
5171             /* Deal with end_sys_ vars */
5172             was_end = false;
5173             if (!strcmp(var->name, "end_sys_globals")) {
5174                 var->uses++;
5175                 parser->crc_globals = vec_size(parser->globals);
5176                 was_end = true;
5177             }
5178             else if (!strcmp(var->name, "end_sys_fields")) {
5179                 var->uses++;
5180                 parser->crc_fields = vec_size(parser->fields);
5181                 was_end = true;
5182             }
5183             if (was_end && var->expression.vtype == TYPE_FIELD) {
5184                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5185                                  "global '%s' hint should not be a field",
5186                                  parser_tokval(parser)))
5187                 {
5188                     retval = false;
5189                     goto cleanup;
5190                 }
5191             }
5192
5193             if (!nofields && var->expression.vtype == TYPE_FIELD)
5194             {
5195                 /* deal with field declarations */
5196                 old = parser_find_field(parser, var->name);
5197                 if (old) {
5198                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5199                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5200                     {
5201                         retval = false;
5202                         goto cleanup;
5203                     }
5204                     ast_delete(var);
5205                     var = NULL;
5206                     goto skipvar;
5207                     /*
5208                     parseerror(parser, "field `%s` already declared here: %s:%i",
5209                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5210                     retval = false;
5211                     goto cleanup;
5212                     */
5213                 }
5214                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5215                     (old = parser_find_global(parser, var->name)))
5216                 {
5217                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5218                     parseerror(parser, "field `%s` already declared here: %s:%i",
5219                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5220                     retval = false;
5221                     goto cleanup;
5222                 }
5223             }
5224             else
5225             {
5226                 /* deal with other globals */
5227                 old = parser_find_global(parser, var->name);
5228                 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5229                 {
5230                     /* This is a function which had a prototype */
5231                     if (!ast_istype(old, ast_value)) {
5232                         parseerror(parser, "internal error: prototype is not an ast_value");
5233                         retval = false;
5234                         goto cleanup;
5235                     }
5236                     proto = (ast_value*)old;
5237                     proto->desc = var->desc;
5238                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5239                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5240                                    proto->name,
5241                                    ast_ctx(proto).file, ast_ctx(proto).line);
5242                         retval = false;
5243                         goto cleanup;
5244                     }
5245                     /* we need the new parameter-names */
5246                     for (i = 0; i < proto->expression.params.size(); ++i)
5247                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5248                     if (!parser_check_qualifiers(parser, var, proto)) {
5249                         retval = false;
5250                         if (proto->desc)
5251                             mem_d(proto->desc);
5252                         proto = NULL;
5253                         goto cleanup;
5254                     }
5255                     proto->expression.flags |= var->expression.flags;
5256                     ast_delete(var);
5257                     var = proto;
5258                 }
5259                 else
5260                 {
5261                     /* other globals */
5262                     if (old) {
5263                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5264                                          "global `%s` already declared here: %s:%i",
5265                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5266                         {
5267                             retval = false;
5268                             goto cleanup;
5269                         }
5270                         if (old->flags & AST_FLAG_FINAL_DECL) {
5271                             parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5272                                        var->name, ast_ctx(old).file, ast_ctx(old).line);
5273                             retval = false;
5274                             goto cleanup;
5275                         }
5276                         proto = (ast_value*)old;
5277                         if (!ast_istype(old, ast_value)) {
5278                             parseerror(parser, "internal error: not an ast_value");
5279                             retval = false;
5280                             proto = NULL;
5281                             goto cleanup;
5282                         }
5283                         if (!parser_check_qualifiers(parser, var, proto)) {
5284                             retval = false;
5285                             proto = NULL;
5286                             goto cleanup;
5287                         }
5288                         proto->expression.flags |= var->expression.flags;
5289                         /* copy the context for finals,
5290                          * so the error can show where it was actually made 'final'
5291                          */
5292                         if (proto->expression.flags & AST_FLAG_FINAL_DECL)
5293                             ast_ctx(old) = ast_ctx(var);
5294                         ast_delete(var);
5295                         var = proto;
5296                     }
5297                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5298                         (old = parser_find_field(parser, var->name)))
5299                     {
5300                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5301                         parseerror(parser, "global `%s` already declared here: %s:%i",
5302                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5303                         retval = false;
5304                         goto cleanup;
5305                     }
5306                 }
5307             }
5308         }
5309         else /* it's not a global */
5310         {
5311             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5312             if (old && !isparam) {
5313                 parseerror(parser, "local `%s` already declared here: %s:%i",
5314                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5315                 retval = false;
5316                 goto cleanup;
5317             }
5318             /* doing this here as the above is just for a single scope */
5319             old = parser_find_local(parser, var->name, 0, &isparam);
5320             if (old && isparam) {
5321                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5322                                  "local `%s` is shadowing a parameter", var->name))
5323                 {
5324                     parseerror(parser, "local `%s` already declared here: %s:%i",
5325                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5326                     retval = false;
5327                     goto cleanup;
5328                 }
5329                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5330                     ast_delete(var);
5331                     if (ast_istype(old, ast_value))
5332                         var = proto = (ast_value*)old;
5333                     else {
5334                         var = NULL;
5335                         goto skipvar;
5336                     }
5337                 }
5338             }
5339         }
5340
5341         /* in a noref section we simply bump the usecount */
5342         if (noref || parser->noref)
5343             var->uses++;
5344
5345         /* Part 2:
5346          * Create the global/local, and deal with vector types.
5347          */
5348         if (!proto) {
5349             if (var->expression.vtype == TYPE_VECTOR)
5350                 isvector = true;
5351             else if (var->expression.vtype == TYPE_FIELD &&
5352                      var->expression.next->vtype == TYPE_VECTOR)
5353                 isvector = true;
5354
5355             if (isvector) {
5356                 if (!create_vector_members(var, me)) {
5357                     retval = false;
5358                     goto cleanup;
5359                 }
5360             }
5361
5362             if (!localblock) {
5363                 /* deal with global variables, fields, functions */
5364                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5365                     var->isfield = true;
5366                     vec_push(parser->fields, (ast_expression*)var);
5367                     util_htset(parser->htfields, var->name, var);
5368                     if (isvector) {
5369                         for (i = 0; i < 3; ++i) {
5370                             vec_push(parser->fields, (ast_expression*)me[i]);
5371                             util_htset(parser->htfields, me[i]->name, me[i]);
5372                         }
5373                     }
5374                 }
5375                 else {
5376                     if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5377                         parser_addglobal(parser, var->name, (ast_expression*)var);
5378                         if (isvector) {
5379                             for (i = 0; i < 3; ++i) {
5380                                 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5381                             }
5382                         }
5383                     } else {
5384                         ast_expression *find  = parser_find_global(parser, var->desc);
5385
5386                         if (!find) {
5387                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5388                             return false;
5389                         }
5390
5391                         if (!ast_compare_type((ast_expression*)var, find)) {
5392                             char ty1[1024];
5393                             char ty2[1024];
5394
5395                             ast_type_to_string(find,                  ty1, sizeof(ty1));
5396                             ast_type_to_string((ast_expression*)var,  ty2, sizeof(ty2));
5397
5398                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5399                                 ty1, ty2, var->name
5400                             );
5401                             return false;
5402                         }
5403
5404                         util_htset(parser->aliases, var->name, find);
5405
5406                         /* generate aliases for vector components */
5407                         if (isvector) {
5408                             char *buffer[3];
5409
5410                             util_asprintf(&buffer[0], "%s_x", var->desc);
5411                             util_asprintf(&buffer[1], "%s_y", var->desc);
5412                             util_asprintf(&buffer[2], "%s_z", var->desc);
5413
5414                             util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5415                             util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5416                             util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5417
5418                             mem_d(buffer[0]);
5419                             mem_d(buffer[1]);
5420                             mem_d(buffer[2]);
5421                         }
5422                     }
5423                 }
5424             } else {
5425                 if (is_static) {
5426                     /* a static adds itself to be generated like any other global
5427                      * but is added to the local namespace instead
5428                      */
5429                     char   *defname = NULL;
5430                     size_t  prefix_len, ln;
5431                     size_t  sn, sn_size;
5432
5433                     ln = strlen(parser->function->name);
5434                     vec_append(defname, ln, parser->function->name);
5435
5436                     vec_append(defname, 2, "::");
5437                     /* remember the length up to here */
5438                     prefix_len = vec_size(defname);
5439
5440                     /* Add it to the local scope */
5441                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5442
5443                     /* now rename the global */
5444                     ln = strlen(var->name);
5445                     vec_append(defname, ln, var->name);
5446                     /* if a variable of that name already existed, add the
5447                      * counter value.
5448                      * The counter is incremented either way.
5449                      */
5450                     sn_size = vec_size(parser->function->static_names);
5451                     for (sn = 0; sn != sn_size; ++sn) {
5452                         if (strcmp(parser->function->static_names[sn], var->name) == 0)
5453                             break;
5454                     }
5455                     if (sn != sn_size) {
5456                         char *num = NULL;
5457                         int   len = util_asprintf(&num, "#%u", parser->function->static_count);
5458                         vec_append(defname, len, num);
5459                         mem_d(num);
5460                     }
5461                     else
5462                         vec_push(parser->function->static_names, util_strdup(var->name));
5463                     parser->function->static_count++;
5464                     ast_value_set_name(var, defname);
5465
5466                     /* push it to the to-be-generated globals */
5467                     vec_push(parser->globals, (ast_expression*)var);
5468
5469                     /* same game for the vector members */
5470                     if (isvector) {
5471                         for (i = 0; i < 3; ++i) {
5472                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5473
5474                             vec_shrinkto(defname, prefix_len);
5475                             ln = strlen(me[i]->name);
5476                             vec_append(defname, ln, me[i]->name);
5477                             ast_member_set_name(me[i], defname);
5478
5479                             vec_push(parser->globals, (ast_expression*)me[i]);
5480                         }
5481                     }
5482                     vec_free(defname);
5483                 } else {
5484                     localblock->locals.push_back(var);
5485                     parser_addlocal(parser, var->name, (ast_expression*)var);
5486                     if (isvector) {
5487                         for (i = 0; i < 3; ++i) {
5488                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5489                             ast_block_collect(localblock, (ast_expression*)me[i]);
5490                         }
5491                     }
5492                 }
5493             }
5494         }
5495         memcpy(last_me, me, sizeof(me));
5496         me[0] = me[1] = me[2] = NULL;
5497         cleanvar = false;
5498         /* Part 2.2
5499          * deal with arrays
5500          */
5501         if (var->expression.vtype == TYPE_ARRAY) {
5502             if (var->expression.count != (size_t)-1) {
5503                 if (!create_array_accessors(parser, var))
5504                     goto cleanup;
5505             }
5506         }
5507         else if (!localblock && !nofields &&
5508                  var->expression.vtype == TYPE_FIELD &&
5509                  var->expression.next->vtype == TYPE_ARRAY)
5510         {
5511             char name[1024];
5512             ast_expression *telem;
5513             ast_value      *tfield;
5514             ast_value      *array = (ast_value*)var->expression.next;
5515
5516             if (!ast_istype(var->expression.next, ast_value)) {
5517                 parseerror(parser, "internal error: field element type must be an ast_value");
5518                 goto cleanup;
5519             }
5520
5521             util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5522             if (!parser_create_array_field_setter(parser, array, name))
5523                 goto cleanup;
5524
5525             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5526             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5527             tfield->expression.next = telem;
5528             util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5529             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5530                 ast_delete(tfield);
5531                 goto cleanup;
5532             }
5533             ast_delete(tfield);
5534         }
5535
5536 skipvar:
5537         if (parser->tok == ';') {
5538             ast_delete(basetype);
5539             if (!parser_next(parser)) {
5540                 parseerror(parser, "error after variable declaration");
5541                 return false;
5542             }
5543             return true;
5544         }
5545
5546         if (parser->tok == ',')
5547             goto another;
5548
5549         /*
5550         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5551         */
5552         if (!var) {
5553             parseerror(parser, "missing comma or semicolon while parsing variables");
5554             break;
5555         }
5556
5557         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5558             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5559                              "initializing expression turns variable `%s` into a constant in this standard",
5560                              var->name) )
5561             {
5562                 break;
5563             }
5564         }
5565
5566         if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5567             if (parser->tok != '=') {
5568                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5569                 break;
5570             }
5571
5572             if (!parser_next(parser)) {
5573                 parseerror(parser, "error parsing initializer");
5574                 break;
5575             }
5576         }
5577         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5578             parseerror(parser, "expected '=' before function body in this standard");
5579         }
5580
5581         if (parser->tok == '#') {
5582             ast_function *func   = NULL;
5583             ast_value    *number = NULL;
5584             float         fractional;
5585             float         integral;
5586             int           builtin_num;
5587
5588             if (localblock) {
5589                 parseerror(parser, "cannot declare builtins within functions");
5590                 break;
5591             }
5592             if (var->expression.vtype != TYPE_FUNCTION) {
5593                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5594                 break;
5595             }
5596             if (!parser_next(parser)) {
5597                 parseerror(parser, "expected builtin number");
5598                 break;
5599             }
5600
5601             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5602                 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5603                 if (!number) {
5604                     parseerror(parser, "builtin number expected");
5605                     break;
5606                 }
5607                 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5608                 {
5609                     ast_unref(number);
5610                     parseerror(parser, "builtin number must be a compile time constant");
5611                     break;
5612                 }
5613                 if (number->expression.vtype == TYPE_INTEGER)
5614                     builtin_num = number->constval.vint;
5615                 else if (number->expression.vtype == TYPE_FLOAT)
5616                     builtin_num = number->constval.vfloat;
5617                 else {
5618                     ast_unref(number);
5619                     parseerror(parser, "builtin number must be an integer constant");
5620                     break;
5621                 }
5622                 ast_unref(number);
5623
5624                 fractional = modff(builtin_num, &integral);
5625                 if (builtin_num < 0 || fractional != 0) {
5626                     parseerror(parser, "builtin number must be an integer greater than zero");
5627                     break;
5628                 }
5629
5630                 /* we only want the integral part anyways */
5631                 builtin_num = integral;
5632             } else if (parser->tok == TOKEN_INTCONST) {
5633                 builtin_num = parser_token(parser)->constval.i;
5634             } else {
5635                 parseerror(parser, "builtin number must be a compile time constant");
5636                 break;
5637             }
5638
5639             if (var->hasvalue) {
5640                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5641                                     "builtin `%s` has already been defined\n"
5642                                     " -> previous declaration here: %s:%i",
5643                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5644             }
5645             else
5646             {
5647                 func = ast_function_new(ast_ctx(var), var->name, var);
5648                 if (!func) {
5649                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5650                     break;
5651                 }
5652                 vec_push(parser->functions, func);
5653
5654                 func->builtin = -builtin_num-1;
5655             }
5656
5657             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5658                     ? (parser->tok != ',' && parser->tok != ';')
5659                     : (!parser_next(parser)))
5660             {
5661                 parseerror(parser, "expected comma or semicolon");
5662                 if (func)
5663                     ast_function_delete(func);
5664                 var->constval.vfunc = NULL;
5665                 break;
5666             }
5667         }
5668         else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5669         {
5670             if (localblock) {
5671                 /* Note that fteqcc and most others don't even *have*
5672                  * local arrays, so this is not a high priority.
5673                  */
5674                 parseerror(parser, "TODO: initializers for local arrays");
5675                 break;
5676             }
5677
5678             var->hasvalue = true;
5679             if (!parse_array(parser, var))
5680                 break;
5681         }
5682         else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5683         {
5684             if (localblock) {
5685                 parseerror(parser, "cannot declare functions within functions");
5686                 break;
5687             }
5688
5689             if (proto)
5690                 ast_ctx(proto) = parser_ctx(parser);
5691
5692             if (!parse_function_body(parser, var))
5693                 break;
5694             ast_delete(basetype);
5695             for (auto &it : parser->gotos)
5696                 parseerror(parser, "undefined label: `%s`", it->name);
5697             return true;
5698         } else {
5699             ast_expression *cexp;
5700             ast_value      *cval;
5701             bool            folded_const = false;
5702
5703             cexp = parse_expression_leave(parser, true, false, false);
5704             if (!cexp)
5705                 break;
5706             cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : NULL;
5707
5708             /* deal with foldable constants: */
5709             if (localblock &&
5710                 var->cvq == CV_CONST && cval && cval->hasvalue && cval->cvq == CV_CONST && !cval->isfield)
5711             {
5712                 /* remove it from the current locals */
5713                 if (isvector) {
5714                     for (i = 0; i < 3; ++i) {
5715                         vec_pop(parser->_locals);
5716                         localblock->collect.pop_back();
5717                     }
5718                 }
5719                 /* do sanity checking, this function really needs refactoring */
5720                 if (vec_last(parser->_locals) != (ast_expression*)var)
5721                     parseerror(parser, "internal error: unexpected change in local variable handling");
5722                 else
5723                     vec_pop(parser->_locals);
5724                 if (localblock->locals.back() != var)
5725                     parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5726                 else
5727                     localblock->locals.pop_back();
5728                 /* push it to the to-be-generated globals */
5729                 vec_push(parser->globals, (ast_expression*)var);
5730                 if (isvector)
5731                     for (i = 0; i < 3; ++i)
5732                         vec_push(parser->globals, (ast_expression*)last_me[i]);
5733                 folded_const = true;
5734             }
5735
5736             if (folded_const || !localblock || is_static) {
5737                 if (cval != parser->nil &&
5738                     (!cval || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5739                    )
5740                 {
5741                     parseerror(parser, "initializer is non constant");
5742                 }
5743                 else
5744                 {
5745                     if (!is_static &&
5746                         !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5747                         qualifier != CV_VAR)
5748                     {
5749                         var->cvq = CV_CONST;
5750                     }
5751                     if (cval == parser->nil)
5752                         var->expression.flags |= AST_FLAG_INITIALIZED;
5753                     else
5754                     {
5755                         var->hasvalue = true;
5756                         if (cval->expression.vtype == TYPE_STRING)
5757                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5758                         else if (cval->expression.vtype == TYPE_FIELD)
5759                             var->constval.vfield = cval;
5760                         else
5761                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5762                         ast_unref(cval);
5763                     }
5764                 }
5765             } else {
5766                 int cvq;
5767                 shunt sy = { NULL, NULL, NULL, NULL };
5768                 cvq = var->cvq;
5769                 var->cvq = CV_NONE;
5770                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5771                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5772                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5773                 if (!parser_sy_apply_operator(parser, &sy))
5774                     ast_unref(cexp);
5775                 else {
5776                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5777                         parseerror(parser, "internal error: leaked operands");
5778                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5779                         break;
5780                 }
5781                 vec_free(sy.out);
5782                 vec_free(sy.ops);
5783                 vec_free(sy.argc);
5784                 var->cvq = cvq;
5785             }
5786             /* a constant initialized to an inexact value should be marked inexact:
5787              * const float x = <inexact>; should propagate the inexact flag
5788              */
5789             if (var->cvq == CV_CONST && var->expression.vtype == TYPE_FLOAT) {
5790                 if (cval && cval->hasvalue && cval->cvq == CV_CONST)
5791                     var->inexact = cval->inexact;
5792             }
5793         }
5794
5795 another:
5796         if (parser->tok == ',') {
5797             if (!parser_next(parser)) {
5798                 parseerror(parser, "expected another variable");
5799                 break;
5800             }
5801
5802             if (parser->tok != TOKEN_IDENT) {
5803                 parseerror(parser, "expected another variable");
5804                 break;
5805             }
5806             var = ast_value_copy(basetype);
5807             cleanvar = true;
5808             ast_value_set_name(var, parser_tokval(parser));
5809             if (!parser_next(parser)) {
5810                 parseerror(parser, "error parsing variable declaration");
5811                 break;
5812             }
5813             continue;
5814         }
5815
5816         if (parser->tok != ';') {
5817             parseerror(parser, "missing semicolon after variables");
5818             break;
5819         }
5820
5821         if (!parser_next(parser)) {
5822             parseerror(parser, "parse error after variable declaration");
5823             break;
5824         }
5825
5826         ast_delete(basetype);
5827         return true;
5828     }
5829
5830     if (cleanvar && var)
5831         ast_delete(var);
5832     ast_delete(basetype);
5833     return false;
5834
5835 cleanup:
5836     ast_delete(basetype);
5837     if (cleanvar && var)
5838         ast_delete(var);
5839     if (me[0]) ast_member_delete(me[0]);
5840     if (me[1]) ast_member_delete(me[1]);
5841     if (me[2]) ast_member_delete(me[2]);
5842     return retval;
5843 }
5844
5845 static bool parser_global_statement(parser_t *parser)
5846 {
5847     int        cvq       = CV_WRONG;
5848     bool       noref     = false;
5849     bool       is_static = false;
5850     uint32_t   qflags    = 0;
5851     ast_value *istype    = NULL;
5852     char      *vstring   = NULL;
5853
5854     if (parser->tok == TOKEN_IDENT)
5855         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5856
5857     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5858     {
5859         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5860     }
5861     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5862     {
5863         if (cvq == CV_WRONG)
5864             return false;
5865         return parse_variable(parser, NULL, false, cvq, NULL, noref, is_static, qflags, vstring);
5866     }
5867     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5868     {
5869         return parse_enum(parser);
5870     }
5871     else if (parser->tok == TOKEN_KEYWORD)
5872     {
5873         if (!strcmp(parser_tokval(parser), "typedef")) {
5874             if (!parser_next(parser)) {
5875                 parseerror(parser, "expected type definition after 'typedef'");
5876                 return false;
5877             }
5878             return parse_typedef(parser);
5879         }
5880         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5881         return false;
5882     }
5883     else if (parser->tok == '#')
5884     {
5885         return parse_pragma(parser);
5886     }
5887     else if (parser->tok == '$')
5888     {
5889         if (!parser_next(parser)) {
5890             parseerror(parser, "parse error");
5891             return false;
5892         }
5893     }
5894     else
5895     {
5896         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5897         return false;
5898     }
5899     return true;
5900 }
5901
5902 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5903 {
5904     return util_crc16(old, str, strlen(str));
5905 }
5906
5907 static void progdefs_crc_file(const char *str)
5908 {
5909     /* write to progdefs.h here */
5910     (void)str;
5911 }
5912
5913 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5914 {
5915     old = progdefs_crc_sum(old, str);
5916     progdefs_crc_file(str);
5917     return old;
5918 }
5919
5920 static void generate_checksum(parser_t *parser, ir_builder *ir)
5921 {
5922     uint16_t   crc = 0xFFFF;
5923     size_t     i;
5924     ast_value *value;
5925
5926     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5927     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5928     /*
5929     progdefs_crc_file("\tint\tpad;\n");
5930     progdefs_crc_file("\tint\tofs_return[3];\n");
5931     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5932     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5933     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5934     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5935     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5936     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5937     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5938     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5939     */
5940     for (i = 0; i < parser->crc_globals; ++i) {
5941         if (!ast_istype(parser->globals[i], ast_value))
5942             continue;
5943         value = (ast_value*)(parser->globals[i]);
5944         switch (value->expression.vtype) {
5945             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5946             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5947             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5948             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5949             default:
5950                 crc = progdefs_crc_both(crc, "\tint\t");
5951                 break;
5952         }
5953         crc = progdefs_crc_both(crc, value->name);
5954         crc = progdefs_crc_both(crc, ";\n");
5955     }
5956     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5957     for (i = 0; i < parser->crc_fields; ++i) {
5958         if (!ast_istype(parser->fields[i], ast_value))
5959             continue;
5960         value = (ast_value*)(parser->fields[i]);
5961         switch (value->expression.next->vtype) {
5962             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5963             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5964             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5965             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5966             default:
5967                 crc = progdefs_crc_both(crc, "\tint\t");
5968                 break;
5969         }
5970         crc = progdefs_crc_both(crc, value->name);
5971         crc = progdefs_crc_both(crc, ";\n");
5972     }
5973     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5974     ir->code->crc = crc;
5975 }
5976
5977 parser_t *parser_create()
5978 {
5979     parser_t *parser;
5980     lex_ctx_t empty_ctx;
5981     size_t i;
5982
5983     parser = (parser_t*)mem_a(sizeof(parser_t));
5984     if (!parser)
5985         return NULL;
5986
5987     memset(parser, 0, sizeof(*parser));
5988
5989     // TODO: remove
5990     new (parser) parser_t();
5991
5992     for (i = 0; i < operator_count; ++i) {
5993         if (operators[i].id == opid1('=')) {
5994             parser->assign_op = operators+i;
5995             break;
5996         }
5997     }
5998     if (!parser->assign_op) {
5999         con_err("internal error: initializing parser: failed to find assign operator\n");
6000         mem_d(parser);
6001         return NULL;
6002     }
6003
6004     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
6005     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6006     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6007     vec_push(parser->_blocktypedefs, 0);
6008
6009     parser->aliases = util_htnew(PARSER_HT_SIZE);
6010
6011     empty_ctx.file   = "<internal>";
6012     empty_ctx.line   = 0;
6013     empty_ctx.column = 0;
6014     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6015     parser->nil->cvq = CV_CONST;
6016     if (OPTS_FLAG(UNTYPED_NIL))
6017         util_htset(parser->htglobals, "nil", (void*)parser->nil);
6018
6019     parser->max_param_count = 1;
6020
6021     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6022     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6023     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6024
6025     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6026         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6027         parser->reserved_version->cvq = CV_CONST;
6028         parser->reserved_version->hasvalue = true;
6029         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6030         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6031     } else {
6032         parser->reserved_version = NULL;
6033     }
6034
6035     parser->fold   = fold_init  (parser);
6036     parser->intrin = intrin_init(parser);
6037     return parser;
6038 }
6039
6040 static bool parser_compile(parser_t *parser)
6041 {
6042     /* initial lexer/parser state */
6043     parser->lex->flags.noops = true;
6044
6045     if (parser_next(parser))
6046     {
6047         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6048         {
6049             if (!parser_global_statement(parser)) {
6050                 if (parser->tok == TOKEN_EOF)
6051                     parseerror(parser, "unexpected end of file");
6052                 else if (compile_errors)
6053                     parseerror(parser, "there have been errors, bailing out");
6054                 lex_close(parser->lex);
6055                 parser->lex = NULL;
6056                 return false;
6057             }
6058         }
6059     } else {
6060         parseerror(parser, "parse error");
6061         lex_close(parser->lex);
6062         parser->lex = NULL;
6063         return false;
6064     }
6065
6066     lex_close(parser->lex);
6067     parser->lex = NULL;
6068
6069     return !compile_errors;
6070 }
6071
6072 bool parser_compile_file(parser_t *parser, const char *filename)
6073 {
6074     parser->lex = lex_open(filename);
6075     if (!parser->lex) {
6076         con_err("failed to open file \"%s\"\n", filename);
6077         return false;
6078     }
6079     return parser_compile(parser);
6080 }
6081
6082 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6083 {
6084     parser->lex = lex_open_string(str, len, name);
6085     if (!parser->lex) {
6086         con_err("failed to create lexer for string \"%s\"\n", name);
6087         return false;
6088     }
6089     return parser_compile(parser);
6090 }
6091
6092 static void parser_remove_ast(parser_t *parser)
6093 {
6094     size_t i;
6095     if (parser->ast_cleaned)
6096         return;
6097     parser->ast_cleaned = true;
6098     for (i = 0; i < vec_size(parser->accessors); ++i) {
6099         ast_delete(parser->accessors[i]->constval.vfunc);
6100         parser->accessors[i]->constval.vfunc = NULL;
6101         ast_delete(parser->accessors[i]);
6102     }
6103     for (i = 0; i < vec_size(parser->functions); ++i) {
6104         ast_delete(parser->functions[i]);
6105     }
6106     for (i = 0; i < vec_size(parser->fields); ++i) {
6107         ast_delete(parser->fields[i]);
6108     }
6109     for (i = 0; i < vec_size(parser->globals); ++i) {
6110         ast_delete(parser->globals[i]);
6111     }
6112     vec_free(parser->accessors);
6113     vec_free(parser->functions);
6114     vec_free(parser->globals);
6115     vec_free(parser->fields);
6116
6117     for (i = 0; i < vec_size(parser->variables); ++i)
6118         util_htdel(parser->variables[i]);
6119     vec_free(parser->variables);
6120     vec_free(parser->_blocklocals);
6121     vec_free(parser->_locals);
6122
6123     for (i = 0; i < vec_size(parser->_typedefs); ++i)
6124         ast_delete(parser->_typedefs[i]);
6125     vec_free(parser->_typedefs);
6126     for (i = 0; i < vec_size(parser->typedefs); ++i)
6127         util_htdel(parser->typedefs[i]);
6128     vec_free(parser->typedefs);
6129     vec_free(parser->_blocktypedefs);
6130
6131     vec_free(parser->_block_ctx);
6132
6133     ast_value_delete(parser->nil);
6134
6135     ast_value_delete(parser->const_vec[0]);
6136     ast_value_delete(parser->const_vec[1]);
6137     ast_value_delete(parser->const_vec[2]);
6138
6139     if (parser->reserved_version)
6140         ast_value_delete(parser->reserved_version);
6141
6142     util_htdel(parser->aliases);
6143     fold_cleanup(parser->fold);
6144     intrin_cleanup(parser->intrin);
6145 }
6146
6147 void parser_cleanup(parser_t *parser)
6148 {
6149     parser_remove_ast(parser);
6150     mem_d(parser);
6151 }
6152
6153 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6154     size_t          i;
6155     ast_expression *expr;
6156     ast_value      *cov;
6157     ast_function   *func;
6158
6159     if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6160         return true;
6161
6162     func = NULL;
6163     for (i = 0; i != vec_size(parser->functions); ++i) {
6164         if (!strcmp(parser->functions[i]->name, "coverage")) {
6165             func = parser->functions[i];
6166             break;
6167         }
6168     }
6169     if (!func) {
6170         if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6171             con_out("coverage support requested but no coverage() builtin declared\n");
6172             ir_builder_delete(ir);
6173             return false;
6174         }
6175         return true;
6176     }
6177
6178     cov  = func->vtype;
6179     expr = (ast_expression*)cov;
6180
6181     if (expr->vtype != TYPE_FUNCTION || expr->params.size()) {
6182         char ty[1024];
6183         ast_type_to_string(expr, ty, sizeof(ty));
6184         con_out("invalid type for coverage(): %s\n", ty);
6185         ir_builder_delete(ir);
6186         return false;
6187     }
6188
6189     ir->coverage_func = func->ir_func->value;
6190     return true;
6191 }
6192
6193 bool parser_finish(parser_t *parser, const char *output)
6194 {
6195     size_t          i;
6196     ir_builder     *ir;
6197     bool            retval = true;
6198
6199     if (compile_errors) {
6200         con_out("*** there were compile errors\n");
6201         return false;
6202     }
6203
6204     ir = ir_builder_new("gmqcc_out");
6205     if (!ir) {
6206         con_out("failed to allocate builder\n");
6207         return false;
6208     }
6209
6210     for (i = 0; i < vec_size(parser->fields); ++i) {
6211         ast_value *field;
6212         bool hasvalue;
6213         if (!ast_istype(parser->fields[i], ast_value))
6214             continue;
6215         field = (ast_value*)parser->fields[i];
6216         hasvalue = field->hasvalue;
6217         field->hasvalue = false;
6218         if (!ast_global_codegen((ast_value*)field, ir, true)) {
6219             con_out("failed to generate field %s\n", field->name);
6220             ir_builder_delete(ir);
6221             return false;
6222         }
6223         if (hasvalue) {
6224             ir_value *ifld;
6225             ast_expression *subtype;
6226             field->hasvalue = true;
6227             subtype = field->expression.next;
6228             ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6229             if (subtype->vtype == TYPE_FIELD)
6230                 ifld->fieldtype = subtype->next->vtype;
6231             else if (subtype->vtype == TYPE_FUNCTION)
6232                 ifld->outtype = subtype->next->vtype;
6233             (void)!ir_value_set_field(field->ir_v, ifld);
6234         }
6235     }
6236     for (i = 0; i < vec_size(parser->globals); ++i) {
6237         ast_value *asvalue;
6238         if (!ast_istype(parser->globals[i], ast_value))
6239             continue;
6240         asvalue = (ast_value*)(parser->globals[i]);
6241         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6242             retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6243                                                 "unused global: `%s`", asvalue->name);
6244         }
6245         if (!ast_global_codegen(asvalue, ir, false)) {
6246             con_out("failed to generate global %s\n", asvalue->name);
6247             ir_builder_delete(ir);
6248             return false;
6249         }
6250     }
6251     /* Build function vararg accessor ast tree now before generating
6252      * immediates, because the accessors may add new immediates
6253      */
6254     for (i = 0; i < vec_size(parser->functions); ++i) {
6255         ast_function *f = parser->functions[i];
6256         if (f->varargs) {
6257             if (parser->max_param_count > f->vtype->expression.params.size()) {
6258                 f->varargs->expression.count = parser->max_param_count - f->vtype->expression.params.size();
6259                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6260                     con_out("failed to generate vararg setter for %s\n", f->name);
6261                     ir_builder_delete(ir);
6262                     return false;
6263                 }
6264                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6265                     con_out("failed to generate vararg getter for %s\n", f->name);
6266                     ir_builder_delete(ir);
6267                     return false;
6268                 }
6269             } else {
6270                 ast_delete(f->varargs);
6271                 f->varargs = NULL;
6272             }
6273         }
6274     }
6275     /* Now we can generate immediates */
6276     if (!fold_generate(parser->fold, ir))
6277         return false;
6278
6279     /* before generating any functions we need to set the coverage_func */
6280     if (!parser_set_coverage_func(parser, ir))
6281         return false;
6282
6283     for (i = 0; i < vec_size(parser->globals); ++i) {
6284         ast_value *asvalue;
6285         if (!ast_istype(parser->globals[i], ast_value))
6286             continue;
6287         asvalue = (ast_value*)(parser->globals[i]);
6288         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6289         {
6290             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6291                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6292                                        "uninitialized constant: `%s`",
6293                                        asvalue->name);
6294             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6295                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6296                                        "uninitialized global: `%s`",
6297                                        asvalue->name);
6298         }
6299         if (!ast_generate_accessors(asvalue, ir)) {
6300             ir_builder_delete(ir);
6301             return false;
6302         }
6303     }
6304     for (i = 0; i < vec_size(parser->fields); ++i) {
6305         ast_value *asvalue;
6306         asvalue = (ast_value*)(parser->fields[i]->next);
6307
6308         if (!ast_istype((ast_expression*)asvalue, ast_value))
6309             continue;
6310         if (asvalue->expression.vtype != TYPE_ARRAY)
6311             continue;
6312         if (!ast_generate_accessors(asvalue, ir)) {
6313             ir_builder_delete(ir);
6314             return false;
6315         }
6316     }
6317     if (parser->reserved_version &&
6318         !ast_global_codegen(parser->reserved_version, ir, false))
6319     {
6320         con_out("failed to generate reserved::version");
6321         ir_builder_delete(ir);
6322         return false;
6323     }
6324     for (i = 0; i < vec_size(parser->functions); ++i) {
6325         ast_function *f = parser->functions[i];
6326         if (!ast_function_codegen(f, ir)) {
6327             con_out("failed to generate function %s\n", f->name);
6328             ir_builder_delete(ir);
6329             return false;
6330         }
6331     }
6332
6333     generate_checksum(parser, ir);
6334
6335     if (OPTS_OPTION_BOOL(OPTION_DUMP))
6336         ir_builder_dump(ir, con_out);
6337     for (i = 0; i < vec_size(parser->functions); ++i) {
6338         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6339             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6340             ir_builder_delete(ir);
6341             return false;
6342         }
6343     }
6344     parser_remove_ast(parser);
6345
6346     if (compile_Werrors) {
6347         con_out("*** there were warnings treated as errors\n");
6348         compile_show_werrors();
6349         retval = false;
6350     }
6351
6352     if (retval) {
6353         if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6354             ir_builder_dump(ir, con_out);
6355
6356         if (!ir_builder_generate(ir, output)) {
6357             con_out("*** failed to generate output file\n");
6358             ir_builder_delete(ir);
6359             return false;
6360         }
6361     }
6362     ir_builder_delete(ir);
6363     return retval;
6364 }