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