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