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