]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
again with the comments...
[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     lex_ctx         ctx     = parser_ctx(parser);
1707
1708     if (!parser->function->varargs) {
1709         parseerror(parser, "function has no variable argument list");
1710         return NULL;
1711     }
1712
1713     if (!parser_next(parser) || parser->tok != '(') {
1714         parseerror(parser, "expected parameter index and type in parenthesis");
1715         return NULL;
1716     }
1717     if (!parser_next(parser)) {
1718         parseerror(parser, "error parsing parameter index");
1719         return NULL;
1720     }
1721
1722     idx = parse_expression_leave(parser, true, false, false);
1723     if (!idx)
1724         return NULL;
1725
1726     if (parser->tok != ',') {
1727         if (parser->tok != ')') {
1728             ast_unref(idx);
1729             parseerror(parser, "expected comma after parameter index");
1730             return NULL;
1731         }
1732         /* vararg piping: ...(start) */
1733         out = (ast_expression*)ast_argpipe_new(ctx, idx);
1734         return out;
1735     }
1736
1737     if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1738         ast_unref(idx);
1739         parseerror(parser, "expected typename for vararg");
1740         return NULL;
1741     }
1742
1743     typevar = parse_typename(parser, NULL, NULL);
1744     if (!typevar) {
1745         ast_unref(idx);
1746         return NULL;
1747     }
1748
1749     if (parser->tok != ')') {
1750         ast_unref(idx);
1751         ast_delete(typevar);
1752         parseerror(parser, "expected closing paren");
1753         return NULL;
1754     }
1755
1756     if (funtype->expression.varparam &&
1757         !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1758     {
1759         char ty1[1024];
1760         char ty2[1024];
1761         ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1762         ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1763         compile_error(ast_ctx(typevar),
1764                       "function was declared to take varargs of type `%s`, requested type is: %s",
1765                       ty2, ty1);
1766     }
1767
1768     out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1769     ast_type_adopt(out, typevar);
1770     ast_delete(typevar);
1771     return out;
1772 }
1773
1774 static ast_expression* parse_vararg(parser_t *parser)
1775 {
1776     bool           old_noops = parser->lex->flags.noops;
1777
1778     ast_expression *out;
1779
1780     parser->lex->flags.noops = true;
1781     out = parse_vararg_do(parser);
1782
1783     parser->lex->flags.noops = old_noops;
1784     return out;
1785 }
1786
1787 /* not to be exposed */
1788 extern bool ftepp_predef_exists(const char *name);
1789
1790 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1791 {
1792     if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1793         parser->tok == TOKEN_IDENT &&
1794         !strcmp(parser_tokval(parser), "_"))
1795     {
1796         /* a translatable string */
1797         ast_value *val;
1798
1799         parser->lex->flags.noops = true;
1800         if (!parser_next(parser) || parser->tok != '(') {
1801             parseerror(parser, "use _(\"string\") to create a translatable string constant");
1802             return false;
1803         }
1804         parser->lex->flags.noops = false;
1805         if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1806             parseerror(parser, "expected a constant string in translatable-string extension");
1807             return false;
1808         }
1809         val = parser_const_string(parser, parser_tokval(parser), true);
1810         if (!val)
1811             return false;
1812         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1813
1814         if (!parser_next(parser) || parser->tok != ')') {
1815             parseerror(parser, "expected closing paren after translatable string");
1816             return false;
1817         }
1818         return true;
1819     }
1820     else if (parser->tok == TOKEN_DOTS)
1821     {
1822         ast_expression *va;
1823         if (!OPTS_FLAG(VARIADIC_ARGS)) {
1824             parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1825             return false;
1826         }
1827         va = parse_vararg(parser);
1828         if (!va)
1829             return false;
1830         vec_push(sy->out, syexp(parser_ctx(parser), va));
1831         return true;
1832     }
1833     else if (parser->tok == TOKEN_FLOATCONST) {
1834         ast_value *val;
1835         val = parser_const_float(parser, (parser_token(parser)->constval.f));
1836         if (!val)
1837             return false;
1838         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1839         return true;
1840     }
1841     else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1842         ast_value *val;
1843         val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1844         if (!val)
1845             return false;
1846         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1847         return true;
1848     }
1849     else if (parser->tok == TOKEN_STRINGCONST) {
1850         ast_value *val;
1851         val = parser_const_string(parser, parser_tokval(parser), false);
1852         if (!val)
1853             return false;
1854         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1855         return true;
1856     }
1857     else if (parser->tok == TOKEN_VECTORCONST) {
1858         ast_value *val;
1859         val = parser_const_vector(parser, parser_token(parser)->constval.v);
1860         if (!val)
1861             return false;
1862         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1863         return true;
1864     }
1865     else if (parser->tok == TOKEN_IDENT)
1866     {
1867         const char     *ctoken = parser_tokval(parser);
1868         ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1869         ast_expression *var;
1870         /* a_vector.{x,y,z} */
1871         if (!vec_size(sy->ops) ||
1872             !vec_last(sy->ops).etype ||
1873             operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1874             (prev >= intrinsic_debug_typestring &&
1875              prev <= intrinsic_debug_typestring))
1876         {
1877             /* When adding more intrinsics, fix the above condition */
1878             prev = NULL;
1879         }
1880         if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1881         {
1882             var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1883         } else {
1884             var = parser_find_var(parser, parser_tokval(parser));
1885             if (!var)
1886                 var = parser_find_field(parser, parser_tokval(parser));
1887         }
1888         if (!var && with_labels) {
1889             var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1890             if (!with_labels) {
1891                 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1892                 var = (ast_expression*)lbl;
1893                 vec_push(parser->labels, lbl);
1894             }
1895         }
1896         if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1897             var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
1898         if (!var) {
1899             /* intrinsics */
1900             if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1901                 var = (ast_expression*)intrinsic_debug_typestring;
1902             }
1903             /* now we try for the real intrinsic hashtable. If the string
1904              * begins with __builtin, we simply skip past it, otherwise we
1905              * use the identifier as is.
1906              */
1907             else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1908                 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1909             }
1910
1911             if (!var) {
1912                 char *correct = NULL;
1913                 size_t i;
1914
1915                 /*
1916                  * sometimes people use preprocessing predefs without enabling them
1917                  * i've done this thousands of times already myself.  Lets check for
1918                  * it in the predef table.  And diagnose it better :)
1919                  */
1920                 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1921                     parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1922                     return false;
1923                 }
1924
1925                 /*
1926                  * TODO: determine the best score for the identifier: be it
1927                  * a variable, a field.
1928                  *
1929                  * We should also consider adding correction tables for
1930                  * other things as well.
1931                  */
1932                 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1933                     correction_t corr;
1934                     correct_init(&corr);
1935
1936                     for (i = 0; i < vec_size(parser->correct_variables); i++) {
1937                         correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1938                         if (strcmp(correct, parser_tokval(parser))) {
1939                             break;
1940                         } else if (correct) {
1941                             mem_d(correct);
1942                             correct = NULL;
1943                         }
1944                     }
1945                     correct_free(&corr);
1946
1947                     if (correct) {
1948                         parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1949                         mem_d(correct);
1950                         return false;
1951                     }
1952                 }
1953                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1954                 return false;
1955             }
1956         }
1957         else
1958         {
1959             if (ast_istype(var, ast_value)) {
1960                 ((ast_value*)var)->uses++;
1961             }
1962             else if (ast_istype(var, ast_member)) {
1963                 ast_member *mem = (ast_member*)var;
1964                 if (ast_istype(mem->owner, ast_value))
1965                     ((ast_value*)(mem->owner))->uses++;
1966             }
1967         }
1968         vec_push(sy->out, syexp(parser_ctx(parser), var));
1969         return true;
1970     }
1971     parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1972     return false;
1973 }
1974
1975 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1976 {
1977     ast_expression *expr = NULL;
1978     shunt sy;
1979     size_t i;
1980     bool wantop = false;
1981     /* only warn once about an assignment in a truth value because the current code
1982      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1983      */
1984     bool warn_truthvalue = true;
1985
1986     /* count the parens because an if starts with one, so the
1987      * end of a condition is an unmatched closing paren
1988      */
1989     int ternaries = 0;
1990
1991     memset(&sy, 0, sizeof(sy));
1992
1993     parser->lex->flags.noops = false;
1994
1995     parser_reclassify_token(parser);
1996
1997     while (true)
1998     {
1999         if (parser->tok == TOKEN_TYPENAME) {
2000             parseerror(parser, "unexpected typename");
2001             goto onerr;
2002         }
2003
2004         if (parser->tok == TOKEN_OPERATOR)
2005         {
2006             /* classify the operator */
2007             const oper_info *op;
2008             const oper_info *olast = NULL;
2009             size_t o;
2010             for (o = 0; o < operator_count; ++o) {
2011                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2012                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2013                     !strcmp(parser_tokval(parser), operators[o].op))
2014                 {
2015                     break;
2016                 }
2017             }
2018             if (o == operator_count) {
2019                 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2020                 goto onerr;
2021             }
2022             /* found an operator */
2023             op = &operators[o];
2024
2025             /* when declaring variables, a comma starts a new variable */
2026             if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2027                 /* fixup the token */
2028                 parser->tok = ',';
2029                 break;
2030             }
2031
2032             /* a colon without a pervious question mark cannot be a ternary */
2033             if (!ternaries && op->id == opid2(':','?')) {
2034                 parser->tok = ':';
2035                 break;
2036             }
2037
2038             if (op->id == opid1(',')) {
2039                 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2040                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2041                 }
2042             }
2043
2044             if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2045                 olast = &operators[vec_last(sy.ops).etype-1];
2046
2047 #define IsAssignOp(x) (\
2048                 (x) == opid1('=') || \
2049                 (x) == opid2('+','=') || \
2050                 (x) == opid2('-','=') || \
2051                 (x) == opid2('*','=') || \
2052                 (x) == opid2('/','=') || \
2053                 (x) == opid2('%','=') || \
2054                 (x) == opid2('&','=') || \
2055                 (x) == opid2('|','=') || \
2056                 (x) == opid3('&','~','=') \
2057                 )
2058             if (warn_truthvalue) {
2059                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2060                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2061                      (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2062                    )
2063                 {
2064                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2065                     warn_truthvalue = false;
2066                 }
2067             }
2068
2069             while (olast && (
2070                     (op->prec < olast->prec) ||
2071                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2072             {
2073                 if (!parser_sy_apply_operator(parser, &sy))
2074                     goto onerr;
2075                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2076                     olast = &operators[vec_last(sy.ops).etype-1];
2077                 else
2078                     olast = NULL;
2079             }
2080
2081             if (op->id == opid1('(')) {
2082                 if (wantop) {
2083                     size_t sycount = vec_size(sy.out);
2084                     /* we expected an operator, this is the function-call operator */
2085                     vec_push(sy.paren, PAREN_FUNC);
2086                     vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2087                     vec_push(sy.argc, 0);
2088                 } else {
2089                     vec_push(sy.paren, PAREN_EXPR);
2090                     vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2091                 }
2092                 wantop = false;
2093             } else if (op->id == opid1('[')) {
2094                 if (!wantop) {
2095                     parseerror(parser, "unexpected array subscript");
2096                     goto onerr;
2097                 }
2098                 vec_push(sy.paren, PAREN_INDEX);
2099                 /* push both the operator and the paren, this makes life easier */
2100                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2101                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2102                 wantop = false;
2103             } else if (op->id == opid2('?',':')) {
2104                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2105                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2106                 wantop = false;
2107                 ++ternaries;
2108                 vec_push(sy.paren, PAREN_TERNARY1);
2109             } else if (op->id == opid2(':','?')) {
2110                 if (!vec_size(sy.paren)) {
2111                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2112                     goto onerr;
2113                 }
2114                 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2115                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2116                     goto onerr;
2117                 }
2118                 if (!parser_close_paren(parser, &sy))
2119                     goto onerr;
2120                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2121                 wantop = false;
2122                 --ternaries;
2123             } else {
2124                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2125                 wantop = !!(op->flags & OP_SUFFIX);
2126             }
2127         }
2128         else if (parser->tok == ')') {
2129             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2130                 if (!parser_sy_apply_operator(parser, &sy))
2131                     goto onerr;
2132             }
2133             if (!vec_size(sy.paren))
2134                 break;
2135             if (wantop) {
2136                 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2137                     parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2138                     goto onerr;
2139                 }
2140                 if (!parser_close_paren(parser, &sy))
2141                     goto onerr;
2142             } else {
2143                 /* must be a function call without parameters */
2144                 if (vec_last(sy.paren) != PAREN_FUNC) {
2145                     parseerror(parser, "closing paren in invalid position");
2146                     goto onerr;
2147                 }
2148                 if (!parser_close_paren(parser, &sy))
2149                     goto onerr;
2150             }
2151             wantop = true;
2152         }
2153         else if (parser->tok == '(') {
2154             parseerror(parser, "internal error: '(' should be classified as operator");
2155             goto onerr;
2156         }
2157         else if (parser->tok == '[') {
2158             parseerror(parser, "internal error: '[' should be classified as operator");
2159             goto onerr;
2160         }
2161         else if (parser->tok == ']') {
2162             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2163                 if (!parser_sy_apply_operator(parser, &sy))
2164                     goto onerr;
2165             }
2166             if (!vec_size(sy.paren))
2167                 break;
2168             if (vec_last(sy.paren) != PAREN_INDEX) {
2169                 parseerror(parser, "mismatched parentheses, unexpected ']'");
2170                 goto onerr;
2171             }
2172             if (!parser_close_paren(parser, &sy))
2173                 goto onerr;
2174             wantop = true;
2175         }
2176         else if (!wantop) {
2177             if (!parse_sya_operand(parser, &sy, with_labels))
2178                 goto onerr;
2179 #if 0
2180             if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2181                 vec_last(sy.argc)++;
2182 #endif
2183             wantop = true;
2184         }
2185         else {
2186             /* in this case we might want to allow constant string concatenation */
2187             bool concatenated = false;
2188             if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2189                 ast_expression *lexpr = vec_last(sy.out).out;
2190                 if (ast_istype(lexpr, ast_value)) {
2191                     ast_value *last = (ast_value*)lexpr;
2192                     if (last->isimm == true && last->cvq == CV_CONST &&
2193                         last->hasvalue && last->expression.vtype == TYPE_STRING)
2194                     {
2195                         char *newstr = NULL;
2196                         util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2197                         vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2198                         mem_d(newstr);
2199                         concatenated = true;
2200                     }
2201                 }
2202             }
2203             if (!concatenated) {
2204                 parseerror(parser, "expected operator or end of statement");
2205                 goto onerr;
2206             }
2207         }
2208
2209         if (!parser_next(parser)) {
2210             goto onerr;
2211         }
2212         if (parser->tok == ';' ||
2213             ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2214             (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2215         {
2216             break;
2217         }
2218     }
2219
2220     while (vec_size(sy.ops)) {
2221         if (!parser_sy_apply_operator(parser, &sy))
2222             goto onerr;
2223     }
2224
2225     parser->lex->flags.noops = true;
2226     if (vec_size(sy.out) != 1) {
2227         parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
2228         expr = NULL;
2229     } else
2230         expr = sy.out[0].out;
2231     vec_free(sy.out);
2232     vec_free(sy.ops);
2233     if (vec_size(sy.paren)) {
2234         parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2235         return NULL;
2236     }
2237     vec_free(sy.paren);
2238     vec_free(sy.argc);
2239     return expr;
2240
2241 onerr:
2242     parser->lex->flags.noops = true;
2243     for (i = 0; i < vec_size(sy.out); ++i) {
2244         if (sy.out[i].out)
2245             ast_unref(sy.out[i].out);
2246     }
2247     vec_free(sy.out);
2248     vec_free(sy.ops);
2249     vec_free(sy.paren);
2250     vec_free(sy.argc);
2251     return NULL;
2252 }
2253
2254 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2255 {
2256     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2257     if (!e)
2258         return NULL;
2259     if (parser->tok != ';') {
2260         parseerror(parser, "semicolon expected after expression");
2261         ast_unref(e);
2262         return NULL;
2263     }
2264     if (!parser_next(parser)) {
2265         ast_unref(e);
2266         return NULL;
2267     }
2268     return e;
2269 }
2270
2271 static void parser_enterblock(parser_t *parser)
2272 {
2273     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2274     vec_push(parser->_blocklocals, vec_size(parser->_locals));
2275     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2276     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2277     vec_push(parser->_block_ctx, parser_ctx(parser));
2278
2279     /* corrector */
2280     vec_push(parser->correct_variables, correct_trie_new());
2281     vec_push(parser->correct_variables_score, NULL);
2282 }
2283
2284 static bool parser_leaveblock(parser_t *parser)
2285 {
2286     bool   rv = true;
2287     size_t locals, typedefs;
2288
2289     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2290         parseerror(parser, "internal error: parser_leaveblock with no block");
2291         return false;
2292     }
2293
2294     util_htdel(vec_last(parser->variables));
2295     correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2296
2297     vec_pop(parser->variables);
2298     vec_pop(parser->correct_variables);
2299     vec_pop(parser->correct_variables_score);
2300     if (!vec_size(parser->_blocklocals)) {
2301         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2302         return false;
2303     }
2304
2305     locals = vec_last(parser->_blocklocals);
2306     vec_pop(parser->_blocklocals);
2307     while (vec_size(parser->_locals) != locals) {
2308         ast_expression *e = vec_last(parser->_locals);
2309         ast_value      *v = (ast_value*)e;
2310         vec_pop(parser->_locals);
2311         if (ast_istype(e, ast_value) && !v->uses) {
2312             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2313                 rv = false;
2314         }
2315     }
2316
2317     typedefs = vec_last(parser->_blocktypedefs);
2318     while (vec_size(parser->_typedefs) != typedefs) {
2319         ast_delete(vec_last(parser->_typedefs));
2320         vec_pop(parser->_typedefs);
2321     }
2322     util_htdel(vec_last(parser->typedefs));
2323     vec_pop(parser->typedefs);
2324
2325     vec_pop(parser->_block_ctx);
2326
2327     return rv;
2328 }
2329
2330 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2331 {
2332     vec_push(parser->_locals, e);
2333     util_htset(vec_last(parser->variables), name, (void*)e);
2334
2335     /* corrector */
2336     correct_add (
2337          vec_last(parser->correct_variables),
2338         &vec_last(parser->correct_variables_score),
2339         name
2340     );
2341 }
2342
2343 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2344 {
2345     vec_push(parser->globals, e);
2346     util_htset(parser->htglobals, name, e);
2347
2348     /* corrector */
2349     correct_add (
2350          parser->correct_variables[0],
2351         &parser->correct_variables_score[0],
2352         name
2353     );
2354 }
2355
2356 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2357 {
2358     bool       ifnot = false;
2359     ast_unary *unary;
2360     ast_expression *prev;
2361
2362     if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2363         char ty[1024];
2364         ast_type_to_string(cond, ty, sizeof(ty));
2365         compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2366     }
2367
2368     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2369     {
2370         prev = cond;
2371         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2372         if (!cond) {
2373             ast_unref(prev);
2374             parseerror(parser, "internal error: failed to process condition");
2375             return NULL;
2376         }
2377         ifnot = !ifnot;
2378     }
2379     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2380     {
2381         /* vector types need to be cast to true booleans */
2382         ast_binary *bin = (ast_binary*)cond;
2383         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2384         {
2385             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2386             prev = cond;
2387             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2388             if (!cond) {
2389                 ast_unref(prev);
2390                 parseerror(parser, "internal error: failed to process condition");
2391                 return NULL;
2392             }
2393             ifnot = !ifnot;
2394         }
2395     }
2396
2397     unary = (ast_unary*)cond;
2398     while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2399     {
2400         cond = unary->operand;
2401         unary->operand = NULL;
2402         ast_delete(unary);
2403         ifnot = !ifnot;
2404         unary = (ast_unary*)cond;
2405     }
2406
2407     if (!cond)
2408         parseerror(parser, "internal error: failed to process condition");
2409
2410     if (ifnot) *_ifnot = !*_ifnot;
2411     return cond;
2412 }
2413
2414 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2415 {
2416     ast_ifthen *ifthen;
2417     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2418     bool ifnot = false;
2419
2420     lex_ctx ctx = parser_ctx(parser);
2421
2422     (void)block; /* not touching */
2423
2424     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2425     if (!parser_next(parser)) {
2426         parseerror(parser, "expected condition or 'not'");
2427         return false;
2428     }
2429     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2430         ifnot = true;
2431         if (!parser_next(parser)) {
2432             parseerror(parser, "expected condition in parenthesis");
2433             return false;
2434         }
2435     }
2436     if (parser->tok != '(') {
2437         parseerror(parser, "expected 'if' condition in parenthesis");
2438         return false;
2439     }
2440     /* parse into the expression */
2441     if (!parser_next(parser)) {
2442         parseerror(parser, "expected 'if' condition after opening paren");
2443         return false;
2444     }
2445     /* parse the condition */
2446     cond = parse_expression_leave(parser, false, true, false);
2447     if (!cond)
2448         return false;
2449     /* closing paren */
2450     if (parser->tok != ')') {
2451         parseerror(parser, "expected closing paren after 'if' condition");
2452         ast_unref(cond);
2453         return false;
2454     }
2455     /* parse into the 'then' branch */
2456     if (!parser_next(parser)) {
2457         parseerror(parser, "expected statement for on-true branch of 'if'");
2458         ast_unref(cond);
2459         return false;
2460     }
2461     if (!parse_statement_or_block(parser, &ontrue)) {
2462         ast_unref(cond);
2463         return false;
2464     }
2465     if (!ontrue)
2466         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2467     /* check for an else */
2468     if (!strcmp(parser_tokval(parser), "else")) {
2469         /* parse into the 'else' branch */
2470         if (!parser_next(parser)) {
2471             parseerror(parser, "expected on-false branch after 'else'");
2472             ast_delete(ontrue);
2473             ast_unref(cond);
2474             return false;
2475         }
2476         if (!parse_statement_or_block(parser, &onfalse)) {
2477             ast_delete(ontrue);
2478             ast_unref(cond);
2479             return false;
2480         }
2481     }
2482
2483     cond = process_condition(parser, cond, &ifnot);
2484     if (!cond) {
2485         if (ontrue)  ast_delete(ontrue);
2486         if (onfalse) ast_delete(onfalse);
2487         return false;
2488     }
2489
2490     if (ifnot)
2491         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2492     else
2493         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2494     *out = (ast_expression*)ifthen;
2495     return true;
2496 }
2497
2498 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2499 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2500 {
2501     bool rv;
2502     char *label = NULL;
2503
2504     /* skip the 'while' and get the body */
2505     if (!parser_next(parser)) {
2506         if (OPTS_FLAG(LOOP_LABELS))
2507             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2508         else
2509             parseerror(parser, "expected 'while' condition in parenthesis");
2510         return false;
2511     }
2512
2513     if (parser->tok == ':') {
2514         if (!OPTS_FLAG(LOOP_LABELS))
2515             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2516         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2517             parseerror(parser, "expected loop label");
2518             return false;
2519         }
2520         label = util_strdup(parser_tokval(parser));
2521         if (!parser_next(parser)) {
2522             mem_d(label);
2523             parseerror(parser, "expected 'while' condition in parenthesis");
2524             return false;
2525         }
2526     }
2527
2528     if (parser->tok != '(') {
2529         parseerror(parser, "expected 'while' condition in parenthesis");
2530         return false;
2531     }
2532
2533     vec_push(parser->breaks, label);
2534     vec_push(parser->continues, label);
2535
2536     rv = parse_while_go(parser, block, out);
2537     if (label)
2538         mem_d(label);
2539     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2540         parseerror(parser, "internal error: label stack corrupted");
2541         rv = false;
2542         ast_delete(*out);
2543         *out = NULL;
2544     }
2545     else {
2546         vec_pop(parser->breaks);
2547         vec_pop(parser->continues);
2548     }
2549     return rv;
2550 }
2551
2552 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2553 {
2554     ast_loop *aloop;
2555     ast_expression *cond, *ontrue;
2556
2557     bool ifnot = false;
2558
2559     lex_ctx ctx = parser_ctx(parser);
2560
2561     (void)block; /* not touching */
2562
2563     /* parse into the expression */
2564     if (!parser_next(parser)) {
2565         parseerror(parser, "expected 'while' condition after opening paren");
2566         return false;
2567     }
2568     /* parse the condition */
2569     cond = parse_expression_leave(parser, false, true, false);
2570     if (!cond)
2571         return false;
2572     /* closing paren */
2573     if (parser->tok != ')') {
2574         parseerror(parser, "expected closing paren after 'while' condition");
2575         ast_unref(cond);
2576         return false;
2577     }
2578     /* parse into the 'then' branch */
2579     if (!parser_next(parser)) {
2580         parseerror(parser, "expected while-loop body");
2581         ast_unref(cond);
2582         return false;
2583     }
2584     if (!parse_statement_or_block(parser, &ontrue)) {
2585         ast_unref(cond);
2586         return false;
2587     }
2588
2589     cond = process_condition(parser, cond, &ifnot);
2590     if (!cond) {
2591         ast_unref(ontrue);
2592         return false;
2593     }
2594     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2595     *out = (ast_expression*)aloop;
2596     return true;
2597 }
2598
2599 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2600 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2601 {
2602     bool rv;
2603     char *label = NULL;
2604
2605     /* skip the 'do' and get the body */
2606     if (!parser_next(parser)) {
2607         if (OPTS_FLAG(LOOP_LABELS))
2608             parseerror(parser, "expected loop label or body");
2609         else
2610             parseerror(parser, "expected loop body");
2611         return false;
2612     }
2613
2614     if (parser->tok == ':') {
2615         if (!OPTS_FLAG(LOOP_LABELS))
2616             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2617         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2618             parseerror(parser, "expected loop label");
2619             return false;
2620         }
2621         label = util_strdup(parser_tokval(parser));
2622         if (!parser_next(parser)) {
2623             mem_d(label);
2624             parseerror(parser, "expected loop body");
2625             return false;
2626         }
2627     }
2628
2629     vec_push(parser->breaks, label);
2630     vec_push(parser->continues, label);
2631
2632     rv = parse_dowhile_go(parser, block, out);
2633     if (label)
2634         mem_d(label);
2635     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2636         parseerror(parser, "internal error: label stack corrupted");
2637         rv = false;
2638         ast_delete(*out);
2639         *out = NULL;
2640     }
2641     else {
2642         vec_pop(parser->breaks);
2643         vec_pop(parser->continues);
2644     }
2645     return rv;
2646 }
2647
2648 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2649 {
2650     ast_loop *aloop;
2651     ast_expression *cond, *ontrue;
2652
2653     bool ifnot = false;
2654
2655     lex_ctx ctx = parser_ctx(parser);
2656
2657     (void)block; /* not touching */
2658
2659     if (!parse_statement_or_block(parser, &ontrue))
2660         return false;
2661
2662     /* expect the "while" */
2663     if (parser->tok != TOKEN_KEYWORD ||
2664         strcmp(parser_tokval(parser), "while"))
2665     {
2666         parseerror(parser, "expected 'while' and condition");
2667         ast_delete(ontrue);
2668         return false;
2669     }
2670
2671     /* skip the 'while' and check for opening paren */
2672     if (!parser_next(parser) || parser->tok != '(') {
2673         parseerror(parser, "expected 'while' condition in parenthesis");
2674         ast_delete(ontrue);
2675         return false;
2676     }
2677     /* parse into the expression */
2678     if (!parser_next(parser)) {
2679         parseerror(parser, "expected 'while' condition after opening paren");
2680         ast_delete(ontrue);
2681         return false;
2682     }
2683     /* parse the condition */
2684     cond = parse_expression_leave(parser, false, true, false);
2685     if (!cond)
2686         return false;
2687     /* closing paren */
2688     if (parser->tok != ')') {
2689         parseerror(parser, "expected closing paren after 'while' condition");
2690         ast_delete(ontrue);
2691         ast_unref(cond);
2692         return false;
2693     }
2694     /* parse on */
2695     if (!parser_next(parser) || parser->tok != ';') {
2696         parseerror(parser, "expected semicolon after condition");
2697         ast_delete(ontrue);
2698         ast_unref(cond);
2699         return false;
2700     }
2701
2702     if (!parser_next(parser)) {
2703         parseerror(parser, "parse error");
2704         ast_delete(ontrue);
2705         ast_unref(cond);
2706         return false;
2707     }
2708
2709     cond = process_condition(parser, cond, &ifnot);
2710     if (!cond) {
2711         ast_delete(ontrue);
2712         return false;
2713     }
2714     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2715     *out = (ast_expression*)aloop;
2716     return true;
2717 }
2718
2719 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2720 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2721 {
2722     bool rv;
2723     char *label = NULL;
2724
2725     /* skip the 'for' and check for opening paren */
2726     if (!parser_next(parser)) {
2727         if (OPTS_FLAG(LOOP_LABELS))
2728             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2729         else
2730             parseerror(parser, "expected 'for' expressions in parenthesis");
2731         return false;
2732     }
2733
2734     if (parser->tok == ':') {
2735         if (!OPTS_FLAG(LOOP_LABELS))
2736             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2737         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2738             parseerror(parser, "expected loop label");
2739             return false;
2740         }
2741         label = util_strdup(parser_tokval(parser));
2742         if (!parser_next(parser)) {
2743             mem_d(label);
2744             parseerror(parser, "expected 'for' expressions in parenthesis");
2745             return false;
2746         }
2747     }
2748
2749     if (parser->tok != '(') {
2750         parseerror(parser, "expected 'for' expressions in parenthesis");
2751         return false;
2752     }
2753
2754     vec_push(parser->breaks, label);
2755     vec_push(parser->continues, label);
2756
2757     rv = parse_for_go(parser, block, out);
2758     if (label)
2759         mem_d(label);
2760     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2761         parseerror(parser, "internal error: label stack corrupted");
2762         rv = false;
2763         ast_delete(*out);
2764         *out = NULL;
2765     }
2766     else {
2767         vec_pop(parser->breaks);
2768         vec_pop(parser->continues);
2769     }
2770     return rv;
2771 }
2772 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2773 {
2774     ast_loop       *aloop;
2775     ast_expression *initexpr, *cond, *increment, *ontrue;
2776     ast_value      *typevar;
2777
2778     bool ifnot  = false;
2779
2780     lex_ctx ctx = parser_ctx(parser);
2781
2782     parser_enterblock(parser);
2783
2784     initexpr  = NULL;
2785     cond      = NULL;
2786     increment = NULL;
2787     ontrue    = NULL;
2788
2789     /* parse into the expression */
2790     if (!parser_next(parser)) {
2791         parseerror(parser, "expected 'for' initializer after opening paren");
2792         goto onerr;
2793     }
2794
2795     typevar = NULL;
2796     if (parser->tok == TOKEN_IDENT)
2797         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2798
2799     if (typevar || parser->tok == TOKEN_TYPENAME) {
2800 #if 0
2801         if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2802             if (parsewarning(parser, WARN_EXTENSIONS,
2803                              "current standard does not allow variable declarations in for-loop initializers"))
2804                 goto onerr;
2805         }
2806 #endif
2807         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2808             goto onerr;
2809     }
2810     else if (parser->tok != ';')
2811     {
2812         initexpr = parse_expression_leave(parser, false, false, false);
2813         if (!initexpr)
2814             goto onerr;
2815     }
2816
2817     /* move on to condition */
2818     if (parser->tok != ';') {
2819         parseerror(parser, "expected semicolon after for-loop initializer");
2820         goto onerr;
2821     }
2822     if (!parser_next(parser)) {
2823         parseerror(parser, "expected for-loop condition");
2824         goto onerr;
2825     }
2826
2827     /* parse the condition */
2828     if (parser->tok != ';') {
2829         cond = parse_expression_leave(parser, false, true, false);
2830         if (!cond)
2831             goto onerr;
2832     }
2833
2834     /* move on to incrementor */
2835     if (parser->tok != ';') {
2836         parseerror(parser, "expected semicolon after for-loop initializer");
2837         goto onerr;
2838     }
2839     if (!parser_next(parser)) {
2840         parseerror(parser, "expected for-loop condition");
2841         goto onerr;
2842     }
2843
2844     /* parse the incrementor */
2845     if (parser->tok != ')') {
2846         lex_ctx condctx = parser_ctx(parser);
2847         increment = parse_expression_leave(parser, false, false, false);
2848         if (!increment)
2849             goto onerr;
2850         if (!ast_side_effects(increment)) {
2851             if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2852                 goto onerr;
2853         }
2854     }
2855
2856     /* closing paren */
2857     if (parser->tok != ')') {
2858         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2859         goto onerr;
2860     }
2861     /* parse into the 'then' branch */
2862     if (!parser_next(parser)) {
2863         parseerror(parser, "expected for-loop body");
2864         goto onerr;
2865     }
2866     if (!parse_statement_or_block(parser, &ontrue))
2867         goto onerr;
2868
2869     if (cond) {
2870         cond = process_condition(parser, cond, &ifnot);
2871         if (!cond)
2872             goto onerr;
2873     }
2874     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2875     *out = (ast_expression*)aloop;
2876
2877     if (!parser_leaveblock(parser)) {
2878         ast_delete(aloop);
2879         return false;
2880     }
2881     return true;
2882 onerr:
2883     if (initexpr)  ast_unref(initexpr);
2884     if (cond)      ast_unref(cond);
2885     if (increment) ast_unref(increment);
2886     (void)!parser_leaveblock(parser);
2887     return false;
2888 }
2889
2890 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2891 {
2892     ast_expression *exp      = NULL;
2893     ast_expression *var      = NULL;
2894     ast_return     *ret      = NULL;
2895     ast_value      *retval   = parser->function->return_value;
2896     ast_value      *expected = parser->function->vtype;
2897
2898     lex_ctx ctx = parser_ctx(parser);
2899
2900     (void)block; /* not touching */
2901
2902     if (!parser_next(parser)) {
2903         parseerror(parser, "expected return expression");
2904         return false;
2905     }
2906
2907     /* return assignments */
2908     if (parser->tok == '=') {
2909         if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2910             parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2911             return false;
2912         }
2913
2914         if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2915             char ty1[1024];
2916             ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2917             parseerror(parser, "invalid return type: `%s'", ty1);
2918             return false;
2919         }
2920
2921         if (!parser_next(parser)) {
2922             parseerror(parser, "expected return assignment expression");
2923             return false;
2924         }
2925
2926         if (!(exp = parse_expression_leave(parser, false, false, false)))
2927             return false;
2928
2929         /* prepare the return value */
2930         if (!retval) {
2931             retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2932             ast_type_adopt(retval, expected->expression.next);
2933             parser->function->return_value = retval;
2934         }
2935
2936         if (!ast_compare_type(exp, (ast_expression*)retval)) {
2937             char ty1[1024], ty2[1024];
2938             ast_type_to_string(exp, ty1, sizeof(ty1));
2939             ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2940             parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2941         }
2942
2943         /* store to 'return' local variable */
2944         var = (ast_expression*)ast_store_new(
2945             ctx,
2946             type_store_instr[expected->expression.next->vtype],
2947             (ast_expression*)retval, exp);
2948
2949         if (!var) {
2950             ast_unref(exp);
2951             return false;
2952         }
2953
2954         if (parser->tok != ';')
2955             parseerror(parser, "missing semicolon after return assignment");
2956         else if (!parser_next(parser))
2957             parseerror(parser, "parse error after return assignment");
2958
2959         *out = var;
2960         return true;
2961     }
2962
2963     if (parser->tok != ';') {
2964         exp = parse_expression(parser, false, false);
2965         if (!exp)
2966             return false;
2967
2968         if (exp->vtype != TYPE_NIL &&
2969             exp->vtype != ((ast_expression*)expected)->next->vtype)
2970         {
2971             parseerror(parser, "return with invalid expression");
2972         }
2973
2974         ret = ast_return_new(ctx, exp);
2975         if (!ret) {
2976             ast_unref(exp);
2977             return false;
2978         }
2979     } else {
2980         if (!parser_next(parser))
2981             parseerror(parser, "parse error");
2982
2983         if (!retval && expected->expression.next->vtype != TYPE_VOID)
2984         {
2985             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2986         }
2987         ret = ast_return_new(ctx, (ast_expression*)retval);
2988     }
2989     *out = (ast_expression*)ret;
2990     return true;
2991 }
2992
2993 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2994 {
2995     size_t       i;
2996     unsigned int levels = 0;
2997     lex_ctx      ctx = parser_ctx(parser);
2998     const char **loops = (is_continue ? parser->continues : parser->breaks);
2999
3000     (void)block; /* not touching */
3001     if (!parser_next(parser)) {
3002         parseerror(parser, "expected semicolon or loop label");
3003         return false;
3004     }
3005
3006     if (!vec_size(loops)) {
3007         if (is_continue)
3008             parseerror(parser, "`continue` can only be used inside loops");
3009         else
3010             parseerror(parser, "`break` can only be used inside loops or switches");
3011     }
3012
3013     if (parser->tok == TOKEN_IDENT) {
3014         if (!OPTS_FLAG(LOOP_LABELS))
3015             parseerror(parser, "labeled loops not activated, try using -floop-labels");
3016         i = vec_size(loops);
3017         while (i--) {
3018             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
3019                 break;
3020             if (!i) {
3021                 parseerror(parser, "no such loop to %s: `%s`",
3022                            (is_continue ? "continue" : "break out of"),
3023                            parser_tokval(parser));
3024                 return false;
3025             }
3026             ++levels;
3027         }
3028         if (!parser_next(parser)) {
3029             parseerror(parser, "expected semicolon");
3030             return false;
3031         }
3032     }
3033
3034     if (parser->tok != ';') {
3035         parseerror(parser, "expected semicolon");
3036         return false;
3037     }
3038
3039     if (!parser_next(parser))
3040         parseerror(parser, "parse error");
3041
3042     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
3043     return true;
3044 }
3045
3046 /* returns true when it was a variable qualifier, false otherwise!
3047  * on error, cvq is set to CV_WRONG
3048  */
3049 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
3050 {
3051     bool had_const    = false;
3052     bool had_var      = false;
3053     bool had_noref    = false;
3054     bool had_attrib   = false;
3055     bool had_static   = false;
3056     uint32_t flags    = 0;
3057
3058     *cvq = CV_NONE;
3059     for (;;) {
3060         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3061             had_attrib = true;
3062             /* parse an attribute */
3063             if (!parser_next(parser)) {
3064                 parseerror(parser, "expected attribute after `[[`");
3065                 *cvq = CV_WRONG;
3066                 return false;
3067             }
3068             if (!strcmp(parser_tokval(parser), "noreturn")) {
3069                 flags |= AST_FLAG_NORETURN;
3070                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3071                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3072                     *cvq = CV_WRONG;
3073                     return false;
3074                 }
3075             }
3076             else if (!strcmp(parser_tokval(parser), "noref")) {
3077                 had_noref = true;
3078                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3079                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3080                     *cvq = CV_WRONG;
3081                     return false;
3082                 }
3083             }
3084             else if (!strcmp(parser_tokval(parser), "inline")) {
3085                 flags |= AST_FLAG_INLINE;
3086                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3087                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3088                     *cvq = CV_WRONG;
3089                     return false;
3090                 }
3091             }
3092             else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3093                 flags   |= AST_FLAG_ALIAS;
3094                 *message = NULL;
3095
3096                 if (!parser_next(parser)) {
3097                     parseerror(parser, "parse error in attribute");
3098                     goto argerr;
3099                 }
3100
3101                 if (parser->tok == '(') {
3102                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3103                         parseerror(parser, "`alias` attribute missing parameter");
3104                         goto argerr;
3105                     }
3106
3107                     *message = util_strdup(parser_tokval(parser));
3108
3109                     if (!parser_next(parser)) {
3110                         parseerror(parser, "parse error in attribute");
3111                         goto argerr;
3112                     }
3113
3114                     if (parser->tok != ')') {
3115                         parseerror(parser, "`alias` attribute expected `)` after parameter");
3116                         goto argerr;
3117                     }
3118
3119                     if (!parser_next(parser)) {
3120                         parseerror(parser, "parse error in attribute");
3121                         goto argerr;
3122                     }
3123                 }
3124
3125                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3126                     parseerror(parser, "`alias` attribute expected `]]`");
3127                     goto argerr;
3128                 }
3129             }
3130             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3131                 flags   |= AST_FLAG_DEPRECATED;
3132                 *message = NULL;
3133
3134                 if (!parser_next(parser)) {
3135                     parseerror(parser, "parse error in attribute");
3136                     goto argerr;
3137                 }
3138
3139                 if (parser->tok == '(') {
3140                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3141                         parseerror(parser, "`deprecated` attribute missing parameter");
3142                         goto argerr;
3143                     }
3144
3145                     *message = util_strdup(parser_tokval(parser));
3146
3147                     if (!parser_next(parser)) {
3148                         parseerror(parser, "parse error in attribute");
3149                         goto argerr;
3150                     }
3151
3152                     if(parser->tok != ')') {
3153                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3154                         goto argerr;
3155                     }
3156
3157                     if (!parser_next(parser)) {
3158                         parseerror(parser, "parse error in attribute");
3159                         goto argerr;
3160                     }
3161                 }
3162                 /* no message */
3163                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3164                     parseerror(parser, "`deprecated` attribute expected `]]`");
3165
3166                     argerr: /* ugly */
3167                     if (*message) mem_d(*message);
3168                     *message = NULL;
3169                     *cvq     = CV_WRONG;
3170                     return false;
3171                 }
3172             }
3173             else
3174             {
3175                 /* Skip tokens until we hit a ]] */
3176                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3177                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3178                     if (!parser_next(parser)) {
3179                         parseerror(parser, "error inside attribute");
3180                         *cvq = CV_WRONG;
3181                         return false;
3182                     }
3183                 }
3184             }
3185         }
3186         else if (with_local && !strcmp(parser_tokval(parser), "static"))
3187             had_static = true;
3188         else if (!strcmp(parser_tokval(parser), "const"))
3189             had_const = true;
3190         else if (!strcmp(parser_tokval(parser), "var"))
3191             had_var = true;
3192         else if (with_local && !strcmp(parser_tokval(parser), "local"))
3193             had_var = true;
3194         else if (!strcmp(parser_tokval(parser), "noref"))
3195             had_noref = true;
3196         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3197             return false;
3198         }
3199         else
3200             break;
3201         if (!parser_next(parser))
3202             goto onerr;
3203     }
3204     if (had_const)
3205         *cvq = CV_CONST;
3206     else if (had_var)
3207         *cvq = CV_VAR;
3208     else
3209         *cvq = CV_NONE;
3210     *noref     = had_noref;
3211     *is_static = had_static;
3212     *_flags    = flags;
3213     return true;
3214 onerr:
3215     parseerror(parser, "parse error after variable qualifier");
3216     *cvq = CV_WRONG;
3217     return true;
3218 }
3219
3220 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3221 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3222 {
3223     bool rv;
3224     char *label = NULL;
3225
3226     /* skip the 'while' and get the body */
3227     if (!parser_next(parser)) {
3228         if (OPTS_FLAG(LOOP_LABELS))
3229             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3230         else
3231             parseerror(parser, "expected 'switch' operand in parenthesis");
3232         return false;
3233     }
3234
3235     if (parser->tok == ':') {
3236         if (!OPTS_FLAG(LOOP_LABELS))
3237             parseerror(parser, "labeled loops not activated, try using -floop-labels");
3238         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3239             parseerror(parser, "expected loop label");
3240             return false;
3241         }
3242         label = util_strdup(parser_tokval(parser));
3243         if (!parser_next(parser)) {
3244             mem_d(label);
3245             parseerror(parser, "expected 'switch' operand in parenthesis");
3246             return false;
3247         }
3248     }
3249
3250     if (parser->tok != '(') {
3251         parseerror(parser, "expected 'switch' operand in parenthesis");
3252         return false;
3253     }
3254
3255     vec_push(parser->breaks, label);
3256
3257     rv = parse_switch_go(parser, block, out);
3258     if (label)
3259         mem_d(label);
3260     if (vec_last(parser->breaks) != label) {
3261         parseerror(parser, "internal error: label stack corrupted");
3262         rv = false;
3263         ast_delete(*out);
3264         *out = NULL;
3265     }
3266     else {
3267         vec_pop(parser->breaks);
3268     }
3269     return rv;
3270 }
3271
3272 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3273 {
3274     ast_expression *operand;
3275     ast_value      *opval;
3276     ast_value      *typevar;
3277     ast_switch     *switchnode;
3278     ast_switch_case swcase;
3279
3280     int  cvq;
3281     bool noref, is_static;
3282     uint32_t qflags = 0;
3283
3284     lex_ctx ctx = parser_ctx(parser);
3285
3286     (void)block; /* not touching */
3287     (void)opval;
3288
3289     /* parse into the expression */
3290     if (!parser_next(parser)) {
3291         parseerror(parser, "expected switch operand");
3292         return false;
3293     }
3294     /* parse the operand */
3295     operand = parse_expression_leave(parser, false, false, false);
3296     if (!operand)
3297         return false;
3298
3299     switchnode = ast_switch_new(ctx, operand);
3300
3301     /* closing paren */
3302     if (parser->tok != ')') {
3303         ast_delete(switchnode);
3304         parseerror(parser, "expected closing paren after 'switch' operand");
3305         return false;
3306     }
3307
3308     /* parse over the opening paren */
3309     if (!parser_next(parser) || parser->tok != '{') {
3310         ast_delete(switchnode);
3311         parseerror(parser, "expected list of cases");
3312         return false;
3313     }
3314
3315     if (!parser_next(parser)) {
3316         ast_delete(switchnode);
3317         parseerror(parser, "expected 'case' or 'default'");
3318         return false;
3319     }
3320
3321     /* new block; allow some variables to be declared here */
3322     parser_enterblock(parser);
3323     while (true) {
3324         typevar = NULL;
3325         if (parser->tok == TOKEN_IDENT)
3326             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3327         if (typevar || parser->tok == TOKEN_TYPENAME) {
3328             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3329                 ast_delete(switchnode);
3330                 return false;
3331             }
3332             continue;
3333         }
3334         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3335         {
3336             if (cvq == CV_WRONG) {
3337                 ast_delete(switchnode);
3338                 return false;
3339             }
3340             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3341                 ast_delete(switchnode);
3342                 return false;
3343             }
3344             continue;
3345         }
3346         break;
3347     }
3348
3349     /* case list! */
3350     while (parser->tok != '}') {
3351         ast_block *caseblock;
3352
3353         if (!strcmp(parser_tokval(parser), "case")) {
3354             if (!parser_next(parser)) {
3355                 ast_delete(switchnode);
3356                 parseerror(parser, "expected expression for case");
3357                 return false;
3358             }
3359             swcase.value = parse_expression_leave(parser, false, false, false);
3360             if (!swcase.value) {
3361                 ast_delete(switchnode);
3362                 parseerror(parser, "expected expression for case");
3363                 return false;
3364             }
3365             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3366                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3367                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3368                     ast_unref(operand);
3369                     return false;
3370                 }
3371             }
3372         }
3373         else if (!strcmp(parser_tokval(parser), "default")) {
3374             swcase.value = NULL;
3375             if (!parser_next(parser)) {
3376                 ast_delete(switchnode);
3377                 parseerror(parser, "expected colon");
3378                 return false;
3379             }
3380         }
3381         else {
3382             ast_delete(switchnode);
3383             parseerror(parser, "expected 'case' or 'default'");
3384             return false;
3385         }
3386
3387         /* Now the colon and body */
3388         if (parser->tok != ':') {
3389             if (swcase.value) ast_unref(swcase.value);
3390             ast_delete(switchnode);
3391             parseerror(parser, "expected colon");
3392             return false;
3393         }
3394
3395         if (!parser_next(parser)) {
3396             if (swcase.value) ast_unref(swcase.value);
3397             ast_delete(switchnode);
3398             parseerror(parser, "expected statements or case");
3399             return false;
3400         }
3401         caseblock = ast_block_new(parser_ctx(parser));
3402         if (!caseblock) {
3403             if (swcase.value) ast_unref(swcase.value);
3404             ast_delete(switchnode);
3405             return false;
3406         }
3407         swcase.code = (ast_expression*)caseblock;
3408         vec_push(switchnode->cases, swcase);
3409         while (true) {
3410             ast_expression *expr;
3411             if (parser->tok == '}')
3412                 break;
3413             if (parser->tok == TOKEN_KEYWORD) {
3414                 if (!strcmp(parser_tokval(parser), "case") ||
3415                     !strcmp(parser_tokval(parser), "default"))
3416                 {
3417                     break;
3418                 }
3419             }
3420             if (!parse_statement(parser, caseblock, &expr, true)) {
3421                 ast_delete(switchnode);
3422                 return false;
3423             }
3424             if (!expr)
3425                 continue;
3426             if (!ast_block_add_expr(caseblock, expr)) {
3427                 ast_delete(switchnode);
3428                 return false;
3429             }
3430         }
3431     }
3432
3433     parser_leaveblock(parser);
3434
3435     /* closing paren */
3436     if (parser->tok != '}') {
3437         ast_delete(switchnode);
3438         parseerror(parser, "expected closing paren of case list");
3439         return false;
3440     }
3441     if (!parser_next(parser)) {
3442         ast_delete(switchnode);
3443         parseerror(parser, "parse error after switch");
3444         return false;
3445     }
3446     *out = (ast_expression*)switchnode;
3447     return true;
3448 }
3449
3450 /* parse computed goto sides */
3451 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3452     ast_expression *on_true;
3453     ast_expression *on_false;
3454     ast_expression *cond;
3455
3456     if (!*side)
3457         return NULL;
3458
3459     if (ast_istype(*side, ast_ternary)) {
3460         ast_ternary *tern = (ast_ternary*)*side;
3461         on_true  = parse_goto_computed(parser, &tern->on_true);
3462         on_false = parse_goto_computed(parser, &tern->on_false);
3463
3464         if (!on_true || !on_false) {
3465             parseerror(parser, "expected label or expression in ternary");
3466             if (on_true) ast_unref(on_true);
3467             if (on_false) ast_unref(on_false);
3468             return NULL;
3469         }
3470
3471         cond = tern->cond;
3472         tern->cond = NULL;
3473         ast_delete(tern);
3474         *side = NULL;
3475         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3476     } else if (ast_istype(*side, ast_label)) {
3477         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3478         ast_goto_set_label(gt, ((ast_label*)*side));
3479         *side = NULL;
3480         return (ast_expression*)gt;
3481     }
3482     return NULL;
3483 }
3484
3485 static bool parse_goto(parser_t *parser, ast_expression **out)
3486 {
3487     ast_goto       *gt = NULL;
3488     ast_expression *lbl;
3489
3490     if (!parser_next(parser))
3491         return false;
3492
3493     if (parser->tok != TOKEN_IDENT) {
3494         ast_expression *expression;
3495
3496         /* could be an expression i.e computed goto :-) */
3497         if (parser->tok != '(') {
3498             parseerror(parser, "expected label name after `goto`");
3499             return false;
3500         }
3501
3502         /* failed to parse expression for goto */
3503         if (!(expression = parse_expression(parser, false, true)) ||
3504             !(*out = parse_goto_computed(parser, &expression))) {
3505             parseerror(parser, "invalid goto expression");
3506             ast_unref(expression);
3507             return false;
3508         }
3509
3510         return true;
3511     }
3512
3513     /* not computed goto */
3514     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3515     lbl = parser_find_label(parser, gt->name);
3516     if (lbl) {
3517         if (!ast_istype(lbl, ast_label)) {
3518             parseerror(parser, "internal error: label is not an ast_label");
3519             ast_delete(gt);
3520             return false;
3521         }
3522         ast_goto_set_label(gt, (ast_label*)lbl);
3523     }
3524     else
3525         vec_push(parser->gotos, gt);
3526
3527     if (!parser_next(parser) || parser->tok != ';') {
3528         parseerror(parser, "semicolon expected after goto label");
3529         return false;
3530     }
3531     if (!parser_next(parser)) {
3532         parseerror(parser, "parse error after goto");
3533         return false;
3534     }
3535
3536     *out = (ast_expression*)gt;
3537     return true;
3538 }
3539
3540 static bool parse_skipwhite(parser_t *parser)
3541 {
3542     do {
3543         if (!parser_next(parser))
3544             return false;
3545     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3546     return parser->tok < TOKEN_ERROR;
3547 }
3548
3549 static bool parse_eol(parser_t *parser)
3550 {
3551     if (!parse_skipwhite(parser))
3552         return false;
3553     return parser->tok == TOKEN_EOL;
3554 }
3555
3556 static bool parse_pragma_do(parser_t *parser)
3557 {
3558     if (!parser_next(parser) ||
3559         parser->tok != TOKEN_IDENT ||
3560         strcmp(parser_tokval(parser), "pragma"))
3561     {
3562         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3563         return false;
3564     }
3565     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3566         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3567         return false;
3568     }
3569
3570     if (!strcmp(parser_tokval(parser), "noref")) {
3571         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3572             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3573             return false;
3574         }
3575         parser->noref = !!parser_token(parser)->constval.i;
3576         if (!parse_eol(parser)) {
3577             parseerror(parser, "parse error after `noref` pragma");
3578             return false;
3579         }
3580     }
3581     else
3582     {
3583         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3584         return false;
3585     }
3586
3587     return true;
3588 }
3589
3590 static bool parse_pragma(parser_t *parser)
3591 {
3592     bool rv;
3593     parser->lex->flags.preprocessing = true;
3594     parser->lex->flags.mergelines = true;
3595     rv = parse_pragma_do(parser);
3596     if (parser->tok != TOKEN_EOL) {
3597         parseerror(parser, "junk after pragma");
3598         rv = false;
3599     }
3600     parser->lex->flags.preprocessing = false;
3601     parser->lex->flags.mergelines = false;
3602     if (!parser_next(parser)) {
3603         parseerror(parser, "parse error after pragma");
3604         rv = false;
3605     }
3606     return rv;
3607 }
3608
3609 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3610 {
3611     bool       noref, is_static;
3612     int        cvq     = CV_NONE;
3613     uint32_t   qflags  = 0;
3614     ast_value *typevar = NULL;
3615     char      *vstring = NULL;
3616
3617     *out = NULL;
3618
3619     if (parser->tok == TOKEN_IDENT)
3620         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3621
3622     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3623     {
3624         /* local variable */
3625         if (!block) {
3626             parseerror(parser, "cannot declare a variable from here");
3627             return false;
3628         }
3629         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3630             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3631                 return false;
3632         }
3633         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3634             return false;
3635         return true;
3636     }
3637     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3638     {
3639         if (cvq == CV_WRONG)
3640             return false;
3641         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3642     }
3643     else if (parser->tok == TOKEN_KEYWORD)
3644     {
3645         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3646         {
3647             char ty[1024];
3648             ast_value *tdef;
3649
3650             if (!parser_next(parser)) {
3651                 parseerror(parser, "parse error after __builtin_debug_printtype");
3652                 return false;
3653             }
3654
3655             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3656             {
3657                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3658                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3659                 if (!parser_next(parser)) {
3660                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3661                     return false;
3662                 }
3663             }
3664             else
3665             {
3666                 if (!parse_statement(parser, block, out, allow_cases))
3667                     return false;
3668                 if (!*out)
3669                     con_out("__builtin_debug_printtype: got no output node\n");
3670                 else
3671                 {
3672                     ast_type_to_string(*out, ty, sizeof(ty));
3673                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3674                 }
3675             }
3676             return true;
3677         }
3678         else if (!strcmp(parser_tokval(parser), "return"))
3679         {
3680             return parse_return(parser, block, out);
3681         }
3682         else if (!strcmp(parser_tokval(parser), "if"))
3683         {
3684             return parse_if(parser, block, out);
3685         }
3686         else if (!strcmp(parser_tokval(parser), "while"))
3687         {
3688             return parse_while(parser, block, out);
3689         }
3690         else if (!strcmp(parser_tokval(parser), "do"))
3691         {
3692             return parse_dowhile(parser, block, out);
3693         }
3694         else if (!strcmp(parser_tokval(parser), "for"))
3695         {
3696             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3697                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3698                     return false;
3699             }
3700             return parse_for(parser, block, out);
3701         }
3702         else if (!strcmp(parser_tokval(parser), "break"))
3703         {
3704             return parse_break_continue(parser, block, out, false);
3705         }
3706         else if (!strcmp(parser_tokval(parser), "continue"))
3707         {
3708             return parse_break_continue(parser, block, out, true);
3709         }
3710         else if (!strcmp(parser_tokval(parser), "switch"))
3711         {
3712             return parse_switch(parser, block, out);
3713         }
3714         else if (!strcmp(parser_tokval(parser), "case") ||
3715                  !strcmp(parser_tokval(parser), "default"))
3716         {
3717             if (!allow_cases) {
3718                 parseerror(parser, "unexpected 'case' label");
3719                 return false;
3720             }
3721             return true;
3722         }
3723         else if (!strcmp(parser_tokval(parser), "goto"))
3724         {
3725             return parse_goto(parser, out);
3726         }
3727         else if (!strcmp(parser_tokval(parser), "typedef"))
3728         {
3729             if (!parser_next(parser)) {
3730                 parseerror(parser, "expected type definition after 'typedef'");
3731                 return false;
3732             }
3733             return parse_typedef(parser);
3734         }
3735         parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3736         return false;
3737     }
3738     else if (parser->tok == '{')
3739     {
3740         ast_block *inner;
3741         inner = parse_block(parser);
3742         if (!inner)
3743             return false;
3744         *out = (ast_expression*)inner;
3745         return true;
3746     }
3747     else if (parser->tok == ':')
3748     {
3749         size_t i;
3750         ast_label *label;
3751         if (!parser_next(parser)) {
3752             parseerror(parser, "expected label name");
3753             return false;
3754         }
3755         if (parser->tok != TOKEN_IDENT) {
3756             parseerror(parser, "label must be an identifier");
3757             return false;
3758         }
3759         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3760         if (label) {
3761             if (!label->undefined) {
3762                 parseerror(parser, "label `%s` already defined", label->name);
3763                 return false;
3764             }
3765             label->undefined = false;
3766         }
3767         else {
3768             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3769             vec_push(parser->labels, label);
3770         }
3771         *out = (ast_expression*)label;
3772         if (!parser_next(parser)) {
3773             parseerror(parser, "parse error after label");
3774             return false;
3775         }
3776         for (i = 0; i < vec_size(parser->gotos); ++i) {
3777             if (!strcmp(parser->gotos[i]->name, label->name)) {
3778                 ast_goto_set_label(parser->gotos[i], label);
3779                 vec_remove(parser->gotos, i, 1);
3780                 --i;
3781             }
3782         }
3783         return true;
3784     }
3785     else if (parser->tok == ';')
3786     {
3787         if (!parser_next(parser)) {
3788             parseerror(parser, "parse error after empty statement");
3789             return false;
3790         }
3791         return true;
3792     }
3793     else
3794     {
3795         lex_ctx ctx = parser_ctx(parser);
3796         ast_expression *exp = parse_expression(parser, false, false);
3797         if (!exp)
3798             return false;
3799         *out = exp;
3800         if (!ast_side_effects(exp)) {
3801             if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3802                 return false;
3803         }
3804         return true;
3805     }
3806 }
3807
3808 static bool parse_enum(parser_t *parser)
3809 {
3810     bool        flag = false;
3811     bool        reverse = false;
3812     qcfloat     num = 0;
3813     ast_value **values = NULL;
3814     ast_value  *var = NULL;
3815     ast_value  *asvalue;
3816
3817     ast_expression *old;
3818
3819     if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3820         parseerror(parser, "expected `{` or `:` after `enum` keyword");
3821         return false;
3822     }
3823
3824     /* enumeration attributes (can add more later) */
3825     if (parser->tok == ':') {
3826         if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3827             parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3828             return false;
3829         }
3830
3831         /* attributes? */
3832         if (!strcmp(parser_tokval(parser), "flag")) {
3833             num  = 1;
3834             flag = true;
3835         }
3836         else if (!strcmp(parser_tokval(parser), "reverse")) {
3837             reverse = true;
3838         }
3839         else {
3840             parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3841             return false;
3842         }
3843
3844         if (!parser_next(parser) || parser->tok != '{') {
3845             parseerror(parser, "expected `{` after enum attribute ");
3846             return false;
3847         }
3848     }
3849
3850     while (true) {
3851         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3852             if (parser->tok == '}') {
3853                 /* allow an empty enum */
3854                 break;
3855             }
3856             parseerror(parser, "expected identifier or `}`");
3857             goto onerror;
3858         }
3859
3860         old = parser_find_field(parser, parser_tokval(parser));
3861         if (!old)
3862             old = parser_find_global(parser, parser_tokval(parser));
3863         if (old) {
3864             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3865                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3866             goto onerror;
3867         }
3868
3869         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3870         vec_push(values, var);
3871         var->cvq             = CV_CONST;
3872         var->hasvalue        = true;
3873
3874         /* for flagged enumerations increment in POTs of TWO */
3875         var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3876         parser_addglobal(parser, var->name, (ast_expression*)var);
3877
3878         if (!parser_next(parser)) {
3879             parseerror(parser, "expected `=`, `}` or comma after identifier");
3880             goto onerror;
3881         }
3882
3883         if (parser->tok == ',')
3884             continue;
3885         if (parser->tok == '}')
3886             break;
3887         if (parser->tok != '=') {
3888             parseerror(parser, "expected `=`, `}` or comma after identifier");
3889             goto onerror;
3890         }
3891
3892         if (!parser_next(parser)) {
3893             parseerror(parser, "expected expression after `=`");
3894             goto onerror;
3895         }
3896
3897         /* We got a value! */
3898         old = parse_expression_leave(parser, true, false, false);
3899         asvalue = (ast_value*)old;
3900         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3901             compile_error(ast_ctx(var), "constant value or expression expected");
3902             goto onerror;
3903         }
3904         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3905
3906         if (parser->tok == '}')
3907             break;
3908         if (parser->tok != ',') {
3909             parseerror(parser, "expected `}` or comma after expression");
3910             goto onerror;
3911         }
3912     }
3913
3914     /* patch them all (for reversed attribute) */
3915     if (reverse) {
3916         size_t i;
3917         for (i = 0; i < vec_size(values); i++)
3918             values[i]->constval.vfloat = vec_size(values) - i - 1;
3919     }
3920
3921     if (parser->tok != '}') {
3922         parseerror(parser, "internal error: breaking without `}`");
3923         goto onerror;
3924     }
3925
3926     if (!parser_next(parser) || parser->tok != ';') {
3927         parseerror(parser, "expected semicolon after enumeration");
3928         goto onerror;
3929     }
3930
3931     if (!parser_next(parser)) {
3932         parseerror(parser, "parse error after enumeration");
3933         goto onerror;
3934     }
3935
3936     vec_free(values);
3937     return true;
3938
3939 onerror:
3940     vec_free(values);
3941     return false;
3942 }
3943
3944 static bool parse_block_into(parser_t *parser, ast_block *block)
3945 {
3946     bool   retval = true;
3947
3948     parser_enterblock(parser);
3949
3950     if (!parser_next(parser)) { /* skip the '{' */
3951         parseerror(parser, "expected function body");
3952         goto cleanup;
3953     }
3954
3955     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3956     {
3957         ast_expression *expr = NULL;
3958         if (parser->tok == '}')
3959             break;
3960
3961         if (!parse_statement(parser, block, &expr, false)) {
3962             /* parseerror(parser, "parse error"); */
3963             block = NULL;
3964             goto cleanup;
3965         }
3966         if (!expr)
3967             continue;
3968         if (!ast_block_add_expr(block, expr)) {
3969             ast_delete(block);
3970             block = NULL;
3971             goto cleanup;
3972         }
3973     }
3974
3975     if (parser->tok != '}') {
3976         block = NULL;
3977     } else {
3978         (void)parser_next(parser);
3979     }
3980
3981 cleanup:
3982     if (!parser_leaveblock(parser))
3983         retval = false;
3984     return retval && !!block;
3985 }
3986
3987 static ast_block* parse_block(parser_t *parser)
3988 {
3989     ast_block *block;
3990     block = ast_block_new(parser_ctx(parser));
3991     if (!block)
3992         return NULL;
3993     if (!parse_block_into(parser, block)) {
3994         ast_block_delete(block);
3995         return NULL;
3996     }
3997     return block;
3998 }
3999
4000 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4001 {
4002     if (parser->tok == '{') {
4003         *out = (ast_expression*)parse_block(parser);
4004         return !!*out;
4005     }
4006     return parse_statement(parser, NULL, out, false);
4007 }
4008
4009 static bool create_vector_members(ast_value *var, ast_member **me)
4010 {
4011     size_t i;
4012     size_t len = strlen(var->name);
4013
4014     for (i = 0; i < 3; ++i) {
4015         char *name = (char*)mem_a(len+3);
4016         memcpy(name, var->name, len);
4017         name[len+0] = '_';
4018         name[len+1] = 'x'+i;
4019         name[len+2] = 0;
4020         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4021         mem_d(name);
4022         if (!me[i])
4023             break;
4024     }
4025     if (i == 3)
4026         return true;
4027
4028     /* unroll */
4029     do { ast_member_delete(me[--i]); } while(i);
4030     return false;
4031 }
4032
4033 static bool parse_function_body(parser_t *parser, ast_value *var)
4034 {
4035     ast_block      *block = NULL;
4036     ast_function   *func;
4037     ast_function   *old;
4038     size_t          parami;
4039
4040     ast_expression *framenum  = NULL;
4041     ast_expression *nextthink = NULL;
4042     /* None of the following have to be deleted */
4043     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4044     ast_expression *gbl_time = NULL, *gbl_self = NULL;
4045     bool            has_frame_think;
4046
4047     bool retval = true;
4048
4049     has_frame_think = false;
4050     old = parser->function;
4051
4052     if (var->expression.flags & AST_FLAG_ALIAS) {
4053         parseerror(parser, "function aliases cannot have bodies");
4054         return false;
4055     }
4056
4057     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4058         parseerror(parser, "gotos/labels leaking");
4059         return false;
4060     }
4061
4062     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4063         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4064                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4065         {
4066             return false;
4067         }
4068     }
4069
4070     if (parser->tok == '[') {
4071         /* got a frame definition: [ framenum, nextthink ]
4072          * this translates to:
4073          * self.frame = framenum;
4074          * self.nextthink = time + 0.1;
4075          * self.think = nextthink;
4076          */
4077         nextthink = NULL;
4078
4079         fld_think     = parser_find_field(parser, "think");
4080         fld_nextthink = parser_find_field(parser, "nextthink");
4081         fld_frame     = parser_find_field(parser, "frame");
4082         if (!fld_think || !fld_nextthink || !fld_frame) {
4083             parseerror(parser, "cannot use [frame,think] notation without the required fields");
4084             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4085             return false;
4086         }
4087         gbl_time      = parser_find_global(parser, "time");
4088         gbl_self      = parser_find_global(parser, "self");
4089         if (!gbl_time || !gbl_self) {
4090             parseerror(parser, "cannot use [frame,think] notation without the required globals");
4091             parseerror(parser, "please declare the following globals: `time`, `self`");
4092             return false;
4093         }
4094
4095         if (!parser_next(parser))
4096             return false;
4097
4098         framenum = parse_expression_leave(parser, true, false, false);
4099         if (!framenum) {
4100             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4101             return false;
4102         }
4103         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4104             ast_unref(framenum);
4105             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4106             return false;
4107         }
4108
4109         if (parser->tok != ',') {
4110             ast_unref(framenum);
4111             parseerror(parser, "expected comma after frame number in [frame,think] notation");
4112             parseerror(parser, "Got a %i\n", parser->tok);
4113             return false;
4114         }
4115
4116         if (!parser_next(parser)) {
4117             ast_unref(framenum);
4118             return false;
4119         }
4120
4121         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4122         {
4123             /* qc allows the use of not-yet-declared functions here
4124              * - this automatically creates a prototype */
4125             ast_value      *thinkfunc;
4126             ast_expression *functype = fld_think->next;
4127
4128             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
4129             if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4130                 ast_unref(framenum);
4131                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4132                 return false;
4133             }
4134             ast_type_adopt(thinkfunc, functype);
4135
4136             if (!parser_next(parser)) {
4137                 ast_unref(framenum);
4138                 ast_delete(thinkfunc);
4139                 return false;
4140             }
4141
4142             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4143
4144             nextthink = (ast_expression*)thinkfunc;
4145
4146         } else {
4147             nextthink = parse_expression_leave(parser, true, false, false);
4148             if (!nextthink) {
4149                 ast_unref(framenum);
4150                 parseerror(parser, "expected a think-function in [frame,think] notation");
4151                 return false;
4152             }
4153         }
4154
4155         if (!ast_istype(nextthink, ast_value)) {
4156             parseerror(parser, "think-function in [frame,think] notation must be a constant");
4157             retval = false;
4158         }
4159
4160         if (retval && parser->tok != ']') {
4161             parseerror(parser, "expected closing `]` for [frame,think] notation");
4162             retval = false;
4163         }
4164
4165         if (retval && !parser_next(parser)) {
4166             retval = false;
4167         }
4168
4169         if (retval && parser->tok != '{') {
4170             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4171             retval = false;
4172         }
4173
4174         if (!retval) {
4175             ast_unref(nextthink);
4176             ast_unref(framenum);
4177             return false;
4178         }
4179
4180         has_frame_think = true;
4181     }
4182
4183     block = ast_block_new(parser_ctx(parser));
4184     if (!block) {
4185         parseerror(parser, "failed to allocate block");
4186         if (has_frame_think) {
4187             ast_unref(nextthink);
4188             ast_unref(framenum);
4189         }
4190         return false;
4191     }
4192
4193     if (has_frame_think) {
4194         lex_ctx ctx;
4195         ast_expression *self_frame;
4196         ast_expression *self_nextthink;
4197         ast_expression *self_think;
4198         ast_expression *time_plus_1;
4199         ast_store *store_frame;
4200         ast_store *store_nextthink;
4201         ast_store *store_think;
4202
4203         ctx = parser_ctx(parser);
4204         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4205         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4206         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4207
4208         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4209                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4210
4211         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4212             if (self_frame)     ast_delete(self_frame);
4213             if (self_nextthink) ast_delete(self_nextthink);
4214             if (self_think)     ast_delete(self_think);
4215             if (time_plus_1)    ast_delete(time_plus_1);
4216             retval = false;
4217         }
4218
4219         if (retval)
4220         {
4221             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
4222             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
4223             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
4224
4225             if (!store_frame) {
4226                 ast_delete(self_frame);
4227                 retval = false;
4228             }
4229             if (!store_nextthink) {
4230                 ast_delete(self_nextthink);
4231                 retval = false;
4232             }
4233             if (!store_think) {
4234                 ast_delete(self_think);
4235                 retval = false;
4236             }
4237             if (!retval) {
4238                 if (store_frame)     ast_delete(store_frame);
4239                 if (store_nextthink) ast_delete(store_nextthink);
4240                 if (store_think)     ast_delete(store_think);
4241                 retval = false;
4242             }
4243             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4244                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4245                 !ast_block_add_expr(block, (ast_expression*)store_think))
4246             {
4247                 retval = false;
4248             }
4249         }
4250
4251         if (!retval) {
4252             parseerror(parser, "failed to generate code for [frame,think]");
4253             ast_unref(nextthink);
4254             ast_unref(framenum);
4255             ast_delete(block);
4256             return false;
4257         }
4258     }
4259
4260     if (var->hasvalue) {
4261         parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4262         ast_block_delete(block);
4263         goto enderr;
4264     }
4265
4266     func = ast_function_new(ast_ctx(var), var->name, var);
4267     if (!func) {
4268         parseerror(parser, "failed to allocate function for `%s`", var->name);
4269         ast_block_delete(block);
4270         goto enderr;
4271     }
4272     vec_push(parser->functions, func);
4273
4274     parser_enterblock(parser);
4275
4276     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4277         size_t     e;
4278         ast_value *param = var->expression.params[parami];
4279         ast_member *me[3];
4280
4281         if (param->expression.vtype != TYPE_VECTOR &&
4282             (param->expression.vtype != TYPE_FIELD ||
4283              param->expression.next->vtype != TYPE_VECTOR))
4284         {
4285             continue;
4286         }
4287
4288         if (!create_vector_members(param, me)) {
4289             ast_block_delete(block);
4290             goto enderrfn;
4291         }
4292
4293         for (e = 0; e < 3; ++e) {
4294             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4295             ast_block_collect(block, (ast_expression*)me[e]);
4296         }
4297     }
4298
4299     if (var->argcounter) {
4300         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4301         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4302         func->argc = argc;
4303     }
4304
4305     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4306         char name[1024];
4307         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4308         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4309         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4310         varargs->expression.count = 0;
4311         util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4312         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4313             ast_delete(varargs);
4314             ast_block_delete(block);
4315             goto enderrfn;
4316         }
4317         util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4318         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4319             ast_delete(varargs);
4320             ast_block_delete(block);
4321             goto enderrfn;
4322         }
4323         func->varargs = varargs;
4324
4325         func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4326     }
4327
4328     parser->function = func;
4329     if (!parse_block_into(parser, block)) {
4330         ast_block_delete(block);
4331         goto enderrfn;
4332     }
4333
4334     vec_push(func->blocks, block);
4335
4336
4337     parser->function = old;
4338     if (!parser_leaveblock(parser))
4339         retval = false;
4340     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4341         parseerror(parser, "internal error: local scopes left");
4342         retval = false;
4343     }
4344
4345     if (parser->tok == ';')
4346         return parser_next(parser);
4347     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4348         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4349     return retval;
4350
4351 enderrfn:
4352     (void)!parser_leaveblock(parser);
4353     vec_pop(parser->functions);
4354     ast_function_delete(func);
4355     var->constval.vfunc = NULL;
4356
4357 enderr:
4358     parser->function = old;
4359     return false;
4360 }
4361
4362 static ast_expression *array_accessor_split(
4363     parser_t  *parser,
4364     ast_value *array,
4365     ast_value *index,
4366     size_t     middle,
4367     ast_expression *left,
4368     ast_expression *right
4369     )
4370 {
4371     ast_ifthen *ifthen;
4372     ast_binary *cmp;
4373
4374     lex_ctx ctx = ast_ctx(array);
4375
4376     if (!left || !right) {
4377         if (left)  ast_delete(left);
4378         if (right) ast_delete(right);
4379         return NULL;
4380     }
4381
4382     cmp = ast_binary_new(ctx, INSTR_LT,
4383                          (ast_expression*)index,
4384                          (ast_expression*)parser_const_float(parser, middle));
4385     if (!cmp) {
4386         ast_delete(left);
4387         ast_delete(right);
4388         parseerror(parser, "internal error: failed to create comparison for array setter");
4389         return NULL;
4390     }
4391
4392     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4393     if (!ifthen) {
4394         ast_delete(cmp); /* will delete left and right */
4395         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4396         return NULL;
4397     }
4398
4399     return (ast_expression*)ifthen;
4400 }
4401
4402 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4403 {
4404     lex_ctx ctx = ast_ctx(array);
4405
4406     if (from+1 == afterend) {
4407         /* set this value */
4408         ast_block       *block;
4409         ast_return      *ret;
4410         ast_array_index *subscript;
4411         ast_store       *st;
4412         int assignop = type_store_instr[value->expression.vtype];
4413
4414         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4415             assignop = INSTR_STORE_V;
4416
4417         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4418         if (!subscript)
4419             return NULL;
4420
4421         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4422         if (!st) {
4423             ast_delete(subscript);
4424             return NULL;
4425         }
4426
4427         block = ast_block_new(ctx);
4428         if (!block) {
4429             ast_delete(st);
4430             return NULL;
4431         }
4432
4433         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4434             ast_delete(block);
4435             return NULL;
4436         }
4437
4438         ret = ast_return_new(ctx, NULL);
4439         if (!ret) {
4440             ast_delete(block);
4441             return NULL;
4442         }
4443
4444         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4445             ast_delete(block);
4446             return NULL;
4447         }
4448
4449         return (ast_expression*)block;
4450     } else {
4451         ast_expression *left, *right;
4452         size_t diff = afterend - from;
4453         size_t middle = from + diff/2;
4454         left  = array_setter_node(parser, array, index, value, from, middle);
4455         right = array_setter_node(parser, array, index, value, middle, afterend);
4456         return array_accessor_split(parser, array, index, middle, left, right);
4457     }
4458 }
4459
4460 static ast_expression *array_field_setter_node(
4461     parser_t  *parser,
4462     ast_value *array,
4463     ast_value *entity,
4464     ast_value *index,
4465     ast_value *value,
4466     size_t     from,
4467     size_t     afterend)
4468 {
4469     lex_ctx ctx = ast_ctx(array);
4470
4471     if (from+1 == afterend) {
4472         /* set this value */
4473         ast_block       *block;
4474         ast_return      *ret;
4475         ast_entfield    *entfield;
4476         ast_array_index *subscript;
4477         ast_store       *st;
4478         int assignop = type_storep_instr[value->expression.vtype];
4479
4480         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4481             assignop = INSTR_STOREP_V;
4482
4483         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4484         if (!subscript)
4485             return NULL;
4486
4487         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4488         subscript->expression.vtype = TYPE_FIELD;
4489
4490         entfield = ast_entfield_new_force(ctx,
4491                                           (ast_expression*)entity,
4492                                           (ast_expression*)subscript,
4493                                           (ast_expression*)subscript);
4494         if (!entfield) {
4495             ast_delete(subscript);
4496             return NULL;
4497         }
4498
4499         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4500         if (!st) {
4501             ast_delete(entfield);
4502             return NULL;
4503         }
4504
4505         block = ast_block_new(ctx);
4506         if (!block) {
4507             ast_delete(st);
4508             return NULL;
4509         }
4510
4511         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4512             ast_delete(block);
4513             return NULL;
4514         }
4515
4516         ret = ast_return_new(ctx, NULL);
4517         if (!ret) {
4518             ast_delete(block);
4519             return NULL;
4520         }
4521
4522         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4523             ast_delete(block);
4524             return NULL;
4525         }
4526
4527         return (ast_expression*)block;
4528     } else {
4529         ast_expression *left, *right;
4530         size_t diff = afterend - from;
4531         size_t middle = from + diff/2;
4532         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4533         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4534         return array_accessor_split(parser, array, index, middle, left, right);
4535     }
4536 }
4537
4538 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4539 {
4540     lex_ctx ctx = ast_ctx(array);
4541
4542     if (from+1 == afterend) {
4543         ast_return      *ret;
4544         ast_array_index *subscript;
4545
4546         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4547         if (!subscript)
4548             return NULL;
4549
4550         ret = ast_return_new(ctx, (ast_expression*)subscript);
4551         if (!ret) {
4552             ast_delete(subscript);
4553             return NULL;
4554         }
4555
4556         return (ast_expression*)ret;
4557     } else {
4558         ast_expression *left, *right;
4559         size_t diff = afterend - from;
4560         size_t middle = from + diff/2;
4561         left  = array_getter_node(parser, array, index, from, middle);
4562         right = array_getter_node(parser, array, index, middle, afterend);
4563         return array_accessor_split(parser, array, index, middle, left, right);
4564     }
4565 }
4566
4567 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4568 {
4569     ast_function   *func = NULL;
4570     ast_value      *fval = NULL;
4571     ast_block      *body = NULL;
4572
4573     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4574     if (!fval) {
4575         parseerror(parser, "failed to create accessor function value");
4576         return false;
4577     }
4578
4579     func = ast_function_new(ast_ctx(array), funcname, fval);
4580     if (!func) {
4581         ast_delete(fval);
4582         parseerror(parser, "failed to create accessor function node");
4583         return false;
4584     }
4585
4586     body = ast_block_new(ast_ctx(array));
4587     if (!body) {
4588         parseerror(parser, "failed to create block for array accessor");
4589         ast_delete(fval);
4590         ast_delete(func);
4591         return false;
4592     }
4593
4594     vec_push(func->blocks, body);
4595     *out = fval;
4596
4597     vec_push(parser->accessors, fval);
4598
4599     return true;
4600 }
4601
4602 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4603 {
4604     ast_value      *index = NULL;
4605     ast_value      *value = NULL;
4606     ast_function   *func;
4607     ast_value      *fval;
4608
4609     if (!ast_istype(array->expression.next, ast_value)) {
4610         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4611         return NULL;
4612     }
4613
4614     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4615         return NULL;
4616     func = fval->constval.vfunc;
4617     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4618
4619     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4620     value = ast_value_copy((ast_value*)array->expression.next);
4621
4622     if (!index || !value) {
4623         parseerror(parser, "failed to create locals for array accessor");
4624         goto cleanup;
4625     }
4626     (void)!ast_value_set_name(value, "value"); /* not important */
4627     vec_push(fval->expression.params, index);
4628     vec_push(fval->expression.params, value);
4629
4630     array->setter = fval;
4631     return fval;
4632 cleanup:
4633     if (index) ast_delete(index);
4634     if (value) ast_delete(value);
4635     ast_delete(func);
4636     ast_delete(fval);
4637     return NULL;
4638 }
4639
4640 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4641 {
4642     ast_expression *root = NULL;
4643     root = array_setter_node(parser, array,
4644                              array->setter->expression.params[0],
4645                              array->setter->expression.params[1],
4646                              0, array->expression.count);
4647     if (!root) {
4648         parseerror(parser, "failed to build accessor search tree");
4649         return false;
4650     }
4651     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4652         ast_delete(root);
4653         return false;
4654     }
4655     return true;
4656 }
4657
4658 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4659 {
4660     if (!parser_create_array_setter_proto(parser, array, funcname))
4661         return false;
4662     return parser_create_array_setter_impl(parser, array);
4663 }
4664
4665 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4666 {
4667     ast_expression *root = NULL;
4668     ast_value      *entity = NULL;
4669     ast_value      *index = NULL;
4670     ast_value      *value = NULL;
4671     ast_function   *func;
4672     ast_value      *fval;
4673
4674     if (!ast_istype(array->expression.next, ast_value)) {
4675         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4676         return false;
4677     }
4678
4679     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4680         return false;
4681     func = fval->constval.vfunc;
4682     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4683
4684     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4685     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4686     value  = ast_value_copy((ast_value*)array->expression.next);
4687     if (!entity || !index || !value) {
4688         parseerror(parser, "failed to create locals for array accessor");
4689         goto cleanup;
4690     }
4691     (void)!ast_value_set_name(value, "value"); /* not important */
4692     vec_push(fval->expression.params, entity);
4693     vec_push(fval->expression.params, index);
4694     vec_push(fval->expression.params, value);
4695
4696     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4697     if (!root) {
4698         parseerror(parser, "failed to build accessor search tree");
4699         goto cleanup;
4700     }
4701
4702     array->setter = fval;
4703     return ast_block_add_expr(func->blocks[0], root);
4704 cleanup:
4705     if (entity) ast_delete(entity);
4706     if (index)  ast_delete(index);
4707     if (value)  ast_delete(value);
4708     if (root)   ast_delete(root);
4709     ast_delete(func);
4710     ast_delete(fval);
4711     return false;
4712 }
4713
4714 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4715 {
4716     ast_value      *index = NULL;
4717     ast_value      *fval;
4718     ast_function   *func;
4719
4720     /* NOTE: checking array->expression.next rather than elemtype since
4721      * for fields elemtype is a temporary fieldtype.
4722      */
4723     if (!ast_istype(array->expression.next, ast_value)) {
4724         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4725         return NULL;
4726     }
4727
4728     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4729         return NULL;
4730     func = fval->constval.vfunc;
4731     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4732
4733     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4734
4735     if (!index) {
4736         parseerror(parser, "failed to create locals for array accessor");
4737         goto cleanup;
4738     }
4739     vec_push(fval->expression.params, index);
4740
4741     array->getter = fval;
4742     return fval;
4743 cleanup:
4744     if (index) ast_delete(index);
4745     ast_delete(func);
4746     ast_delete(fval);
4747     return NULL;
4748 }
4749
4750 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4751 {
4752     ast_expression *root = NULL;
4753
4754     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4755     if (!root) {
4756         parseerror(parser, "failed to build accessor search tree");
4757         return false;
4758     }
4759     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4760         ast_delete(root);
4761         return false;
4762     }
4763     return true;
4764 }
4765
4766 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4767 {
4768     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4769         return false;
4770     return parser_create_array_getter_impl(parser, array);
4771 }
4772
4773 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4774 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4775 {
4776     lex_ctx     ctx;
4777     size_t      i;
4778     ast_value **params;
4779     ast_value  *param;
4780     ast_value  *fval;
4781     bool        first = true;
4782     bool        variadic = false;
4783     ast_value  *varparam = NULL;
4784     char       *argcounter = NULL;
4785
4786     ctx = parser_ctx(parser);
4787
4788     /* for the sake of less code we parse-in in this function */
4789     if (!parser_next(parser)) {
4790         ast_delete(var);
4791         parseerror(parser, "expected parameter list");
4792         return NULL;
4793     }
4794
4795     params = NULL;
4796
4797     /* parse variables until we hit a closing paren */
4798     while (parser->tok != ')') {
4799         if (!first) {
4800             /* there must be commas between them */
4801             if (parser->tok != ',') {
4802                 parseerror(parser, "expected comma or end of parameter list");
4803                 goto on_error;
4804             }
4805             if (!parser_next(parser)) {
4806                 parseerror(parser, "expected parameter");
4807                 goto on_error;
4808             }
4809         }
4810         first = false;
4811
4812         if (parser->tok == TOKEN_DOTS) {
4813             /* '...' indicates a varargs function */
4814             variadic = true;
4815             if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4816                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4817                 goto on_error;
4818             }
4819             if (parser->tok == TOKEN_IDENT) {
4820                 argcounter = util_strdup(parser_tokval(parser));
4821                 if (!parser_next(parser) || parser->tok != ')') {
4822                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4823                     goto on_error;
4824                 }
4825             }
4826         }
4827         else
4828         {
4829             /* for anything else just parse a typename */
4830             param = parse_typename(parser, NULL, NULL);
4831             if (!param)
4832                 goto on_error;
4833             vec_push(params, param);
4834             if (param->expression.vtype >= TYPE_VARIANT) {
4835                 char tname[1024]; /* typename is reserved in C++ */
4836                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4837                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4838                 goto on_error;
4839             }
4840             /* type-restricted varargs */
4841             if (parser->tok == TOKEN_DOTS) {
4842                 variadic = true;
4843                 varparam = vec_last(params);
4844                 vec_pop(params);
4845                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4846                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4847                     goto on_error;
4848                 }
4849                 if (parser->tok == TOKEN_IDENT) {
4850                     argcounter = util_strdup(parser_tokval(parser));
4851                     if (!parser_next(parser) || parser->tok != ')') {
4852                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4853                         goto on_error;
4854                     }
4855                 }
4856             }
4857         }
4858     }
4859
4860     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4861         vec_free(params);
4862
4863     /* sanity check */
4864     if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4865         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4866
4867     /* parse-out */
4868     if (!parser_next(parser)) {
4869         parseerror(parser, "parse error after typename");
4870         goto on_error;
4871     }
4872
4873     /* now turn 'var' into a function type */
4874     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4875     fval->expression.next     = (ast_expression*)var;
4876     if (variadic)
4877         fval->expression.flags |= AST_FLAG_VARIADIC;
4878     var = fval;
4879
4880     var->expression.params   = params;
4881     var->expression.varparam = (ast_expression*)varparam;
4882     var->argcounter          = argcounter;
4883     params = NULL;
4884
4885     return var;
4886
4887 on_error:
4888     if (argcounter)
4889         mem_d(argcounter);
4890     if (varparam)
4891         ast_delete(varparam);
4892     ast_delete(var);
4893     for (i = 0; i < vec_size(params); ++i)
4894         ast_delete(params[i]);
4895     vec_free(params);
4896     return NULL;
4897 }
4898
4899 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4900 {
4901     ast_expression *cexp;
4902     ast_value      *cval, *tmp;
4903     lex_ctx ctx;
4904
4905     ctx = parser_ctx(parser);
4906
4907     if (!parser_next(parser)) {
4908         ast_delete(var);
4909         parseerror(parser, "expected array-size");
4910         return NULL;
4911     }
4912
4913     if (parser->tok != ']') {
4914         cexp = parse_expression_leave(parser, true, false, false);
4915
4916         if (!cexp || !ast_istype(cexp, ast_value)) {
4917             if (cexp)
4918                 ast_unref(cexp);
4919             ast_delete(var);
4920             parseerror(parser, "expected array-size as constant positive integer");
4921             return NULL;
4922         }
4923         cval = (ast_value*)cexp;
4924     }
4925     else {
4926         cexp = NULL;
4927         cval = NULL;
4928     }
4929
4930     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4931     tmp->expression.next = (ast_expression*)var;
4932     var = tmp;
4933
4934     if (cval) {
4935         if (cval->expression.vtype == TYPE_INTEGER)
4936             tmp->expression.count = cval->constval.vint;
4937         else if (cval->expression.vtype == TYPE_FLOAT)
4938             tmp->expression.count = cval->constval.vfloat;
4939         else {
4940             ast_unref(cexp);
4941             ast_delete(var);
4942             parseerror(parser, "array-size must be a positive integer constant");
4943             return NULL;
4944         }
4945
4946         ast_unref(cexp);
4947     } else {
4948         var->expression.count = -1;
4949         var->expression.flags |= AST_FLAG_ARRAY_INIT;
4950     }
4951
4952     if (parser->tok != ']') {
4953         ast_delete(var);
4954         parseerror(parser, "expected ']' after array-size");
4955         return NULL;
4956     }
4957     if (!parser_next(parser)) {
4958         ast_delete(var);
4959         parseerror(parser, "error after parsing array size");
4960         return NULL;
4961     }
4962     return var;
4963 }
4964
4965 /* Parse a complete typename.
4966  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4967  * but when parsing variables separated by comma
4968  * 'storebase' should point to where the base-type should be kept.
4969  * The base type makes up every bit of type information which comes *before* the
4970  * variable name.
4971  *
4972  * The following will be parsed in its entirety:
4973  *     void() foo()
4974  * The 'basetype' in this case is 'void()'
4975  * and if there's a comma after it, say:
4976  *     void() foo(), bar
4977  * then the type-information 'void()' can be stored in 'storebase'
4978  */
4979 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4980 {
4981     ast_value *var, *tmp;
4982     lex_ctx    ctx;
4983
4984     const char *name = NULL;
4985     bool        isfield  = false;
4986     bool        wasarray = false;
4987     size_t      morefields = 0;
4988
4989     ctx = parser_ctx(parser);
4990
4991     /* types may start with a dot */
4992     if (parser->tok == '.') {
4993         isfield = true;
4994         /* if we parsed a dot we need a typename now */
4995         if (!parser_next(parser)) {
4996             parseerror(parser, "expected typename for field definition");
4997             return NULL;
4998         }
4999
5000         /* Further dots are handled seperately because they won't be part of the
5001          * basetype
5002          */
5003         while (parser->tok == '.') {
5004             ++morefields;
5005             if (!parser_next(parser)) {
5006                 parseerror(parser, "expected typename for field definition");
5007                 return NULL;
5008             }
5009         }
5010     }
5011     if (parser->tok == TOKEN_IDENT)
5012         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5013     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5014         parseerror(parser, "expected typename");
5015         return NULL;
5016     }
5017
5018     /* generate the basic type value */
5019     if (cached_typedef) {
5020         var = ast_value_copy(cached_typedef);
5021         ast_value_set_name(var, "<type(from_def)>");
5022     } else
5023         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5024
5025     for (; morefields; --morefields) {
5026         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5027         tmp->expression.next = (ast_expression*)var;
5028         var = tmp;
5029     }
5030
5031     /* do not yet turn into a field - remember:
5032      * .void() foo; is a field too
5033      * .void()() foo; is a function
5034      */
5035
5036     /* parse on */
5037     if (!parser_next(parser)) {
5038         ast_delete(var);
5039         parseerror(parser, "parse error after typename");
5040         return NULL;
5041     }
5042
5043     /* an opening paren now starts the parameter-list of a function
5044      * this is where original-QC has parameter lists.
5045      * We allow a single parameter list here.
5046      * Much like fteqcc we don't allow `float()() x`
5047      */
5048     if (parser->tok == '(') {
5049         var = parse_parameter_list(parser, var);
5050         if (!var)
5051             return NULL;
5052     }
5053
5054     /* store the base if requested */
5055     if (storebase) {
5056         *storebase = ast_value_copy(var);
5057         if (isfield) {
5058             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5059             tmp->expression.next = (ast_expression*)*storebase;
5060             *storebase = tmp;
5061         }
5062     }
5063
5064     /* there may be a name now */
5065     if (parser->tok == TOKEN_IDENT) {
5066         name = util_strdup(parser_tokval(parser));
5067         /* parse on */
5068         if (!parser_next(parser)) {
5069             ast_delete(var);
5070             mem_d(name);
5071             parseerror(parser, "error after variable or field declaration");
5072             return NULL;
5073         }
5074     }
5075
5076     /* now this may be an array */
5077     if (parser->tok == '[') {
5078         wasarray = true;
5079         var = parse_arraysize(parser, var);
5080         if (!var) {
5081             if (name) mem_d(name);
5082             return NULL;
5083         }
5084     }
5085
5086     /* This is the point where we can turn it into a field */
5087     if (isfield) {
5088         /* turn it into a field if desired */
5089         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5090         tmp->expression.next = (ast_expression*)var;
5091         var = tmp;
5092     }
5093
5094     /* now there may be function parens again */
5095     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5096         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5097     if (parser->tok == '(' && wasarray)
5098         parseerror(parser, "arrays as part of a return type is not supported");
5099     while (parser->tok == '(') {
5100         var = parse_parameter_list(parser, var);
5101         if (!var) {
5102             if (name) mem_d(name);
5103             return NULL;
5104         }
5105     }
5106
5107     /* finally name it */
5108     if (name) {
5109         if (!ast_value_set_name(var, name)) {
5110             ast_delete(var);
5111             mem_d(name);
5112             parseerror(parser, "internal error: failed to set name");
5113             return NULL;
5114         }
5115         /* free the name, ast_value_set_name duplicates */
5116         mem_d(name);
5117     }
5118
5119     return var;
5120 }
5121
5122 static bool parse_typedef(parser_t *parser)
5123 {
5124     ast_value      *typevar, *oldtype;
5125     ast_expression *old;
5126
5127     typevar = parse_typename(parser, NULL, NULL);
5128
5129     if (!typevar)
5130         return false;
5131
5132     if ( (old = parser_find_var(parser, typevar->name)) ) {
5133         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5134                    " -> `%s` has been declared here: %s:%i",
5135                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5136         ast_delete(typevar);
5137         return false;
5138     }
5139
5140     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5141         parseerror(parser, "type `%s` has already been declared here: %s:%i",
5142                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5143         ast_delete(typevar);
5144         return false;
5145     }
5146
5147     vec_push(parser->_typedefs, typevar);
5148     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5149
5150     if (parser->tok != ';') {
5151         parseerror(parser, "expected semicolon after typedef");
5152         return false;
5153     }
5154     if (!parser_next(parser)) {
5155         parseerror(parser, "parse error after typedef");
5156         return false;
5157     }
5158
5159     return true;
5160 }
5161
5162 static const char *cvq_to_str(int cvq) {
5163     switch (cvq) {
5164         case CV_NONE:  return "none";
5165         case CV_VAR:   return "`var`";
5166         case CV_CONST: return "`const`";
5167         default:       return "<INVALID>";
5168     }
5169 }
5170
5171 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5172 {
5173     bool av, ao;
5174     if (proto->cvq != var->cvq) {
5175         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5176               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5177               parser->tok == '='))
5178         {
5179             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5180                                  "`%s` declared with different qualifiers: %s\n"
5181                                  " -> previous declaration here: %s:%i uses %s",
5182                                  var->name, cvq_to_str(var->cvq),
5183                                  ast_ctx(proto).file, ast_ctx(proto).line,
5184                                  cvq_to_str(proto->cvq));
5185         }
5186     }
5187     av = (var  ->expression.flags & AST_FLAG_NORETURN);
5188     ao = (proto->expression.flags & AST_FLAG_NORETURN);
5189     if (!av != !ao) {
5190         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5191                              "`%s` declared with different attributes%s\n"
5192                              " -> previous declaration here: %s:%i",
5193                              var->name, (av ? ": noreturn" : ""),
5194                              ast_ctx(proto).file, ast_ctx(proto).line,
5195                              (ao ? ": noreturn" : ""));
5196     }
5197     return true;
5198 }
5199
5200 static bool create_array_accessors(parser_t *parser, ast_value *var)
5201 {
5202     char name[1024];
5203     util_snprintf(name, sizeof(name), "%s##SET", var->name);
5204     if (!parser_create_array_setter(parser, var, name))
5205         return false;
5206     util_snprintf(name, sizeof(name), "%s##GET", var->name);
5207     if (!parser_create_array_getter(parser, var, var->expression.next, name))
5208         return false;
5209     return true;
5210 }
5211
5212 static bool parse_array(parser_t *parser, ast_value *array)
5213 {
5214     size_t i;
5215     if (array->initlist) {
5216         parseerror(parser, "array already initialized elsewhere");
5217         return false;
5218     }
5219     if (!parser_next(parser)) {
5220         parseerror(parser, "parse error in array initializer");
5221         return false;
5222     }
5223     i = 0;
5224     while (parser->tok != '}') {
5225         ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5226         if (!v)
5227             return false;
5228         if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5229             ast_unref(v);
5230             parseerror(parser, "initializing element must be a compile time constant");
5231             return false;
5232         }
5233         vec_push(array->initlist, v->constval);
5234         if (v->expression.vtype == TYPE_STRING) {
5235             array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5236             ++i;
5237         }
5238         ast_unref(v);
5239         if (parser->tok == '}')
5240             break;
5241         if (parser->tok != ',' || !parser_next(parser)) {
5242             parseerror(parser, "expected comma or '}' in element list");
5243             return false;
5244         }
5245     }
5246     if (!parser_next(parser) || parser->tok != ';') {
5247         parseerror(parser, "expected semicolon after initializer, got %s");
5248         return false;
5249     }
5250     /*
5251     if (!parser_next(parser)) {
5252         parseerror(parser, "parse error after initializer");
5253         return false;
5254     }
5255     */
5256
5257     if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5258         if (array->expression.count != (size_t)-1) {
5259             parseerror(parser, "array `%s' has already been initialized with %u elements",
5260                        array->name, (unsigned)array->expression.count);
5261         }
5262         array->expression.count = vec_size(array->initlist);
5263         if (!create_array_accessors(parser, array))
5264             return false;
5265     }
5266     return true;
5267 }
5268
5269 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)
5270 {
5271     ast_value *var;
5272     ast_value *proto;
5273     ast_expression *old;
5274     bool       was_end;
5275     size_t     i;
5276
5277     ast_value *basetype = NULL;
5278     bool      retval    = true;
5279     bool      isparam   = false;
5280     bool      isvector  = false;
5281     bool      cleanvar  = true;
5282     bool      wasarray  = false;
5283
5284     ast_member *me[3] = { NULL, NULL, NULL };
5285
5286     if (!localblock && is_static)
5287         parseerror(parser, "`static` qualifier is not supported in global scope");
5288
5289     /* get the first complete variable */
5290     var = parse_typename(parser, &basetype, cached_typedef);
5291     if (!var) {
5292         if (basetype)
5293             ast_delete(basetype);
5294         return false;
5295     }
5296
5297     while (true) {
5298         proto = NULL;
5299         wasarray = false;
5300
5301         /* Part 0: finish the type */
5302         if (parser->tok == '(') {
5303             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5304                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5305             var = parse_parameter_list(parser, var);
5306             if (!var) {
5307                 retval = false;
5308                 goto cleanup;
5309             }
5310         }
5311         /* we only allow 1-dimensional arrays */
5312         if (parser->tok == '[') {
5313             wasarray = true;
5314             var = parse_arraysize(parser, var);
5315             if (!var) {
5316                 retval = false;
5317                 goto cleanup;
5318             }
5319         }
5320         if (parser->tok == '(' && wasarray) {
5321             parseerror(parser, "arrays as part of a return type is not supported");
5322             /* we'll still parse the type completely for now */
5323         }
5324         /* for functions returning functions */
5325         while (parser->tok == '(') {
5326             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5327                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5328             var = parse_parameter_list(parser, var);
5329             if (!var) {
5330                 retval = false;
5331                 goto cleanup;
5332             }
5333         }
5334
5335         var->cvq = qualifier;
5336         var->expression.flags |= qflags;
5337
5338         /*
5339          * store the vstring back to var for alias and
5340          * deprecation messages.
5341          */
5342         if (var->expression.flags & AST_FLAG_DEPRECATED ||
5343             var->expression.flags & AST_FLAG_ALIAS)
5344             var->desc = vstring;
5345
5346         /* Part 1:
5347          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5348          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5349          * is then filled with the previous definition and the parameter-names replaced.
5350          */
5351         if (!strcmp(var->name, "nil")) {
5352             if (OPTS_FLAG(UNTYPED_NIL)) {
5353                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5354                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5355             } else
5356                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5357         }
5358         if (!localblock) {
5359             /* Deal with end_sys_ vars */
5360             was_end = false;
5361             if (!strcmp(var->name, "end_sys_globals")) {
5362                 var->uses++;
5363                 parser->crc_globals = vec_size(parser->globals);
5364                 was_end = true;
5365             }
5366             else if (!strcmp(var->name, "end_sys_fields")) {
5367                 var->uses++;
5368                 parser->crc_fields = vec_size(parser->fields);
5369                 was_end = true;
5370             }
5371             if (was_end && var->expression.vtype == TYPE_FIELD) {
5372                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5373                                  "global '%s' hint should not be a field",
5374                                  parser_tokval(parser)))
5375                 {
5376                     retval = false;
5377                     goto cleanup;
5378                 }
5379             }
5380
5381             if (!nofields && var->expression.vtype == TYPE_FIELD)
5382             {
5383                 /* deal with field declarations */
5384                 old = parser_find_field(parser, var->name);
5385                 if (old) {
5386                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5387                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5388                     {
5389                         retval = false;
5390                         goto cleanup;
5391                     }
5392                     ast_delete(var);
5393                     var = NULL;
5394                     goto skipvar;
5395                     /*
5396                     parseerror(parser, "field `%s` already declared here: %s:%i",
5397                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5398                     retval = false;
5399                     goto cleanup;
5400                     */
5401                 }
5402                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5403                     (old = parser_find_global(parser, var->name)))
5404                 {
5405                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5406                     parseerror(parser, "field `%s` already declared here: %s:%i",
5407                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5408                     retval = false;
5409                     goto cleanup;
5410                 }
5411             }
5412             else
5413             {
5414                 /* deal with other globals */
5415                 old = parser_find_global(parser, var->name);
5416                 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5417                 {
5418                     /* This is a function which had a prototype */
5419                     if (!ast_istype(old, ast_value)) {
5420                         parseerror(parser, "internal error: prototype is not an ast_value");
5421                         retval = false;
5422                         goto cleanup;
5423                     }
5424                     proto = (ast_value*)old;
5425                     proto->desc = var->desc;
5426                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5427                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5428                                    proto->name,
5429                                    ast_ctx(proto).file, ast_ctx(proto).line);
5430                         retval = false;
5431                         goto cleanup;
5432                     }
5433                     /* we need the new parameter-names */
5434                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5435                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5436                     if (!parser_check_qualifiers(parser, var, proto)) {
5437                         retval = false;
5438                         if (proto->desc)
5439                             mem_d(proto->desc);
5440                         proto = NULL;
5441                         goto cleanup;
5442                     }
5443                     proto->expression.flags |= var->expression.flags;
5444                     ast_delete(var);
5445                     var = proto;
5446                 }
5447                 else
5448                 {
5449                     /* other globals */
5450                     if (old) {
5451                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5452                                          "global `%s` already declared here: %s:%i",
5453                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5454                         {
5455                             retval = false;
5456                             goto cleanup;
5457                         }
5458                         proto = (ast_value*)old;
5459                         if (!ast_istype(old, ast_value)) {
5460                             parseerror(parser, "internal error: not an ast_value");
5461                             retval = false;
5462                             proto = NULL;
5463                             goto cleanup;
5464                         }
5465                         if (!parser_check_qualifiers(parser, var, proto)) {
5466                             retval = false;
5467                             proto = NULL;
5468                             goto cleanup;
5469                         }
5470                         proto->expression.flags |= var->expression.flags;
5471                         ast_delete(var);
5472                         var = proto;
5473                     }
5474                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5475                         (old = parser_find_field(parser, var->name)))
5476                     {
5477                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5478                         parseerror(parser, "global `%s` already declared here: %s:%i",
5479                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5480                         retval = false;
5481                         goto cleanup;
5482                     }
5483                 }
5484             }
5485         }
5486         else /* it's not a global */
5487         {
5488             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5489             if (old && !isparam) {
5490                 parseerror(parser, "local `%s` already declared here: %s:%i",
5491                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5492                 retval = false;
5493                 goto cleanup;
5494             }
5495             old = parser_find_local(parser, var->name, 0, &isparam);
5496             if (old && isparam) {
5497                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5498                                  "local `%s` is shadowing a parameter", var->name))
5499                 {
5500                     parseerror(parser, "local `%s` already declared here: %s:%i",
5501                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5502                     retval = false;
5503                     goto cleanup;
5504                 }
5505                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5506                     ast_delete(var);
5507                     var = NULL;
5508                     goto skipvar;
5509                 }
5510             }
5511         }
5512
5513         /* in a noref section we simply bump the usecount */
5514         if (noref || parser->noref)
5515             var->uses++;
5516
5517         /* Part 2:
5518          * Create the global/local, and deal with vector types.
5519          */
5520         if (!proto) {
5521             if (var->expression.vtype == TYPE_VECTOR)
5522                 isvector = true;
5523             else if (var->expression.vtype == TYPE_FIELD &&
5524                      var->expression.next->vtype == TYPE_VECTOR)
5525                 isvector = true;
5526
5527             if (isvector) {
5528                 if (!create_vector_members(var, me)) {
5529                     retval = false;
5530                     goto cleanup;
5531                 }
5532             }
5533
5534             if (!localblock) {
5535                 /* deal with global variables, fields, functions */
5536                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5537                     var->isfield = true;
5538                     vec_push(parser->fields, (ast_expression*)var);
5539                     util_htset(parser->htfields, var->name, var);
5540                     if (isvector) {
5541                         for (i = 0; i < 3; ++i) {
5542                             vec_push(parser->fields, (ast_expression*)me[i]);
5543                             util_htset(parser->htfields, me[i]->name, me[i]);
5544                         }
5545                     }
5546                 }
5547                 else {
5548                     if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5549                         parser_addglobal(parser, var->name, (ast_expression*)var);
5550                         if (isvector) {
5551                             for (i = 0; i < 3; ++i) {
5552                                 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5553                             }
5554                         }
5555                     } else {
5556                         ast_expression *find  = parser_find_global(parser, var->desc);
5557
5558                         if (!find) {
5559                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5560                             return false;
5561                         }
5562
5563                         if (var->expression.vtype != find->vtype) {
5564                             char ty1[1024];
5565                             char ty2[1024];
5566
5567                             ast_type_to_string(find,                  ty1, sizeof(ty1));
5568                             ast_type_to_string((ast_expression*)var,  ty2, sizeof(ty2));
5569
5570                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5571                                 ty1, ty2, var->name
5572                             );
5573                             return false;
5574                         }
5575
5576                         /*
5577                          * add alias to aliases table and to corrector
5578                          * so corrections can apply for aliases as well.
5579                          */
5580                         util_htset(parser->aliases, var->name, find);
5581
5582                         /*
5583                          * add to corrector so corrections can work
5584                          * even for aliases too.
5585                          */
5586                         correct_add (
5587                              vec_last(parser->correct_variables),
5588                             &vec_last(parser->correct_variables_score),
5589                             var->name
5590                         );
5591
5592                         /* generate aliases for vector components */
5593                         if (isvector) {
5594                             char *buffer[3];
5595
5596                             util_asprintf(&buffer[0], "%s_x", var->desc);
5597                             util_asprintf(&buffer[1], "%s_y", var->desc);
5598                             util_asprintf(&buffer[2], "%s_z", var->desc);
5599
5600                             util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5601                             util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5602                             util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5603
5604                             mem_d(buffer[0]);
5605                             mem_d(buffer[1]);
5606                             mem_d(buffer[2]);
5607
5608                             /*
5609                              * add to corrector so corrections can work
5610                              * even for aliases too.
5611                              */
5612                             correct_add (
5613                                  vec_last(parser->correct_variables),
5614                                 &vec_last(parser->correct_variables_score),
5615                                 me[0]->name
5616                             );
5617                             correct_add (
5618                                  vec_last(parser->correct_variables),
5619                                 &vec_last(parser->correct_variables_score),
5620                                 me[1]->name
5621                             );
5622                             correct_add (
5623                                  vec_last(parser->correct_variables),
5624                                 &vec_last(parser->correct_variables_score),
5625                                 me[2]->name
5626                             );
5627                         }
5628                     }
5629                 }
5630             } else {
5631                 if (is_static) {
5632                     /* a static adds itself to be generated like any other global
5633                      * but is added to the local namespace instead
5634                      */
5635                     char   *defname = NULL;
5636                     size_t  prefix_len, ln;
5637
5638                     ln = strlen(parser->function->name);
5639                     vec_append(defname, ln, parser->function->name);
5640
5641                     vec_append(defname, 2, "::");
5642                     /* remember the length up to here */
5643                     prefix_len = vec_size(defname);
5644
5645                     /* Add it to the local scope */
5646                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5647
5648                     /* corrector */
5649                     correct_add (
5650                          vec_last(parser->correct_variables),
5651                         &vec_last(parser->correct_variables_score),
5652                         var->name
5653                     );
5654
5655                     /* now rename the global */
5656                     ln = strlen(var->name);
5657                     vec_append(defname, ln, var->name);
5658                     ast_value_set_name(var, defname);
5659
5660                     /* push it to the to-be-generated globals */
5661                     vec_push(parser->globals, (ast_expression*)var);
5662
5663                     /* same game for the vector members */
5664                     if (isvector) {
5665                         for (i = 0; i < 3; ++i) {
5666                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5667
5668                             /* corrector */
5669                             correct_add(
5670                                  vec_last(parser->correct_variables),
5671                                 &vec_last(parser->correct_variables_score),
5672                                 me[i]->name
5673                             );
5674
5675                             vec_shrinkto(defname, prefix_len);
5676                             ln = strlen(me[i]->name);
5677                             vec_append(defname, ln, me[i]->name);
5678                             ast_member_set_name(me[i], defname);
5679
5680                             vec_push(parser->globals, (ast_expression*)me[i]);
5681                         }
5682                     }
5683                     vec_free(defname);
5684                 } else {
5685                     vec_push(localblock->locals, var);
5686                     parser_addlocal(parser, var->name, (ast_expression*)var);
5687                     if (isvector) {
5688                         for (i = 0; i < 3; ++i) {
5689                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5690                             ast_block_collect(localblock, (ast_expression*)me[i]);
5691                         }
5692                     }
5693                 }
5694             }
5695         }
5696         me[0] = me[1] = me[2] = NULL;
5697         cleanvar = false;
5698         /* Part 2.2
5699          * deal with arrays
5700          */
5701         if (var->expression.vtype == TYPE_ARRAY) {
5702             if (var->expression.count != (size_t)-1) {
5703                 if (!create_array_accessors(parser, var))
5704                     goto cleanup;
5705             }
5706         }
5707         else if (!localblock && !nofields &&
5708                  var->expression.vtype == TYPE_FIELD &&
5709                  var->expression.next->vtype == TYPE_ARRAY)
5710         {
5711             char name[1024];
5712             ast_expression *telem;
5713             ast_value      *tfield;
5714             ast_value      *array = (ast_value*)var->expression.next;
5715
5716             if (!ast_istype(var->expression.next, ast_value)) {
5717                 parseerror(parser, "internal error: field element type must be an ast_value");
5718                 goto cleanup;
5719             }
5720
5721             util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5722             if (!parser_create_array_field_setter(parser, array, name))
5723                 goto cleanup;
5724
5725             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5726             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5727             tfield->expression.next = telem;
5728             util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5729             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5730                 ast_delete(tfield);
5731                 goto cleanup;
5732             }
5733             ast_delete(tfield);
5734         }
5735
5736 skipvar:
5737         if (parser->tok == ';') {
5738             ast_delete(basetype);
5739             if (!parser_next(parser)) {
5740                 parseerror(parser, "error after variable declaration");
5741                 return false;
5742             }
5743             return true;
5744         }
5745
5746         if (parser->tok == ',')
5747             goto another;
5748
5749         /*
5750         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5751         */
5752         if (!var) {
5753             parseerror(parser, "missing comma or semicolon while parsing variables");
5754             break;
5755         }
5756
5757         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5758             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5759                              "initializing expression turns variable `%s` into a constant in this standard",
5760                              var->name) )
5761             {
5762                 break;
5763             }
5764         }
5765
5766         if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5767             if (parser->tok != '=') {
5768                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5769                 break;
5770             }
5771
5772             if (!parser_next(parser)) {
5773                 parseerror(parser, "error parsing initializer");
5774                 break;
5775             }
5776         }
5777         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5778             parseerror(parser, "expected '=' before function body in this standard");
5779         }
5780
5781         if (parser->tok == '#') {
5782             ast_function *func   = NULL;
5783             ast_value    *number = NULL;
5784             float         fractional;
5785             float         integral;
5786             int           builtin_num;
5787
5788             if (localblock) {
5789                 parseerror(parser, "cannot declare builtins within functions");
5790                 break;
5791             }
5792             if (var->expression.vtype != TYPE_FUNCTION) {
5793                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5794                 break;
5795             }
5796             if (!parser_next(parser)) {
5797                 parseerror(parser, "expected builtin number");
5798                 break;
5799             }
5800
5801             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5802                 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5803                 if (!number) {
5804                     parseerror(parser, "builtin number expected");
5805                     break;
5806                 }
5807                 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5808                 {
5809                     ast_unref(number);
5810                     parseerror(parser, "builtin number must be a compile time constant");
5811                     break;
5812                 }
5813                 if (number->expression.vtype == TYPE_INTEGER)
5814                     builtin_num = number->constval.vint;
5815                 else if (number->expression.vtype == TYPE_FLOAT)
5816                     builtin_num = number->constval.vfloat;
5817                 else {
5818                     ast_unref(number);
5819                     parseerror(parser, "builtin number must be an integer constant");
5820                     break;
5821                 }
5822                 ast_unref(number);
5823
5824                 fractional = modff(builtin_num, &integral);
5825                 if (builtin_num < 0 || fractional != 0) {
5826                     parseerror(parser, "builtin number must be an integer greater than zero");
5827                     break;
5828                 }
5829
5830                 /* we only want the integral part anyways */
5831                 builtin_num = integral;
5832             } else if (parser->tok == TOKEN_INTCONST) {
5833                 builtin_num = parser_token(parser)->constval.i;
5834             } else {
5835                 parseerror(parser, "builtin number must be a compile time constant");
5836                 break;
5837             }
5838
5839             if (var->hasvalue) {
5840                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5841                                     "builtin `%s` has already been defined\n"
5842                                     " -> previous declaration here: %s:%i",
5843                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5844             }
5845             else
5846             {
5847                 func = ast_function_new(ast_ctx(var), var->name, var);
5848                 if (!func) {
5849                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5850                     break;
5851                 }
5852                 vec_push(parser->functions, func);
5853
5854                 func->builtin = -builtin_num-1;
5855             }
5856
5857             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5858                     ? (parser->tok != ',' && parser->tok != ';')
5859                     : (!parser_next(parser)))
5860             {
5861                 parseerror(parser, "expected comma or semicolon");
5862                 if (func)
5863                     ast_function_delete(func);
5864                 var->constval.vfunc = NULL;
5865                 break;
5866             }
5867         }
5868         else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5869         {
5870             if (localblock) {
5871                 /* Note that fteqcc and most others don't even *have*
5872                  * local arrays, so this is not a high priority.
5873                  */
5874                 parseerror(parser, "TODO: initializers for local arrays");
5875                 break;
5876             }
5877
5878             var->hasvalue = true;
5879             if (!parse_array(parser, var))
5880                 break;
5881         }
5882         else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5883         {
5884             if (localblock) {
5885                 parseerror(parser, "cannot declare functions within functions");
5886                 break;
5887             }
5888
5889             if (proto)
5890                 ast_ctx(proto) = parser_ctx(parser);
5891
5892             if (!parse_function_body(parser, var))
5893                 break;
5894             ast_delete(basetype);
5895             for (i = 0; i < vec_size(parser->gotos); ++i)
5896                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5897             vec_free(parser->gotos);
5898             vec_free(parser->labels);
5899             return true;
5900         } else {
5901             ast_expression *cexp;
5902             ast_value      *cval;
5903
5904             cexp = parse_expression_leave(parser, true, false, false);
5905             if (!cexp)
5906                 break;
5907
5908             if (!localblock) {
5909                 cval = (ast_value*)cexp;
5910                 if (cval != parser->nil &&
5911                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5912                    )
5913                 {
5914                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5915                 }
5916                 else
5917                 {
5918                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5919                         qualifier != CV_VAR)
5920                     {
5921                         var->cvq = CV_CONST;
5922                     }
5923                     if (cval == parser->nil)
5924                         var->expression.flags |= AST_FLAG_INITIALIZED;
5925                     else
5926                     {
5927                         var->hasvalue = true;
5928                         if (cval->expression.vtype == TYPE_STRING)
5929                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5930                         else if (cval->expression.vtype == TYPE_FIELD)
5931                             var->constval.vfield = cval;
5932                         else
5933                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5934                         ast_unref(cval);
5935                     }
5936                 }
5937             } else {
5938                 int cvq;
5939                 shunt sy = { NULL, NULL, NULL, NULL };
5940                 cvq = var->cvq;
5941                 var->cvq = CV_NONE;
5942                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5943                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5944                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5945                 if (!parser_sy_apply_operator(parser, &sy))
5946                     ast_unref(cexp);
5947                 else {
5948                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5949                         parseerror(parser, "internal error: leaked operands");
5950                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5951                         break;
5952                 }
5953                 vec_free(sy.out);
5954                 vec_free(sy.ops);
5955                 vec_free(sy.argc);
5956                 var->cvq = cvq;
5957             }
5958         }
5959
5960 another:
5961         if (parser->tok == ',') {
5962             if (!parser_next(parser)) {
5963                 parseerror(parser, "expected another variable");
5964                 break;
5965             }
5966
5967             if (parser->tok != TOKEN_IDENT) {
5968                 parseerror(parser, "expected another variable");
5969                 break;
5970             }
5971             var = ast_value_copy(basetype);
5972             cleanvar = true;
5973             ast_value_set_name(var, parser_tokval(parser));
5974             if (!parser_next(parser)) {
5975                 parseerror(parser, "error parsing variable declaration");
5976                 break;
5977             }
5978             continue;
5979         }
5980
5981         if (parser->tok != ';') {
5982             parseerror(parser, "missing semicolon after variables");
5983             break;
5984         }
5985
5986         if (!parser_next(parser)) {
5987             parseerror(parser, "parse error after variable declaration");
5988             break;
5989         }
5990
5991         ast_delete(basetype);
5992         return true;
5993     }
5994
5995     if (cleanvar && var)
5996         ast_delete(var);
5997     ast_delete(basetype);
5998     return false;
5999
6000 cleanup:
6001     ast_delete(basetype);
6002     if (cleanvar && var)
6003         ast_delete(var);
6004     if (me[0]) ast_member_delete(me[0]);
6005     if (me[1]) ast_member_delete(me[1]);
6006     if (me[2]) ast_member_delete(me[2]);
6007     return retval;
6008 }
6009
6010 static bool parser_global_statement(parser_t *parser)
6011 {
6012     int        cvq       = CV_WRONG;
6013     bool       noref     = false;
6014     bool       is_static = false;
6015     uint32_t   qflags    = 0;
6016     ast_value *istype    = NULL;
6017     char      *vstring   = NULL;
6018
6019     if (parser->tok == TOKEN_IDENT)
6020         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6021
6022     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6023     {
6024         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6025     }
6026     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6027     {
6028         if (cvq == CV_WRONG)
6029             return false;
6030         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6031     }
6032     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6033     {
6034         return parse_enum(parser);
6035     }
6036     else if (parser->tok == TOKEN_KEYWORD)
6037     {
6038         if (!strcmp(parser_tokval(parser), "typedef")) {
6039             if (!parser_next(parser)) {
6040                 parseerror(parser, "expected type definition after 'typedef'");
6041                 return false;
6042             }
6043             return parse_typedef(parser);
6044         }
6045         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6046         return false;
6047     }
6048     else if (parser->tok == '#')
6049     {
6050         return parse_pragma(parser);
6051     }
6052     else if (parser->tok == '$')
6053     {
6054         if (!parser_next(parser)) {
6055             parseerror(parser, "parse error");
6056             return false;
6057         }
6058     }
6059     else
6060     {
6061         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6062         return false;
6063     }
6064     return true;
6065 }
6066
6067 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6068 {
6069     return util_crc16(old, str, strlen(str));
6070 }
6071
6072 static void progdefs_crc_file(const char *str)
6073 {
6074     /* write to progdefs.h here */
6075     (void)str;
6076 }
6077
6078 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6079 {
6080     old = progdefs_crc_sum(old, str);
6081     progdefs_crc_file(str);
6082     return old;
6083 }
6084
6085 static void generate_checksum(parser_t *parser)
6086 {
6087     uint16_t   crc = 0xFFFF;
6088     size_t     i;
6089     ast_value *value;
6090
6091     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6092     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6093     /*
6094     progdefs_crc_file("\tint\tpad;\n");
6095     progdefs_crc_file("\tint\tofs_return[3];\n");
6096     progdefs_crc_file("\tint\tofs_parm0[3];\n");
6097     progdefs_crc_file("\tint\tofs_parm1[3];\n");
6098     progdefs_crc_file("\tint\tofs_parm2[3];\n");
6099     progdefs_crc_file("\tint\tofs_parm3[3];\n");
6100     progdefs_crc_file("\tint\tofs_parm4[3];\n");
6101     progdefs_crc_file("\tint\tofs_parm5[3];\n");
6102     progdefs_crc_file("\tint\tofs_parm6[3];\n");
6103     progdefs_crc_file("\tint\tofs_parm7[3];\n");
6104     */
6105     for (i = 0; i < parser->crc_globals; ++i) {
6106         if (!ast_istype(parser->globals[i], ast_value))
6107             continue;
6108         value = (ast_value*)(parser->globals[i]);
6109         switch (value->expression.vtype) {
6110             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6111             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6112             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6113             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6114             default:
6115                 crc = progdefs_crc_both(crc, "\tint\t");
6116                 break;
6117         }
6118         crc = progdefs_crc_both(crc, value->name);
6119         crc = progdefs_crc_both(crc, ";\n");
6120     }
6121     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6122     for (i = 0; i < parser->crc_fields; ++i) {
6123         if (!ast_istype(parser->fields[i], ast_value))
6124             continue;
6125         value = (ast_value*)(parser->fields[i]);
6126         switch (value->expression.next->vtype) {
6127             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6128             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6129             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6130             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6131             default:
6132                 crc = progdefs_crc_both(crc, "\tint\t");
6133                 break;
6134         }
6135         crc = progdefs_crc_both(crc, value->name);
6136         crc = progdefs_crc_both(crc, ";\n");
6137     }
6138     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6139
6140     parser->code->crc = crc;
6141 }
6142
6143 parser_t *parser_create()
6144 {
6145     parser_t *parser;
6146     lex_ctx empty_ctx;
6147     size_t i;
6148
6149     parser = (parser_t*)mem_a(sizeof(parser_t));
6150     if (!parser)
6151         return NULL;
6152
6153     memset(parser, 0, sizeof(*parser));
6154
6155     if (!(parser->code = code_init())) {
6156         mem_d(parser);
6157         return NULL;
6158     }
6159
6160     for (i = 0; i < operator_count; ++i) {
6161         if (operators[i].id == opid1('=')) {
6162             parser->assign_op = operators+i;
6163             break;
6164         }
6165     }
6166     if (!parser->assign_op) {
6167         printf("internal error: initializing parser: failed to find assign operator\n");
6168         mem_d(parser);
6169         return NULL;
6170     }
6171
6172     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
6173     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6174     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6175     vec_push(parser->_blocktypedefs, 0);
6176
6177     parser->aliases = util_htnew(PARSER_HT_SIZE);
6178
6179     parser->ht_imm_string = util_htnew(512);
6180
6181     /* corrector */
6182     vec_push(parser->correct_variables, correct_trie_new());
6183     vec_push(parser->correct_variables_score, NULL);
6184
6185     empty_ctx.file = "<internal>";
6186     empty_ctx.line = 0;
6187     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6188     parser->nil->cvq = CV_CONST;
6189     if (OPTS_FLAG(UNTYPED_NIL))
6190         util_htset(parser->htglobals, "nil", (void*)parser->nil);
6191
6192     parser->max_param_count = 1;
6193
6194     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6195     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6196     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6197
6198     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6199         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6200         parser->reserved_version->cvq = CV_CONST;
6201         parser->reserved_version->hasvalue = true;
6202         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6203         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6204     } else {
6205         parser->reserved_version = NULL;
6206     }
6207
6208     return parser;
6209 }
6210
6211 static bool parser_compile(parser_t *parser)
6212 {
6213     /* initial lexer/parser state */
6214     parser->lex->flags.noops = true;
6215
6216     if (parser_next(parser))
6217     {
6218         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6219         {
6220             if (!parser_global_statement(parser)) {
6221                 if (parser->tok == TOKEN_EOF)
6222                     parseerror(parser, "unexpected eof");
6223                 else if (compile_errors)
6224                     parseerror(parser, "there have been errors, bailing out");
6225                 lex_close(parser->lex);
6226                 parser->lex = NULL;
6227                 return false;
6228             }
6229         }
6230     } else {
6231         parseerror(parser, "parse error");
6232         lex_close(parser->lex);
6233         parser->lex = NULL;
6234         return false;
6235     }
6236
6237     lex_close(parser->lex);
6238     parser->lex = NULL;
6239
6240     return !compile_errors;
6241 }
6242
6243 bool parser_compile_file(parser_t *parser, const char *filename)
6244 {
6245     parser->lex = lex_open(filename);
6246     if (!parser->lex) {
6247         con_err("failed to open file \"%s\"\n", filename);
6248         return false;
6249     }
6250     return parser_compile(parser);
6251 }
6252
6253 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6254 {
6255     parser->lex = lex_open_string(str, len, name);
6256     if (!parser->lex) {
6257         con_err("failed to create lexer for string \"%s\"\n", name);
6258         return false;
6259     }
6260     return parser_compile(parser);
6261 }
6262
6263 static void parser_remove_ast(parser_t *parser)
6264 {
6265     size_t i;
6266     if (parser->ast_cleaned)
6267         return;
6268     parser->ast_cleaned = true;
6269     for (i = 0; i < vec_size(parser->accessors); ++i) {
6270         ast_delete(parser->accessors[i]->constval.vfunc);
6271         parser->accessors[i]->constval.vfunc = NULL;
6272         ast_delete(parser->accessors[i]);
6273     }
6274     for (i = 0; i < vec_size(parser->functions); ++i) {
6275         ast_delete(parser->functions[i]);
6276     }
6277     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6278         ast_delete(parser->imm_vector[i]);
6279     }
6280     for (i = 0; i < vec_size(parser->imm_string); ++i) {
6281         ast_delete(parser->imm_string[i]);
6282     }
6283     for (i = 0; i < vec_size(parser->imm_float); ++i) {
6284         ast_delete(parser->imm_float[i]);
6285     }
6286     for (i = 0; i < vec_size(parser->fields); ++i) {
6287         ast_delete(parser->fields[i]);
6288     }
6289     for (i = 0; i < vec_size(parser->globals); ++i) {
6290         ast_delete(parser->globals[i]);
6291     }
6292     vec_free(parser->accessors);
6293     vec_free(parser->functions);
6294     vec_free(parser->imm_vector);
6295     vec_free(parser->imm_string);
6296     util_htdel(parser->ht_imm_string);
6297     vec_free(parser->imm_float);
6298     vec_free(parser->globals);
6299     vec_free(parser->fields);
6300
6301     for (i = 0; i < vec_size(parser->variables); ++i)
6302         util_htdel(parser->variables[i]);
6303     vec_free(parser->variables);
6304     vec_free(parser->_blocklocals);
6305     vec_free(parser->_locals);
6306
6307     /* corrector */
6308     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6309         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6310     }
6311     vec_free(parser->correct_variables);
6312     vec_free(parser->correct_variables_score);
6313
6314
6315     for (i = 0; i < vec_size(parser->_typedefs); ++i)
6316         ast_delete(parser->_typedefs[i]);
6317     vec_free(parser->_typedefs);
6318     for (i = 0; i < vec_size(parser->typedefs); ++i)
6319         util_htdel(parser->typedefs[i]);
6320     vec_free(parser->typedefs);
6321     vec_free(parser->_blocktypedefs);
6322
6323     vec_free(parser->_block_ctx);
6324
6325     vec_free(parser->labels);
6326     vec_free(parser->gotos);
6327     vec_free(parser->breaks);
6328     vec_free(parser->continues);
6329
6330     ast_value_delete(parser->nil);
6331
6332     ast_value_delete(parser->const_vec[0]);
6333     ast_value_delete(parser->const_vec[1]);
6334     ast_value_delete(parser->const_vec[2]);
6335
6336     util_htdel(parser->aliases);
6337     intrin_intrinsics_destroy(parser);
6338 }
6339
6340 void parser_cleanup(parser_t *parser)
6341 {
6342     parser_remove_ast(parser);
6343     code_cleanup(parser->code);
6344
6345     mem_d(parser);
6346 }
6347
6348 bool parser_finish(parser_t *parser, const char *output)
6349 {
6350     size_t i;
6351     ir_builder *ir;
6352     bool retval = true;
6353
6354     if (compile_errors) {
6355         con_out("*** there were compile errors\n");
6356         return false;
6357     }
6358
6359     ir = ir_builder_new("gmqcc_out");
6360     if (!ir) {
6361         con_out("failed to allocate builder\n");
6362         return false;
6363     }
6364
6365     for (i = 0; i < vec_size(parser->fields); ++i) {
6366         ast_value *field;
6367         bool hasvalue;
6368         if (!ast_istype(parser->fields[i], ast_value))
6369             continue;
6370         field = (ast_value*)parser->fields[i];
6371         hasvalue = field->hasvalue;
6372         field->hasvalue = false;
6373         if (!ast_global_codegen((ast_value*)field, ir, true)) {
6374             con_out("failed to generate field %s\n", field->name);
6375             ir_builder_delete(ir);
6376             return false;
6377         }
6378         if (hasvalue) {
6379             ir_value *ifld;
6380             ast_expression *subtype;
6381             field->hasvalue = true;
6382             subtype = field->expression.next;
6383             ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6384             if (subtype->vtype == TYPE_FIELD)
6385                 ifld->fieldtype = subtype->next->vtype;
6386             else if (subtype->vtype == TYPE_FUNCTION)
6387                 ifld->outtype = subtype->next->vtype;
6388             (void)!ir_value_set_field(field->ir_v, ifld);
6389         }
6390     }
6391     for (i = 0; i < vec_size(parser->globals); ++i) {
6392         ast_value *asvalue;
6393         if (!ast_istype(parser->globals[i], ast_value))
6394             continue;
6395         asvalue = (ast_value*)(parser->globals[i]);
6396         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6397             retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6398                                                 "unused global: `%s`", asvalue->name);
6399         }
6400         if (!ast_global_codegen(asvalue, ir, false)) {
6401             con_out("failed to generate global %s\n", asvalue->name);
6402             ir_builder_delete(ir);
6403             return false;
6404         }
6405     }
6406     /* Build function vararg accessor ast tree now before generating
6407      * immediates, because the accessors may add new immediates
6408      */
6409     for (i = 0; i < vec_size(parser->functions); ++i) {
6410         ast_function *f = parser->functions[i];
6411         if (f->varargs) {
6412             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6413                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6414                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6415                     con_out("failed to generate vararg setter for %s\n", f->name);
6416                     ir_builder_delete(ir);
6417                     return false;
6418                 }
6419                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6420                     con_out("failed to generate vararg getter for %s\n", f->name);
6421                     ir_builder_delete(ir);
6422                     return false;
6423                 }
6424             } else {
6425                 ast_delete(f->varargs);
6426                 f->varargs = NULL;
6427             }
6428         }
6429     }
6430     /* Now we can generate immediates */
6431     for (i = 0; i < vec_size(parser->imm_float); ++i) {
6432         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6433             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6434             ir_builder_delete(ir);
6435             return false;
6436         }
6437     }
6438     for (i = 0; i < vec_size(parser->imm_string); ++i) {
6439         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6440             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6441             ir_builder_delete(ir);
6442             return false;
6443         }
6444     }
6445     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6446         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6447             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6448             ir_builder_delete(ir);
6449             return false;
6450         }
6451     }
6452     for (i = 0; i < vec_size(parser->globals); ++i) {
6453         ast_value *asvalue;
6454         if (!ast_istype(parser->globals[i], ast_value))
6455             continue;
6456         asvalue = (ast_value*)(parser->globals[i]);
6457         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6458         {
6459             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6460                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6461                                        "uninitialized constant: `%s`",
6462                                        asvalue->name);
6463             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6464                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6465                                        "uninitialized global: `%s`",
6466                                        asvalue->name);
6467         }
6468         if (!ast_generate_accessors(asvalue, ir)) {
6469             ir_builder_delete(ir);
6470             return false;
6471         }
6472     }
6473     for (i = 0; i < vec_size(parser->fields); ++i) {
6474         ast_value *asvalue;
6475         asvalue = (ast_value*)(parser->fields[i]->next);
6476
6477         if (!ast_istype((ast_expression*)asvalue, ast_value))
6478             continue;
6479         if (asvalue->expression.vtype != TYPE_ARRAY)
6480             continue;
6481         if (!ast_generate_accessors(asvalue, ir)) {
6482             ir_builder_delete(ir);
6483             return false;
6484         }
6485     }
6486     if (parser->reserved_version &&
6487         !ast_global_codegen(parser->reserved_version, ir, false))
6488     {
6489         con_out("failed to generate reserved::version");
6490         ir_builder_delete(ir);
6491         return false;
6492     }
6493     for (i = 0; i < vec_size(parser->functions); ++i) {
6494         ast_function *f = parser->functions[i];
6495         if (!ast_function_codegen(f, ir)) {
6496             con_out("failed to generate function %s\n", f->name);
6497             ir_builder_delete(ir);
6498             return false;
6499         }
6500     }
6501
6502     generate_checksum(parser);
6503     if (OPTS_OPTION_BOOL(OPTION_DUMP))
6504         ir_builder_dump(ir, con_out);
6505     for (i = 0; i < vec_size(parser->functions); ++i) {
6506         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6507             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6508             ir_builder_delete(ir);
6509             return false;
6510         }
6511     }
6512     parser_remove_ast(parser);
6513
6514     if (compile_Werrors) {
6515         con_out("*** there were warnings treated as errors\n");
6516         compile_show_werrors();
6517         retval = false;
6518     }
6519
6520     if (retval) {
6521         if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6522             ir_builder_dump(ir, con_out);
6523
6524         if (!ir_builder_generate(parser->code, ir, output)) {
6525             con_out("*** failed to generate output file\n");
6526             ir_builder_delete(ir);
6527             return false;
6528         }
6529     }
6530     ir_builder_delete(ir);
6531     return retval;
6532 }