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