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