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