]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.cpp
Remove parser m_uses in favor of {IR,AST}_FLAG_NOREF instead
[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 = vec_size(parser->variables); 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 = vec_size(parser->typedefs); 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         case opid2('&','&'):
732             generated_op += INSTR_AND;
733             if (!(out = parser->m_fold.op(op, exprs))) {
734                 if (OPTS_FLAG(PERL_LOGIC) && !exprs[0]->compareType(*exprs[1])) {
735                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
736                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
737                     compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
738                     return false;
739                 }
740                 for (i = 0; i < 2; ++i) {
741                     if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->m_vtype == TYPE_VECTOR) {
742                         out = ast_unary::make(ctx, INSTR_NOT_V, exprs[i]);
743                         if (!out) break;
744                         out = ast_unary::make(ctx, INSTR_NOT_F, out);
745                         if (!out) break;
746                         exprs[i] = out; out = nullptr;
747                         if (OPTS_FLAG(PERL_LOGIC)) {
748                             /* here we want to keep the right expressions' type */
749                             break;
750                         }
751                     }
752                     else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->m_vtype == TYPE_STRING) {
753                         out = ast_unary::make(ctx, INSTR_NOT_S, exprs[i]);
754                         if (!out) break;
755                         out = ast_unary::make(ctx, INSTR_NOT_F, out);
756                         if (!out) break;
757                         exprs[i] = out; out = nullptr;
758                         if (OPTS_FLAG(PERL_LOGIC)) {
759                             /* here we want to keep the right expressions' type */
760                             break;
761                         }
762                     }
763                 }
764                 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
765             }
766             break;
767
768         case opid2('?',':'):
769             if (sy->paren.back() != PAREN_TERNARY2) {
770                 compile_error(ctx, "mismatched parenthesis/ternary");
771                 return false;
772             }
773             sy->paren.pop_back();
774             if (!exprs[1]->compareType(*exprs[2])) {
775                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
776                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
777                 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
778                 return false;
779             }
780             if (!(out = parser->m_fold.op(op, exprs)))
781                 out = new ast_ternary(ctx, exprs[0], exprs[1], exprs[2]);
782             break;
783
784         case opid2('*', '*'):
785             if (NotSameType(TYPE_FLOAT)) {
786                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
787                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
788                 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
789                     ty1, ty2);
790                 return false;
791             }
792
793             if (!(out = parser->m_fold.op(op, exprs))) {
794                 ast_call *gencall = ast_call::make(parser_ctx(parser), parser->m_intrin.func("pow"));
795                 gencall->m_params.push_back(exprs[0]);
796                 gencall->m_params.push_back(exprs[1]);
797                 out = gencall;
798             }
799             break;
800
801         case opid2('>', '<'):
802             if (NotSameType(TYPE_VECTOR)) {
803                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
804                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
805                 compile_error(ctx, "invalid types used in cross product: %s and %s",
806                     ty1, ty2);
807                 return false;
808             }
809
810             if (!(out = parser->m_fold.op(op, exprs))) {
811                 out = fold::binary(
812                     parser_ctx(parser),
813                     VINSTR_CROSS,
814                     exprs[0],
815                     exprs[1]
816                 );
817             }
818
819             break;
820
821         case opid3('<','=','>'): /* -1, 0, or 1 */
822             if (NotSameType(TYPE_FLOAT)) {
823                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
824                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
825                 compile_error(ctx, "invalid types used in comparision: %s and %s",
826                     ty1, ty2);
827
828                 return false;
829             }
830
831             if (!(out = parser->m_fold.op(op, exprs))) {
832                 /* This whole block is NOT fold_binary safe */
833                 ast_binary *eq = new ast_binary(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
834
835                 eq->m_refs = AST_REF_NONE;
836
837                     /* if (lt) { */
838                 out = new ast_ternary(ctx,
839                         new ast_binary(ctx, INSTR_LT, exprs[0], exprs[1]),
840                         /* out = -1 */
841                         parser->m_fold.imm_float(2),
842                     /* } else { */
843                         /* if (eq) { */
844                         new ast_ternary(ctx, eq,
845                             /* out = 0 */
846                             parser->m_fold.imm_float(0),
847                         /* } else { */
848                             /* out = 1 */
849                             parser->m_fold.imm_float(1)
850                         /* } */
851                         )
852                     /* } */
853                     );
854
855             }
856             break;
857
858         case opid1('>'):
859             generated_op += 1; /* INSTR_GT */
860         case opid1('<'):
861             generated_op += 1; /* INSTR_LT */
862         case opid2('>', '='):
863             generated_op += 1; /* INSTR_GE */
864         case opid2('<', '='):
865             generated_op += INSTR_LE;
866             if (NotSameType(TYPE_FLOAT)) {
867                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
868                               type_name[exprs[0]->m_vtype],
869                               type_name[exprs[1]->m_vtype]);
870                 return false;
871             }
872             if (!(out = parser->m_fold.op(op, exprs)))
873                 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
874             break;
875         case opid2('!', '='):
876             if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
877                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
878                               type_name[exprs[0]->m_vtype],
879                               type_name[exprs[1]->m_vtype]);
880                 return false;
881             }
882             if (!(out = parser->m_fold.op(op, exprs)))
883                 out = fold::binary(ctx, type_ne_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
884             break;
885         case opid2('=', '='):
886             if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
887                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
888                               type_name[exprs[0]->m_vtype],
889                               type_name[exprs[1]->m_vtype]);
890                 return false;
891             }
892             if (!(out = parser->m_fold.op(op, exprs)))
893                 out = fold::binary(ctx, type_eq_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
894             break;
895
896         case opid1('='):
897             if (ast_istype(exprs[0], ast_entfield)) {
898                 ast_expression *field = ((ast_entfield*)exprs[0])->m_field;
899                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
900                     exprs[0]->m_vtype == TYPE_FIELD &&
901                     exprs[0]->m_next->m_vtype == TYPE_VECTOR)
902                 {
903                     assignop = type_storep_instr[TYPE_VECTOR];
904                 }
905                 else
906                     assignop = type_storep_instr[exprs[0]->m_vtype];
907                 if (assignop == VINSTR_END || !field->m_next->compareType(*exprs[1]))
908                 {
909                     ast_type_to_string(field->m_next, ty1, sizeof(ty1));
910                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
911                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
912                         field->m_next->m_vtype == TYPE_FUNCTION &&
913                         exprs[1]->m_vtype == TYPE_FUNCTION)
914                     {
915                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
916                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
917                     }
918                     else
919                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
920                 }
921             }
922             else
923             {
924                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
925                     exprs[0]->m_vtype == TYPE_FIELD &&
926                     exprs[0]->m_next->m_vtype == TYPE_VECTOR)
927                 {
928                     assignop = type_store_instr[TYPE_VECTOR];
929                 }
930                 else {
931                     assignop = type_store_instr[exprs[0]->m_vtype];
932                 }
933
934                 if (assignop == VINSTR_END) {
935                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
936                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
937                     compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
938                 }
939                 else if (!exprs[0]->compareType(*exprs[1]))
940                 {
941                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
942                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
943                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
944                         exprs[0]->m_vtype == TYPE_FUNCTION &&
945                         exprs[1]->m_vtype == TYPE_FUNCTION)
946                     {
947                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
948                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
949                     }
950                     else
951                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
952                 }
953             }
954             (void)check_write_to(ctx, exprs[0]);
955             /* When we're a vector of part of an entity field we use STOREP */
956             if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->m_owner, ast_entfield))
957                 assignop = INSTR_STOREP_F;
958             out = new ast_store(ctx, assignop, exprs[0], exprs[1]);
959             break;
960         case opid3('+','+','P'):
961         case opid3('-','-','P'):
962             /* prefix ++ */
963             if (exprs[0]->m_vtype != TYPE_FLOAT) {
964                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
965                 compile_error(exprs[0]->m_context, "invalid type for prefix increment: %s", ty1);
966                 return false;
967             }
968             if (op->id == opid3('+','+','P'))
969                 addop = INSTR_ADD_F;
970             else
971                 addop = INSTR_SUB_F;
972             (void)check_write_to(exprs[0]->m_context, exprs[0]);
973             if (ast_istype(exprs[0], ast_entfield)) {
974                 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
975                                        exprs[0],
976                                        parser->m_fold.imm_float(1));
977             } else {
978                 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
979                                        exprs[0],
980                                        parser->m_fold.imm_float(1));
981             }
982             break;
983         case opid3('S','+','+'):
984         case opid3('S','-','-'):
985             /* prefix ++ */
986             if (exprs[0]->m_vtype != TYPE_FLOAT) {
987                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
988                 compile_error(exprs[0]->m_context, "invalid type for suffix increment: %s", ty1);
989                 return false;
990             }
991             if (op->id == opid3('S','+','+')) {
992                 addop = INSTR_ADD_F;
993                 subop = INSTR_SUB_F;
994             } else {
995                 addop = INSTR_SUB_F;
996                 subop = INSTR_ADD_F;
997             }
998             (void)check_write_to(exprs[0]->m_context, exprs[0]);
999             if (ast_istype(exprs[0], ast_entfield)) {
1000                 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
1001                                        exprs[0],
1002                                        parser->m_fold.imm_float(1));
1003             } else {
1004                 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
1005                                        exprs[0],
1006                                        parser->m_fold.imm_float(1));
1007             }
1008             if (!out)
1009                 return false;
1010             out = fold::binary(ctx, subop,
1011                               out,
1012                               parser->m_fold.imm_float(1));
1013
1014             break;
1015         case opid2('+','='):
1016         case opid2('-','='):
1017             if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
1018                 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
1019             {
1020                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1021                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1022                 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1023                               ty1, ty2);
1024                 return false;
1025             }
1026             (void)check_write_to(ctx, exprs[0]);
1027             if (ast_istype(exprs[0], ast_entfield))
1028                 assignop = type_storep_instr[exprs[0]->m_vtype];
1029             else
1030                 assignop = type_store_instr[exprs[0]->m_vtype];
1031             switch (exprs[0]->m_vtype) {
1032                 case TYPE_FLOAT:
1033                     out = new ast_binstore(ctx, assignop,
1034                                            (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1035                                            exprs[0], exprs[1]);
1036                     break;
1037                 case TYPE_VECTOR:
1038                     out = new ast_binstore(ctx, assignop,
1039                                            (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1040                                            exprs[0], exprs[1]);
1041                     break;
1042                 default:
1043                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1044                                   type_name[exprs[0]->m_vtype],
1045                                   type_name[exprs[1]->m_vtype]);
1046                     return false;
1047             };
1048             break;
1049         case opid2('*','='):
1050         case opid2('/','='):
1051             if (exprs[1]->m_vtype != TYPE_FLOAT ||
1052                 !(exprs[0]->m_vtype == TYPE_FLOAT ||
1053                   exprs[0]->m_vtype == TYPE_VECTOR))
1054             {
1055                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1056                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1057                 compile_error(ctx, "invalid types used in expression: %s and %s",
1058                               ty1, ty2);
1059                 return false;
1060             }
1061             (void)check_write_to(ctx, exprs[0]);
1062             if (ast_istype(exprs[0], ast_entfield))
1063                 assignop = type_storep_instr[exprs[0]->m_vtype];
1064             else
1065                 assignop = type_store_instr[exprs[0]->m_vtype];
1066             switch (exprs[0]->m_vtype) {
1067                 case TYPE_FLOAT:
1068                     out = new ast_binstore(ctx, assignop,
1069                                            (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1070                                            exprs[0], exprs[1]);
1071                     break;
1072                 case TYPE_VECTOR:
1073                     if (op->id == opid2('*','=')) {
1074                         out = new ast_binstore(ctx, assignop, INSTR_MUL_VF,
1075                                                exprs[0], exprs[1]);
1076                     } else {
1077                         out = fold::binary(ctx, INSTR_DIV_F,
1078                                          parser->m_fold.imm_float(1),
1079                                          exprs[1]);
1080                         if (!out) {
1081                             compile_error(ctx, "internal error: failed to generate division");
1082                             return false;
1083                         }
1084                         out = new ast_binstore(ctx, assignop, INSTR_MUL_VF,
1085                                                exprs[0], out);
1086                     }
1087                     break;
1088                 default:
1089                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1090                                   type_name[exprs[0]->m_vtype],
1091                                   type_name[exprs[1]->m_vtype]);
1092                     return false;
1093             };
1094             break;
1095         case opid2('&','='):
1096         case opid2('|','='):
1097         case opid2('^','='):
1098             if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1099                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1100                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1101                 compile_error(ctx, "invalid types used in expression: %s and %s",
1102                               ty1, ty2);
1103                 return false;
1104             }
1105             (void)check_write_to(ctx, exprs[0]);
1106             if (ast_istype(exprs[0], ast_entfield))
1107                 assignop = type_storep_instr[exprs[0]->m_vtype];
1108             else
1109                 assignop = type_store_instr[exprs[0]->m_vtype];
1110             if (exprs[0]->m_vtype == TYPE_FLOAT)
1111                 out = new ast_binstore(ctx, assignop,
1112                                        (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1113                                        exprs[0], exprs[1]);
1114             else
1115                 out = new ast_binstore(ctx, assignop,
1116                                        (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1117                                        exprs[0], exprs[1]);
1118             break;
1119         case opid3('&','~','='):
1120             /* This is like: a &= ~(b);
1121              * But QC has no bitwise-not, so we implement it as
1122              * a -= a & (b);
1123              */
1124             if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1125                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1126                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1127                 compile_error(ctx, "invalid types used in expression: %s and %s",
1128                               ty1, ty2);
1129                 return false;
1130             }
1131             if (ast_istype(exprs[0], ast_entfield))
1132                 assignop = type_storep_instr[exprs[0]->m_vtype];
1133             else
1134                 assignop = type_store_instr[exprs[0]->m_vtype];
1135             if (exprs[0]->m_vtype == TYPE_FLOAT)
1136                 out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1137             else
1138                 out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1139             if (!out)
1140                 return false;
1141             (void)check_write_to(ctx, exprs[0]);
1142             if (exprs[0]->m_vtype == TYPE_FLOAT)
1143                 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1144             else
1145                 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1146             asbinstore->m_keep_dest = true;
1147             out = asbinstore;
1148             break;
1149
1150         case opid3('l', 'e', 'n'):
1151             if (exprs[0]->m_vtype != TYPE_STRING && exprs[0]->m_vtype != TYPE_ARRAY) {
1152                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1153                 compile_error(exprs[0]->m_context, "invalid type for length operator: %s", ty1);
1154                 return false;
1155             }
1156             /* strings must be const, arrays are statically sized */
1157             if (exprs[0]->m_vtype == TYPE_STRING &&
1158                 !(((ast_value*)exprs[0])->m_hasvalue && ((ast_value*)exprs[0])->m_cvq == CV_CONST))
1159             {
1160                 compile_error(exprs[0]->m_context, "operand of length operator not a valid constant expression");
1161                 return false;
1162             }
1163             out = parser->m_fold.op(op, exprs);
1164             break;
1165
1166         case opid2('~', 'P'):
1167             if (exprs[0]->m_vtype != TYPE_FLOAT && exprs[0]->m_vtype != TYPE_VECTOR) {
1168                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1169                 compile_error(exprs[0]->m_context, "invalid type for bit not: %s", ty1);
1170                 return false;
1171             }
1172             if (!(out = parser->m_fold.op(op, exprs))) {
1173                 if (exprs[0]->m_vtype == TYPE_FLOAT) {
1174                     out = fold::binary(ctx, INSTR_SUB_F, parser->m_fold.imm_float(2), exprs[0]);
1175                 } else {
1176                     out = fold::binary(ctx, INSTR_SUB_V, parser->m_fold.imm_vector(1), exprs[0]);
1177                 }
1178             }
1179             break;
1180     }
1181 #undef NotSameType
1182     if (!out) {
1183         compile_error(ctx, "failed to apply operator %s", op->op);
1184         return false;
1185     }
1186
1187     sy->out.push_back(syexp(ctx, out));
1188     return true;
1189 }
1190
1191 static bool parser_close_call(parser_t *parser, shunt *sy)
1192 {
1193     /* was a function call */
1194     ast_expression *fun;
1195     ast_value      *funval = nullptr;
1196     ast_call       *call;
1197
1198     size_t          fid;
1199     size_t          paramcount, i;
1200     bool            fold = true;
1201
1202     fid = sy->ops.back().off;
1203     sy->ops.pop_back();
1204
1205     /* out[fid] is the function
1206      * everything above is parameters...
1207      */
1208     if (sy->argc.empty()) {
1209         parseerror(parser, "internal error: no argument counter available");
1210         return false;
1211     }
1212
1213     paramcount = sy->argc.back();
1214     sy->argc.pop_back();
1215
1216     if (sy->out.size() < fid) {
1217         parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1218                    sy->out.size(),
1219                    fid,
1220                    paramcount);
1221         return false;
1222     }
1223
1224     /*
1225      * TODO handle this at the intrinsic level with an ast_intrinsic
1226      * node and codegen.
1227      */
1228     if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1229         char ty[1024];
1230         if (fid+2 != sy->out.size() || sy->out.back().block) {
1231             parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1232             return false;
1233         }
1234         ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1235         ast_unref(sy->out.back().out);
1236         sy->out[fid] = syexp(sy->out.back().out->m_context,
1237                              parser->m_fold.constgen_string(ty, false));
1238         sy->out.pop_back();
1239         return true;
1240     }
1241
1242     /*
1243      * Now we need to determine if the function that is being called is
1244      * an intrinsic so we can evaluate if the arguments to it are constant
1245      * and than fruitfully fold them.
1246      */
1247 #define fold_can_1(X)  \
1248     (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
1249                 ((X))->m_vtype != TYPE_FUNCTION)
1250
1251     if (fid + 1 < sy->out.size())
1252         ++paramcount;
1253
1254     for (i = 0; i < paramcount; ++i) {
1255         if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1256             fold = false;
1257             break;
1258         }
1259     }
1260
1261     /*
1262      * All is well which ends well, if we make it into here we can ignore the
1263      * intrinsic call and just evaluate it i.e constant fold it.
1264      */
1265     if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) {
1266         ast_expression **exprs  = nullptr;
1267         ast_expression *foldval = nullptr;
1268
1269         for (i = 0; i < paramcount; i++)
1270             vec_push(exprs, sy->out[fid+1 + i].out);
1271
1272         if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs))) {
1273             vec_free(exprs);
1274             goto fold_leave;
1275         }
1276
1277         /*
1278          * Blub: what sorts of unreffing and resizing of
1279          * sy->out should I be doing here?
1280          */
1281         sy->out[fid] = syexp(foldval->m_context, foldval);
1282         sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1283         vec_free(exprs);
1284
1285         return true;
1286     }
1287
1288     fold_leave:
1289     call = ast_call::make(sy->ops[sy->ops.size()].ctx, fun);
1290
1291     if (!call)
1292         return false;
1293
1294     if (fid+1 + paramcount != sy->out.size()) {
1295         parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1296                    fid,
1297                    paramcount,
1298                    sy->out.size());
1299         return false;
1300     }
1301
1302     for (i = 0; i < paramcount; ++i)
1303         call->m_params.push_back(sy->out[fid+1 + i].out);
1304     sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1305     (void)!call->checkTypes(parser->function->m_function_type->m_varparam);
1306     if (parser->max_param_count < paramcount)
1307         parser->max_param_count = paramcount;
1308
1309     if (ast_istype(fun, ast_value)) {
1310         funval = (ast_value*)fun;
1311         if ((fun->m_flags & AST_FLAG_VARIADIC) &&
1312             !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin))
1313         {
1314             call->m_va_count = parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1315         }
1316     }
1317
1318     /* overwrite fid, the function, with a call */
1319     sy->out[fid] = syexp(call->m_context, call);
1320
1321     if (fun->m_vtype != TYPE_FUNCTION) {
1322         parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]);
1323         return false;
1324     }
1325
1326     if (!fun->m_next) {
1327         parseerror(parser, "could not determine function return type");
1328         return false;
1329     } else {
1330         ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1331
1332         if (fun->m_flags & AST_FLAG_DEPRECATED) {
1333             if (!fval) {
1334                 return !parsewarning(parser, WARN_DEPRECATED,
1335                         "call to function (which is marked deprecated)\n",
1336                         "-> it has been declared here: %s:%i",
1337                         fun->m_context.file, fun->m_context.line);
1338             }
1339             if (!fval->m_desc.length()) {
1340                 return !parsewarning(parser, WARN_DEPRECATED,
1341                         "call to `%s` (which is marked deprecated)\n"
1342                         "-> `%s` declared here: %s:%i",
1343                         fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line);
1344             }
1345             return !parsewarning(parser, WARN_DEPRECATED,
1346                     "call to `%s` (deprecated: %s)\n"
1347                     "-> `%s` declared here: %s:%i",
1348                     fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file,
1349                     fun->m_context.line);
1350         }
1351
1352         if (fun->m_type_params.size() != paramcount &&
1353             !((fun->m_flags & AST_FLAG_VARIADIC) &&
1354               fun->m_type_params.size() < paramcount))
1355         {
1356             const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many";
1357             if (fval)
1358                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1359                                      "too %s parameters for call to %s: expected %i, got %i\n"
1360                                      " -> `%s` has been declared here: %s:%i",
1361                                      fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount,
1362                                      fval->m_name, fun->m_context.file, (int)fun->m_context.line);
1363             else
1364                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1365                                      "too %s parameters for function call: expected %i, got %i\n"
1366                                      " -> it has been declared here: %s:%i",
1367                                      fewmany, (int)fun->m_type_params.size(), (int)paramcount,
1368                                      fun->m_context.file, (int)fun->m_context.line);
1369         }
1370     }
1371
1372     return true;
1373 }
1374
1375 static bool parser_close_paren(parser_t *parser, shunt *sy)
1376 {
1377     if (sy->ops.empty()) {
1378         parseerror(parser, "unmatched closing paren");
1379         return false;
1380     }
1381
1382     while (sy->ops.size()) {
1383         if (sy->ops.back().isparen) {
1384             if (sy->paren.back() == PAREN_FUNC) {
1385                 sy->paren.pop_back();
1386                 if (!parser_close_call(parser, sy))
1387                     return false;
1388                 break;
1389             }
1390             if (sy->paren.back() == PAREN_EXPR) {
1391                 sy->paren.pop_back();
1392                 if (sy->out.empty()) {
1393                     compile_error(sy->ops.back().ctx, "empty paren expression");
1394                     sy->ops.pop_back();
1395                     return false;
1396                 }
1397                 sy->ops.pop_back();
1398                 break;
1399             }
1400             if (sy->paren.back() == PAREN_INDEX) {
1401                 sy->paren.pop_back();
1402                 // pop off the parenthesis
1403                 sy->ops.pop_back();
1404                 /* then apply the index operator */
1405                 if (!parser_sy_apply_operator(parser, sy))
1406                     return false;
1407                 break;
1408             }
1409             if (sy->paren.back() == PAREN_TERNARY1) {
1410                 sy->paren.back() = PAREN_TERNARY2;
1411                 // pop off the parenthesis
1412                 sy->ops.pop_back();
1413                 break;
1414             }
1415             compile_error(sy->ops.back().ctx, "invalid parenthesis");
1416             return false;
1417         }
1418         if (!parser_sy_apply_operator(parser, sy))
1419             return false;
1420     }
1421     return true;
1422 }
1423
1424 static void parser_reclassify_token(parser_t *parser)
1425 {
1426     size_t i;
1427     if (parser->tok >= TOKEN_START)
1428         return;
1429     for (i = 0; i < operator_count; ++i) {
1430         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1431             parser->tok = TOKEN_OPERATOR;
1432             return;
1433         }
1434     }
1435 }
1436
1437 static ast_expression* parse_vararg_do(parser_t *parser)
1438 {
1439     ast_expression *idx, *out;
1440     ast_value      *typevar;
1441     ast_value      *funtype = parser->function->m_function_type;
1442     lex_ctx_t         ctx     = parser_ctx(parser);
1443
1444     if (!parser->function->m_varargs) {
1445         parseerror(parser, "function has no variable argument list");
1446         return nullptr;
1447     }
1448
1449     if (!parser_next(parser) || parser->tok != '(') {
1450         parseerror(parser, "expected parameter index and type in parenthesis");
1451         return nullptr;
1452     }
1453     if (!parser_next(parser)) {
1454         parseerror(parser, "error parsing parameter index");
1455         return nullptr;
1456     }
1457
1458     idx = parse_expression_leave(parser, true, false, false);
1459     if (!idx)
1460         return nullptr;
1461
1462     if (parser->tok != ',') {
1463         if (parser->tok != ')') {
1464             ast_unref(idx);
1465             parseerror(parser, "expected comma after parameter index");
1466             return nullptr;
1467         }
1468         // vararg piping: ...(start)
1469         out = new ast_argpipe(ctx, idx);
1470         return out;
1471     }
1472
1473     if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1474         ast_unref(idx);
1475         parseerror(parser, "expected typename for vararg");
1476         return nullptr;
1477     }
1478
1479     typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1480     if (!typevar) {
1481         ast_unref(idx);
1482         return nullptr;
1483     }
1484
1485     if (parser->tok != ')') {
1486         ast_unref(idx);
1487         delete typevar;
1488         parseerror(parser, "expected closing paren");
1489         return nullptr;
1490     }
1491
1492     if (funtype->m_varparam &&
1493         !typevar->compareType(*funtype->m_varparam))
1494     {
1495         char ty1[1024];
1496         char ty2[1024];
1497         ast_type_to_string(typevar, ty1, sizeof(ty1));
1498         ast_type_to_string(funtype->m_varparam, ty2, sizeof(ty2));
1499         compile_error(typevar->m_context,
1500                       "function was declared to take varargs of type `%s`, requested type is: %s",
1501                       ty2, ty1);
1502     }
1503
1504     out = ast_array_index::make(ctx, parser->function->m_varargs.get(), idx);
1505     out->adoptType(*typevar);
1506     delete typevar;
1507     return out;
1508 }
1509
1510 static ast_expression* parse_vararg(parser_t *parser)
1511 {
1512     bool           old_noops = parser->lex->flags.noops;
1513
1514     ast_expression *out;
1515
1516     parser->lex->flags.noops = true;
1517     out = parse_vararg_do(parser);
1518
1519     parser->lex->flags.noops = old_noops;
1520     return out;
1521 }
1522
1523 /* not to be exposed */
1524 bool ftepp_predef_exists(const char *name);
1525 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1526 {
1527     if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1528         parser->tok == TOKEN_IDENT &&
1529         !strcmp(parser_tokval(parser), "_"))
1530     {
1531         /* a translatable string */
1532         ast_value *val;
1533
1534         parser->lex->flags.noops = true;
1535         if (!parser_next(parser) || parser->tok != '(') {
1536             parseerror(parser, "use _(\"string\") to create a translatable string constant");
1537             return false;
1538         }
1539         parser->lex->flags.noops = false;
1540         if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1541             parseerror(parser, "expected a constant string in translatable-string extension");
1542             return false;
1543         }
1544         val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1545         if (!val)
1546             return false;
1547         sy->out.push_back(syexp(parser_ctx(parser), val));
1548
1549         if (!parser_next(parser) || parser->tok != ')') {
1550             parseerror(parser, "expected closing paren after translatable string");
1551             return false;
1552         }
1553         return true;
1554     }
1555     else if (parser->tok == TOKEN_DOTS)
1556     {
1557         ast_expression *va;
1558         if (!OPTS_FLAG(VARIADIC_ARGS)) {
1559             parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1560             return false;
1561         }
1562         va = parse_vararg(parser);
1563         if (!va)
1564             return false;
1565         sy->out.push_back(syexp(parser_ctx(parser), va));
1566         return true;
1567     }
1568     else if (parser->tok == TOKEN_FLOATCONST) {
1569         ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1570         if (!val)
1571             return false;
1572         sy->out.push_back(syexp(parser_ctx(parser), val));
1573         return true;
1574     }
1575     else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1576         ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1577         if (!val)
1578             return false;
1579         sy->out.push_back(syexp(parser_ctx(parser), val));
1580         return true;
1581     }
1582     else if (parser->tok == TOKEN_STRINGCONST) {
1583         ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1584         if (!val)
1585             return false;
1586         sy->out.push_back(syexp(parser_ctx(parser), val));
1587         return true;
1588     }
1589     else if (parser->tok == TOKEN_VECTORCONST) {
1590         ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1591         if (!val)
1592             return false;
1593         sy->out.push_back(syexp(parser_ctx(parser), val));
1594         return true;
1595     }
1596     else if (parser->tok == TOKEN_IDENT)
1597     {
1598         const char     *ctoken = parser_tokval(parser);
1599         ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1600         ast_expression *var;
1601         /* a_vector.{x,y,z} */
1602         if (sy->ops.empty() ||
1603             !sy->ops.back().etype ||
1604             operators[sy->ops.back().etype-1].id != opid1('.'))
1605         {
1606             /* When adding more intrinsics, fix the above condition */
1607             prev = nullptr;
1608         }
1609         if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1610         {
1611             var = parser->const_vec[ctoken[0]-'x'];
1612         } else {
1613             var = parser_find_var(parser, parser_tokval(parser));
1614             if (!var)
1615                 var = parser_find_field(parser, parser_tokval(parser));
1616         }
1617         if (!var && with_labels) {
1618             var = parser_find_label(parser, parser_tokval(parser));
1619             if (!with_labels) {
1620                 ast_label *lbl = new ast_label(parser_ctx(parser), parser_tokval(parser), true);
1621                 var = lbl;
1622                 parser->labels.push_back(lbl);
1623             }
1624         }
1625         if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1626             var = parser->m_fold.constgen_string(parser->function->m_name, false);
1627         if (!var) {
1628             /*
1629              * now we try for the real intrinsic hashtable. If the string
1630              * begins with __builtin, we simply skip past it, otherwise we
1631              * use the identifier as is.
1632              */
1633             if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1634                 var = parser->m_intrin.func(parser_tokval(parser));
1635             }
1636
1637             /*
1638              * Try it again, intrin_func deals with the alias method as well
1639              * the first one masks for __builtin though, we emit warning here.
1640              */
1641             if (!var) {
1642                 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1643                     (void)!compile_warning(
1644                         parser_ctx(parser),
1645                         WARN_BUILTINS,
1646                         "using implicitly defined builtin `__builtin_%s' for `%s'",
1647                         parser_tokval(parser),
1648                         parser_tokval(parser)
1649                     );
1650                 }
1651             }
1652
1653
1654             if (!var) {
1655                 /*
1656                  * sometimes people use preprocessing predefs without enabling them
1657                  * i've done this thousands of times already myself.  Lets check for
1658                  * it in the predef table.  And diagnose it better :)
1659                  */
1660                 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1661                     parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1662                     return false;
1663                 }
1664
1665                 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1666                 return false;
1667             }
1668         }
1669         else
1670         {
1671             // promote these to norefs
1672             if (ast_istype(var, ast_value))
1673             {
1674                 ((ast_value *)var)->m_flags |= AST_FLAG_NOREF;
1675             }
1676             else if (ast_istype(var, ast_member))
1677             {
1678                 ast_member *mem = (ast_member *)var;
1679                 if (ast_istype(mem->m_owner, ast_value))
1680                     ((ast_value *)mem->m_owner)->m_flags |= AST_FLAG_NOREF;
1681             }
1682         }
1683         sy->out.push_back(syexp(parser_ctx(parser), var));
1684         return true;
1685     }
1686     parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1687     return false;
1688 }
1689
1690 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1691 {
1692     ast_expression *expr = nullptr;
1693     shunt sy;
1694     bool wantop = false;
1695     /* only warn once about an assignment in a truth value because the current code
1696      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1697      */
1698     bool warn_parenthesis = true;
1699
1700     /* count the parens because an if starts with one, so the
1701      * end of a condition is an unmatched closing paren
1702      */
1703     int ternaries = 0;
1704
1705     memset(&sy, 0, sizeof(sy));
1706
1707     parser->lex->flags.noops = false;
1708
1709     parser_reclassify_token(parser);
1710
1711     while (true)
1712     {
1713         if (parser->tok == TOKEN_TYPENAME) {
1714             parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1715             goto onerr;
1716         }
1717
1718         if (parser->tok == TOKEN_OPERATOR)
1719         {
1720             /* classify the operator */
1721             const oper_info *op;
1722             const oper_info *olast = nullptr;
1723             size_t o;
1724             for (o = 0; o < operator_count; ++o) {
1725                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1726                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1727                     !strcmp(parser_tokval(parser), operators[o].op))
1728                 {
1729                     break;
1730                 }
1731             }
1732             if (o == operator_count) {
1733                 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1734                 goto onerr;
1735             }
1736             /* found an operator */
1737             op = &operators[o];
1738
1739             /* when declaring variables, a comma starts a new variable */
1740             if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1741                 /* fixup the token */
1742                 parser->tok = ',';
1743                 break;
1744             }
1745
1746             /* a colon without a pervious question mark cannot be a ternary */
1747             if (!ternaries && op->id == opid2(':','?')) {
1748                 parser->tok = ':';
1749                 break;
1750             }
1751
1752             if (op->id == opid1(',')) {
1753                 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1754                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1755                 }
1756             }
1757
1758             if (sy.ops.size() && !sy.ops.back().isparen)
1759                 olast = &operators[sy.ops.back().etype-1];
1760
1761             /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1762             while (olast && op->prec < olast->prec)
1763             {
1764                 if (!parser_sy_apply_operator(parser, &sy))
1765                     goto onerr;
1766                 if (sy.ops.size() && !sy.ops.back().isparen)
1767                     olast = &operators[sy.ops.back().etype-1];
1768                 else
1769                     olast = nullptr;
1770             }
1771
1772 #define IsAssignOp(x) (\
1773                 (x) == opid1('=') || \
1774                 (x) == opid2('+','=') || \
1775                 (x) == opid2('-','=') || \
1776                 (x) == opid2('*','=') || \
1777                 (x) == opid2('/','=') || \
1778                 (x) == opid2('%','=') || \
1779                 (x) == opid2('&','=') || \
1780                 (x) == opid2('|','=') || \
1781                 (x) == opid3('&','~','=') \
1782                 )
1783             if (warn_parenthesis) {
1784                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1785                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1786                      (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1787                    )
1788                 {
1789                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1790                     warn_parenthesis = false;
1791                 }
1792
1793                 if (olast && olast->id != op->id) {
1794                     if ((op->id    == opid1('&') || op->id    == opid1('|') || op->id    == opid1('^')) &&
1795                         (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1796                     {
1797                         (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1798                         warn_parenthesis = false;
1799                     }
1800                     else if ((op->id    == opid2('&','&') || op->id    == opid2('|','|')) &&
1801                              (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1802                     {
1803                         (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1804                         warn_parenthesis = false;
1805                     }
1806                 }
1807             }
1808
1809             while (olast && (
1810                     (op->prec < olast->prec) ||
1811                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1812             {
1813                 if (!parser_sy_apply_operator(parser, &sy))
1814                     goto onerr;
1815                 if (sy.ops.size() && !sy.ops.back().isparen)
1816                     olast = &operators[sy.ops.back().etype-1];
1817                 else
1818                     olast = nullptr;
1819             }
1820
1821             if (op->id == opid1('(')) {
1822                 if (wantop) {
1823                     size_t sycount = sy.out.size();
1824                     /* we expected an operator, this is the function-call operator */
1825                     sy.paren.push_back(PAREN_FUNC);
1826                     sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1827                     sy.argc.push_back(0);
1828                 } else {
1829                     sy.paren.push_back(PAREN_EXPR);
1830                     sy.ops.push_back(syparen(parser_ctx(parser), 0));
1831                 }
1832                 wantop = false;
1833             } else if (op->id == opid1('[')) {
1834                 if (!wantop) {
1835                     parseerror(parser, "unexpected array subscript");
1836                     goto onerr;
1837                 }
1838                 sy.paren.push_back(PAREN_INDEX);
1839                 /* push both the operator and the paren, this makes life easier */
1840                 sy.ops.push_back(syop(parser_ctx(parser), op));
1841                 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1842                 wantop = false;
1843             } else if (op->id == opid2('?',':')) {
1844                 sy.ops.push_back(syop(parser_ctx(parser), op));
1845                 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1846                 wantop = false;
1847                 ++ternaries;
1848                 sy.paren.push_back(PAREN_TERNARY1);
1849             } else if (op->id == opid2(':','?')) {
1850                 if (sy.paren.empty()) {
1851                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1852                     goto onerr;
1853                 }
1854                 if (sy.paren.back() != PAREN_TERNARY1) {
1855                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1856                     goto onerr;
1857                 }
1858                 if (!parser_close_paren(parser, &sy))
1859                     goto onerr;
1860                 sy.ops.push_back(syop(parser_ctx(parser), op));
1861                 wantop = false;
1862                 --ternaries;
1863             } else {
1864                 sy.ops.push_back(syop(parser_ctx(parser), op));
1865                 wantop = !!(op->flags & OP_SUFFIX);
1866             }
1867         }
1868         else if (parser->tok == ')') {
1869             while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1870                 if (!parser_sy_apply_operator(parser, &sy))
1871                     goto onerr;
1872             }
1873             if (sy.paren.empty())
1874                 break;
1875             if (wantop) {
1876                 if (sy.paren.back() == PAREN_TERNARY1) {
1877                     parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1878                     goto onerr;
1879                 }
1880                 if (!parser_close_paren(parser, &sy))
1881                     goto onerr;
1882             } else {
1883                 /* must be a function call without parameters */
1884                 if (sy.paren.back() != PAREN_FUNC) {
1885                     parseerror(parser, "closing paren in invalid position");
1886                     goto onerr;
1887                 }
1888                 if (!parser_close_paren(parser, &sy))
1889                     goto onerr;
1890             }
1891             wantop = true;
1892         }
1893         else if (parser->tok == '(') {
1894             parseerror(parser, "internal error: '(' should be classified as operator");
1895             goto onerr;
1896         }
1897         else if (parser->tok == '[') {
1898             parseerror(parser, "internal error: '[' should be classified as operator");
1899             goto onerr;
1900         }
1901         else if (parser->tok == ']') {
1902             while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1903                 if (!parser_sy_apply_operator(parser, &sy))
1904                     goto onerr;
1905             }
1906             if (sy.paren.empty())
1907                 break;
1908             if (sy.paren.back() != PAREN_INDEX) {
1909                 parseerror(parser, "mismatched parentheses, unexpected ']'");
1910                 goto onerr;
1911             }
1912             if (!parser_close_paren(parser, &sy))
1913                 goto onerr;
1914             wantop = true;
1915         }
1916         else if (!wantop) {
1917             if (!parse_sya_operand(parser, &sy, with_labels))
1918                 goto onerr;
1919             wantop = true;
1920         }
1921         else {
1922             /* in this case we might want to allow constant string concatenation */
1923             bool concatenated = false;
1924             if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1925                 ast_expression *lexpr = sy.out.back().out;
1926                 if (ast_istype(lexpr, ast_value)) {
1927                     ast_value *last = (ast_value*)lexpr;
1928                     if (last->m_isimm == true && last->m_cvq == CV_CONST &&
1929                         last->m_hasvalue && last->m_vtype == TYPE_STRING)
1930                     {
1931                         char *newstr = nullptr;
1932                         util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser));
1933                         sy.out.back().out = parser->m_fold.constgen_string(newstr, false);
1934                         mem_d(newstr);
1935                         concatenated = true;
1936                     }
1937                 }
1938             }
1939             if (!concatenated) {
1940                 parseerror(parser, "expected operator or end of statement");
1941                 goto onerr;
1942             }
1943         }
1944
1945         if (!parser_next(parser)) {
1946             goto onerr;
1947         }
1948         if (parser->tok == ';' ||
1949             ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1950             (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1951         {
1952             break;
1953         }
1954     }
1955
1956     while (sy.ops.size()) {
1957         if (!parser_sy_apply_operator(parser, &sy))
1958             goto onerr;
1959     }
1960
1961     parser->lex->flags.noops = true;
1962     if (sy.out.size() != 1) {
1963         parseerror(parser, "expression expected");
1964         expr = nullptr;
1965     } else
1966         expr = sy.out[0].out;
1967     if (sy.paren.size()) {
1968         parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1969         return nullptr;
1970     }
1971     return expr;
1972
1973 onerr:
1974     parser->lex->flags.noops = true;
1975     for (auto &it : sy.out)
1976         if (it.out) ast_unref(it.out);
1977     return nullptr;
1978 }
1979
1980 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1981 {
1982     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1983     if (!e)
1984         return nullptr;
1985     if (parser->tok != ';') {
1986         parseerror(parser, "semicolon expected after expression");
1987         ast_unref(e);
1988         return nullptr;
1989     }
1990     if (!parser_next(parser)) {
1991         ast_unref(e);
1992         return nullptr;
1993     }
1994     return e;
1995 }
1996
1997 static void parser_enterblock(parser_t *parser)
1998 {
1999     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2000     vec_push(parser->_blocklocals, vec_size(parser->_locals));
2001     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2002     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2003     vec_push(parser->_block_ctx, parser_ctx(parser));
2004 }
2005
2006 static bool parser_leaveblock(parser_t *parser)
2007 {
2008     bool   rv = true;
2009     size_t locals, typedefs;
2010
2011     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2012         parseerror(parser, "internal error: parser_leaveblock with no block");
2013         return false;
2014     }
2015
2016     util_htdel(vec_last(parser->variables));
2017
2018     vec_pop(parser->variables);
2019     if (!vec_size(parser->_blocklocals)) {
2020         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2021         return false;
2022     }
2023
2024     locals = vec_last(parser->_blocklocals);
2025     vec_pop(parser->_blocklocals);
2026     while (vec_size(parser->_locals) != locals)
2027         vec_pop(parser->_locals);
2028
2029     typedefs = vec_last(parser->_blocktypedefs);
2030     while (vec_size(parser->_typedefs) != typedefs) {
2031         delete vec_last(parser->_typedefs);
2032         vec_pop(parser->_typedefs);
2033     }
2034     util_htdel(vec_last(parser->typedefs));
2035     vec_pop(parser->typedefs);
2036
2037     vec_pop(parser->_block_ctx);
2038
2039     return rv;
2040 }
2041
2042 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2043 {
2044     vec_push(parser->_locals, e);
2045     util_htset(vec_last(parser->variables), name, (void*)e);
2046 }
2047 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e) {
2048     return parser_addlocal(parser, name.c_str(), e);
2049 }
2050
2051 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2052 {
2053     parser->globals.push_back(e);
2054     util_htset(parser->htglobals, name, e);
2055 }
2056 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e) {
2057     return parser_addglobal(parser, name.c_str(), e);
2058 }
2059
2060 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2061 {
2062     bool       ifnot = false;
2063     ast_unary *unary;
2064     ast_expression *prev;
2065
2066     if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) {
2067         char ty[1024];
2068         ast_type_to_string(cond, ty, sizeof(ty));
2069         compile_error(cond->m_context, "invalid type for if() condition: %s", ty);
2070     }
2071
2072     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING)
2073     {
2074         prev = cond;
2075         cond = ast_unary::make(cond->m_context, INSTR_NOT_S, cond);
2076         if (!cond) {
2077             ast_unref(prev);
2078             parseerror(parser, "internal error: failed to process condition");
2079             return nullptr;
2080         }
2081         ifnot = !ifnot;
2082     }
2083     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR)
2084     {
2085         /* vector types need to be cast to true booleans */
2086         ast_binary *bin = (ast_binary*)cond;
2087         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR))
2088         {
2089             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2090             prev = cond;
2091             cond = ast_unary::make(cond->m_context, INSTR_NOT_V, cond);
2092             if (!cond) {
2093                 ast_unref(prev);
2094                 parseerror(parser, "internal error: failed to process condition");
2095                 return nullptr;
2096             }
2097             ifnot = !ifnot;
2098         }
2099     }
2100
2101     unary = (ast_unary*)cond;
2102     /* ast_istype dereferences cond, should test here for safety */
2103     while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F)
2104     {
2105         cond = unary->m_operand;
2106         unary->m_operand = nullptr;
2107         delete unary;
2108         ifnot = !ifnot;
2109         unary = (ast_unary*)cond;
2110     }
2111
2112     if (!cond)
2113         parseerror(parser, "internal error: failed to process condition");
2114
2115     if (ifnot) *_ifnot = !*_ifnot;
2116     return cond;
2117 }
2118
2119 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2120 {
2121     ast_ifthen *ifthen;
2122     ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2123     bool ifnot = false;
2124
2125     lex_ctx_t ctx = parser_ctx(parser);
2126
2127     (void)block; /* not touching */
2128
2129     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2130     if (!parser_next(parser)) {
2131         parseerror(parser, "expected condition or 'not'");
2132         return false;
2133     }
2134     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2135         ifnot = true;
2136         if (!parser_next(parser)) {
2137             parseerror(parser, "expected condition in parenthesis");
2138             return false;
2139         }
2140     }
2141     if (parser->tok != '(') {
2142         parseerror(parser, "expected 'if' condition in parenthesis");
2143         return false;
2144     }
2145     /* parse into the expression */
2146     if (!parser_next(parser)) {
2147         parseerror(parser, "expected 'if' condition after opening paren");
2148         return false;
2149     }
2150     /* parse the condition */
2151     cond = parse_expression_leave(parser, false, true, false);
2152     if (!cond)
2153         return false;
2154     /* closing paren */
2155     if (parser->tok != ')') {
2156         parseerror(parser, "expected closing paren after 'if' condition");
2157         ast_unref(cond);
2158         return false;
2159     }
2160     /* parse into the 'then' branch */
2161     if (!parser_next(parser)) {
2162         parseerror(parser, "expected statement for on-true branch of 'if'");
2163         ast_unref(cond);
2164         return false;
2165     }
2166     if (!parse_statement_or_block(parser, &ontrue)) {
2167         ast_unref(cond);
2168         return false;
2169     }
2170     if (!ontrue)
2171         ontrue = new ast_block(parser_ctx(parser));
2172     /* check for an else */
2173     if (!strcmp(parser_tokval(parser), "else")) {
2174         /* parse into the 'else' branch */
2175         if (!parser_next(parser)) {
2176             parseerror(parser, "expected on-false branch after 'else'");
2177             delete ontrue;
2178             ast_unref(cond);
2179             return false;
2180         }
2181         if (!parse_statement_or_block(parser, &onfalse)) {
2182             delete ontrue;
2183             ast_unref(cond);
2184             return false;
2185         }
2186     }
2187
2188     cond = process_condition(parser, cond, &ifnot);
2189     if (!cond) {
2190         if (ontrue)  delete ontrue;
2191         if (onfalse) delete onfalse;
2192         return false;
2193     }
2194
2195     if (ifnot)
2196         ifthen = new ast_ifthen(ctx, cond, onfalse, ontrue);
2197     else
2198         ifthen = new ast_ifthen(ctx, cond, ontrue, onfalse);
2199     *out = ifthen;
2200     return true;
2201 }
2202
2203 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2204 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2205 {
2206     bool rv;
2207     char *label = nullptr;
2208
2209     /* skip the 'while' and get the body */
2210     if (!parser_next(parser)) {
2211         if (OPTS_FLAG(LOOP_LABELS))
2212             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2213         else
2214             parseerror(parser, "expected 'while' condition in parenthesis");
2215         return false;
2216     }
2217
2218     if (parser->tok == ':') {
2219         if (!OPTS_FLAG(LOOP_LABELS))
2220             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2221         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2222             parseerror(parser, "expected loop label");
2223             return false;
2224         }
2225         label = util_strdup(parser_tokval(parser));
2226         if (!parser_next(parser)) {
2227             mem_d(label);
2228             parseerror(parser, "expected 'while' condition in parenthesis");
2229             return false;
2230         }
2231     }
2232
2233     if (parser->tok != '(') {
2234         parseerror(parser, "expected 'while' condition in parenthesis");
2235         return false;
2236     }
2237
2238     parser->breaks.push_back(label);
2239     parser->continues.push_back(label);
2240
2241     rv = parse_while_go(parser, block, out);
2242     if (label)
2243         mem_d(label);
2244     if (parser->breaks.back() != label || parser->continues.back() != label) {
2245         parseerror(parser, "internal error: label stack corrupted");
2246         rv = false;
2247         delete *out;
2248         *out = nullptr;
2249     }
2250     else {
2251         parser->breaks.pop_back();
2252         parser->continues.pop_back();
2253     }
2254     return rv;
2255 }
2256
2257 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2258 {
2259     ast_loop *aloop;
2260     ast_expression *cond, *ontrue;
2261
2262     bool ifnot = false;
2263
2264     lex_ctx_t ctx = parser_ctx(parser);
2265
2266     (void)block; /* not touching */
2267
2268     /* parse into the expression */
2269     if (!parser_next(parser)) {
2270         parseerror(parser, "expected 'while' condition after opening paren");
2271         return false;
2272     }
2273     /* parse the condition */
2274     cond = parse_expression_leave(parser, false, true, false);
2275     if (!cond)
2276         return false;
2277     /* closing paren */
2278     if (parser->tok != ')') {
2279         parseerror(parser, "expected closing paren after 'while' condition");
2280         ast_unref(cond);
2281         return false;
2282     }
2283     /* parse into the 'then' branch */
2284     if (!parser_next(parser)) {
2285         parseerror(parser, "expected while-loop body");
2286         ast_unref(cond);
2287         return false;
2288     }
2289     if (!parse_statement_or_block(parser, &ontrue)) {
2290         ast_unref(cond);
2291         return false;
2292     }
2293
2294     cond = process_condition(parser, cond, &ifnot);
2295     if (!cond) {
2296         ast_unref(ontrue);
2297         return false;
2298     }
2299     aloop = new ast_loop(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2300     *out = aloop;
2301     return true;
2302 }
2303
2304 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2305 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2306 {
2307     bool rv;
2308     char *label = nullptr;
2309
2310     /* skip the 'do' and get the body */
2311     if (!parser_next(parser)) {
2312         if (OPTS_FLAG(LOOP_LABELS))
2313             parseerror(parser, "expected loop label or body");
2314         else
2315             parseerror(parser, "expected loop body");
2316         return false;
2317     }
2318
2319     if (parser->tok == ':') {
2320         if (!OPTS_FLAG(LOOP_LABELS))
2321             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2322         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2323             parseerror(parser, "expected loop label");
2324             return false;
2325         }
2326         label = util_strdup(parser_tokval(parser));
2327         if (!parser_next(parser)) {
2328             mem_d(label);
2329             parseerror(parser, "expected loop body");
2330             return false;
2331         }
2332     }
2333
2334     parser->breaks.push_back(label);
2335     parser->continues.push_back(label);
2336
2337     rv = parse_dowhile_go(parser, block, out);
2338     if (label)
2339         mem_d(label);
2340     if (parser->breaks.back() != label || parser->continues.back() != label) {
2341         parseerror(parser, "internal error: label stack corrupted");
2342         rv = false;
2343         delete *out;
2344         *out = nullptr;
2345     }
2346     else {
2347         parser->breaks.pop_back();
2348         parser->continues.pop_back();
2349     }
2350     return rv;
2351 }
2352
2353 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2354 {
2355     ast_loop *aloop;
2356     ast_expression *cond, *ontrue;
2357
2358     bool ifnot = false;
2359
2360     lex_ctx_t ctx = parser_ctx(parser);
2361
2362     (void)block; /* not touching */
2363
2364     if (!parse_statement_or_block(parser, &ontrue))
2365         return false;
2366
2367     /* expect the "while" */
2368     if (parser->tok != TOKEN_KEYWORD ||
2369         strcmp(parser_tokval(parser), "while"))
2370     {
2371         parseerror(parser, "expected 'while' and condition");
2372         delete ontrue;
2373         return false;
2374     }
2375
2376     /* skip the 'while' and check for opening paren */
2377     if (!parser_next(parser) || parser->tok != '(') {
2378         parseerror(parser, "expected 'while' condition in parenthesis");
2379         delete ontrue;
2380         return false;
2381     }
2382     /* parse into the expression */
2383     if (!parser_next(parser)) {
2384         parseerror(parser, "expected 'while' condition after opening paren");
2385         delete ontrue;
2386         return false;
2387     }
2388     /* parse the condition */
2389     cond = parse_expression_leave(parser, false, true, false);
2390     if (!cond)
2391         return false;
2392     /* closing paren */
2393     if (parser->tok != ')') {
2394         parseerror(parser, "expected closing paren after 'while' condition");
2395         delete ontrue;
2396         ast_unref(cond);
2397         return false;
2398     }
2399     /* parse on */
2400     if (!parser_next(parser) || parser->tok != ';') {
2401         parseerror(parser, "expected semicolon after condition");
2402         delete ontrue;
2403         ast_unref(cond);
2404         return false;
2405     }
2406
2407     if (!parser_next(parser)) {
2408         parseerror(parser, "parse error");
2409         delete ontrue;
2410         ast_unref(cond);
2411         return false;
2412     }
2413
2414     cond = process_condition(parser, cond, &ifnot);
2415     if (!cond) {
2416         delete ontrue;
2417         return false;
2418     }
2419     aloop = new ast_loop(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2420     *out = aloop;
2421     return true;
2422 }
2423
2424 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2425 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2426 {
2427     bool rv;
2428     char *label = nullptr;
2429
2430     /* skip the 'for' and check for opening paren */
2431     if (!parser_next(parser)) {
2432         if (OPTS_FLAG(LOOP_LABELS))
2433             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2434         else
2435             parseerror(parser, "expected 'for' expressions in parenthesis");
2436         return false;
2437     }
2438
2439     if (parser->tok == ':') {
2440         if (!OPTS_FLAG(LOOP_LABELS))
2441             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2442         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2443             parseerror(parser, "expected loop label");
2444             return false;
2445         }
2446         label = util_strdup(parser_tokval(parser));
2447         if (!parser_next(parser)) {
2448             mem_d(label);
2449             parseerror(parser, "expected 'for' expressions in parenthesis");
2450             return false;
2451         }
2452     }
2453
2454     if (parser->tok != '(') {
2455         parseerror(parser, "expected 'for' expressions in parenthesis");
2456         return false;
2457     }
2458
2459     parser->breaks.push_back(label);
2460     parser->continues.push_back(label);
2461
2462     rv = parse_for_go(parser, block, out);
2463     if (label)
2464         mem_d(label);
2465     if (parser->breaks.back() != label || parser->continues.back() != label) {
2466         parseerror(parser, "internal error: label stack corrupted");
2467         rv = false;
2468         delete *out;
2469         *out = nullptr;
2470     }
2471     else {
2472         parser->breaks.pop_back();
2473         parser->continues.pop_back();
2474     }
2475     return rv;
2476 }
2477 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2478 {
2479     ast_loop       *aloop;
2480     ast_expression *initexpr, *cond, *increment, *ontrue;
2481     ast_value      *typevar;
2482
2483     bool ifnot  = false;
2484
2485     lex_ctx_t ctx = parser_ctx(parser);
2486
2487     parser_enterblock(parser);
2488
2489     initexpr  = nullptr;
2490     cond      = nullptr;
2491     increment = nullptr;
2492     ontrue    = nullptr;
2493
2494     /* parse into the expression */
2495     if (!parser_next(parser)) {
2496         parseerror(parser, "expected 'for' initializer after opening paren");
2497         goto onerr;
2498     }
2499
2500     typevar = nullptr;
2501     if (parser->tok == TOKEN_IDENT)
2502         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2503
2504     if (typevar || parser->tok == TOKEN_TYPENAME) {
2505         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2506             goto onerr;
2507     }
2508     else if (parser->tok != ';')
2509     {
2510         initexpr = parse_expression_leave(parser, false, false, false);
2511         if (!initexpr)
2512             goto onerr;
2513         /* move on to condition */
2514         if (parser->tok != ';') {
2515             parseerror(parser, "expected semicolon after for-loop initializer");
2516             goto onerr;
2517         }
2518         if (!parser_next(parser)) {
2519             parseerror(parser, "expected for-loop condition");
2520             goto onerr;
2521         }
2522     } else if (!parser_next(parser)) {
2523         parseerror(parser, "expected for-loop condition");
2524         goto onerr;
2525     }
2526
2527     /* parse the condition */
2528     if (parser->tok != ';') {
2529         cond = parse_expression_leave(parser, false, true, false);
2530         if (!cond)
2531             goto onerr;
2532     }
2533     /* move on to incrementor */
2534     if (parser->tok != ';') {
2535         parseerror(parser, "expected semicolon after for-loop initializer");
2536         goto onerr;
2537     }
2538     if (!parser_next(parser)) {
2539         parseerror(parser, "expected for-loop condition");
2540         goto onerr;
2541     }
2542
2543     /* parse the incrementor */
2544     if (parser->tok != ')') {
2545         lex_ctx_t condctx = parser_ctx(parser);
2546         increment = parse_expression_leave(parser, false, false, false);
2547         if (!increment)
2548             goto onerr;
2549         if (!increment->m_side_effects) {
2550             if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2551                 goto onerr;
2552         }
2553     }
2554
2555     /* closing paren */
2556     if (parser->tok != ')') {
2557         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2558         goto onerr;
2559     }
2560     /* parse into the 'then' branch */
2561     if (!parser_next(parser)) {
2562         parseerror(parser, "expected for-loop body");
2563         goto onerr;
2564     }
2565     if (!parse_statement_or_block(parser, &ontrue))
2566         goto onerr;
2567
2568     if (cond) {
2569         cond = process_condition(parser, cond, &ifnot);
2570         if (!cond)
2571             goto onerr;
2572     }
2573     aloop = new ast_loop(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2574     *out = aloop;
2575
2576     if (!parser_leaveblock(parser)) {
2577         delete aloop;
2578         return false;
2579     }
2580     return true;
2581 onerr:
2582     if (initexpr)  ast_unref(initexpr);
2583     if (cond)      ast_unref(cond);
2584     if (increment) ast_unref(increment);
2585     (void)!parser_leaveblock(parser);
2586     return false;
2587 }
2588
2589 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2590 {
2591     ast_expression *exp      = nullptr;
2592     ast_expression *var      = nullptr;
2593     ast_return     *ret      = nullptr;
2594     ast_value      *retval   = parser->function->m_return_value;
2595     ast_value      *expected = parser->function->m_function_type;
2596
2597     lex_ctx_t ctx = parser_ctx(parser);
2598
2599     (void)block; /* not touching */
2600
2601     if (!parser_next(parser)) {
2602         parseerror(parser, "expected return expression");
2603         return false;
2604     }
2605
2606     /* return assignments */
2607     if (parser->tok == '=') {
2608         if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2609             parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2610             return false;
2611         }
2612
2613         if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) {
2614             char ty1[1024];
2615             ast_type_to_string(expected->m_next, ty1, sizeof(ty1));
2616             parseerror(parser, "invalid return type: `%s'", ty1);
2617             return false;
2618         }
2619
2620         if (!parser_next(parser)) {
2621             parseerror(parser, "expected return assignment expression");
2622             return false;
2623         }
2624
2625         if (!(exp = parse_expression_leave(parser, false, false, false)))
2626             return false;
2627
2628         /* prepare the return value */
2629         if (!retval) {
2630             retval = new ast_value(ctx, "#LOCAL_RETURN", TYPE_VOID);
2631             retval->adoptType(*expected->m_next);
2632             parser->function->m_return_value = retval;
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 **values = nullptr;
3626     ast_value  *var = nullptr;
3627     ast_value  *asvalue;
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             goto onerror;
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             goto onerror;
3679         }
3680
3681         var = new ast_value(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3682         vec_push(values, 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             goto onerror;
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             goto onerror;
3702         }
3703
3704         if (!parser_next(parser)) {
3705             parseerror(parser, "expected expression after `=`");
3706             goto onerror;
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             goto onerror;
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             goto onerror;
3723         }
3724     }
3725
3726     /* patch them all (for reversed attribute) */
3727     if (reverse) {
3728         size_t i;
3729         for (i = 0; i < vec_size(values); i++)
3730             values[i]->m_constval.vfloat = vec_size(values) - i - 1;
3731     }
3732
3733     if (parser->tok != '}') {
3734         parseerror(parser, "internal error: breaking without `}`");
3735         goto onerror;
3736     }
3737
3738     if (!parser_next(parser) || parser->tok != ';') {
3739         parseerror(parser, "expected semicolon after enumeration");
3740         goto onerror;
3741     }
3742
3743     if (!parser_next(parser)) {
3744         parseerror(parser, "parse error after enumeration");
3745         goto onerror;
3746     }
3747
3748     vec_free(values);
3749     return true;
3750
3751 onerror:
3752     vec_free(values);
3753     return false;
3754 }
3755
3756 static bool parse_block_into(parser_t *parser, ast_block *block)
3757 {
3758     bool   retval = true;
3759
3760     parser_enterblock(parser);
3761
3762     if (!parser_next(parser)) { /* skip the '{' */
3763         parseerror(parser, "expected function body");
3764         goto cleanup;
3765     }
3766
3767     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3768     {
3769         ast_expression *expr = nullptr;
3770         if (parser->tok == '}')
3771             break;
3772
3773         if (!parse_statement(parser, block, &expr, false)) {
3774             /* parseerror(parser, "parse error"); */
3775             block = nullptr;
3776             goto cleanup;
3777         }
3778         if (!expr)
3779             continue;
3780         if (!block->addExpr(expr)) {
3781             delete block;
3782             block = nullptr;
3783             goto cleanup;
3784         }
3785     }
3786
3787     if (parser->tok != '}') {
3788         block = nullptr;
3789     } else {
3790         (void)parser_next(parser);
3791     }
3792
3793 cleanup:
3794     if (!parser_leaveblock(parser))
3795         retval = false;
3796     return retval && !!block;
3797 }
3798
3799 static ast_block* parse_block(parser_t *parser)
3800 {
3801     ast_block *block;
3802     block = new ast_block(parser_ctx(parser));
3803     if (!block)
3804         return nullptr;
3805     if (!parse_block_into(parser, block)) {
3806         delete block;
3807         return nullptr;
3808     }
3809     return block;
3810 }
3811
3812 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3813 {
3814     if (parser->tok == '{') {
3815         *out = parse_block(parser);
3816         return !!*out;
3817     }
3818     return parse_statement(parser, nullptr, out, false);
3819 }
3820
3821 static bool create_vector_members(ast_value *var, ast_member **me)
3822 {
3823     size_t i;
3824     size_t len = var->m_name.length();
3825
3826     for (i = 0; i < 3; ++i) {
3827         char *name = (char*)mem_a(len+3);
3828         memcpy(name, var->m_name.c_str(), len);
3829         name[len+0] = '_';
3830         name[len+1] = 'x'+i;
3831         name[len+2] = 0;
3832         me[i] = ast_member::make(var->m_context, var, i, name);
3833         mem_d(name);
3834         if (!me[i])
3835             break;
3836     }
3837     if (i == 3)
3838         return true;
3839
3840     /* unroll */
3841     do { delete me[--i]; } while(i);
3842     return false;
3843 }
3844
3845 static bool parse_function_body(parser_t *parser, ast_value *var)
3846 {
3847     ast_block *block = nullptr;
3848     ast_function *func;
3849     ast_function *old;
3850
3851     ast_expression *framenum  = nullptr;
3852     ast_expression *nextthink = nullptr;
3853     /* None of the following have to be deleted */
3854     ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3855     ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3856     bool has_frame_think;
3857
3858     bool retval = true;
3859
3860     has_frame_think = false;
3861     old = parser->function;
3862
3863     if (var->m_flags & AST_FLAG_ALIAS) {
3864         parseerror(parser, "function aliases cannot have bodies");
3865         return false;
3866     }
3867
3868     if (parser->gotos.size() || parser->labels.size()) {
3869         parseerror(parser, "gotos/labels leaking");
3870         return false;
3871     }
3872
3873     if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) {
3874         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3875                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3876         {
3877             return false;
3878         }
3879     }
3880
3881     if (parser->tok == '[') {
3882         /* got a frame definition: [ framenum, nextthink ]
3883          * this translates to:
3884          * self.frame = framenum;
3885          * self.nextthink = time + 0.1;
3886          * self.think = nextthink;
3887          */
3888         nextthink = nullptr;
3889
3890         fld_think     = parser_find_field(parser, "think");
3891         fld_nextthink = parser_find_field(parser, "nextthink");
3892         fld_frame     = parser_find_field(parser, "frame");
3893         if (!fld_think || !fld_nextthink || !fld_frame) {
3894             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3895             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3896             return false;
3897         }
3898         gbl_time      = parser_find_global(parser, "time");
3899         gbl_self      = parser_find_global(parser, "self");
3900         if (!gbl_time || !gbl_self) {
3901             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3902             parseerror(parser, "please declare the following globals: `time`, `self`");
3903             return false;
3904         }
3905
3906         if (!parser_next(parser))
3907             return false;
3908
3909         framenum = parse_expression_leave(parser, true, false, false);
3910         if (!framenum) {
3911             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3912             return false;
3913         }
3914         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) {
3915             ast_unref(framenum);
3916             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3917             return false;
3918         }
3919
3920         if (parser->tok != ',') {
3921             ast_unref(framenum);
3922             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3923             parseerror(parser, "Got a %i\n", parser->tok);
3924             return false;
3925         }
3926
3927         if (!parser_next(parser)) {
3928             ast_unref(framenum);
3929             return false;
3930         }
3931
3932         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3933         {
3934             /* qc allows the use of not-yet-declared functions here
3935              * - this automatically creates a prototype */
3936             ast_value      *thinkfunc;
3937             ast_expression *functype = fld_think->m_next;
3938
3939             thinkfunc = new ast_value(parser_ctx(parser), parser_tokval(parser), functype->m_vtype);
3940             if (!thinkfunc) { /* || !thinkfunc->adoptType(*functype)*/
3941                 ast_unref(framenum);
3942                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3943                 return false;
3944             }
3945             thinkfunc->adoptType(*functype);
3946
3947             if (!parser_next(parser)) {
3948                 ast_unref(framenum);
3949                 delete thinkfunc;
3950                 return false;
3951             }
3952
3953             parser_addglobal(parser, thinkfunc->m_name, thinkfunc);
3954
3955             nextthink = thinkfunc;
3956
3957         } else {
3958             nextthink = parse_expression_leave(parser, true, false, false);
3959             if (!nextthink) {
3960                 ast_unref(framenum);
3961                 parseerror(parser, "expected a think-function in [frame,think] notation");
3962                 return false;
3963             }
3964         }
3965
3966         if (!ast_istype(nextthink, ast_value)) {
3967             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3968             retval = false;
3969         }
3970
3971         if (retval && parser->tok != ']') {
3972             parseerror(parser, "expected closing `]` for [frame,think] notation");
3973             retval = false;
3974         }
3975
3976         if (retval && !parser_next(parser)) {
3977             retval = false;
3978         }
3979
3980         if (retval && parser->tok != '{') {
3981             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3982             retval = false;
3983         }
3984
3985         if (!retval) {
3986             ast_unref(nextthink);
3987             ast_unref(framenum);
3988             return false;
3989         }
3990
3991         has_frame_think = true;
3992     }
3993
3994     block = new ast_block(parser_ctx(parser));
3995     if (!block) {
3996         parseerror(parser, "failed to allocate block");
3997         if (has_frame_think) {
3998             ast_unref(nextthink);
3999             ast_unref(framenum);
4000         }
4001         return false;
4002     }
4003
4004     if (has_frame_think) {
4005         if (!OPTS_FLAG(EMULATE_STATE)) {
4006             ast_state *state_op = new ast_state(parser_ctx(parser), framenum, nextthink);
4007             if (!block->addExpr(state_op)) {
4008                 parseerror(parser, "failed to generate state op for [frame,think]");
4009                 ast_unref(nextthink);
4010                 ast_unref(framenum);
4011                 delete block;
4012                 return false;
4013             }
4014         } else {
4015             /* emulate OP_STATE in code: */
4016             lex_ctx_t ctx;
4017             ast_expression *self_frame;
4018             ast_expression *self_nextthink;
4019             ast_expression *self_think;
4020             ast_expression *time_plus_1;
4021             ast_store *store_frame;
4022             ast_store *store_nextthink;
4023             ast_store *store_think;
4024
4025             float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
4026
4027             ctx = parser_ctx(parser);
4028             self_frame     = new ast_entfield(ctx, gbl_self, fld_frame);
4029             self_nextthink = new ast_entfield(ctx, gbl_self, fld_nextthink);
4030             self_think     = new ast_entfield(ctx, gbl_self, fld_think);
4031
4032             time_plus_1    = new ast_binary(ctx, INSTR_ADD_F,
4033                              gbl_time, parser->m_fold.constgen_float(frame_delta, false));
4034
4035             if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4036                 if (self_frame)     delete self_frame;
4037                 if (self_nextthink) delete self_nextthink;
4038                 if (self_think)     delete self_think;
4039                 if (time_plus_1)    delete time_plus_1;
4040                 retval = false;
4041             }
4042
4043             if (retval)
4044             {
4045                 store_frame     = new ast_store(ctx, INSTR_STOREP_F,   self_frame,     framenum);
4046                 store_nextthink = new ast_store(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
4047                 store_think     = new ast_store(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
4048
4049                 if (!store_frame) {
4050                     delete self_frame;
4051                     retval = false;
4052                 }
4053                 if (!store_nextthink) {
4054                     delete self_nextthink;
4055                     retval = false;
4056                 }
4057                 if (!store_think) {
4058                     delete self_think;
4059                     retval = false;
4060                 }
4061                 if (!retval) {
4062                     if (store_frame)     delete store_frame;
4063                     if (store_nextthink) delete store_nextthink;
4064                     if (store_think)     delete store_think;
4065                     retval = false;
4066                 }
4067                 if (!block->addExpr(store_frame) ||
4068                     !block->addExpr(store_nextthink) ||
4069                     !block->addExpr(store_think))
4070                 {
4071                     retval = false;
4072                 }
4073             }
4074
4075             if (!retval) {
4076                 parseerror(parser, "failed to generate code for [frame,think]");
4077                 ast_unref(nextthink);
4078                 ast_unref(framenum);
4079                 delete block;
4080                 return false;
4081             }
4082         }
4083     }
4084
4085     if (var->m_hasvalue) {
4086         if (!(var->m_flags & AST_FLAG_ACCUMULATE)) {
4087             parseerror(parser, "function `%s` declared with multiple bodies", var->m_name);
4088             delete block;
4089             goto enderr;
4090         }
4091         func = var->m_constval.vfunc;
4092
4093         if (!func) {
4094             parseerror(parser, "internal error: nullptr function: `%s`", var->m_name);
4095             delete block;
4096             goto enderr;
4097         }
4098     } else {
4099         func = ast_function::make(var->m_context, var->m_name, var);
4100
4101         if (!func) {
4102             parseerror(parser, "failed to allocate function for `%s`", var->m_name);
4103             delete block;
4104             goto enderr;
4105         }
4106         parser->functions.push_back(func);
4107     }
4108
4109     parser_enterblock(parser);
4110
4111     for (auto &it : var->m_type_params) {
4112         size_t e;
4113         ast_member *me[3];
4114
4115         if (it->m_vtype != TYPE_VECTOR &&
4116             (it->m_vtype != TYPE_FIELD ||
4117              it->m_next->m_vtype != TYPE_VECTOR))
4118         {
4119             continue;
4120         }
4121
4122         if (!create_vector_members(it.get(), me)) {
4123             delete block;
4124             goto enderrfn;
4125         }
4126
4127         for (e = 0; e < 3; ++e) {
4128             parser_addlocal(parser, me[e]->m_name, me[e]);
4129             block->collect(me[e]);
4130         }
4131     }
4132
4133     if (var->m_argcounter && !func->m_argc) {
4134         ast_value *argc = new ast_value(var->m_context, var->m_argcounter, TYPE_FLOAT);
4135         parser_addlocal(parser, argc->m_name, argc);
4136         func->m_argc.reset(argc);
4137     }
4138
4139     if (OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC && !func->m_varargs) {
4140         char name[1024];
4141         ast_value *varargs = new ast_value(var->m_context, "reserved:va_args", TYPE_ARRAY);
4142         varargs->m_flags |= AST_FLAG_IS_VARARG;
4143         varargs->m_next = new ast_value(var->m_context, "", TYPE_VECTOR);
4144         varargs->m_count = 0;
4145         util_snprintf(name, sizeof(name), "%s##va##SET", var->m_name.c_str());
4146         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4147             delete varargs;
4148             delete block;
4149             goto enderrfn;
4150         }
4151         util_snprintf(name, sizeof(name), "%s##va##GET", var->m_name.c_str());
4152         if (!parser_create_array_getter_proto(parser, varargs, varargs->m_next, name)) {
4153             delete varargs;
4154             delete block;
4155             goto enderrfn;
4156         }
4157         func->m_varargs.reset(varargs);
4158         func->m_fixedparams = (ast_value*)parser->m_fold.constgen_float(var->m_type_params.size(), false);
4159     }
4160
4161     parser->function = func;
4162     if (!parse_block_into(parser, block)) {
4163         delete block;
4164         goto enderrfn;
4165     }
4166
4167     func->m_blocks.emplace_back(block);
4168
4169     parser->function = old;
4170     if (!parser_leaveblock(parser))
4171         retval = false;
4172     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4173         parseerror(parser, "internal error: local scopes left");
4174         retval = false;
4175     }
4176
4177     if (parser->tok == ';')
4178         return parser_next(parser);
4179     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4180         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4181     return retval;
4182
4183 enderrfn:
4184     (void)!parser_leaveblock(parser);
4185     parser->functions.pop_back();
4186     delete func;
4187     var->m_constval.vfunc = nullptr;
4188
4189 enderr:
4190     parser->function = old;
4191     return false;
4192 }
4193
4194 static ast_expression *array_accessor_split(
4195     parser_t  *parser,
4196     ast_value *array,
4197     ast_value *index,
4198     size_t     middle,
4199     ast_expression *left,
4200     ast_expression *right
4201     )
4202 {
4203     ast_ifthen *ifthen;
4204     ast_binary *cmp;
4205
4206     lex_ctx_t ctx = array->m_context;
4207
4208     if (!left || !right) {
4209         if (left)  delete left;
4210         if (right) delete right;
4211         return nullptr;
4212     }
4213
4214     cmp = new ast_binary(ctx, INSTR_LT,
4215                          index,
4216                          parser->m_fold.constgen_float(middle, false));
4217     if (!cmp) {
4218         delete left;
4219         delete right;
4220         parseerror(parser, "internal error: failed to create comparison for array setter");
4221         return nullptr;
4222     }
4223
4224     ifthen = new ast_ifthen(ctx, cmp, left, right);
4225     if (!ifthen) {
4226         delete cmp; /* will delete left and right */
4227         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4228         return nullptr;
4229     }
4230
4231     return ifthen;
4232 }
4233
4234 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4235 {
4236     lex_ctx_t ctx = array->m_context;
4237
4238     if (from+1 == afterend) {
4239         /* set this value */
4240         ast_block       *block;
4241         ast_return      *ret;
4242         ast_array_index *subscript;
4243         ast_store       *st;
4244         int assignop = type_store_instr[value->m_vtype];
4245
4246         if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4247             assignop = INSTR_STORE_V;
4248
4249         subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4250         if (!subscript)
4251             return nullptr;
4252
4253         st = new ast_store(ctx, assignop, subscript, value);
4254         if (!st) {
4255             delete subscript;
4256             return nullptr;
4257         }
4258
4259         block = new ast_block(ctx);
4260         if (!block) {
4261             delete st;
4262             return nullptr;
4263         }
4264
4265         if (!block->addExpr(st)) {
4266             delete block;
4267             return nullptr;
4268         }
4269
4270         ret = new ast_return(ctx, nullptr);
4271         if (!ret) {
4272             delete block;
4273             return nullptr;
4274         }
4275
4276         if (!block->addExpr(ret)) {
4277             delete block;
4278             return nullptr;
4279         }
4280
4281         return block;
4282     } else {
4283         ast_expression *left, *right;
4284         size_t diff = afterend - from;
4285         size_t middle = from + diff/2;
4286         left  = array_setter_node(parser, array, index, value, from, middle);
4287         right = array_setter_node(parser, array, index, value, middle, afterend);
4288         return array_accessor_split(parser, array, index, middle, left, right);
4289     }
4290 }
4291
4292 static ast_expression *array_field_setter_node(
4293     parser_t  *parser,
4294     ast_value *array,
4295     ast_value *entity,
4296     ast_value *index,
4297     ast_value *value,
4298     size_t     from,
4299     size_t     afterend)
4300 {
4301     lex_ctx_t ctx = array->m_context;
4302
4303     if (from+1 == afterend) {
4304         /* set this value */
4305         ast_block       *block;
4306         ast_return      *ret;
4307         ast_entfield    *entfield;
4308         ast_array_index *subscript;
4309         ast_store       *st;
4310         int assignop = type_storep_instr[value->m_vtype];
4311
4312         if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4313             assignop = INSTR_STOREP_V;
4314
4315         subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4316         if (!subscript)
4317             return nullptr;
4318
4319         subscript->m_next = new ast_expression(ast_copy_type, subscript->m_context, *subscript);
4320         subscript->m_vtype = TYPE_FIELD;
4321
4322         entfield = new ast_entfield(ctx, entity, subscript, subscript);
4323         if (!entfield) {
4324             delete subscript;
4325             return nullptr;
4326         }
4327
4328         st = new ast_store(ctx, assignop, entfield, value);
4329         if (!st) {
4330             delete entfield;
4331             return nullptr;
4332         }
4333
4334         block = new ast_block(ctx);
4335         if (!block) {
4336             delete st;
4337             return nullptr;
4338         }
4339
4340         if (!block->addExpr(st)) {
4341             delete block;
4342             return nullptr;
4343         }
4344
4345         ret = new ast_return(ctx, nullptr);
4346         if (!ret) {
4347             delete block;
4348             return nullptr;
4349         }
4350
4351         if (!block->addExpr(ret)) {
4352             delete block;
4353             return nullptr;
4354         }
4355
4356         return block;
4357     } else {
4358         ast_expression *left, *right;
4359         size_t diff = afterend - from;
4360         size_t middle = from + diff/2;
4361         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4362         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4363         return array_accessor_split(parser, array, index, middle, left, right);
4364     }
4365 }
4366
4367 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4368 {
4369     lex_ctx_t ctx = array->m_context;
4370
4371     if (from+1 == afterend) {
4372         ast_return      *ret;
4373         ast_array_index *subscript;
4374
4375         subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4376         if (!subscript)
4377             return nullptr;
4378
4379         ret = new ast_return(ctx, subscript);
4380         if (!ret) {
4381             delete subscript;
4382             return nullptr;
4383         }
4384
4385         return ret;
4386     } else {
4387         ast_expression *left, *right;
4388         size_t diff = afterend - from;
4389         size_t middle = from + diff/2;
4390         left  = array_getter_node(parser, array, index, from, middle);
4391         right = array_getter_node(parser, array, index, middle, afterend);
4392         return array_accessor_split(parser, array, index, middle, left, right);
4393     }
4394 }
4395
4396 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4397 {
4398     ast_function   *func = nullptr;
4399     ast_value      *fval = nullptr;
4400     ast_block      *body = nullptr;
4401
4402     fval = new ast_value(array->m_context, funcname, TYPE_FUNCTION);
4403     if (!fval) {
4404         parseerror(parser, "failed to create accessor function value");
4405         return false;
4406     }
4407     fval->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
4408
4409     func = ast_function::make(array->m_context, funcname, fval);
4410     if (!func) {
4411         delete fval;
4412         parseerror(parser, "failed to create accessor function node");
4413         return false;
4414     }
4415
4416     body = new ast_block(array->m_context);
4417     if (!body) {
4418         parseerror(parser, "failed to create block for array accessor");
4419         delete fval;
4420         delete func;
4421         return false;
4422     }
4423
4424     func->m_blocks.emplace_back(body);
4425     *out = fval;
4426
4427     parser->accessors.push_back(fval);
4428
4429     return true;
4430 }
4431
4432 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4433 {
4434     ast_value      *index = nullptr;
4435     ast_value      *value = nullptr;
4436     ast_function   *func;
4437     ast_value      *fval;
4438
4439     if (!ast_istype(array->m_next, ast_value)) {
4440         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4441         return nullptr;
4442     }
4443
4444     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4445         return nullptr;
4446     func = fval->m_constval.vfunc;
4447     fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4448
4449     index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4450     value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4451
4452     if (!index || !value) {
4453         parseerror(parser, "failed to create locals for array accessor");
4454         goto cleanup;
4455     }
4456     value->m_name = "value"; // not important
4457     fval->m_type_params.emplace_back(index);
4458     fval->m_type_params.emplace_back(value);
4459
4460     array->m_setter = fval;
4461     return fval;
4462 cleanup:
4463     if (index) delete index;
4464     if (value) delete value;
4465     delete func;
4466     delete fval;
4467     return nullptr;
4468 }
4469
4470 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4471 {
4472     ast_expression *root = nullptr;
4473     root = array_setter_node(parser, array,
4474                              array->m_setter->m_type_params[0].get(),
4475                              array->m_setter->m_type_params[1].get(),
4476                              0, array->m_count);
4477     if (!root) {
4478         parseerror(parser, "failed to build accessor search tree");
4479         return false;
4480     }
4481     if (!array->m_setter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4482         delete root;
4483         return false;
4484     }
4485     return true;
4486 }
4487
4488 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4489 {
4490     if (!parser_create_array_setter_proto(parser, array, funcname))
4491         return false;
4492     return parser_create_array_setter_impl(parser, array);
4493 }
4494
4495 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4496 {
4497     ast_expression *root = nullptr;
4498     ast_value      *entity = nullptr;
4499     ast_value      *index = nullptr;
4500     ast_value      *value = nullptr;
4501     ast_function   *func;
4502     ast_value      *fval;
4503
4504     if (!ast_istype(array->m_next, ast_value)) {
4505         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4506         return false;
4507     }
4508
4509     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4510         return false;
4511     func = fval->m_constval.vfunc;
4512     fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4513
4514     entity = new ast_value(array->m_context, "entity", TYPE_ENTITY);
4515     index  = new ast_value(array->m_context, "index",  TYPE_FLOAT);
4516     value  = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4517     if (!entity || !index || !value) {
4518         parseerror(parser, "failed to create locals for array accessor");
4519         goto cleanup;
4520     }
4521     value->m_name = "value"; // not important
4522     fval->m_type_params.emplace_back(entity);
4523     fval->m_type_params.emplace_back(index);
4524     fval->m_type_params.emplace_back(value);
4525
4526     root = array_field_setter_node(parser, array, entity, index, value, 0, array->m_count);
4527     if (!root) {
4528         parseerror(parser, "failed to build accessor search tree");
4529         goto cleanup;
4530     }
4531
4532     array->m_setter = fval;
4533     return func->m_blocks[0].get()->addExpr(root);
4534 cleanup:
4535     if (entity) delete entity;
4536     if (index)  delete index;
4537     if (value)  delete value;
4538     if (root)   delete root;
4539     delete func;
4540     delete fval;
4541     return false;
4542 }
4543
4544 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4545 {
4546     ast_value      *index = nullptr;
4547     ast_value      *fval;
4548     ast_function   *func;
4549
4550     /* NOTE: checking array->m_next rather than elemtype since
4551      * for fields elemtype is a temporary fieldtype.
4552      */
4553     if (!ast_istype(array->m_next, ast_value)) {
4554         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4555         return nullptr;
4556     }
4557
4558     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4559         return nullptr;
4560     func = fval->m_constval.vfunc;
4561     fval->m_next = new ast_expression(ast_copy_type, array->m_context, *elemtype);
4562
4563     index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4564
4565     if (!index) {
4566         parseerror(parser, "failed to create locals for array accessor");
4567         goto cleanup;
4568     }
4569     fval->m_type_params.emplace_back(index);
4570
4571     array->m_getter = fval;
4572     return fval;
4573 cleanup:
4574     if (index) delete index;
4575     delete func;
4576     delete fval;
4577     return nullptr;
4578 }
4579
4580 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4581 {
4582     ast_expression *root = nullptr;
4583
4584     root = array_getter_node(parser, array, array->m_getter->m_type_params[0].get(), 0, array->m_count);
4585     if (!root) {
4586         parseerror(parser, "failed to build accessor search tree");
4587         return false;
4588     }
4589     if (!array->m_getter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4590         delete root;
4591         return false;
4592     }
4593     return true;
4594 }
4595
4596 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4597 {
4598     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4599         return false;
4600     return parser_create_array_getter_impl(parser, array);
4601 }
4602
4603 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4604 {
4605     lex_ctx_t ctx = parser_ctx(parser);
4606     std::vector<std::unique_ptr<ast_value>> params;
4607     ast_value *fval;
4608     bool first = true;
4609     bool variadic = false;
4610     ast_value *varparam = nullptr;
4611     char *argcounter = nullptr;
4612
4613     /* for the sake of less code we parse-in in this function */
4614     if (!parser_next(parser)) {
4615         delete var;
4616         parseerror(parser, "expected parameter list");
4617         return nullptr;
4618     }
4619
4620     /* parse variables until we hit a closing paren */
4621     while (parser->tok != ')') {
4622         bool is_varargs = false;
4623
4624         if (!first) {
4625             /* there must be commas between them */
4626             if (parser->tok != ',') {
4627                 parseerror(parser, "expected comma or end of parameter list");
4628                 goto on_error;
4629             }
4630             if (!parser_next(parser)) {
4631                 parseerror(parser, "expected parameter");
4632                 goto on_error;
4633             }
4634         }
4635         first = false;
4636
4637         ast_value *param = parse_typename(parser, nullptr, nullptr, &is_varargs);
4638         if (!param && !is_varargs)
4639             goto on_error;
4640         if (is_varargs) {
4641             /* '...' indicates a varargs function */
4642             variadic = true;
4643             if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4644                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4645                 goto on_error;
4646             }
4647             if (parser->tok == TOKEN_IDENT) {
4648                 argcounter = util_strdup(parser_tokval(parser));
4649                 if (!parser_next(parser) || parser->tok != ')') {
4650                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4651                     goto on_error;
4652                 }
4653             }
4654         } else {
4655             params.emplace_back(param);
4656             if (param->m_vtype >= TYPE_VARIANT) {
4657                 char tname[1024]; /* typename is reserved in C++ */
4658                 ast_type_to_string(param, tname, sizeof(tname));
4659                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4660                 goto on_error;
4661             }
4662             /* type-restricted varargs */
4663             if (parser->tok == TOKEN_DOTS) {
4664                 variadic = true;
4665                 varparam = params.back().release();
4666                 params.pop_back();
4667                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4668                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4669                     goto on_error;
4670                 }
4671                 if (parser->tok == TOKEN_IDENT) {
4672                     argcounter = util_strdup(parser_tokval(parser));
4673                     param->m_name = argcounter;
4674                     if (!parser_next(parser) || parser->tok != ')') {
4675                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4676                         goto on_error;
4677                     }
4678                 }
4679             }
4680             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->m_name[0] == '<') {
4681                 parseerror(parser, "parameter name omitted");
4682                 goto on_error;
4683             }
4684         }
4685     }
4686
4687     if (params.size() == 1 && params[0]->m_vtype == TYPE_VOID)
4688         params.clear();
4689
4690     /* sanity check */
4691     if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4692         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4693
4694     /* parse-out */
4695     if (!parser_next(parser)) {
4696         parseerror(parser, "parse error after typename");
4697         goto on_error;
4698     }
4699
4700     /* now turn 'var' into a function type */
4701     fval = new ast_value(ctx, "<type()>", TYPE_FUNCTION);
4702     fval->m_next = var;
4703     if (variadic)
4704         fval->m_flags |= AST_FLAG_VARIADIC;
4705     var = fval;
4706
4707     var->m_type_params = move(params);
4708     var->m_varparam = varparam;
4709     var->m_argcounter = argcounter;
4710
4711     return var;
4712
4713 on_error:
4714     if (argcounter)
4715         mem_d(argcounter);
4716     if (varparam)
4717         delete varparam;
4718     delete var;
4719     return nullptr;
4720 }
4721
4722 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4723 {
4724     ast_expression *cexp;
4725     ast_value      *cval, *tmp;
4726     lex_ctx_t ctx;
4727
4728     ctx = parser_ctx(parser);
4729
4730     if (!parser_next(parser)) {
4731         delete var;
4732         parseerror(parser, "expected array-size");
4733         return nullptr;
4734     }
4735
4736     if (parser->tok != ']') {
4737         cexp = parse_expression_leave(parser, true, false, false);
4738
4739         if (!cexp || !ast_istype(cexp, ast_value)) {
4740             if (cexp)
4741                 ast_unref(cexp);
4742             delete var;
4743             parseerror(parser, "expected array-size as constant positive integer");
4744             return nullptr;
4745         }
4746         cval = (ast_value*)cexp;
4747     }
4748     else {
4749         cexp = nullptr;
4750         cval = nullptr;
4751     }
4752
4753     tmp = new ast_value(ctx, "<type[]>", TYPE_ARRAY);
4754     tmp->m_next = var;
4755     var = tmp;
4756
4757     if (cval) {
4758         if (cval->m_vtype == TYPE_INTEGER)
4759             tmp->m_count = cval->m_constval.vint;
4760         else if (cval->m_vtype == TYPE_FLOAT)
4761             tmp->m_count = cval->m_constval.vfloat;
4762         else {
4763             ast_unref(cexp);
4764             delete var;
4765             parseerror(parser, "array-size must be a positive integer constant");
4766             return nullptr;
4767         }
4768
4769         ast_unref(cexp);
4770     } else {
4771         var->m_count = -1;
4772         var->m_flags |= AST_FLAG_ARRAY_INIT;
4773     }
4774
4775     if (parser->tok != ']') {
4776         delete var;
4777         parseerror(parser, "expected ']' after array-size");
4778         return nullptr;
4779     }
4780     if (!parser_next(parser)) {
4781         delete var;
4782         parseerror(parser, "error after parsing array size");
4783         return nullptr;
4784     }
4785     return var;
4786 }
4787
4788 /* Parse a complete typename.
4789  * for single-variables (ie. function parameters or typedefs) storebase should be nullptr
4790  * but when parsing variables separated by comma
4791  * 'storebase' should point to where the base-type should be kept.
4792  * The base type makes up every bit of type information which comes *before* the
4793  * variable name.
4794  *
4795  * NOTE: The value must either be named, have a nullptr name, or a name starting
4796  *       with '<'. In the first case, this will be the actual variable or type
4797  *       name, in the other cases it is assumed that the name will appear
4798  *       later, and an error is generated otherwise.
4799  *
4800  * The following will be parsed in its entirety:
4801  *     void() foo()
4802  * The 'basetype' in this case is 'void()'
4803  * and if there's a comma after it, say:
4804  *     void() foo(), bar
4805  * then the type-information 'void()' can be stored in 'storebase'
4806  */
4807 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4808 {
4809     ast_value *var, *tmp;
4810     lex_ctx_t    ctx;
4811
4812     const char *name = nullptr;
4813     bool        isfield  = false;
4814     bool        wasarray = false;
4815     size_t      morefields = 0;
4816
4817     bool        vararg = (parser->tok == TOKEN_DOTS);
4818
4819     ctx = parser_ctx(parser);
4820
4821     /* types may start with a dot */
4822     if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4823         isfield = true;
4824         if (parser->tok == TOKEN_DOTS)
4825             morefields += 2;
4826         /* if we parsed a dot we need a typename now */
4827         if (!parser_next(parser)) {
4828             parseerror(parser, "expected typename for field definition");
4829             return nullptr;
4830         }
4831
4832         /* Further dots are handled seperately because they won't be part of the
4833          * basetype
4834          */
4835         while (true) {
4836             if (parser->tok == '.')
4837                 ++morefields;
4838             else if (parser->tok == TOKEN_DOTS)
4839                 morefields += 3;
4840             else
4841                 break;
4842             vararg = false;
4843             if (!parser_next(parser)) {
4844                 parseerror(parser, "expected typename for field definition");
4845                 return nullptr;
4846             }
4847         }
4848     }
4849     if (parser->tok == TOKEN_IDENT)
4850         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4851     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4852         if (vararg && is_vararg) {
4853             *is_vararg = true;
4854             return nullptr;
4855         }
4856         parseerror(parser, "expected typename");
4857         return nullptr;
4858     }
4859
4860     /* generate the basic type value */
4861     if (cached_typedef) {
4862         var = new ast_value(ast_copy_type, *cached_typedef);
4863         var->m_name = "<type(from_def)>";
4864     } else
4865         var = new ast_value(ctx, "<type>", parser_token(parser)->constval.t);
4866
4867     for (; morefields; --morefields) {
4868         tmp = new ast_value(ctx, "<.type>", TYPE_FIELD);
4869         tmp->m_next = var;
4870         var = tmp;
4871     }
4872
4873     /* do not yet turn into a field - remember:
4874      * .void() foo; is a field too
4875      * .void()() foo; is a function
4876      */
4877
4878     /* parse on */
4879     if (!parser_next(parser)) {
4880         delete var;
4881         parseerror(parser, "parse error after typename");
4882         return nullptr;
4883     }
4884
4885     /* an opening paren now starts the parameter-list of a function
4886      * this is where original-QC has parameter lists.
4887      * We allow a single parameter list here.
4888      * Much like fteqcc we don't allow `float()() x`
4889      */
4890     if (parser->tok == '(') {
4891         var = parse_parameter_list(parser, var);
4892         if (!var)
4893             return nullptr;
4894     }
4895
4896     /* store the base if requested */
4897     if (storebase) {
4898         *storebase = new ast_value(ast_copy_type, *var);
4899         if (isfield) {
4900             tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4901             tmp->m_next = *storebase;
4902             *storebase = tmp;
4903         }
4904     }
4905
4906     /* there may be a name now */
4907     if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4908         if (!strcmp(parser_tokval(parser), "break"))
4909             (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4910         else if (parser->tok == TOKEN_KEYWORD)
4911             goto leave;
4912
4913         name = util_strdup(parser_tokval(parser));
4914
4915         /* parse on */
4916         if (!parser_next(parser)) {
4917             delete var;
4918             mem_d(name);
4919             parseerror(parser, "error after variable or field declaration");
4920             return nullptr;
4921         }
4922     }
4923
4924     leave:
4925     /* now this may be an array */
4926     if (parser->tok == '[') {
4927         wasarray = true;
4928         var = parse_arraysize(parser, var);
4929         if (!var) {
4930             if (name) mem_d(name);
4931             return nullptr;
4932         }
4933     }
4934
4935     /* This is the point where we can turn it into a field */
4936     if (isfield) {
4937         /* turn it into a field if desired */
4938         tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4939         tmp->m_next = var;
4940         var = tmp;
4941     }
4942
4943     /* now there may be function parens again */
4944     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4945         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4946     if (parser->tok == '(' && wasarray)
4947         parseerror(parser, "arrays as part of a return type is not supported");
4948     while (parser->tok == '(') {
4949         var = parse_parameter_list(parser, var);
4950         if (!var) {
4951             if (name) mem_d(name);
4952             return nullptr;
4953         }
4954     }
4955
4956     /* finally name it */
4957     if (name) {
4958         var->m_name = name;
4959         // free the name, ast_value_set_name duplicates
4960         mem_d(name);
4961     }
4962
4963     return var;
4964 }
4965
4966 static bool parse_typedef(parser_t *parser)
4967 {
4968     ast_value      *typevar, *oldtype;
4969     ast_expression *old;
4970
4971     typevar = parse_typename(parser, nullptr, nullptr, nullptr);
4972
4973     if (!typevar)
4974         return false;
4975
4976     // while parsing types, the ast_value's get named '<something>'
4977     if (!typevar->m_name.length() || typevar->m_name[0] == '<') {
4978         parseerror(parser, "missing name in typedef");
4979         delete typevar;
4980         return false;
4981     }
4982
4983     if ( (old = parser_find_var(parser, typevar->m_name)) ) {
4984         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4985                    " -> `%s` has been declared here: %s:%i",
4986                    typevar->m_name, old->m_context.file, old->m_context.line);
4987         delete typevar;
4988         return false;
4989     }
4990
4991     if ( (oldtype = parser_find_typedef(parser, typevar->m_name, vec_last(parser->_blocktypedefs))) ) {
4992         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4993                    typevar->m_name, oldtype->m_context.file, oldtype->m_context.line);
4994         delete typevar;
4995         return false;
4996     }
4997
4998     vec_push(parser->_typedefs, typevar);
4999     util_htset(vec_last(parser->typedefs), typevar->m_name.c_str(), typevar);
5000
5001     if (parser->tok != ';') {
5002         parseerror(parser, "expected semicolon after typedef");
5003         return false;
5004     }
5005     if (!parser_next(parser)) {
5006         parseerror(parser, "parse error after typedef");
5007         return false;
5008     }
5009
5010     return true;
5011 }
5012
5013 static const char *cvq_to_str(int cvq) {
5014     switch (cvq) {
5015         case CV_NONE:  return "none";
5016         case CV_VAR:   return "`var`";
5017         case CV_CONST: return "`const`";
5018         default:       return "<INVALID>";
5019     }
5020 }
5021
5022 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5023 {
5024     bool av, ao;
5025     if (proto->m_cvq != var->m_cvq) {
5026         if (!(proto->m_cvq == CV_CONST && var->m_cvq == CV_NONE &&
5027               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5028               parser->tok == '='))
5029         {
5030             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5031                                  "`%s` declared with different qualifiers: %s\n"
5032                                  " -> previous declaration here: %s:%i uses %s",
5033                                  var->m_name, cvq_to_str(var->m_cvq),
5034                                  proto->m_context.file, proto->m_context.line,
5035                                  cvq_to_str(proto->m_cvq));
5036         }
5037     }
5038     av = (var  ->m_flags & AST_FLAG_NORETURN);
5039     ao = (proto->m_flags & AST_FLAG_NORETURN);
5040     if (!av != !ao) {
5041         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5042                              "`%s` declared with different attributes%s\n"
5043                              " -> previous declaration here: %s:%i",
5044                              var->m_name, (av ? ": noreturn" : ""),
5045                              proto->m_context.file, proto->m_context.line,
5046                              (ao ? ": noreturn" : ""));
5047     }
5048     return true;
5049 }
5050
5051 static bool create_array_accessors(parser_t *parser, ast_value *var)
5052 {
5053     char name[1024];
5054     util_snprintf(name, sizeof(name), "%s##SET", var->m_name.c_str());
5055     if (!parser_create_array_setter(parser, var, name))
5056         return false;
5057     util_snprintf(name, sizeof(name), "%s##GET", var->m_name.c_str());
5058     if (!parser_create_array_getter(parser, var, var->m_next, name))
5059         return false;
5060     return true;
5061 }
5062
5063 static bool parse_array(parser_t *parser, ast_value *array)
5064 {
5065     size_t i;
5066     if (array->m_initlist.size()) {
5067         parseerror(parser, "array already initialized elsewhere");
5068         return false;
5069     }
5070     if (!parser_next(parser)) {
5071         parseerror(parser, "parse error in array initializer");
5072         return false;
5073     }
5074     i = 0;
5075     while (parser->tok != '}') {
5076         ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5077         if (!v)
5078             return false;
5079         if (!ast_istype(v, ast_value) || !v->m_hasvalue || v->m_cvq != CV_CONST) {
5080             ast_unref(v);
5081             parseerror(parser, "initializing element must be a compile time constant");
5082             return false;
5083         }
5084         array->m_initlist.push_back(v->m_constval);
5085         if (v->m_vtype == TYPE_STRING) {
5086             array->m_initlist[i].vstring = util_strdupe(array->m_initlist[i].vstring);
5087             ++i;
5088         }
5089         ast_unref(v);
5090         if (parser->tok == '}')
5091             break;
5092         if (parser->tok != ',' || !parser_next(parser)) {
5093             parseerror(parser, "expected comma or '}' in element list");
5094             return false;
5095         }
5096     }
5097     if (!parser_next(parser) || parser->tok != ';') {
5098         parseerror(parser, "expected semicolon after initializer, got %s");
5099         return false;
5100     }
5101     /*
5102     if (!parser_next(parser)) {
5103         parseerror(parser, "parse error after initializer");
5104         return false;
5105     }
5106     */
5107
5108     if (array->m_flags & AST_FLAG_ARRAY_INIT) {
5109         if (array->m_count != (size_t)-1) {
5110             parseerror(parser, "array `%s' has already been initialized with %u elements",
5111                        array->m_name, (unsigned)array->m_count);
5112         }
5113         array->m_count = array->m_initlist.size();
5114         if (!create_array_accessors(parser, array))
5115             return false;
5116     }
5117     return true;
5118 }
5119
5120 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)
5121 {
5122     ast_value *var;
5123     ast_value *proto;
5124     ast_expression *old;
5125     bool       was_end;
5126     size_t     i;
5127
5128     ast_value *basetype = nullptr;
5129     bool      retval    = true;
5130     bool      isparam   = false;
5131     bool      isvector  = false;
5132     bool      cleanvar  = true;
5133     bool      wasarray  = false;
5134
5135     ast_member *me[3] = { nullptr, nullptr, nullptr };
5136     ast_member *last_me[3] = { nullptr, nullptr, nullptr };
5137
5138     if (!localblock && is_static)
5139         parseerror(parser, "`static` qualifier is not supported in global scope");
5140
5141     /* get the first complete variable */
5142     var = parse_typename(parser, &basetype, cached_typedef, nullptr);
5143     if (!var) {
5144         if (basetype)
5145             delete basetype;
5146         return false;
5147     }
5148
5149     /* while parsing types, the ast_value's get named '<something>' */
5150     if (!var->m_name.length() || var->m_name[0] == '<') {
5151         parseerror(parser, "declaration does not declare anything");
5152         if (basetype)
5153             delete basetype;
5154         return false;
5155     }
5156
5157     while (true) {
5158         proto = nullptr;
5159         wasarray = false;
5160
5161         /* Part 0: finish the type */
5162         if (parser->tok == '(') {
5163             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5164                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5165             var = parse_parameter_list(parser, var);
5166             if (!var) {
5167                 retval = false;
5168                 goto cleanup;
5169             }
5170         }
5171         /* we only allow 1-dimensional arrays */
5172         if (parser->tok == '[') {
5173             wasarray = true;
5174             var = parse_arraysize(parser, var);
5175             if (!var) {
5176                 retval = false;
5177                 goto cleanup;
5178             }
5179         }
5180         if (parser->tok == '(' && wasarray) {
5181             parseerror(parser, "arrays as part of a return type is not supported");
5182             /* we'll still parse the type completely for now */
5183         }
5184         /* for functions returning functions */
5185         while (parser->tok == '(') {
5186             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5187                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5188             var = parse_parameter_list(parser, var);
5189             if (!var) {
5190                 retval = false;
5191                 goto cleanup;
5192             }
5193         }
5194
5195         var->m_cvq = qualifier;
5196         if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5197             var->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
5198         var->m_flags |= qflags;
5199
5200         /*
5201          * store the vstring back to var for alias and
5202          * deprecation messages.
5203          */
5204         if (var->m_flags & AST_FLAG_DEPRECATED ||
5205             var->m_flags & AST_FLAG_ALIAS)
5206             var->m_desc = vstring;
5207
5208         if (parser_find_global(parser, var->m_name) && var->m_flags & AST_FLAG_ALIAS) {
5209             parseerror(parser, "function aliases cannot be forward declared");
5210             retval = false;
5211             goto cleanup;
5212         }
5213
5214
5215         /* Part 1:
5216          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5217          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5218          * is then filled with the previous definition and the parameter-names replaced.
5219          */
5220         if (var->m_name == "nil") {
5221             if (OPTS_FLAG(UNTYPED_NIL)) {
5222                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5223                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5224             } else
5225                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5226         }
5227         if (!localblock) {
5228             /* Deal with end_sys_ vars */
5229             was_end = false;
5230             if (var->m_name == "end_sys_globals") {
5231                 var->m_flags |= AST_FLAG_NOREF;
5232                 parser->crc_globals = parser->globals.size();
5233                 was_end = true;
5234             }
5235             else if (var->m_name == "end_sys_fields") {
5236                 var->m_flags |= AST_FLAG_NOREF;
5237                 parser->crc_fields = parser->fields.size();
5238                 was_end = true;
5239             }
5240             if (was_end && var->m_vtype == TYPE_FIELD) {
5241                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5242                                  "global '%s' hint should not be a field",
5243                                  parser_tokval(parser)))
5244                 {
5245                     retval = false;
5246                     goto cleanup;
5247                 }
5248             }
5249
5250             if (!nofields && var->m_vtype == TYPE_FIELD)
5251             {
5252                 /* deal with field declarations */
5253                 old = parser_find_field(parser, var->m_name);
5254                 if (old) {
5255                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5256                                      var->m_name, old->m_context.file, (int)old->m_context.line))
5257                     {
5258                         retval = false;
5259                         goto cleanup;
5260                     }
5261                     delete var;
5262                     var = nullptr;
5263                     goto skipvar;
5264                     /*
5265                     parseerror(parser, "field `%s` already declared here: %s:%i",
5266                                var->m_name, old->m_context.file, old->m_context.line);
5267                     retval = false;
5268                     goto cleanup;
5269                     */
5270                 }
5271                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5272                     (old = parser_find_global(parser, var->m_name)))
5273                 {
5274                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5275                     parseerror(parser, "field `%s` already declared here: %s:%i",
5276                                var->m_name, old->m_context.file, old->m_context.line);
5277                     retval = false;
5278                     goto cleanup;
5279                 }
5280             }
5281             else
5282             {
5283                 /* deal with other globals */
5284                 old = parser_find_global(parser, var->m_name);
5285                 if (old && var->m_vtype == TYPE_FUNCTION && old->m_vtype == TYPE_FUNCTION)
5286                 {
5287                     /* This is a function which had a prototype */
5288                     if (!ast_istype(old, ast_value)) {
5289                         parseerror(parser, "internal error: prototype is not an ast_value");
5290                         retval = false;
5291                         goto cleanup;
5292                     }
5293                     proto = (ast_value*)old;
5294                     proto->m_desc = var->m_desc;
5295                     if (!proto->compareType(*var)) {
5296                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5297                                    proto->m_name,
5298                                    proto->m_context.file, proto->m_context.line);
5299                         retval = false;
5300                         goto cleanup;
5301                     }
5302                     /* we need the new parameter-names */
5303                     for (i = 0; i < proto->m_type_params.size(); ++i)
5304                         proto->m_type_params[i]->m_name = var->m_type_params[i]->m_name;
5305                     if (!parser_check_qualifiers(parser, var, proto)) {
5306                         retval = false;
5307                         proto = nullptr;
5308                         goto cleanup;
5309                     }
5310                     proto->m_flags |= var->m_flags;
5311                     delete var;
5312                     var = proto;
5313                 }
5314                 else
5315                 {
5316                     /* other globals */
5317                     if (old) {
5318                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5319                                          "global `%s` already declared here: %s:%i",
5320                                          var->m_name, old->m_context.file, old->m_context.line))
5321                         {
5322                             retval = false;
5323                             goto cleanup;
5324                         }
5325                         if (old->m_flags & AST_FLAG_FINAL_DECL) {
5326                             parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5327                                        var->m_name, old->m_context.file, old->m_context.line);
5328                             retval = false;
5329                             goto cleanup;
5330                         }
5331                         proto = (ast_value*)old;
5332                         if (!ast_istype(old, ast_value)) {
5333                             parseerror(parser, "internal error: not an ast_value");
5334                             retval = false;
5335                             proto = nullptr;
5336                             goto cleanup;
5337                         }
5338                         if (!parser_check_qualifiers(parser, var, proto)) {
5339                             retval = false;
5340                             proto = nullptr;
5341                             goto cleanup;
5342                         }
5343                         proto->m_flags |= var->m_flags;
5344                         /* copy the context for finals,
5345                          * so the error can show where it was actually made 'final'
5346                          */
5347                         if (proto->m_flags & AST_FLAG_FINAL_DECL)
5348                             old->m_context = var->m_context;
5349                         delete var;
5350                         var = proto;
5351                     }
5352                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5353                         (old = parser_find_field(parser, var->m_name)))
5354                     {
5355                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5356                         parseerror(parser, "global `%s` already declared here: %s:%i",
5357                                    var->m_name, old->m_context.file, old->m_context.line);
5358                         retval = false;
5359                         goto cleanup;
5360                     }
5361                 }
5362             }
5363         }
5364         else /* it's not a global */
5365         {
5366             old = parser_find_local(parser, var->m_name, vec_size(parser->variables)-1, &isparam);
5367             if (old && !isparam) {
5368                 parseerror(parser, "local `%s` already declared here: %s:%i",
5369                            var->m_name, old->m_context.file, (int)old->m_context.line);
5370                 retval = false;
5371                 goto cleanup;
5372             }
5373             /* doing this here as the above is just for a single scope */
5374             old = parser_find_local(parser, var->m_name, 0, &isparam);
5375             if (old && isparam) {
5376                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5377                                  "local `%s` is shadowing a parameter", var->m_name))
5378                 {
5379                     parseerror(parser, "local `%s` already declared here: %s:%i",
5380                                var->m_name, old->m_context.file, (int)old->m_context.line);
5381                     retval = false;
5382                     goto cleanup;
5383                 }
5384                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5385                     delete var;
5386                     if (ast_istype(old, ast_value))
5387                         var = proto = (ast_value*)old;
5388                     else {
5389                         var = nullptr;
5390                         goto skipvar;
5391                     }
5392                 }
5393             }
5394         }
5395
5396         if (noref || parser->noref)
5397             var->m_flags |= AST_FLAG_NOREF;
5398
5399         /* Part 2:
5400          * Create the global/local, and deal with vector types.
5401          */
5402         if (!proto) {
5403             if (var->m_vtype == TYPE_VECTOR)
5404                 isvector = true;
5405             else if (var->m_vtype == TYPE_FIELD &&
5406                      var->m_next->m_vtype == TYPE_VECTOR)
5407                 isvector = true;
5408
5409             if (isvector) {
5410                 if (!create_vector_members(var, me)) {
5411                     retval = false;
5412                     goto cleanup;
5413                 }
5414             }
5415
5416             if (!localblock) {
5417                 /* deal with global variables, fields, functions */
5418                 if (!nofields && var->m_vtype == TYPE_FIELD && parser->tok != '=') {
5419                     var->m_isfield = true;
5420                     parser->fields.push_back(var);
5421                     util_htset(parser->htfields, var->m_name.c_str(), var);
5422                     if (isvector) {
5423                         for (i = 0; i < 3; ++i) {
5424                             parser->fields.push_back(me[i]);
5425                             util_htset(parser->htfields, me[i]->m_name.c_str(), me[i]);
5426                         }
5427                     }
5428                 }
5429                 else {
5430                     if (!(var->m_flags & AST_FLAG_ALIAS)) {
5431                         parser_addglobal(parser, var->m_name, var);
5432                         if (isvector) {
5433                             for (i = 0; i < 3; ++i) {
5434                                 parser_addglobal(parser, me[i]->m_name.c_str(), me[i]);
5435                             }
5436                         }
5437                     } else {
5438                         ast_expression *find  = parser_find_global(parser, var->m_desc);
5439
5440                         if (!find) {
5441                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->m_desc, var->m_name);
5442                             return false;
5443                         }
5444
5445                         if (!var->compareType(*find)) {
5446                             char ty1[1024];
5447                             char ty2[1024];
5448
5449                             ast_type_to_string(find, ty1, sizeof(ty1));
5450                             ast_type_to_string(var,  ty2, sizeof(ty2));
5451
5452                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5453                                 ty1, ty2, var->m_name
5454                             );
5455                             return false;
5456                         }
5457
5458                         util_htset(parser->aliases, var->m_name.c_str(), find);
5459
5460                         /* generate aliases for vector components */
5461                         if (isvector) {
5462                             char *buffer[3];
5463
5464                             util_asprintf(&buffer[0], "%s_x", var->m_desc.c_str());
5465                             util_asprintf(&buffer[1], "%s_y", var->m_desc.c_str());
5466                             util_asprintf(&buffer[2], "%s_z", var->m_desc.c_str());
5467
5468                             util_htset(parser->aliases, me[0]->m_name.c_str(), parser_find_global(parser, buffer[0]));
5469                             util_htset(parser->aliases, me[1]->m_name.c_str(), parser_find_global(parser, buffer[1]));
5470                             util_htset(parser->aliases, me[2]->m_name.c_str(), parser_find_global(parser, buffer[2]));
5471
5472                             mem_d(buffer[0]);
5473                             mem_d(buffer[1]);
5474                             mem_d(buffer[2]);
5475                         }
5476                     }
5477                 }
5478             } else {
5479                 if (is_static) {
5480                     // a static adds itself to be generated like any other global
5481                     // but is added to the local namespace instead
5482                     std::string defname;
5483                     size_t  prefix_len;
5484                     size_t  sn, sn_size;
5485
5486                     defname = parser->function->m_name;
5487                     defname.append(2, ':');
5488
5489                     // remember the length up to here
5490                     prefix_len = defname.length();
5491
5492                     // Add it to the local scope
5493                     util_htset(vec_last(parser->variables), var->m_name.c_str(), (void*)var);
5494
5495                     // now rename the global
5496                     defname.append(var->m_name);
5497                     // if a variable of that name already existed, add the
5498                     // counter value.
5499                     // The counter is incremented either way.
5500                     sn_size = parser->function->m_static_names.size();
5501                     for (sn = 0; sn != sn_size; ++sn) {
5502                         if (parser->function->m_static_names[sn] == var->m_name.c_str())
5503                             break;
5504                     }
5505                     if (sn != sn_size) {
5506                         char *num = nullptr;
5507                         int   len = util_asprintf(&num, "#%u", parser->function->m_static_count);
5508                         defname.append(num, 0, len);
5509                         mem_d(num);
5510                     }
5511                     else
5512                         parser->function->m_static_names.emplace_back(var->m_name);
5513                     parser->function->m_static_count++;
5514                     var->m_name = defname;
5515
5516                     // push it to the to-be-generated globals
5517                     parser->globals.push_back(var);
5518
5519                     // same game for the vector members
5520                     if (isvector) {
5521                         defname.erase(prefix_len);
5522                         for (i = 0; i < 3; ++i) {
5523                             util_htset(vec_last(parser->variables), me[i]->m_name.c_str(), (void*)(me[i]));
5524                             me[i]->m_name = move(defname + me[i]->m_name);
5525                             parser->globals.push_back(me[i]);
5526                         }
5527                     }
5528                 } else {
5529                     localblock->m_locals.push_back(var);
5530                     parser_addlocal(parser, var->m_name, var);
5531                     if (isvector) {
5532                         for (i = 0; i < 3; ++i) {
5533                             parser_addlocal(parser, me[i]->m_name, me[i]);
5534                             localblock->collect(me[i]);
5535                         }
5536                     }
5537                 }
5538             }
5539         }
5540         memcpy(last_me, me, sizeof(me));
5541         me[0] = me[1] = me[2] = nullptr;
5542         cleanvar = false;
5543         /* Part 2.2
5544          * deal with arrays
5545          */
5546         if (var->m_vtype == TYPE_ARRAY) {
5547             if (var->m_count != (size_t)-1) {
5548                 if (!create_array_accessors(parser, var))
5549                     goto cleanup;
5550             }
5551         }
5552         else if (!localblock && !nofields &&
5553                  var->m_vtype == TYPE_FIELD &&
5554                  var->m_next->m_vtype == TYPE_ARRAY)
5555         {
5556             char name[1024];
5557             ast_expression *telem;
5558             ast_value      *tfield;
5559             ast_value      *array = (ast_value*)var->m_next;
5560
5561             if (!ast_istype(var->m_next, ast_value)) {
5562                 parseerror(parser, "internal error: field element type must be an ast_value");
5563                 goto cleanup;
5564             }
5565
5566             util_snprintf(name, sizeof(name), "%s##SETF", var->m_name.c_str());
5567             if (!parser_create_array_field_setter(parser, array, name))
5568                 goto cleanup;
5569
5570             telem = new ast_expression(ast_copy_type, var->m_context, *array->m_next);
5571             tfield = new ast_value(var->m_context, "<.type>", TYPE_FIELD);
5572             tfield->m_next = telem;
5573             util_snprintf(name, sizeof(name), "%s##GETFP", var->m_name.c_str());
5574             if (!parser_create_array_getter(parser, array, tfield, name)) {
5575                 delete tfield;
5576                 goto cleanup;
5577             }
5578             delete tfield;
5579         }
5580
5581 skipvar:
5582         if (parser->tok == ';') {
5583             delete basetype;
5584             if (!parser_next(parser)) {
5585                 parseerror(parser, "error after variable declaration");
5586                 return false;
5587             }
5588             return true;
5589         }
5590
5591         if (parser->tok == ',')
5592             goto another;
5593
5594         /*
5595         if (!var || (!localblock && !nofields && basetype->m_vtype == TYPE_FIELD)) {
5596         */
5597         if (!var) {
5598             parseerror(parser, "missing comma or semicolon while parsing variables");
5599             break;
5600         }
5601
5602         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5603             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5604                              "initializing expression turns variable `%s` into a constant in this standard",
5605                              var->m_name) )
5606             {
5607                 break;
5608             }
5609         }
5610
5611         if (parser->tok != '{' || var->m_vtype != TYPE_FUNCTION) {
5612             if (parser->tok != '=') {
5613                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5614                 break;
5615             }
5616
5617             if (!parser_next(parser)) {
5618                 parseerror(parser, "error parsing initializer");
5619                 break;
5620             }
5621         }
5622         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5623             parseerror(parser, "expected '=' before function body in this standard");
5624         }
5625
5626         if (parser->tok == '#') {
5627             ast_function *func   = nullptr;
5628             ast_value    *number = nullptr;
5629             float         fractional;
5630             float         integral;
5631             int           builtin_num;
5632
5633             if (localblock) {
5634                 parseerror(parser, "cannot declare builtins within functions");
5635                 break;
5636             }
5637             if (var->m_vtype != TYPE_FUNCTION) {
5638                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->m_name);
5639                 break;
5640             }
5641             if (!parser_next(parser)) {
5642                 parseerror(parser, "expected builtin number");
5643                 break;
5644             }
5645
5646             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5647                 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5648                 if (!number) {
5649                     parseerror(parser, "builtin number expected");
5650                     break;
5651                 }
5652                 if (!ast_istype(number, ast_value) || !number->m_hasvalue || number->m_cvq != CV_CONST)
5653                 {
5654                     ast_unref(number);
5655                     parseerror(parser, "builtin number must be a compile time constant");
5656                     break;
5657                 }
5658                 if (number->m_vtype == TYPE_INTEGER)
5659                     builtin_num = number->m_constval.vint;
5660                 else if (number->m_vtype == TYPE_FLOAT)
5661                     builtin_num = number->m_constval.vfloat;
5662                 else {
5663                     ast_unref(number);
5664                     parseerror(parser, "builtin number must be an integer constant");
5665                     break;
5666                 }
5667                 ast_unref(number);
5668
5669                 fractional = modff(builtin_num, &integral);
5670                 if (builtin_num < 0 || fractional != 0) {
5671                     parseerror(parser, "builtin number must be an integer greater than zero");
5672                     break;
5673                 }
5674
5675                 /* we only want the integral part anyways */
5676                 builtin_num = integral;
5677             } else if (parser->tok == TOKEN_INTCONST) {
5678                 builtin_num = parser_token(parser)->constval.i;
5679             } else {
5680                 parseerror(parser, "builtin number must be a compile time constant");
5681                 break;
5682             }
5683
5684             if (var->m_hasvalue) {
5685                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5686                                     "builtin `%s` has already been defined\n"
5687                                     " -> previous declaration here: %s:%i",
5688                                     var->m_name, var->m_context.file, (int)var->m_context.line);
5689             }
5690             else
5691             {
5692                 func = ast_function::make(var->m_context, var->m_name, var);
5693                 if (!func) {
5694                     parseerror(parser, "failed to allocate function for `%s`", var->m_name);
5695                     break;
5696                 }
5697                 parser->functions.push_back(func);
5698
5699                 func->m_builtin = -builtin_num-1;
5700             }
5701
5702             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5703                     ? (parser->tok != ',' && parser->tok != ';')
5704                     : (!parser_next(parser)))
5705             {
5706                 parseerror(parser, "expected comma or semicolon");
5707                 delete func;
5708                 var->m_constval.vfunc = nullptr;
5709                 break;
5710             }
5711         }
5712         else if (var->m_vtype == TYPE_ARRAY && parser->tok == '{')
5713         {
5714             if (localblock) {
5715                 /* Note that fteqcc and most others don't even *have*
5716                  * local arrays, so this is not a high priority.
5717                  */
5718                 parseerror(parser, "TODO: initializers for local arrays");
5719                 break;
5720             }
5721
5722             var->m_hasvalue = true;
5723             if (!parse_array(parser, var))
5724                 break;
5725         }
5726         else if (var->m_vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5727         {
5728             if (localblock) {
5729                 parseerror(parser, "cannot declare functions within functions");
5730                 break;
5731             }
5732
5733             if (proto)
5734                 proto->m_context = parser_ctx(parser);
5735
5736             if (!parse_function_body(parser, var))
5737                 break;
5738             delete basetype;
5739             for (auto &it : parser->gotos)
5740                 parseerror(parser, "undefined label: `%s`", it->m_name);
5741             parser->gotos.clear();
5742             parser->labels.clear();
5743             return true;
5744         } else {
5745             ast_expression *cexp;
5746             ast_value      *cval;
5747             bool            folded_const = false;
5748
5749             cexp = parse_expression_leave(parser, true, false, false);
5750             if (!cexp)
5751                 break;
5752             cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : nullptr;
5753
5754             /* deal with foldable constants: */
5755             if (localblock &&
5756                 var->m_cvq == CV_CONST && cval && cval->m_hasvalue && cval->m_cvq == CV_CONST && !cval->m_isfield)
5757             {
5758                 /* remove it from the current locals */
5759                 if (isvector) {
5760                     for (i = 0; i < 3; ++i) {
5761                         vec_pop(parser->_locals);
5762                         localblock->m_collect.pop_back();
5763                     }
5764                 }
5765                 /* do sanity checking, this function really needs refactoring */
5766                 if (vec_last(parser->_locals) != var)
5767                     parseerror(parser, "internal error: unexpected change in local variable handling");
5768                 else
5769                     vec_pop(parser->_locals);
5770                 if (localblock->m_locals.back() != var)
5771                     parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5772                 else
5773                     localblock->m_locals.pop_back();
5774                 /* push it to the to-be-generated globals */
5775                 parser->globals.push_back(var);
5776                 if (isvector)
5777                     for (i = 0; i < 3; ++i)
5778                         parser->globals.push_back(last_me[i]);
5779                 folded_const = true;
5780             }
5781
5782             if (folded_const || !localblock || is_static) {
5783                 if (cval != parser->nil &&
5784                     (!cval || ((!cval->m_hasvalue || cval->m_cvq != CV_CONST) && !cval->m_isfield))
5785                    )
5786                 {
5787                     parseerror(parser, "initializer is non constant");
5788                 }
5789                 else
5790                 {
5791                     if (!is_static &&
5792                         !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5793                         qualifier != CV_VAR)
5794                     {
5795                         var->m_cvq = CV_CONST;
5796                     }
5797                     if (cval == parser->nil)
5798                     {
5799                         var->m_flags |= AST_FLAG_INITIALIZED;
5800                         var->m_flags |= AST_FLAG_NOREF;
5801                     }
5802                     else
5803                     {
5804                         var->m_hasvalue = true;
5805                         if (cval->m_vtype == TYPE_STRING)
5806                             var->m_constval.vstring = parser_strdup(cval->m_constval.vstring);
5807                         else if (cval->m_vtype == TYPE_FIELD)
5808                             var->m_constval.vfield = cval;
5809                         else
5810                             memcpy(&var->m_constval, &cval->m_constval, sizeof(var->m_constval));
5811                         ast_unref(cval);
5812                     }
5813                 }
5814             } else {
5815                 int cvq;
5816                 shunt sy;
5817                 cvq = var->m_cvq;
5818                 var->m_cvq = CV_NONE;
5819                 sy.out.push_back(syexp(var->m_context, var));
5820                 sy.out.push_back(syexp(cexp->m_context, cexp));
5821                 sy.ops.push_back(syop(var->m_context, parser->assign_op));
5822                 if (!parser_sy_apply_operator(parser, &sy))
5823                     ast_unref(cexp);
5824                 else {
5825                     if (sy.out.size() != 1 && sy.ops.size() != 0)
5826                         parseerror(parser, "internal error: leaked operands");
5827                     if (!localblock->addExpr(sy.out[0].out))
5828                         break;
5829                 }
5830                 var->m_cvq = cvq;
5831             }
5832             /* a constant initialized to an inexact value should be marked inexact:
5833              * const float x = <inexact>; should propagate the inexact flag
5834              */
5835             if (var->m_cvq == CV_CONST && var->m_vtype == TYPE_FLOAT) {
5836                 if (cval && cval->m_hasvalue && cval->m_cvq == CV_CONST)
5837                     var->m_inexact = cval->m_inexact;
5838             }
5839         }
5840
5841 another:
5842         if (parser->tok == ',') {
5843             if (!parser_next(parser)) {
5844                 parseerror(parser, "expected another variable");
5845                 break;
5846             }
5847
5848             if (parser->tok != TOKEN_IDENT) {
5849                 parseerror(parser, "expected another variable");
5850                 break;
5851             }
5852             var = new ast_value(ast_copy_type, *basetype);
5853             cleanvar = true;
5854             var->m_name = parser_tokval(parser);
5855             if (!parser_next(parser)) {
5856                 parseerror(parser, "error parsing variable declaration");
5857                 break;
5858             }
5859             continue;
5860         }
5861
5862         if (parser->tok != ';') {
5863             parseerror(parser, "missing semicolon after variables");
5864             break;
5865         }
5866
5867         if (!parser_next(parser)) {
5868             parseerror(parser, "parse error after variable declaration");
5869             break;
5870         }
5871
5872         delete basetype;
5873         return true;
5874     }
5875
5876     if (cleanvar && var)
5877         delete var;
5878     delete basetype;
5879     return false;
5880
5881 cleanup:
5882     delete basetype;
5883     if (cleanvar && var)
5884         delete var;
5885     delete me[0];
5886     delete me[1];
5887     delete me[2];
5888     return retval;
5889 }
5890
5891 static bool parser_global_statement(parser_t *parser)
5892 {
5893     int        cvq       = CV_WRONG;
5894     bool       noref     = false;
5895     bool       is_static = false;
5896     uint32_t   qflags    = 0;
5897     ast_value *istype    = nullptr;
5898     char      *vstring   = nullptr;
5899
5900     if (parser->tok == TOKEN_IDENT)
5901         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5902
5903     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5904     {
5905         return parse_variable(parser, nullptr, false, CV_NONE, istype, false, false, 0, nullptr);
5906     }
5907     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5908     {
5909         if (cvq == CV_WRONG)
5910             return false;
5911         return parse_variable(parser, nullptr, false, cvq, nullptr, noref, is_static, qflags, vstring);
5912     }
5913     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5914     {
5915         return parse_enum(parser);
5916     }
5917     else if (parser->tok == TOKEN_KEYWORD)
5918     {
5919         if (!strcmp(parser_tokval(parser), "typedef")) {
5920             if (!parser_next(parser)) {
5921                 parseerror(parser, "expected type definition after 'typedef'");
5922                 return false;
5923             }
5924             return parse_typedef(parser);
5925         }
5926         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5927         return false;
5928     }
5929     else if (parser->tok == '#')
5930     {
5931         return parse_pragma(parser);
5932     }
5933     else if (parser->tok == '$')
5934     {
5935         if (!parser_next(parser)) {
5936             parseerror(parser, "parse error");
5937             return false;
5938         }
5939     }
5940     else
5941     {
5942         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5943         return false;
5944     }
5945     return true;
5946 }
5947
5948 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5949 {
5950     return util_crc16(old, str, strlen(str));
5951 }
5952
5953 static void progdefs_crc_file(const char *str)
5954 {
5955     /* write to progdefs.h here */
5956     (void)str;
5957 }
5958
5959 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5960 {
5961     old = progdefs_crc_sum(old, str);
5962     progdefs_crc_file(str);
5963     return old;
5964 }
5965
5966 static void generate_checksum(parser_t *parser, ir_builder *ir)
5967 {
5968     uint16_t   crc = 0xFFFF;
5969     size_t     i;
5970     ast_value *value;
5971
5972     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5973     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5974     /*
5975     progdefs_crc_file("\tint\tpad;\n");
5976     progdefs_crc_file("\tint\tofs_return[3];\n");
5977     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5978     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5979     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5980     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5981     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5982     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5983     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5984     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5985     */
5986     for (i = 0; i < parser->crc_globals; ++i) {
5987         if (!ast_istype(parser->globals[i], ast_value))
5988             continue;
5989         value = (ast_value*)(parser->globals[i]);
5990         switch (value->m_vtype) {
5991             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5992             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5993             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5994             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5995             default:
5996                 crc = progdefs_crc_both(crc, "\tint\t");
5997                 break;
5998         }
5999         crc = progdefs_crc_both(crc, value->m_name.c_str());
6000         crc = progdefs_crc_both(crc, ";\n");
6001     }
6002     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6003     for (i = 0; i < parser->crc_fields; ++i) {
6004         if (!ast_istype(parser->fields[i], ast_value))
6005             continue;
6006         value = (ast_value*)(parser->fields[i]);
6007         switch (value->m_next->m_vtype) {
6008             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6009             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6010             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6011             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6012             default:
6013                 crc = progdefs_crc_both(crc, "\tint\t");
6014                 break;
6015         }
6016         crc = progdefs_crc_both(crc, value->m_name.c_str());
6017         crc = progdefs_crc_both(crc, ";\n");
6018     }
6019     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6020     ir->m_code->crc = crc;
6021 }
6022
6023 parser_t *parser_create()
6024 {
6025     parser_t *parser;
6026     lex_ctx_t empty_ctx;
6027     size_t i;
6028
6029     parser = (parser_t*)mem_a(sizeof(parser_t));
6030     if (!parser)
6031         return nullptr;
6032
6033     memset(parser, 0, sizeof(*parser));
6034
6035     // TODO: remove
6036     new (parser) parser_t();
6037
6038     for (i = 0; i < operator_count; ++i) {
6039         if (operators[i].id == opid1('=')) {
6040             parser->assign_op = operators+i;
6041             break;
6042         }
6043     }
6044     if (!parser->assign_op) {
6045         con_err("internal error: initializing parser: failed to find assign operator\n");
6046         mem_d(parser);
6047         return nullptr;
6048     }
6049
6050     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
6051     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6052     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6053     vec_push(parser->_blocktypedefs, 0);
6054
6055     parser->aliases = util_htnew(PARSER_HT_SIZE);
6056
6057     empty_ctx.file   = "<internal>";
6058     empty_ctx.line   = 0;
6059     empty_ctx.column = 0;
6060     parser->nil = new ast_value(empty_ctx, "nil", TYPE_NIL);
6061     parser->nil->m_cvq = CV_CONST;
6062     if (OPTS_FLAG(UNTYPED_NIL))
6063         util_htset(parser->htglobals, "nil", (void*)parser->nil);
6064
6065     parser->max_param_count = 1;
6066
6067     parser->const_vec[0] = new ast_value(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6068     parser->const_vec[1] = new ast_value(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6069     parser->const_vec[2] = new ast_value(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6070
6071     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6072         parser->reserved_version = new ast_value(empty_ctx, "reserved:version", TYPE_STRING);
6073         parser->reserved_version->m_cvq = CV_CONST;
6074         parser->reserved_version->m_hasvalue = true;
6075         parser->reserved_version->m_flags |= AST_FLAG_INCLUDE_DEF;
6076         parser->reserved_version->m_flags |= AST_FLAG_NOREF;
6077         parser->reserved_version->m_constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6078     } else {
6079         parser->reserved_version = nullptr;
6080     }
6081
6082     parser->m_fold = fold(parser);
6083     parser->m_intrin = intrin(parser);
6084     return parser;
6085 }
6086
6087 static bool parser_compile(parser_t *parser)
6088 {
6089     /* initial lexer/parser state */
6090     parser->lex->flags.noops = true;
6091
6092     if (parser_next(parser))
6093     {
6094         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6095         {
6096             if (!parser_global_statement(parser)) {
6097                 if (parser->tok == TOKEN_EOF)
6098                     parseerror(parser, "unexpected end of file");
6099                 else if (compile_errors)
6100                     parseerror(parser, "there have been errors, bailing out");
6101                 lex_close(parser->lex);
6102                 parser->lex = nullptr;
6103                 return false;
6104             }
6105         }
6106     } else {
6107         parseerror(parser, "parse error");
6108         lex_close(parser->lex);
6109         parser->lex = nullptr;
6110         return false;
6111     }
6112
6113     lex_close(parser->lex);
6114     parser->lex = nullptr;
6115
6116     return !compile_errors;
6117 }
6118
6119 bool parser_compile_file(parser_t *parser, const char *filename)
6120 {
6121     parser->lex = lex_open(filename);
6122     if (!parser->lex) {
6123         con_err("failed to open file \"%s\"\n", filename);
6124         return false;
6125     }
6126     return parser_compile(parser);
6127 }
6128
6129 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6130 {
6131     parser->lex = lex_open_string(str, len, name);
6132     if (!parser->lex) {
6133         con_err("failed to create lexer for string \"%s\"\n", name);
6134         return false;
6135     }
6136     return parser_compile(parser);
6137 }
6138
6139 static void parser_remove_ast(parser_t *parser)
6140 {
6141     size_t i;
6142     if (parser->ast_cleaned)
6143         return;
6144     parser->ast_cleaned = true;
6145     for (auto &it : parser->accessors) {
6146         delete it->m_constval.vfunc;
6147         it->m_constval.vfunc = nullptr;
6148         delete it;
6149     }
6150     for (auto &it : parser->functions) delete it;
6151     for (auto &it : parser->globals) delete it;
6152     for (auto &it : parser->fields) delete it;
6153
6154     for (i = 0; i < vec_size(parser->variables); ++i)
6155         util_htdel(parser->variables[i]);
6156     vec_free(parser->variables);
6157     vec_free(parser->_blocklocals);
6158     vec_free(parser->_locals);
6159
6160     for (i = 0; i < vec_size(parser->_typedefs); ++i)
6161         delete parser->_typedefs[i];
6162     vec_free(parser->_typedefs);
6163     for (i = 0; i < vec_size(parser->typedefs); ++i)
6164         util_htdel(parser->typedefs[i]);
6165     vec_free(parser->typedefs);
6166     vec_free(parser->_blocktypedefs);
6167
6168     vec_free(parser->_block_ctx);
6169
6170     delete parser->nil;
6171
6172     delete parser->const_vec[0];
6173     delete parser->const_vec[1];
6174     delete parser->const_vec[2];
6175
6176     if (parser->reserved_version)
6177         delete parser->reserved_version;
6178
6179     util_htdel(parser->aliases);
6180 }
6181
6182 void parser_cleanup(parser_t *parser)
6183 {
6184     parser_remove_ast(parser);
6185     parser->~parser_t();
6186     mem_d(parser);
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(parser);
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 }