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