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