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