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