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