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