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