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