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