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