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