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