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