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