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