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