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