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