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