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