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