]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Copying arg counter into the local
[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->argcounter) {
4010         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4011         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4012         func->argc = argc;
4013     }
4014
4015     if (var->expression.flags & AST_FLAG_VARIADIC) {
4016         char name[1024];
4017         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4018         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4019         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4020         varargs->expression.count = 0;
4021         snprintf(name, sizeof(name), "%s##va##SET", var->name);
4022         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4023             ast_delete(varargs);
4024             ast_block_delete(block);
4025             goto enderr;
4026         }
4027         snprintf(name, sizeof(name), "%s##va##GET", var->name);
4028         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4029             ast_delete(varargs);
4030             ast_block_delete(block);
4031             goto enderr;
4032         }
4033         func->varargs = varargs;
4034     }
4035
4036     parser->function = func;
4037     if (!parse_block_into(parser, block)) {
4038         ast_block_delete(block);
4039         goto enderrfn;
4040     }
4041
4042     vec_push(func->blocks, block);
4043
4044     parser->function = old;
4045     if (!parser_leaveblock(parser))
4046         retval = false;
4047     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4048         parseerror(parser, "internal error: local scopes left");
4049         retval = false;
4050     }
4051
4052     if (parser->tok == ';')
4053         return parser_next(parser);
4054     else if (opts.standard == COMPILER_QCC)
4055         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4056     return retval;
4057
4058 enderrfn:
4059     vec_pop(parser->functions);
4060     ast_function_delete(func);
4061     var->constval.vfunc = NULL;
4062
4063 enderr:
4064     (void)!parser_leaveblock(parser);
4065     parser->function = old;
4066     return false;
4067 }
4068
4069 static ast_expression *array_accessor_split(
4070     parser_t  *parser,
4071     ast_value *array,
4072     ast_value *index,
4073     size_t     middle,
4074     ast_expression *left,
4075     ast_expression *right
4076     )
4077 {
4078     ast_ifthen *ifthen;
4079     ast_binary *cmp;
4080
4081     lex_ctx ctx = ast_ctx(array);
4082
4083     if (!left || !right) {
4084         if (left)  ast_delete(left);
4085         if (right) ast_delete(right);
4086         return NULL;
4087     }
4088
4089     cmp = ast_binary_new(ctx, INSTR_LT,
4090                          (ast_expression*)index,
4091                          (ast_expression*)parser_const_float(parser, middle));
4092     if (!cmp) {
4093         ast_delete(left);
4094         ast_delete(right);
4095         parseerror(parser, "internal error: failed to create comparison for array setter");
4096         return NULL;
4097     }
4098
4099     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4100     if (!ifthen) {
4101         ast_delete(cmp); /* will delete left and right */
4102         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4103         return NULL;
4104     }
4105
4106     return (ast_expression*)ifthen;
4107 }
4108
4109 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4110 {
4111     lex_ctx ctx = ast_ctx(array);
4112
4113     if (from+1 == afterend) {
4114         /* set this value */
4115         ast_block       *block;
4116         ast_return      *ret;
4117         ast_array_index *subscript;
4118         ast_store       *st;
4119         int assignop = type_store_instr[value->expression.vtype];
4120
4121         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4122             assignop = INSTR_STORE_V;
4123
4124         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4125         if (!subscript)
4126             return NULL;
4127
4128         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4129         if (!st) {
4130             ast_delete(subscript);
4131             return NULL;
4132         }
4133
4134         block = ast_block_new(ctx);
4135         if (!block) {
4136             ast_delete(st);
4137             return NULL;
4138         }
4139
4140         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4141             ast_delete(block);
4142             return NULL;
4143         }
4144
4145         ret = ast_return_new(ctx, NULL);
4146         if (!ret) {
4147             ast_delete(block);
4148             return NULL;
4149         }
4150
4151         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4152             ast_delete(block);
4153             return NULL;
4154         }
4155
4156         return (ast_expression*)block;
4157     } else {
4158         ast_expression *left, *right;
4159         size_t diff = afterend - from;
4160         size_t middle = from + diff/2;
4161         left  = array_setter_node(parser, array, index, value, from, middle);
4162         right = array_setter_node(parser, array, index, value, middle, afterend);
4163         return array_accessor_split(parser, array, index, middle, left, right);
4164     }
4165 }
4166
4167 static ast_expression *array_field_setter_node(
4168     parser_t  *parser,
4169     ast_value *array,
4170     ast_value *entity,
4171     ast_value *index,
4172     ast_value *value,
4173     size_t     from,
4174     size_t     afterend)
4175 {
4176     lex_ctx ctx = ast_ctx(array);
4177
4178     if (from+1 == afterend) {
4179         /* set this value */
4180         ast_block       *block;
4181         ast_return      *ret;
4182         ast_entfield    *entfield;
4183         ast_array_index *subscript;
4184         ast_store       *st;
4185         int assignop = type_storep_instr[value->expression.vtype];
4186
4187         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4188             assignop = INSTR_STOREP_V;
4189
4190         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4191         if (!subscript)
4192             return NULL;
4193
4194         entfield = ast_entfield_new_force(ctx,
4195                                           (ast_expression*)entity,
4196                                           (ast_expression*)subscript,
4197                                           (ast_expression*)subscript);
4198         if (!entfield) {
4199             ast_delete(subscript);
4200             return NULL;
4201         }
4202
4203         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4204         if (!st) {
4205             ast_delete(entfield);
4206             return NULL;
4207         }
4208
4209         block = ast_block_new(ctx);
4210         if (!block) {
4211             ast_delete(st);
4212             return NULL;
4213         }
4214
4215         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4216             ast_delete(block);
4217             return NULL;
4218         }
4219
4220         ret = ast_return_new(ctx, NULL);
4221         if (!ret) {
4222             ast_delete(block);
4223             return NULL;
4224         }
4225
4226         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4227             ast_delete(block);
4228             return NULL;
4229         }
4230
4231         return (ast_expression*)block;
4232     } else {
4233         ast_expression *left, *right;
4234         size_t diff = afterend - from;
4235         size_t middle = from + diff/2;
4236         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4237         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4238         return array_accessor_split(parser, array, index, middle, left, right);
4239     }
4240 }
4241
4242 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4243 {
4244     lex_ctx ctx = ast_ctx(array);
4245
4246     if (from+1 == afterend) {
4247         ast_return      *ret;
4248         ast_array_index *subscript;
4249
4250         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4251         if (!subscript)
4252             return NULL;
4253
4254         ret = ast_return_new(ctx, (ast_expression*)subscript);
4255         if (!ret) {
4256             ast_delete(subscript);
4257             return NULL;
4258         }
4259
4260         return (ast_expression*)ret;
4261     } else {
4262         ast_expression *left, *right;
4263         size_t diff = afterend - from;
4264         size_t middle = from + diff/2;
4265         left  = array_getter_node(parser, array, index, from, middle);
4266         right = array_getter_node(parser, array, index, middle, afterend);
4267         return array_accessor_split(parser, array, index, middle, left, right);
4268     }
4269 }
4270
4271 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4272 {
4273     ast_function   *func = NULL;
4274     ast_value      *fval = NULL;
4275     ast_block      *body = NULL;
4276
4277     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4278     if (!fval) {
4279         parseerror(parser, "failed to create accessor function value");
4280         return false;
4281     }
4282
4283     func = ast_function_new(ast_ctx(array), funcname, fval);
4284     if (!func) {
4285         ast_delete(fval);
4286         parseerror(parser, "failed to create accessor function node");
4287         return false;
4288     }
4289
4290     body = ast_block_new(ast_ctx(array));
4291     if (!body) {
4292         parseerror(parser, "failed to create block for array accessor");
4293         ast_delete(fval);
4294         ast_delete(func);
4295         return false;
4296     }
4297
4298     vec_push(func->blocks, body);
4299     *out = fval;
4300
4301     vec_push(parser->accessors, fval);
4302
4303     return true;
4304 }
4305
4306 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4307 {
4308     ast_value      *index = NULL;
4309     ast_value      *value = NULL;
4310     ast_function   *func;
4311     ast_value      *fval;
4312
4313     if (!ast_istype(array->expression.next, ast_value)) {
4314         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4315         return NULL;
4316     }
4317
4318     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4319         return NULL;
4320     func = fval->constval.vfunc;
4321     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4322
4323     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4324     value = ast_value_copy((ast_value*)array->expression.next);
4325
4326     if (!index || !value) {
4327         parseerror(parser, "failed to create locals for array accessor");
4328         goto cleanup;
4329     }
4330     (void)!ast_value_set_name(value, "value"); /* not important */
4331     vec_push(fval->expression.params, index);
4332     vec_push(fval->expression.params, value);
4333
4334     array->setter = fval;
4335     return fval;
4336 cleanup:
4337     if (index) ast_delete(index);
4338     if (value) ast_delete(value);
4339     ast_delete(func);
4340     ast_delete(fval);
4341     return NULL;
4342 }
4343
4344 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4345 {
4346     ast_expression *root = NULL;
4347     root = array_setter_node(parser, array,
4348                              array->setter->expression.params[0],
4349                              array->setter->expression.params[1],
4350                              0, array->expression.count);
4351     if (!root) {
4352         parseerror(parser, "failed to build accessor search tree");
4353         return false;
4354     }
4355     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4356         ast_delete(root);
4357         return false;
4358     }
4359     return true;
4360 }
4361
4362 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4363 {
4364     if (!parser_create_array_setter_proto(parser, array, funcname))
4365         return false;
4366     return parser_create_array_setter_impl(parser, array);
4367 }
4368
4369 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4370 {
4371     ast_expression *root = NULL;
4372     ast_value      *entity = NULL;
4373     ast_value      *index = NULL;
4374     ast_value      *value = NULL;
4375     ast_function   *func;
4376     ast_value      *fval;
4377
4378     if (!ast_istype(array->expression.next, ast_value)) {
4379         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4380         return false;
4381     }
4382
4383     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4384         return false;
4385     func = fval->constval.vfunc;
4386     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4387
4388     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4389     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4390     value  = ast_value_copy((ast_value*)array->expression.next);
4391     if (!entity || !index || !value) {
4392         parseerror(parser, "failed to create locals for array accessor");
4393         goto cleanup;
4394     }
4395     (void)!ast_value_set_name(value, "value"); /* not important */
4396     vec_push(fval->expression.params, entity);
4397     vec_push(fval->expression.params, index);
4398     vec_push(fval->expression.params, value);
4399
4400     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4401     if (!root) {
4402         parseerror(parser, "failed to build accessor search tree");
4403         goto cleanup;
4404     }
4405
4406     array->setter = fval;
4407     return ast_block_add_expr(func->blocks[0], root);
4408 cleanup:
4409     if (entity) ast_delete(entity);
4410     if (index)  ast_delete(index);
4411     if (value)  ast_delete(value);
4412     if (root)   ast_delete(root);
4413     ast_delete(func);
4414     ast_delete(fval);
4415     return false;
4416 }
4417
4418 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4419 {
4420     ast_value      *index = NULL;
4421     ast_value      *fval;
4422     ast_function   *func;
4423
4424     /* NOTE: checking array->expression.next rather than elemtype since
4425      * for fields elemtype is a temporary fieldtype.
4426      */
4427     if (!ast_istype(array->expression.next, ast_value)) {
4428         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4429         return NULL;
4430     }
4431
4432     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4433         return NULL;
4434     func = fval->constval.vfunc;
4435     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4436
4437     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4438
4439     if (!index) {
4440         parseerror(parser, "failed to create locals for array accessor");
4441         goto cleanup;
4442     }
4443     vec_push(fval->expression.params, index);
4444
4445     array->getter = fval;
4446     return fval;
4447 cleanup:
4448     if (index) ast_delete(index);
4449     ast_delete(func);
4450     ast_delete(fval);
4451     return NULL;
4452 }
4453
4454 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4455 {
4456     ast_expression *root = NULL;
4457
4458     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4459     if (!root) {
4460         parseerror(parser, "failed to build accessor search tree");
4461         return false;
4462     }
4463     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4464         ast_delete(root);
4465         return false;
4466     }
4467     return true;
4468 }
4469
4470 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4471 {
4472     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4473         return false;
4474     return parser_create_array_getter_impl(parser, array);
4475 }
4476
4477 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4478 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4479 {
4480     lex_ctx     ctx;
4481     size_t      i;
4482     ast_value **params;
4483     ast_value  *param;
4484     ast_value  *fval;
4485     bool        first = true;
4486     bool        variadic = false;
4487     ast_value  *varparam = NULL;
4488     char       *argcounter = NULL;
4489
4490     ctx = parser_ctx(parser);
4491
4492     /* for the sake of less code we parse-in in this function */
4493     if (!parser_next(parser)) {
4494         parseerror(parser, "expected parameter list");
4495         return NULL;
4496     }
4497
4498     params = NULL;
4499
4500     /* parse variables until we hit a closing paren */
4501     while (parser->tok != ')') {
4502         if (!first) {
4503             /* there must be commas between them */
4504             if (parser->tok != ',') {
4505                 parseerror(parser, "expected comma or end of parameter list");
4506                 goto on_error;
4507             }
4508             if (!parser_next(parser)) {
4509                 parseerror(parser, "expected parameter");
4510                 goto on_error;
4511             }
4512         }
4513         first = false;
4514
4515         if (parser->tok == TOKEN_DOTS) {
4516             /* '...' indicates a varargs function */
4517             variadic = true;
4518             if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4519                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4520                 goto on_error;
4521             }
4522             if (parser->tok == TOKEN_IDENT) {
4523                 argcounter = util_strdup(parser_tokval(parser));
4524                 if (!parser_next(parser) || parser->tok != ')') {
4525                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4526                     goto on_error;
4527                 }
4528             }
4529         }
4530         else
4531         {
4532             /* for anything else just parse a typename */
4533             param = parse_typename(parser, NULL, NULL);
4534             if (!param)
4535                 goto on_error;
4536             vec_push(params, param);
4537             if (param->expression.vtype >= TYPE_VARIANT) {
4538                 char tname[1024]; /* typename is reserved in C++ */
4539                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4540                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4541                 goto on_error;
4542             }
4543             /* type-restricted varargs */
4544             if (parser->tok == TOKEN_DOTS) {
4545                 variadic = true;
4546                 varparam = vec_last(params);
4547                 vec_pop(params);
4548                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4549                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4550                     goto on_error;
4551                 }
4552                 if (parser->tok == TOKEN_IDENT) {
4553                     argcounter = util_strdup(parser_tokval(parser));
4554                     if (!parser_next(parser) || parser->tok != ')') {
4555                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4556                         goto on_error;
4557                     }
4558                 }
4559             }
4560         }
4561     }
4562
4563     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4564         vec_free(params);
4565
4566     /* sanity check */
4567     if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4568         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4569
4570     /* parse-out */
4571     if (!parser_next(parser)) {
4572         parseerror(parser, "parse error after typename");
4573         goto on_error;
4574     }
4575
4576     /* now turn 'var' into a function type */
4577     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4578     fval->expression.next     = (ast_expression*)var;
4579     if (variadic)
4580         fval->expression.flags |= AST_FLAG_VARIADIC;
4581     var = fval;
4582
4583     var->expression.params   = params;
4584     var->expression.varparam = (ast_expression*)varparam;
4585     var->argcounter          = argcounter;
4586     params = NULL;
4587
4588     return var;
4589
4590 on_error:
4591     if (argcounter)
4592         mem_d(argcounter);
4593     ast_delete(var);
4594     for (i = 0; i < vec_size(params); ++i)
4595         ast_delete(params[i]);
4596     vec_free(params);
4597     return NULL;
4598 }
4599
4600 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4601 {
4602     ast_expression *cexp;
4603     ast_value      *cval, *tmp;
4604     lex_ctx ctx;
4605
4606     ctx = parser_ctx(parser);
4607
4608     if (!parser_next(parser)) {
4609         ast_delete(var);
4610         parseerror(parser, "expected array-size");
4611         return NULL;
4612     }
4613
4614     cexp = parse_expression_leave(parser, true, false, false);
4615
4616     if (!cexp || !ast_istype(cexp, ast_value)) {
4617         if (cexp)
4618             ast_unref(cexp);
4619         ast_delete(var);
4620         parseerror(parser, "expected array-size as constant positive integer");
4621         return NULL;
4622     }
4623     cval = (ast_value*)cexp;
4624
4625     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4626     tmp->expression.next = (ast_expression*)var;
4627     var = tmp;
4628
4629     if (cval->expression.vtype == TYPE_INTEGER)
4630         tmp->expression.count = cval->constval.vint;
4631     else if (cval->expression.vtype == TYPE_FLOAT)
4632         tmp->expression.count = cval->constval.vfloat;
4633     else {
4634         ast_unref(cexp);
4635         ast_delete(var);
4636         parseerror(parser, "array-size must be a positive integer constant");
4637         return NULL;
4638     }
4639     ast_unref(cexp);
4640
4641     if (parser->tok != ']') {
4642         ast_delete(var);
4643         parseerror(parser, "expected ']' after array-size");
4644         return NULL;
4645     }
4646     if (!parser_next(parser)) {
4647         ast_delete(var);
4648         parseerror(parser, "error after parsing array size");
4649         return NULL;
4650     }
4651     return var;
4652 }
4653
4654 /* Parse a complete typename.
4655  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4656  * but when parsing variables separated by comma
4657  * 'storebase' should point to where the base-type should be kept.
4658  * The base type makes up every bit of type information which comes *before* the
4659  * variable name.
4660  *
4661  * The following will be parsed in its entirety:
4662  *     void() foo()
4663  * The 'basetype' in this case is 'void()'
4664  * and if there's a comma after it, say:
4665  *     void() foo(), bar
4666  * then the type-information 'void()' can be stored in 'storebase'
4667  */
4668 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4669 {
4670     ast_value *var, *tmp;
4671     lex_ctx    ctx;
4672
4673     const char *name = NULL;
4674     bool        isfield  = false;
4675     bool        wasarray = false;
4676     size_t      morefields = 0;
4677
4678     ctx = parser_ctx(parser);
4679
4680     /* types may start with a dot */
4681     if (parser->tok == '.') {
4682         isfield = true;
4683         /* if we parsed a dot we need a typename now */
4684         if (!parser_next(parser)) {
4685             parseerror(parser, "expected typename for field definition");
4686             return NULL;
4687         }
4688
4689         /* Further dots are handled seperately because they won't be part of the
4690          * basetype
4691          */
4692         while (parser->tok == '.') {
4693             ++morefields;
4694             if (!parser_next(parser)) {
4695                 parseerror(parser, "expected typename for field definition");
4696                 return NULL;
4697             }
4698         }
4699     }
4700     if (parser->tok == TOKEN_IDENT)
4701         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4702     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4703         parseerror(parser, "expected typename");
4704         return NULL;
4705     }
4706
4707     /* generate the basic type value */
4708     if (cached_typedef) {
4709         var = ast_value_copy(cached_typedef);
4710         ast_value_set_name(var, "<type(from_def)>");
4711     } else
4712         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4713
4714     for (; morefields; --morefields) {
4715         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4716         tmp->expression.next = (ast_expression*)var;
4717         var = tmp;
4718     }
4719
4720     /* do not yet turn into a field - remember:
4721      * .void() foo; is a field too
4722      * .void()() foo; is a function
4723      */
4724
4725     /* parse on */
4726     if (!parser_next(parser)) {
4727         ast_delete(var);
4728         parseerror(parser, "parse error after typename");
4729         return NULL;
4730     }
4731
4732     /* an opening paren now starts the parameter-list of a function
4733      * this is where original-QC has parameter lists.
4734      * We allow a single parameter list here.
4735      * Much like fteqcc we don't allow `float()() x`
4736      */
4737     if (parser->tok == '(') {
4738         var = parse_parameter_list(parser, var);
4739         if (!var)
4740             return NULL;
4741     }
4742
4743     /* store the base if requested */
4744     if (storebase) {
4745         *storebase = ast_value_copy(var);
4746         if (isfield) {
4747             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4748             tmp->expression.next = (ast_expression*)*storebase;
4749             *storebase = tmp;
4750         }
4751     }
4752
4753     /* there may be a name now */
4754     if (parser->tok == TOKEN_IDENT) {
4755         name = util_strdup(parser_tokval(parser));
4756         /* parse on */
4757         if (!parser_next(parser)) {
4758             ast_delete(var);
4759             parseerror(parser, "error after variable or field declaration");
4760             return NULL;
4761         }
4762     }
4763
4764     /* now this may be an array */
4765     if (parser->tok == '[') {
4766         wasarray = true;
4767         var = parse_arraysize(parser, var);
4768         if (!var)
4769             return NULL;
4770     }
4771
4772     /* This is the point where we can turn it into a field */
4773     if (isfield) {
4774         /* turn it into a field if desired */
4775         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4776         tmp->expression.next = (ast_expression*)var;
4777         var = tmp;
4778     }
4779
4780     /* now there may be function parens again */
4781     if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4782         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4783     if (parser->tok == '(' && wasarray)
4784         parseerror(parser, "arrays as part of a return type is not supported");
4785     while (parser->tok == '(') {
4786         var = parse_parameter_list(parser, var);
4787         if (!var) {
4788             if (name)
4789                 mem_d((void*)name);
4790             ast_delete(var);
4791             return NULL;
4792         }
4793     }
4794
4795     /* finally name it */
4796     if (name) {
4797         if (!ast_value_set_name(var, name)) {
4798             ast_delete(var);
4799             parseerror(parser, "internal error: failed to set name");
4800             return NULL;
4801         }
4802         /* free the name, ast_value_set_name duplicates */
4803         mem_d((void*)name);
4804     }
4805
4806     return var;
4807 }
4808
4809 static bool parse_typedef(parser_t *parser)
4810 {
4811     ast_value      *typevar, *oldtype;
4812     ast_expression *old;
4813
4814     typevar = parse_typename(parser, NULL, NULL);
4815
4816     if (!typevar)
4817         return false;
4818
4819     if ( (old = parser_find_var(parser, typevar->name)) ) {
4820         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4821                    " -> `%s` has been declared here: %s:%i",
4822                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4823         ast_delete(typevar);
4824         return false;
4825     }
4826
4827     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4828         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4829                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4830         ast_delete(typevar);
4831         return false;
4832     }
4833
4834     vec_push(parser->_typedefs, typevar);
4835     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4836
4837     if (parser->tok != ';') {
4838         parseerror(parser, "expected semicolon after typedef");
4839         return false;
4840     }
4841     if (!parser_next(parser)) {
4842         parseerror(parser, "parse error after typedef");
4843         return false;
4844     }
4845
4846     return true;
4847 }
4848
4849 static const char *cvq_to_str(int cvq) {
4850     switch (cvq) {
4851         case CV_NONE:  return "none";
4852         case CV_VAR:   return "`var`";
4853         case CV_CONST: return "`const`";
4854         default:       return "<INVALID>";
4855     }
4856 }
4857
4858 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4859 {
4860     bool av, ao;
4861     if (proto->cvq != var->cvq) {
4862         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4863               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4864               parser->tok == '='))
4865         {
4866             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4867                                  "`%s` declared with different qualifiers: %s\n"
4868                                  " -> previous declaration here: %s:%i uses %s",
4869                                  var->name, cvq_to_str(var->cvq),
4870                                  ast_ctx(proto).file, ast_ctx(proto).line,
4871                                  cvq_to_str(proto->cvq));
4872         }
4873     }
4874     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4875     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4876     if (!av != !ao) {
4877         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4878                              "`%s` declared with different attributes%s\n"
4879                              " -> previous declaration here: %s:%i",
4880                              var->name, (av ? ": noreturn" : ""),
4881                              ast_ctx(proto).file, ast_ctx(proto).line,
4882                              (ao ? ": noreturn" : ""));
4883     }
4884     return true;
4885 }
4886
4887 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)
4888 {
4889     ast_value *var;
4890     ast_value *proto;
4891     ast_expression *old;
4892     bool       was_end;
4893     size_t     i;
4894
4895     ast_value *basetype = NULL;
4896     bool      retval    = true;
4897     bool      isparam   = false;
4898     bool      isvector  = false;
4899     bool      cleanvar  = true;
4900     bool      wasarray  = false;
4901
4902     ast_member *me[3];
4903
4904     if (!localblock && is_static)
4905         parseerror(parser, "`static` qualifier is not supported in global scope");
4906
4907     /* get the first complete variable */
4908     var = parse_typename(parser, &basetype, cached_typedef);
4909     if (!var) {
4910         if (basetype)
4911             ast_delete(basetype);
4912         return false;
4913     }
4914
4915     while (true) {
4916         proto = NULL;
4917         wasarray = false;
4918
4919         /* Part 0: finish the type */
4920         if (parser->tok == '(') {
4921             if (opts.standard == COMPILER_QCC)
4922                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4923             var = parse_parameter_list(parser, var);
4924             if (!var) {
4925                 retval = false;
4926                 goto cleanup;
4927             }
4928         }
4929         /* we only allow 1-dimensional arrays */
4930         if (parser->tok == '[') {
4931             wasarray = true;
4932             var = parse_arraysize(parser, var);
4933             if (!var) {
4934                 retval = false;
4935                 goto cleanup;
4936             }
4937         }
4938         if (parser->tok == '(' && wasarray) {
4939             parseerror(parser, "arrays as part of a return type is not supported");
4940             /* we'll still parse the type completely for now */
4941         }
4942         /* for functions returning functions */
4943         while (parser->tok == '(') {
4944             if (opts.standard == COMPILER_QCC)
4945                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4946             var = parse_parameter_list(parser, var);
4947             if (!var) {
4948                 retval = false;
4949                 goto cleanup;
4950             }
4951         }
4952
4953         var->cvq = qualifier;
4954         var->expression.flags |= qflags;
4955         if (var->expression.flags & AST_FLAG_DEPRECATED)
4956             var->desc = vstring;
4957
4958         /* Part 1:
4959          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4960          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4961          * is then filled with the previous definition and the parameter-names replaced.
4962          */
4963         if (!strcmp(var->name, "nil")) {
4964             if (OPTS_FLAG(UNTYPED_NIL)) {
4965                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4966                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4967             } else
4968                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4969         }
4970         if (!localblock) {
4971             /* Deal with end_sys_ vars */
4972             was_end = false;
4973             if (!strcmp(var->name, "end_sys_globals")) {
4974                 var->uses++;
4975                 parser->crc_globals = vec_size(parser->globals);
4976                 was_end = true;
4977             }
4978             else if (!strcmp(var->name, "end_sys_fields")) {
4979                 var->uses++;
4980                 parser->crc_fields = vec_size(parser->fields);
4981                 was_end = true;
4982             }
4983             if (was_end && var->expression.vtype == TYPE_FIELD) {
4984                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4985                                  "global '%s' hint should not be a field",
4986                                  parser_tokval(parser)))
4987                 {
4988                     retval = false;
4989                     goto cleanup;
4990                 }
4991             }
4992
4993             if (!nofields && var->expression.vtype == TYPE_FIELD)
4994             {
4995                 /* deal with field declarations */
4996                 old = parser_find_field(parser, var->name);
4997                 if (old) {
4998                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4999                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5000                     {
5001                         retval = false;
5002                         goto cleanup;
5003                     }
5004                     ast_delete(var);
5005                     var = NULL;
5006                     goto skipvar;
5007                     /*
5008                     parseerror(parser, "field `%s` already declared here: %s:%i",
5009                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5010                     retval = false;
5011                     goto cleanup;
5012                     */
5013                 }
5014                 if (opts.standard == COMPILER_QCC &&
5015                     (old = parser_find_global(parser, var->name)))
5016                 {
5017                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5018                     parseerror(parser, "field `%s` already declared here: %s:%i",
5019                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5020                     retval = false;
5021                     goto cleanup;
5022                 }
5023             }
5024             else
5025             {
5026                 /* deal with other globals */
5027                 old = parser_find_global(parser, var->name);
5028                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5029                 {
5030                     /* This is a function which had a prototype */
5031                     if (!ast_istype(old, ast_value)) {
5032                         parseerror(parser, "internal error: prototype is not an ast_value");
5033                         retval = false;
5034                         goto cleanup;
5035                     }
5036                     proto = (ast_value*)old;
5037                     proto->desc = var->desc;
5038                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5039                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5040                                    proto->name,
5041                                    ast_ctx(proto).file, ast_ctx(proto).line);
5042                         retval = false;
5043                         goto cleanup;
5044                     }
5045                     /* we need the new parameter-names */
5046                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5047                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5048                     if (!parser_check_qualifiers(parser, var, proto)) {
5049                         retval = false;
5050                         if (proto->desc) 
5051                             mem_d(proto->desc);
5052                         proto = NULL;
5053                         goto cleanup;
5054                     }
5055                     proto->expression.flags |= var->expression.flags;
5056                     ast_delete(var);
5057                     var = proto;
5058                 }
5059                 else
5060                 {
5061                     /* other globals */
5062                     if (old) {
5063                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5064                                          "global `%s` already declared here: %s:%i",
5065                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5066                         {
5067                             retval = false;
5068                             goto cleanup;
5069                         }
5070                         proto = (ast_value*)old;
5071                         if (!ast_istype(old, ast_value)) {
5072                             parseerror(parser, "internal error: not an ast_value");
5073                             retval = false;
5074                             proto = NULL;
5075                             goto cleanup;
5076                         }
5077                         if (!parser_check_qualifiers(parser, var, proto)) {
5078                             retval = false;
5079                             proto = NULL;
5080                             goto cleanup;
5081                         }
5082                         proto->expression.flags |= var->expression.flags;
5083                         ast_delete(var);
5084                         var = proto;
5085                     }
5086                     if (opts.standard == COMPILER_QCC &&
5087                         (old = parser_find_field(parser, var->name)))
5088                     {
5089                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5090                         parseerror(parser, "global `%s` already declared here: %s:%i",
5091                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5092                         retval = false;
5093                         goto cleanup;
5094                     }
5095                 }
5096             }
5097         }
5098         else /* it's not a global */
5099         {
5100             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5101             if (old && !isparam) {
5102                 parseerror(parser, "local `%s` already declared here: %s:%i",
5103                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5104                 retval = false;
5105                 goto cleanup;
5106             }
5107             old = parser_find_local(parser, var->name, 0, &isparam);
5108             if (old && isparam) {
5109                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5110                                  "local `%s` is shadowing a parameter", var->name))
5111                 {
5112                     parseerror(parser, "local `%s` already declared here: %s:%i",
5113                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5114                     retval = false;
5115                     goto cleanup;
5116                 }
5117                 if (opts.standard != COMPILER_GMQCC) {
5118                     ast_delete(var);
5119                     var = NULL;
5120                     goto skipvar;
5121                 }
5122             }
5123         }
5124
5125         /* in a noref section we simply bump the usecount */
5126         if (noref || parser->noref)
5127             var->uses++;
5128
5129         /* Part 2:
5130          * Create the global/local, and deal with vector types.
5131          */
5132         if (!proto) {
5133             if (var->expression.vtype == TYPE_VECTOR)
5134                 isvector = true;
5135             else if (var->expression.vtype == TYPE_FIELD &&
5136                      var->expression.next->expression.vtype == TYPE_VECTOR)
5137                 isvector = true;
5138
5139             if (isvector) {
5140                 if (!create_vector_members(var, me)) {
5141                     retval = false;
5142                     goto cleanup;
5143                 }
5144             }
5145
5146             if (!localblock) {
5147                 /* deal with global variables, fields, functions */
5148                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5149                     var->isfield = true;
5150                     vec_push(parser->fields, (ast_expression*)var);
5151                     util_htset(parser->htfields, var->name, var);
5152                     if (isvector) {
5153                         for (i = 0; i < 3; ++i) {
5154                             vec_push(parser->fields, (ast_expression*)me[i]);
5155                             util_htset(parser->htfields, me[i]->name, me[i]);
5156                         }
5157                     }
5158                 }
5159                 else {
5160                     parser_addglobal(parser, var->name, (ast_expression*)var);
5161                     if (isvector) {
5162                         for (i = 0; i < 3; ++i) {
5163                             parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5164                         }
5165                     }
5166                 }
5167             } else {
5168                 if (is_static) {
5169                     /* a static adds itself to be generated like any other global
5170                      * but is added to the local namespace instead
5171                      */
5172                     char   *defname = NULL;
5173                     size_t  prefix_len, ln;
5174
5175                     ln = strlen(parser->function->name);
5176                     vec_append(defname, ln, parser->function->name);
5177
5178                     vec_append(defname, 2, "::");
5179                     /* remember the length up to here */
5180                     prefix_len = vec_size(defname);
5181
5182                     /* Add it to the local scope */
5183                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5184
5185                     /* corrector */
5186                     correct_add (
5187                          vec_last(parser->correct_variables),
5188                         &vec_last(parser->correct_variables_score),
5189                         var->name
5190                     );
5191
5192                     /* now rename the global */
5193                     ln = strlen(var->name);
5194                     vec_append(defname, ln, var->name);
5195                     ast_value_set_name(var, defname);
5196
5197                     /* push it to the to-be-generated globals */
5198                     vec_push(parser->globals, (ast_expression*)var);
5199
5200                     /* same game for the vector members */
5201                     if (isvector) {
5202                         for (i = 0; i < 3; ++i) {
5203                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5204
5205                             /* corrector */
5206                             correct_add(
5207                                  vec_last(parser->correct_variables),
5208                                 &vec_last(parser->correct_variables_score),
5209                                 me[i]->name
5210                             );
5211
5212                             vec_shrinkto(defname, prefix_len);
5213                             ln = strlen(me[i]->name);
5214                             vec_append(defname, ln, me[i]->name);
5215                             ast_member_set_name(me[i], defname);
5216
5217                             vec_push(parser->globals, (ast_expression*)me[i]);
5218                         }
5219                     }
5220                     vec_free(defname);
5221                 } else {
5222                     vec_push(localblock->locals, var);
5223                     parser_addlocal(parser, var->name, (ast_expression*)var);
5224                     if (isvector) {
5225                         for (i = 0; i < 3; ++i) {
5226                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5227                             ast_block_collect(localblock, (ast_expression*)me[i]);
5228                         }
5229                     }
5230                 }
5231             }
5232         }
5233         me[0] = me[1] = me[2] = NULL;
5234         cleanvar = false;
5235         /* Part 2.2
5236          * deal with arrays
5237          */
5238         if (var->expression.vtype == TYPE_ARRAY) {
5239             char name[1024];
5240             snprintf(name, sizeof(name), "%s##SET", var->name);
5241             if (!parser_create_array_setter(parser, var, name))
5242                 goto cleanup;
5243             snprintf(name, sizeof(name), "%s##GET", var->name);
5244             if (!parser_create_array_getter(parser, var, var->expression.next, name))
5245                 goto cleanup;
5246         }
5247         else if (!localblock && !nofields &&
5248                  var->expression.vtype == TYPE_FIELD &&
5249                  var->expression.next->expression.vtype == TYPE_ARRAY)
5250         {
5251             char name[1024];
5252             ast_expression *telem;
5253             ast_value      *tfield;
5254             ast_value      *array = (ast_value*)var->expression.next;
5255
5256             if (!ast_istype(var->expression.next, ast_value)) {
5257                 parseerror(parser, "internal error: field element type must be an ast_value");
5258                 goto cleanup;
5259             }
5260
5261             snprintf(name, sizeof(name), "%s##SETF", var->name);
5262             if (!parser_create_array_field_setter(parser, array, name))
5263                 goto cleanup;
5264
5265             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5266             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5267             tfield->expression.next = telem;
5268             snprintf(name, sizeof(name), "%s##GETFP", var->name);
5269             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5270                 ast_delete(tfield);
5271                 goto cleanup;
5272             }
5273             ast_delete(tfield);
5274         }
5275
5276 skipvar:
5277         if (parser->tok == ';') {
5278             ast_delete(basetype);
5279             if (!parser_next(parser)) {
5280                 parseerror(parser, "error after variable declaration");
5281                 return false;
5282             }
5283             return true;
5284         }
5285
5286         if (parser->tok == ',')
5287             goto another;
5288
5289         /*
5290         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5291         */
5292         if (!var) {
5293             parseerror(parser, "missing comma or semicolon while parsing variables");
5294             break;
5295         }
5296
5297         if (localblock && opts.standard == COMPILER_QCC) {
5298             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5299                              "initializing expression turns variable `%s` into a constant in this standard",
5300                              var->name) )
5301             {
5302                 break;
5303             }
5304         }
5305
5306         if (parser->tok != '{') {
5307             if (parser->tok != '=') {
5308                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5309                 break;
5310             }
5311
5312             if (!parser_next(parser)) {
5313                 parseerror(parser, "error parsing initializer");
5314                 break;
5315             }
5316         }
5317         else if (opts.standard == COMPILER_QCC) {
5318             parseerror(parser, "expected '=' before function body in this standard");
5319         }
5320
5321         if (parser->tok == '#') {
5322             ast_function *func = NULL;
5323
5324             if (localblock) {
5325                 parseerror(parser, "cannot declare builtins within functions");
5326                 break;
5327             }
5328             if (var->expression.vtype != TYPE_FUNCTION) {
5329                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5330                 break;
5331             }
5332             if (!parser_next(parser)) {
5333                 parseerror(parser, "expected builtin number");
5334                 break;
5335             }
5336             if (parser->tok != TOKEN_INTCONST) {
5337                 parseerror(parser, "builtin number must be an integer constant");
5338                 break;
5339             }
5340             if (parser_token(parser)->constval.i < 0) {
5341                 parseerror(parser, "builtin number must be an integer greater than zero");
5342                 break;
5343             }
5344
5345             if (var->hasvalue) {
5346                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5347                                     "builtin `%s` has already been defined\n"
5348                                     " -> previous declaration here: %s:%i",
5349                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5350             }
5351             else
5352             {
5353                 func = ast_function_new(ast_ctx(var), var->name, var);
5354                 if (!func) {
5355                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5356                     break;
5357                 }
5358                 vec_push(parser->functions, func);
5359
5360                 func->builtin = -parser_token(parser)->constval.i-1;
5361             }
5362
5363             if (!parser_next(parser)) {
5364                 parseerror(parser, "expected comma or semicolon");
5365                 if (func)
5366                     ast_function_delete(func);
5367                 var->constval.vfunc = NULL;
5368                 break;
5369             }
5370         }
5371         else if (parser->tok == '{' || parser->tok == '[')
5372         {
5373             if (localblock) {
5374                 parseerror(parser, "cannot declare functions within functions");
5375                 break;
5376             }
5377
5378             if (proto)
5379                 ast_ctx(proto) = parser_ctx(parser);
5380
5381             if (!parse_function_body(parser, var))
5382                 break;
5383             ast_delete(basetype);
5384             for (i = 0; i < vec_size(parser->gotos); ++i)
5385                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5386             vec_free(parser->gotos);
5387             vec_free(parser->labels);
5388             return true;
5389         } else {
5390             ast_expression *cexp;
5391             ast_value      *cval;
5392
5393             cexp = parse_expression_leave(parser, true, false, false);
5394             if (!cexp)
5395                 break;
5396
5397             if (!localblock) {
5398                 cval = (ast_value*)cexp;
5399                 if (cval != parser->nil &&
5400                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5401                    )
5402                 {
5403                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5404                 }
5405                 else
5406                 {
5407                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5408                         qualifier != CV_VAR)
5409                     {
5410                         var->cvq = CV_CONST;
5411                     }
5412                     if (cval == parser->nil)
5413                         var->expression.flags |= AST_FLAG_INITIALIZED;
5414                     else
5415                     {
5416                         var->hasvalue = true;
5417                         if (cval->expression.vtype == TYPE_STRING)
5418                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5419                         else if (cval->expression.vtype == TYPE_FIELD)
5420                             var->constval.vfield = cval;
5421                         else
5422                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5423                         ast_unref(cval);
5424                     }
5425                 }
5426             } else {
5427                 int cvq;
5428                 shunt sy = { NULL, NULL };
5429                 cvq = var->cvq;
5430                 var->cvq = CV_NONE;
5431                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5432                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5433                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5434                 if (!parser_sy_apply_operator(parser, &sy))
5435                     ast_unref(cexp);
5436                 else {
5437                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5438                         parseerror(parser, "internal error: leaked operands");
5439                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5440                         break;
5441                 }
5442                 vec_free(sy.out);
5443                 vec_free(sy.ops);
5444                 var->cvq = cvq;
5445             }
5446         }
5447
5448 another:
5449         if (parser->tok == ',') {
5450             if (!parser_next(parser)) {
5451                 parseerror(parser, "expected another variable");
5452                 break;
5453             }
5454
5455             if (parser->tok != TOKEN_IDENT) {
5456                 parseerror(parser, "expected another variable");
5457                 break;
5458             }
5459             var = ast_value_copy(basetype);
5460             cleanvar = true;
5461             ast_value_set_name(var, parser_tokval(parser));
5462             if (!parser_next(parser)) {
5463                 parseerror(parser, "error parsing variable declaration");
5464                 break;
5465             }
5466             continue;
5467         }
5468
5469         if (parser->tok != ';') {
5470             parseerror(parser, "missing semicolon after variables");
5471             break;
5472         }
5473
5474         if (!parser_next(parser)) {
5475             parseerror(parser, "parse error after variable declaration");
5476             break;
5477         }
5478
5479         ast_delete(basetype);
5480         return true;
5481     }
5482
5483     if (cleanvar && var)
5484         ast_delete(var);
5485     ast_delete(basetype);
5486     return false;
5487
5488 cleanup:
5489     ast_delete(basetype);
5490     if (cleanvar && var)
5491         ast_delete(var);
5492     if (me[0]) ast_member_delete(me[0]);
5493     if (me[1]) ast_member_delete(me[1]);
5494     if (me[2]) ast_member_delete(me[2]);
5495     return retval;
5496 }
5497
5498 static bool parser_global_statement(parser_t *parser)
5499 {
5500     int        cvq       = CV_WRONG;
5501     bool       noref     = false;
5502     bool       is_static = false;
5503     uint32_t   qflags    = 0;
5504     ast_value *istype    = NULL;
5505     char      *vstring   = NULL;
5506
5507     if (parser->tok == TOKEN_IDENT)
5508         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5509
5510     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5511     {
5512         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5513     }
5514     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5515     {
5516         if (cvq == CV_WRONG)
5517             return false;
5518         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5519     }
5520     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5521     {
5522         return parse_enum(parser);
5523     }
5524     else if (parser->tok == TOKEN_KEYWORD)
5525     {
5526         if (!strcmp(parser_tokval(parser), "typedef")) {
5527             if (!parser_next(parser)) {
5528                 parseerror(parser, "expected type definition after 'typedef'");
5529                 return false;
5530             }
5531             return parse_typedef(parser);
5532         }
5533         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5534         return false;
5535     }
5536     else if (parser->tok == '#')
5537     {
5538         return parse_pragma(parser);
5539     }
5540     else if (parser->tok == '$')
5541     {
5542         if (!parser_next(parser)) {
5543             parseerror(parser, "parse error");
5544             return false;
5545         }
5546     }
5547     else
5548     {
5549         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5550         return false;
5551     }
5552     return true;
5553 }
5554
5555 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5556 {
5557     return util_crc16(old, str, strlen(str));
5558 }
5559
5560 static void progdefs_crc_file(const char *str)
5561 {
5562     /* write to progdefs.h here */
5563     (void)str;
5564 }
5565
5566 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5567 {
5568     old = progdefs_crc_sum(old, str);
5569     progdefs_crc_file(str);
5570     return old;
5571 }
5572
5573 static void generate_checksum(parser_t *parser)
5574 {
5575     uint16_t   crc = 0xFFFF;
5576     size_t     i;
5577     ast_value *value;
5578
5579     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5580     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5581     /*
5582     progdefs_crc_file("\tint\tpad;\n");
5583     progdefs_crc_file("\tint\tofs_return[3];\n");
5584     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5585     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5586     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5587     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5588     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5589     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5590     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5591     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5592     */
5593     for (i = 0; i < parser->crc_globals; ++i) {
5594         if (!ast_istype(parser->globals[i], ast_value))
5595             continue;
5596         value = (ast_value*)(parser->globals[i]);
5597         switch (value->expression.vtype) {
5598             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5599             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5600             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5601             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5602             default:
5603                 crc = progdefs_crc_both(crc, "\tint\t");
5604                 break;
5605         }
5606         crc = progdefs_crc_both(crc, value->name);
5607         crc = progdefs_crc_both(crc, ";\n");
5608     }
5609     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5610     for (i = 0; i < parser->crc_fields; ++i) {
5611         if (!ast_istype(parser->fields[i], ast_value))
5612             continue;
5613         value = (ast_value*)(parser->fields[i]);
5614         switch (value->expression.next->expression.vtype) {
5615             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5616             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5617             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5618             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5619             default:
5620                 crc = progdefs_crc_both(crc, "\tint\t");
5621                 break;
5622         }
5623         crc = progdefs_crc_both(crc, value->name);
5624         crc = progdefs_crc_both(crc, ";\n");
5625     }
5626     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5627
5628     code_crc = crc;
5629 }
5630
5631 static parser_t *parser;
5632
5633 bool parser_init()
5634 {
5635     lex_ctx empty_ctx;
5636     size_t i;
5637
5638     parser = (parser_t*)mem_a(sizeof(parser_t));
5639     if (!parser)
5640         return false;
5641
5642     memset(parser, 0, sizeof(*parser));
5643
5644     for (i = 0; i < operator_count; ++i) {
5645         if (operators[i].id == opid1('=')) {
5646             parser->assign_op = operators+i;
5647             break;
5648         }
5649     }
5650     if (!parser->assign_op) {
5651         printf("internal error: initializing parser: failed to find assign operator\n");
5652         mem_d(parser);
5653         return false;
5654     }
5655
5656     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5657     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5658     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5659     vec_push(parser->_blocktypedefs, 0);
5660
5661     /* corrector */
5662     vec_push(parser->correct_variables, correct_trie_new());
5663     vec_push(parser->correct_variables_score, NULL);
5664
5665     empty_ctx.file = "<internal>";
5666     empty_ctx.line = 0;
5667     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5668     parser->nil->cvq = CV_CONST;
5669     if (OPTS_FLAG(UNTYPED_NIL))
5670         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5671
5672     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5673     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5674     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5675
5676     if (opts.add_info) {
5677         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5678         parser->reserved_version->cvq = CV_CONST;
5679         parser->reserved_version->hasvalue = true;
5680         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5681         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5682     } else {
5683         parser->reserved_version = NULL;
5684     }
5685     return true;
5686 }
5687
5688 bool parser_compile()
5689 {
5690     /* initial lexer/parser state */
5691     parser->lex->flags.noops = true;
5692
5693     if (parser_next(parser))
5694     {
5695         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5696         {
5697             if (!parser_global_statement(parser)) {
5698                 if (parser->tok == TOKEN_EOF)
5699                     parseerror(parser, "unexpected eof");
5700                 else if (compile_errors)
5701                     parseerror(parser, "there have been errors, bailing out");
5702                 lex_close(parser->lex);
5703                 parser->lex = NULL;
5704                 return false;
5705             }
5706         }
5707     } else {
5708         parseerror(parser, "parse error");
5709         lex_close(parser->lex);
5710         parser->lex = NULL;
5711         return false;
5712     }
5713
5714     lex_close(parser->lex);
5715     parser->lex = NULL;
5716
5717     return !compile_errors;
5718 }
5719
5720 bool parser_compile_file(const char *filename)
5721 {
5722     parser->lex = lex_open(filename);
5723     if (!parser->lex) {
5724         con_err("failed to open file \"%s\"\n", filename);
5725         return false;
5726     }
5727     return parser_compile();
5728 }
5729
5730 bool parser_compile_string(const char *name, const char *str, size_t len)
5731 {
5732     parser->lex = lex_open_string(str, len, name);
5733     if (!parser->lex) {
5734         con_err("failed to create lexer for string \"%s\"\n", name);
5735         return false;
5736     }
5737     return parser_compile();
5738 }
5739
5740 void parser_cleanup()
5741 {
5742     size_t i;
5743     for (i = 0; i < vec_size(parser->accessors); ++i) {
5744         ast_delete(parser->accessors[i]->constval.vfunc);
5745         parser->accessors[i]->constval.vfunc = NULL;
5746         ast_delete(parser->accessors[i]);
5747     }
5748     for (i = 0; i < vec_size(parser->functions); ++i) {
5749         ast_delete(parser->functions[i]);
5750     }
5751     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5752         ast_delete(parser->imm_vector[i]);
5753     }
5754     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5755         ast_delete(parser->imm_string[i]);
5756     }
5757     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5758         ast_delete(parser->imm_float[i]);
5759     }
5760     for (i = 0; i < vec_size(parser->fields); ++i) {
5761         ast_delete(parser->fields[i]);
5762     }
5763     for (i = 0; i < vec_size(parser->globals); ++i) {
5764         ast_delete(parser->globals[i]);
5765     }
5766     vec_free(parser->accessors);
5767     vec_free(parser->functions);
5768     vec_free(parser->imm_vector);
5769     vec_free(parser->imm_string);
5770     vec_free(parser->imm_float);
5771     vec_free(parser->globals);
5772     vec_free(parser->fields);
5773
5774     for (i = 0; i < vec_size(parser->variables); ++i)
5775         util_htdel(parser->variables[i]);
5776     vec_free(parser->variables);
5777     vec_free(parser->_blocklocals);
5778     vec_free(parser->_locals);
5779
5780     /* corrector */
5781     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5782         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5783     }
5784     vec_free(parser->correct_variables);
5785     vec_free(parser->correct_variables_score);
5786
5787
5788     for (i = 0; i < vec_size(parser->_typedefs); ++i)
5789         ast_delete(parser->_typedefs[i]);
5790     vec_free(parser->_typedefs);
5791     for (i = 0; i < vec_size(parser->typedefs); ++i)
5792         util_htdel(parser->typedefs[i]);
5793     vec_free(parser->typedefs);
5794     vec_free(parser->_blocktypedefs);
5795
5796     vec_free(parser->_block_ctx);
5797
5798     vec_free(parser->labels);
5799     vec_free(parser->gotos);
5800     vec_free(parser->breaks);
5801     vec_free(parser->continues);
5802
5803     ast_value_delete(parser->nil);
5804
5805     ast_value_delete(parser->const_vec[0]);
5806     ast_value_delete(parser->const_vec[1]);
5807     ast_value_delete(parser->const_vec[2]);
5808
5809     mem_d(parser);
5810 }
5811
5812 bool parser_finish(const char *output)
5813 {
5814     size_t i;
5815     ir_builder *ir;
5816     bool retval = true;
5817
5818     if (compile_errors) {
5819         con_out("*** there were compile errors\n");
5820         return false;
5821     }
5822
5823     ir = ir_builder_new("gmqcc_out");
5824     if (!ir) {
5825         con_out("failed to allocate builder\n");
5826         return false;
5827     }
5828
5829     for (i = 0; i < vec_size(parser->fields); ++i) {
5830         ast_value *field;
5831         bool hasvalue;
5832         if (!ast_istype(parser->fields[i], ast_value))
5833             continue;
5834         field = (ast_value*)parser->fields[i];
5835         hasvalue = field->hasvalue;
5836         field->hasvalue = false;
5837         if (!ast_global_codegen((ast_value*)field, ir, true)) {
5838             con_out("failed to generate field %s\n", field->name);
5839             ir_builder_delete(ir);
5840             return false;
5841         }
5842         if (hasvalue) {
5843             ir_value *ifld;
5844             ast_expression *subtype;
5845             field->hasvalue = true;
5846             subtype = field->expression.next;
5847             ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5848             if (subtype->expression.vtype == TYPE_FIELD)
5849                 ifld->fieldtype = subtype->expression.next->expression.vtype;
5850             else if (subtype->expression.vtype == TYPE_FUNCTION)
5851                 ifld->outtype = subtype->expression.next->expression.vtype;
5852             (void)!ir_value_set_field(field->ir_v, ifld);
5853         }
5854     }
5855     for (i = 0; i < vec_size(parser->globals); ++i) {
5856         ast_value *asvalue;
5857         if (!ast_istype(parser->globals[i], ast_value))
5858             continue;
5859         asvalue = (ast_value*)(parser->globals[i]);
5860         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5861             retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5862                                            "unused global: `%s`", asvalue->name);
5863         }
5864         if (!ast_global_codegen(asvalue, ir, false)) {
5865             con_out("failed to generate global %s\n", asvalue->name);
5866             ir_builder_delete(ir);
5867             return false;
5868         }
5869     }
5870     /* Build function vararg accessor ast tree now before generating
5871      * immediates, because the accessors may add new immediates
5872      */
5873     for (i = 0; i < vec_size(parser->functions); ++i) {
5874         ast_function *f = parser->functions[i];
5875         if (f->varargs) {
5876             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
5877                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
5878                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
5879                     con_out("failed to generate vararg setter for %s\n", f->name);
5880                     ir_builder_delete(ir);
5881                     return false;
5882                 }
5883                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
5884                     con_out("failed to generate vararg getter for %s\n", f->name);
5885                     ir_builder_delete(ir);
5886                     return false;
5887                 }
5888             } else {
5889                 ast_delete(f->varargs);
5890                 f->varargs = NULL;
5891             }
5892         }
5893     }
5894     /* Now we can generate immediates */
5895     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5896         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5897             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5898             ir_builder_delete(ir);
5899             return false;
5900         }
5901     }
5902     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5903         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5904             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5905             ir_builder_delete(ir);
5906             return false;
5907         }
5908     }
5909     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5910         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5911             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5912             ir_builder_delete(ir);
5913             return false;
5914         }
5915     }
5916     for (i = 0; i < vec_size(parser->globals); ++i) {
5917         ast_value *asvalue;
5918         if (!ast_istype(parser->globals[i], ast_value))
5919             continue;
5920         asvalue = (ast_value*)(parser->globals[i]);
5921         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5922         {
5923             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5924                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5925                                        "uninitialized constant: `%s`",
5926                                        asvalue->name);
5927             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5928                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5929                                        "uninitialized global: `%s`",
5930                                        asvalue->name);
5931         }
5932         if (!ast_generate_accessors(asvalue, ir)) {
5933             ir_builder_delete(ir);
5934             return false;
5935         }
5936     }
5937     for (i = 0; i < vec_size(parser->fields); ++i) {
5938         ast_value *asvalue;
5939         asvalue = (ast_value*)(parser->fields[i]->expression.next);
5940
5941         if (!ast_istype((ast_expression*)asvalue, ast_value))
5942             continue;
5943         if (asvalue->expression.vtype != TYPE_ARRAY)
5944             continue;
5945         if (!ast_generate_accessors(asvalue, ir)) {
5946             ir_builder_delete(ir);
5947             return false;
5948         }
5949     }
5950     if (parser->reserved_version &&
5951         !ast_global_codegen(parser->reserved_version, ir, false))
5952     {
5953         con_out("failed to generate reserved::version");
5954         ir_builder_delete(ir);
5955         return false;
5956     }
5957     for (i = 0; i < vec_size(parser->functions); ++i) {
5958         ast_function *f = parser->functions[i];
5959         if (!ast_function_codegen(f, ir)) {
5960             con_out("failed to generate function %s\n", f->name);
5961             ir_builder_delete(ir);
5962             return false;
5963         }
5964     }
5965     if (opts.dump)
5966         ir_builder_dump(ir, con_out);
5967     for (i = 0; i < vec_size(parser->functions); ++i) {
5968         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5969             con_out("failed to finalize function %s\n", parser->functions[i]->name);
5970             ir_builder_delete(ir);
5971             return false;
5972         }
5973     }
5974
5975     if (compile_Werrors) {
5976         con_out("*** there were warnings treated as errors\n");
5977         compile_show_werrors();
5978         retval = false;
5979     }
5980
5981     if (retval) {
5982         if (opts.dumpfin)
5983             ir_builder_dump(ir, con_out);
5984
5985         generate_checksum(parser);
5986
5987         if (!ir_builder_generate(ir, output)) {
5988             con_out("*** failed to generate output file\n");
5989             ir_builder_delete(ir);
5990             return false;
5991         }
5992     }
5993
5994     ir_builder_delete(ir);
5995     return retval;
5996 }