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