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