]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
-Wternary-precedence; *sight* this is tough
[xonotic/gmqcc.git] / parser.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdio.h>
24 #include <stdarg.h>
25
26 #include "gmqcc.h"
27 #include "lexer.h"
28
29 #define PARSER_HT_FIELDS  0
30 #define PARSER_HT_GLOBALS 1
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 typedef struct {
38     lex_file *lex;
39     int      tok;
40
41     ast_expression **globals;
42     ast_expression **fields;
43     ast_function **functions;
44     ast_value    **imm_float;
45     ast_value    **imm_string;
46     ast_value    **imm_vector;
47     size_t         translated;
48
49     /* must be deleted first, they reference immediates and values */
50     ast_value    **accessors;
51
52     ast_value *imm_float_zero;
53     ast_value *imm_float_one;
54     ast_value *imm_vector_zero;
55
56     size_t crc_globals;
57     size_t crc_fields;
58
59     ast_function *function;
60
61     /* All the labels the function defined...
62      * Should they be in ast_function instead?
63      */
64     ast_label **labels;
65     ast_goto  **gotos;
66
67     /* A list of hashtables for each scope */
68     ht *variables;
69     ht htfields;
70     ht htglobals;
71     ht *typedefs;
72
73     /* not to be used directly, we use the hash table */
74     ast_expression **_locals;
75     size_t          *_blocklocals;
76     ast_value      **_typedefs;
77     size_t          *_blocktypedefs;
78     lex_ctx         *_block_ctx;
79
80     size_t errors;
81
82     /* we store the '=' operator info */
83     const oper_info *assign_op;
84
85     /* TYPE_FIELD -> parser_find_fields is used instead of find_var
86      * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
87      * anything else: type error
88      */
89     qcint  memberof;
90
91     /* Keep track of our ternary vs parenthesis nesting state.
92      * If we reach a 'comma' operator in a ternary without a paren,
93      * we shall trigger -Wternary-precedence.
94      */
95     enum { POT_PAREN, POT_TERNARY1, POT_TERNARY2 } *pot;
96 } parser_t;
97
98 static void parser_enterblock(parser_t *parser);
99 static bool parser_leaveblock(parser_t *parser);
100 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
101 static bool parse_typedef(parser_t *parser);
102 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef);
103 static ast_block* parse_block(parser_t *parser);
104 static bool parse_block_into(parser_t *parser, ast_block *block);
105 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
106 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
107 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
108 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
109
110 static void parseerror(parser_t *parser, const char *fmt, ...)
111 {
112         va_list ap;
113
114         parser->errors++;
115
116         va_start(ap, fmt);
117     con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
118         va_end(ap);
119 }
120
121 /* returns true if it counts as an error */
122 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
123 {
124         va_list ap;
125         int lvl = LVL_WARNING;
126
127     if (!OPTS_WARN(warntype))
128         return false;
129
130     if (opts_werror) {
131             parser->errors++;
132             lvl = LVL_ERROR;
133         }
134
135         va_start(ap, fmt);
136     con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
137         va_end(ap);
138
139         return opts_werror;
140 }
141
142 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
143 {
144         va_list ap;
145         int lvl = LVL_WARNING;
146
147     if (!OPTS_WARN(warntype))
148         return false;
149
150     if (opts_werror)
151             lvl = LVL_ERROR;
152
153         va_start(ap, fmt);
154     con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
155         va_end(ap);
156
157         return opts_werror;
158 }
159
160 /**********************************************************************
161  * some maths used for constant folding
162  */
163
164 vector vec3_add(vector a, vector b)
165 {
166     vector out;
167     out.x = a.x + b.x;
168     out.y = a.y + b.y;
169     out.z = a.z + b.z;
170     return out;
171 }
172
173 vector vec3_sub(vector a, vector b)
174 {
175     vector out;
176     out.x = a.x - b.x;
177     out.y = a.y - b.y;
178     out.z = a.z - b.z;
179     return out;
180 }
181
182 qcfloat vec3_mulvv(vector a, vector b)
183 {
184     return (a.x * b.x + a.y * b.y + a.z * b.z);
185 }
186
187 vector vec3_mulvf(vector a, float b)
188 {
189     vector out;
190     out.x = a.x * b;
191     out.y = a.y * b;
192     out.z = a.z * b;
193     return out;
194 }
195
196 /**********************************************************************
197  * parsing
198  */
199
200 bool parser_next(parser_t *parser)
201 {
202     /* lex_do kills the previous token */
203     parser->tok = lex_do(parser->lex);
204     if (parser->tok == TOKEN_EOF)
205         return true;
206     if (parser->tok >= TOKEN_ERROR) {
207         parseerror(parser, "lex error");
208         return false;
209     }
210     return true;
211 }
212
213 #define parser_tokval(p) ((p)->lex->tok.value)
214 #define parser_token(p)  (&((p)->lex->tok))
215 #define parser_ctx(p)    ((p)->lex->tok.ctx)
216
217 static ast_value* parser_const_float(parser_t *parser, double d)
218 {
219     size_t i;
220     ast_value *out;
221     for (i = 0; i < vec_size(parser->imm_float); ++i) {
222         const double compare = parser->imm_float[i]->constval.vfloat;
223         if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
224             return parser->imm_float[i];
225     }
226     out = ast_value_new(parser_ctx(parser), "#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 = 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 util_htget(parser->htfields, name);
315 }
316
317 static ast_expression* parser_find_global(parser_t *parser, const char *name)
318 {
319     return util_htget(parser->htglobals, name);
320 }
321
322 static ast_expression* parser_find_param(parser_t *parser, const char *name)
323 {
324     size_t i;
325     ast_value *fun;
326     if (!parser->function)
327         return NULL;
328     fun = parser->function->vtype;
329     for (i = 0; i < vec_size(fun->expression.params); ++i) {
330         if (!strcmp(fun->expression.params[i]->name, name))
331             return (ast_expression*)(fun->expression.params[i]);
332     }
333     return NULL;
334 }
335
336 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
337 {
338     size_t          i, hash;
339     ast_expression *e;
340
341     hash = util_hthash(parser->htglobals, name);
342
343     *isparam = false;
344     for (i = vec_size(parser->variables); i > upto;) {
345         --i;
346         if ( (e = util_htgeth(parser->variables[i], name, hash)) )
347             return e;
348     }
349     *isparam = true;
350     return parser_find_param(parser, name);
351 }
352
353 static ast_expression* parser_find_var(parser_t *parser, const char *name)
354 {
355     bool dummy;
356     ast_expression *v;
357     v         = parser_find_local(parser, name, 0, &dummy);
358     if (!v) v = parser_find_global(parser, name);
359     return v;
360 }
361
362 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
363 {
364     size_t     i, hash;
365     ast_value *e;
366     hash = util_hthash(parser->typedefs[0], name);
367
368     for (i = vec_size(parser->typedefs); i > upto;) {
369         --i;
370         if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
371             return e;
372     }
373     return NULL;
374 }
375
376 typedef struct
377 {
378     size_t etype; /* 0 = expression, others are operators */
379     int             paren;
380     size_t          off;
381     ast_expression *out;
382     ast_block      *block; /* for commas and function calls */
383     lex_ctx ctx;
384 } sy_elem;
385 typedef struct
386 {
387     sy_elem *out;
388     sy_elem *ops;
389 } shunt;
390
391 #define SY_PAREN_EXPR '('
392 #define SY_PAREN_FUNC 'f'
393 #define SY_PAREN_INDEX '['
394 #define SY_PAREN_TERNARY '?'
395
396 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
397     sy_elem e;
398     e.etype = 0;
399     e.off   = 0;
400     e.out   = v;
401     e.block = NULL;
402     e.ctx   = ctx;
403     e.paren = 0;
404     return e;
405 }
406
407 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
408     sy_elem e;
409     e.etype = 0;
410     e.off   = 0;
411     e.out   = (ast_expression*)v;
412     e.block = v;
413     e.ctx   = ctx;
414     e.paren = 0;
415     return e;
416 }
417
418 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
419     sy_elem e;
420     e.etype = 1 + (op - operators);
421     e.off   = 0;
422     e.out   = NULL;
423     e.block = NULL;
424     e.ctx   = ctx;
425     e.paren = 0;
426     return e;
427 }
428
429 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
430     sy_elem e;
431     e.etype = 0;
432     e.off   = off;
433     e.out   = NULL;
434     e.block = NULL;
435     e.ctx   = ctx;
436     e.paren = p;
437     return e;
438 }
439
440 #ifdef DEBUGSHUNT
441 # define DEBUGSHUNTDO(x) x
442 #else
443 # define DEBUGSHUNTDO(x)
444 #endif
445
446 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
447  * so we need to rotate it to become ent.(foo[n]).
448  */
449 static bool rotate_entfield_array_index_nodes(ast_expression **out)
450 {
451     ast_array_index *index;
452     ast_entfield    *entfield;
453
454     ast_value       *field;
455     ast_expression  *sub;
456     ast_expression  *entity;
457
458     lex_ctx ctx = ast_ctx(*out);
459
460     if (!ast_istype(*out, ast_array_index))
461         return false;
462     index = (ast_array_index*)*out;
463
464     if (!ast_istype(index->array, ast_entfield))
465         return false;
466     entfield = (ast_entfield*)index->array;
467
468     if (!ast_istype(entfield->field, ast_value))
469         return false;
470     field = (ast_value*)entfield->field;
471
472     sub    = index->index;
473     entity = entfield->entity;
474
475     ast_delete(index);
476
477     index = ast_array_index_new(ctx, (ast_expression*)field, sub);
478     entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
479     *out = (ast_expression*)entfield;
480
481     return true;
482 }
483
484 static bool parser_sy_pop(parser_t *parser, shunt *sy)
485 {
486     const oper_info *op;
487     lex_ctx ctx;
488     ast_expression *out = NULL;
489     ast_expression *exprs[3];
490     ast_block      *blocks[3];
491     ast_value      *asvalue[3];
492     ast_binstore   *asbinstore;
493     size_t i, assignop, addop, subop;
494     qcint  generated_op = 0;
495
496     char ty1[1024];
497     char ty2[1024];
498
499     if (!vec_size(sy->ops)) {
500         parseerror(parser, "internal error: missing operator");
501         return false;
502     }
503
504     if (vec_last(sy->ops).paren) {
505         parseerror(parser, "unmatched parenthesis");
506         return false;
507     }
508
509     op = &operators[vec_last(sy->ops).etype - 1];
510     ctx = vec_last(sy->ops).ctx;
511
512     DEBUGSHUNTDO(con_out("apply %s\n", op->op));
513
514     if (vec_size(sy->out) < op->operands) {
515         parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
516                    op->op, (int)op->id);
517         return false;
518     }
519
520     vec_shrinkby(sy->ops, 1);
521
522     /* op(:?) has no input and no output */
523     if (!op->operands)
524         return true;
525
526     vec_shrinkby(sy->out, op->operands);
527     for (i = 0; i < op->operands; ++i) {
528         exprs[i]  = sy->out[vec_size(sy->out)+i].out;
529         blocks[i] = sy->out[vec_size(sy->out)+i].block;
530         asvalue[i] = (ast_value*)exprs[i];
531     }
532
533     if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
534         parseerror(parser, "internal error: operator cannot be applied on empty blocks");
535         return false;
536     }
537
538 #define NotSameType(T) \
539              (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
540               exprs[0]->expression.vtype != T)
541 #define CanConstFold1(A) \
542              (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST))
543 #define CanConstFold(A, B) \
544              (CanConstFold1(A) && CanConstFold1(B))
545 #define ConstV(i) (asvalue[(i)]->constval.vvec)
546 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
547 #define ConstS(i) (asvalue[(i)]->constval.vstring)
548     switch (op->id)
549     {
550         default:
551             parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
552             return false;
553
554         case opid1('.'):
555             if (exprs[0]->expression.vtype == TYPE_ENTITY) {
556                 if (exprs[1]->expression.vtype != TYPE_FIELD) {
557                     parseerror(parser, "type error: right hand of member-operand should be an entity-field");
558                     return false;
559                 }
560                 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
561             }
562             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
563                 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
564                 return false;
565             }
566             else {
567                 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
568                 return false;
569             }
570             break;
571
572         case opid1('['):
573             if (exprs[0]->expression.vtype != TYPE_ARRAY &&
574                 !(exprs[0]->expression.vtype == TYPE_FIELD &&
575                   exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
576             {
577                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
578                 parseerror(parser, "cannot index value of type %s", ty1);
579                 return false;
580             }
581             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
582                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
583                 parseerror(parser, "index must be of type float, not %s", ty1);
584                 return false;
585             }
586             out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
587             if (rotate_entfield_array_index_nodes(&out))
588             {
589 #if 0
590                 /* This is not broken in fteqcc anymore */
591                 if (opts_standard != COMPILER_GMQCC) {
592                     /* this error doesn't need to make us bail out */
593                     (void)!parsewarning(parser, WARN_EXTENSIONS,
594                                         "accessing array-field members of an entity without parenthesis\n"
595                                         " -> this is an extension from -std=gmqcc");
596                 }
597 #endif
598             }
599             break;
600
601         case opid1(','):
602             if (blocks[0]) {
603                 ast_block_add_expr(blocks[0], exprs[1]);
604             } else {
605                 blocks[0] = ast_block_new(ctx);
606                 ast_block_add_expr(blocks[0], exprs[0]);
607                 ast_block_add_expr(blocks[0], exprs[1]);
608             }
609             if (!ast_block_set_type(blocks[0], exprs[1]))
610                 return false;
611
612             vec_push(sy->out, syblock(ctx, blocks[0]));
613             return true;
614
615         case opid2('+','P'):
616             out = exprs[0];
617             break;
618         case opid2('-','P'):
619             switch (exprs[0]->expression.vtype) {
620                 case TYPE_FLOAT:
621                     if (CanConstFold1(exprs[0]))
622                         out = (ast_expression*)parser_const_float(parser, -ConstF(0));
623                     else
624                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
625                                                               (ast_expression*)parser_const_float_0(parser),
626                                                               exprs[0]);
627                     break;
628                 case TYPE_VECTOR:
629                     if (CanConstFold1(exprs[0]))
630                         out = (ast_expression*)parser_const_vector_f(parser,
631                             -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
632                     else
633                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
634                                                               (ast_expression*)parser_const_vector_0(parser),
635                                                               exprs[0]);
636                     break;
637                 default:
638                 parseerror(parser, "invalid types used in expression: cannot negate type %s",
639                            type_name[exprs[0]->expression.vtype]);
640                 return false;
641             }
642             break;
643
644         case opid2('!','P'):
645             switch (exprs[0]->expression.vtype) {
646                 case TYPE_FLOAT:
647                     if (CanConstFold1(exprs[0]))
648                         out = (ast_expression*)parser_const_float(parser, !ConstF(0));
649                     else
650                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
651                     break;
652                 case TYPE_VECTOR:
653                     if (CanConstFold1(exprs[0]))
654                         out = (ast_expression*)parser_const_float(parser,
655                             (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
656                     else
657                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
658                     break;
659                 case TYPE_STRING:
660                     if (CanConstFold1(exprs[0]))
661                         out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
662                     else
663                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
664                     break;
665                 /* we don't constant-fold NOT for these types */
666                 case TYPE_ENTITY:
667                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
668                     break;
669                 case TYPE_FUNCTION:
670                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
671                     break;
672                 default:
673                 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
674                            type_name[exprs[0]->expression.vtype]);
675                 return false;
676             }
677             break;
678
679         case opid1('+'):
680             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
681                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
682             {
683                 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
684                            type_name[exprs[0]->expression.vtype],
685                            type_name[exprs[1]->expression.vtype]);
686                 return false;
687             }
688             switch (exprs[0]->expression.vtype) {
689                 case TYPE_FLOAT:
690                     if (CanConstFold(exprs[0], exprs[1]))
691                     {
692                         out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
693                     }
694                     else
695                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
696                     break;
697                 case TYPE_VECTOR:
698                     if (CanConstFold(exprs[0], exprs[1]))
699                         out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
700                     else
701                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
702                     break;
703                 default:
704                     parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
705                                type_name[exprs[0]->expression.vtype],
706                                type_name[exprs[1]->expression.vtype]);
707                     return false;
708             };
709             break;
710         case opid1('-'):
711             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
712                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
713             {
714                 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
715                            type_name[exprs[1]->expression.vtype],
716                            type_name[exprs[0]->expression.vtype]);
717                 return false;
718             }
719             switch (exprs[0]->expression.vtype) {
720                 case TYPE_FLOAT:
721                     if (CanConstFold(exprs[0], exprs[1]))
722                         out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
723                     else
724                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
725                     break;
726                 case TYPE_VECTOR:
727                     if (CanConstFold(exprs[0], exprs[1]))
728                         out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
729                     else
730                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
731                     break;
732                 default:
733                     parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
734                                type_name[exprs[1]->expression.vtype],
735                                type_name[exprs[0]->expression.vtype]);
736                     return false;
737             };
738             break;
739         case opid1('*'):
740             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
741                 exprs[0]->expression.vtype != TYPE_VECTOR &&
742                 exprs[0]->expression.vtype != TYPE_FLOAT &&
743                 exprs[1]->expression.vtype != TYPE_VECTOR &&
744                 exprs[1]->expression.vtype != TYPE_FLOAT)
745             {
746                 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
747                            type_name[exprs[1]->expression.vtype],
748                            type_name[exprs[0]->expression.vtype]);
749                 return false;
750             }
751             switch (exprs[0]->expression.vtype) {
752                 case TYPE_FLOAT:
753                     if (exprs[1]->expression.vtype == TYPE_VECTOR)
754                     {
755                         if (CanConstFold(exprs[0], exprs[1]))
756                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
757                         else
758                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
759                     }
760                     else
761                     {
762                         if (CanConstFold(exprs[0], exprs[1]))
763                             out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
764                         else
765                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
766                     }
767                     break;
768                 case TYPE_VECTOR:
769                     if (exprs[1]->expression.vtype == TYPE_FLOAT)
770                     {
771                         if (CanConstFold(exprs[0], exprs[1]))
772                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
773                         else
774                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
775                     }
776                     else
777                     {
778                         if (CanConstFold(exprs[0], exprs[1]))
779                             out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
780                         else
781                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
782                     }
783                     break;
784                 default:
785                     parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
786                                type_name[exprs[1]->expression.vtype],
787                                type_name[exprs[0]->expression.vtype]);
788                     return false;
789             };
790             break;
791         case opid1('/'):
792             if (NotSameType(TYPE_FLOAT)) {
793                 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
794                            type_name[exprs[0]->expression.vtype],
795                            type_name[exprs[1]->expression.vtype]);
796                 return false;
797             }
798             if (CanConstFold(exprs[0], exprs[1]))
799                 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
800             else
801                 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
802             break;
803         case opid1('%'):
804         case opid2('%','='):
805             parseerror(parser, "qc does not have a modulo operator");
806             return false;
807         case opid1('|'):
808         case opid1('&'):
809             if (NotSameType(TYPE_FLOAT)) {
810                 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
811                            type_name[exprs[0]->expression.vtype],
812                            type_name[exprs[1]->expression.vtype]);
813                 return false;
814             }
815             if (CanConstFold(exprs[0], exprs[1]))
816                 out = (ast_expression*)parser_const_float(parser,
817                     (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
818                                             (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
819             else
820                 out = (ast_expression*)ast_binary_new(ctx,
821                     (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
822                     exprs[0], exprs[1]);
823             break;
824         case opid1('^'):
825             parseerror(parser, "TODO: bitxor");
826             return false;
827
828         case opid2('<','<'):
829         case opid2('>','>'):
830         case opid3('<','<','='):
831         case opid3('>','>','='):
832             parseerror(parser, "TODO: shifts");
833             return false;
834
835         case opid2('|','|'):
836             generated_op += 1; /* INSTR_OR */
837         case opid2('&','&'):
838             generated_op += INSTR_AND;
839 #if 0
840             if (NotSameType(TYPE_FLOAT)) {
841                 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
842                            type_name[exprs[0]->expression.vtype],
843                            type_name[exprs[1]->expression.vtype]);
844                 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
845                 parseerror(parser, "TODO: optional early out");
846                 return false;
847             }
848 #endif
849             if (opts_standard == COMPILER_GMQCC)
850                 con_out("TODO: early out logic\n");
851             if (CanConstFold(exprs[0], exprs[1]))
852                 out = (ast_expression*)parser_const_float(parser,
853                     (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
854             else
855                 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
856             break;
857
858         case opid2('?',':'):
859             if (vec_last(parser->pot) != POT_TERNARY2) {
860                 parseerror(parser, "mismatched parenthesis/ternary");
861                 return false;
862             }
863             vec_pop(parser->pot);
864             if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
865                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
866                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
867                 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
868                 return false;
869             }
870             if (CanConstFold1(exprs[0]))
871                 out = (ConstF(0) ? exprs[1] : exprs[2]);
872             else
873                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
874             break;
875
876         case opid1('>'):
877             generated_op += 1; /* INSTR_GT */
878         case opid1('<'):
879             generated_op += 1; /* INSTR_LT */
880         case opid2('>', '='):
881             generated_op += 1; /* INSTR_GE */
882         case opid2('<', '='):
883             generated_op += INSTR_LE;
884             if (NotSameType(TYPE_FLOAT)) {
885                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
886                            type_name[exprs[0]->expression.vtype],
887                            type_name[exprs[1]->expression.vtype]);
888                 return false;
889             }
890             out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
891             break;
892         case opid2('!', '='):
893             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
894                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
895                            type_name[exprs[0]->expression.vtype],
896                            type_name[exprs[1]->expression.vtype]);
897                 return false;
898             }
899             out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
900             break;
901         case opid2('=', '='):
902             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
903                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
904                            type_name[exprs[0]->expression.vtype],
905                            type_name[exprs[1]->expression.vtype]);
906                 return false;
907             }
908             out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
909             break;
910
911         case opid1('='):
912             if (ast_istype(exprs[0], ast_entfield)) {
913                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
914                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
915                     exprs[0]->expression.vtype == TYPE_FIELD &&
916                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
917                 {
918                     assignop = type_storep_instr[TYPE_VECTOR];
919                 }
920                 else
921                     assignop = type_storep_instr[exprs[0]->expression.vtype];
922                 if (!ast_compare_type(field->expression.next, exprs[1])) {
923                     ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
924                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
925                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
926                         field->expression.next->expression.vtype == TYPE_FUNCTION &&
927                         exprs[1]->expression.vtype == TYPE_FUNCTION)
928                     {
929                         if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
930                                          "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
931                         {
932                             parser->errors++;
933                         }
934                     }
935                     else
936                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
937                 }
938             }
939             else
940             {
941                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
942                     exprs[0]->expression.vtype == TYPE_FIELD &&
943                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
944                 {
945                     assignop = type_store_instr[TYPE_VECTOR];
946                 }
947                 else {
948                     assignop = type_store_instr[exprs[0]->expression.vtype];
949                 }
950
951                 if (assignop == AINSTR_END) {
952                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
953                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
954                     parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
955                 }
956                 else if (!ast_compare_type(exprs[0], exprs[1])) {
957                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
958                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
959                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
960                         exprs[0]->expression.vtype == TYPE_FUNCTION &&
961                         exprs[1]->expression.vtype == TYPE_FUNCTION)
962                     {
963                         if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
964                                          "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
965                         {
966                             parser->errors++;
967                         }
968                     }
969                     else
970                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
971                 }
972             }
973             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
974                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
975             }
976             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
977             break;
978         case opid3('+','+','P'):
979         case opid3('-','-','P'):
980             /* prefix ++ */
981             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
982                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
983                 parseerror(parser, "invalid type for prefix increment: %s", ty1);
984                 return false;
985             }
986             if (op->id == opid3('+','+','P'))
987                 addop = INSTR_ADD_F;
988             else
989                 addop = INSTR_SUB_F;
990             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
991                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
992             }
993             if (ast_istype(exprs[0], ast_entfield)) {
994                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
995                                                         exprs[0],
996                                                         (ast_expression*)parser_const_float_1(parser));
997             } else {
998                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
999                                                         exprs[0],
1000                                                         (ast_expression*)parser_const_float_1(parser));
1001             }
1002             break;
1003         case opid3('S','+','+'):
1004         case opid3('S','-','-'):
1005             /* prefix ++ */
1006             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1007                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1008                 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1009                 return false;
1010             }
1011             if (op->id == opid3('S','+','+')) {
1012                 addop = INSTR_ADD_F;
1013                 subop = INSTR_SUB_F;
1014             } else {
1015                 addop = INSTR_SUB_F;
1016                 subop = INSTR_ADD_F;
1017             }
1018             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1019                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1020             }
1021             if (ast_istype(exprs[0], ast_entfield)) {
1022                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1023                                                         exprs[0],
1024                                                         (ast_expression*)parser_const_float_1(parser));
1025             } else {
1026                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1027                                                         exprs[0],
1028                                                         (ast_expression*)parser_const_float_1(parser));
1029             }
1030             if (!out)
1031                 return false;
1032             out = (ast_expression*)ast_binary_new(ctx, subop,
1033                                                   out,
1034                                                   (ast_expression*)parser_const_float_1(parser));
1035             break;
1036         case opid2('+','='):
1037         case opid2('-','='):
1038             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1039                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1040             {
1041                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1042                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1043                 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1044                            ty1, ty2);
1045                 return false;
1046             }
1047             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1048                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1049             }
1050             if (ast_istype(exprs[0], ast_entfield))
1051                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1052             else
1053                 assignop = type_store_instr[exprs[0]->expression.vtype];
1054             switch (exprs[0]->expression.vtype) {
1055                 case TYPE_FLOAT:
1056                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1057                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1058                                                             exprs[0], exprs[1]);
1059                     break;
1060                 case TYPE_VECTOR:
1061                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1062                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1063                                                             exprs[0], exprs[1]);
1064                     break;
1065                 default:
1066                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1067                                type_name[exprs[0]->expression.vtype],
1068                                type_name[exprs[1]->expression.vtype]);
1069                     return false;
1070             };
1071             break;
1072         case opid2('*','='):
1073         case opid2('/','='):
1074             if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1075                 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1076                   exprs[0]->expression.vtype == TYPE_VECTOR))
1077             {
1078                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1079                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1080                 parseerror(parser, "invalid types used in expression: %s and %s",
1081                            ty1, ty2);
1082                 return false;
1083             }
1084             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1085                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1086             }
1087             if (ast_istype(exprs[0], ast_entfield))
1088                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1089             else
1090                 assignop = type_store_instr[exprs[0]->expression.vtype];
1091             switch (exprs[0]->expression.vtype) {
1092                 case TYPE_FLOAT:
1093                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1094                                                             (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1095                                                             exprs[0], exprs[1]);
1096                     break;
1097                 case TYPE_VECTOR:
1098                     if (op->id == opid2('*','=')) {
1099                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1100                                                                 exprs[0], exprs[1]);
1101                     } else {
1102                         /* there's no DIV_VF */
1103                         out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1104                                                               (ast_expression*)parser_const_float_1(parser),
1105                                                               exprs[1]);
1106                         if (!out)
1107                             return false;
1108                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1109                                                                 exprs[0], out);
1110                     }
1111                     break;
1112                 default:
1113                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1114                                type_name[exprs[0]->expression.vtype],
1115                                type_name[exprs[1]->expression.vtype]);
1116                     return false;
1117             };
1118             break;
1119         case opid2('&','='):
1120         case opid2('|','='):
1121             if (NotSameType(TYPE_FLOAT)) {
1122                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1123                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1124                 parseerror(parser, "invalid types used in expression: %s and %s",
1125                            ty1, ty2);
1126                 return false;
1127             }
1128             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1129                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1130             }
1131             if (ast_istype(exprs[0], ast_entfield))
1132                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1133             else
1134                 assignop = type_store_instr[exprs[0]->expression.vtype];
1135             out = (ast_expression*)ast_binstore_new(ctx, assignop,
1136                                                     (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1137                                                     exprs[0], exprs[1]);
1138             break;
1139         case opid3('&','~','='):
1140             /* This is like: a &= ~(b);
1141              * But QC has no bitwise-not, so we implement it as
1142              * a -= a & (b);
1143              */
1144             if (NotSameType(TYPE_FLOAT)) {
1145                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1146                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1147                 parseerror(parser, "invalid types used in expression: %s and %s",
1148                            ty1, ty2);
1149                 return false;
1150             }
1151             if (ast_istype(exprs[0], ast_entfield))
1152                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1153             else
1154                 assignop = type_store_instr[exprs[0]->expression.vtype];
1155             out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1156             if (!out)
1157                 return false;
1158             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1159                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1160             }
1161             asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1162             asbinstore->keep_dest = true;
1163             out = (ast_expression*)asbinstore;
1164             break;
1165     }
1166 #undef NotSameType
1167
1168     if (!out) {
1169         parseerror(parser, "failed to apply operand %s", op->op);
1170         return false;
1171     }
1172
1173     DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1174     vec_push(sy->out, syexp(ctx, out));
1175     return true;
1176 }
1177
1178 static bool parser_close_call(parser_t *parser, shunt *sy)
1179 {
1180     /* was a function call */
1181     ast_expression *fun;
1182     ast_call       *call;
1183
1184     size_t          fid;
1185     size_t          paramcount;
1186
1187     vec_shrinkby(sy->ops, 1);
1188     fid = sy->ops[vec_size(sy->ops)].off;
1189
1190     /* out[fid] is the function
1191      * everything above is parameters...
1192      * 0 params = nothing
1193      * 1 params = ast_expression
1194      * more = ast_block
1195      */
1196
1197     if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1198         parseerror(parser, "internal error: function call needs function and parameter list...");
1199         return false;
1200     }
1201
1202     fun = sy->out[fid].out;
1203
1204     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1205     if (!call) {
1206         parseerror(parser, "out of memory");
1207         return false;
1208     }
1209
1210     if (fid+1 == vec_size(sy->out)) {
1211         /* no arguments */
1212         paramcount = 0;
1213     } else if (fid+2 == vec_size(sy->out)) {
1214         ast_block *params;
1215         vec_shrinkby(sy->out, 1);
1216         params = sy->out[vec_size(sy->out)].block;
1217         if (!params) {
1218             /* 1 param */
1219             paramcount = 1;
1220             vec_push(call->params, sy->out[vec_size(sy->out)].out);
1221         } else {
1222             paramcount = vec_size(params->exprs);
1223             call->params = params->exprs;
1224             params->exprs = NULL;
1225             ast_delete(params);
1226         }
1227         if (!ast_call_check_types(call))
1228             parser->errors++;
1229     } else {
1230         parseerror(parser, "invalid function call");
1231         return false;
1232     }
1233
1234     /* overwrite fid, the function, with a call */
1235     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1236
1237     if (fun->expression.vtype != TYPE_FUNCTION) {
1238         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1239         return false;
1240     }
1241
1242     if (!fun->expression.next) {
1243         parseerror(parser, "could not determine function return type");
1244         return false;
1245     } else {
1246         if (vec_size(fun->expression.params) != paramcount &&
1247             !(fun->expression.variadic &&
1248               vec_size(fun->expression.params) < paramcount))
1249         {
1250             ast_value *fval;
1251             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1252
1253             fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1254             if (opts_standard == COMPILER_GMQCC)
1255             {
1256                 if (fval)
1257                     parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1258                                " -> `%s` has been declared here: %s:%i",
1259                                fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1260                                fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1261                 else
1262                     parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1263                                " -> `%s` has been declared here: %s:%i",
1264                                fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1265                                fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1266                 return false;
1267             }
1268             else
1269             {
1270                 if (fval)
1271                     return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1272                                          "too %s parameters for call to %s: expected %i, got %i\n"
1273                                          " -> `%s` has been declared here: %s:%i",
1274                                          fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1275                                          fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1276                 else
1277                     return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1278                                          "too %s parameters for function call: expected %i, got %i\n"
1279                                          " -> `%s` has been declared here: %s:%i",
1280                                          fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1281                                          fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1282             }
1283         }
1284     }
1285
1286     return true;
1287 }
1288
1289 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1290 {
1291     if (!vec_size(sy->ops)) {
1292         parseerror(parser, "unmatched closing paren");
1293         return false;
1294     }
1295     /* this would for bit a + (x) because there are no operators inside (x)
1296     if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1297         parseerror(parser, "empty parenthesis expression");
1298         return false;
1299     }
1300     */
1301     while (vec_size(sy->ops)) {
1302         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1303             if (!parser_close_call(parser, sy))
1304                 return false;
1305             break;
1306         }
1307         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1308             vec_shrinkby(sy->ops, 1);
1309             return !functions_only;
1310         }
1311         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1312             if (functions_only)
1313                 return false;
1314             /* pop off the parenthesis */
1315             vec_shrinkby(sy->ops, 1);
1316             /* then apply the index operator */
1317             if (!parser_sy_pop(parser, sy))
1318                 return false;
1319             return true;
1320         }
1321         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1322             if (functions_only)
1323                 return false;
1324             if (vec_last(parser->pot) != POT_TERNARY1) {
1325                 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1326                 return false;
1327             }
1328             vec_last(parser->pot) = POT_TERNARY2;
1329             /* pop off the parenthesis */
1330             vec_shrinkby(sy->ops, 1);
1331             return true;
1332         }
1333         if (!parser_sy_pop(parser, sy))
1334             return false;
1335     }
1336     return true;
1337 }
1338
1339 static void parser_reclassify_token(parser_t *parser)
1340 {
1341     size_t i;
1342     for (i = 0; i < operator_count; ++i) {
1343         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1344             parser->tok = TOKEN_OPERATOR;
1345             return;
1346         }
1347     }
1348 }
1349
1350 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1351 {
1352     ast_expression *expr = NULL;
1353     shunt sy;
1354     bool wantop = false;
1355     bool gotmemberof = false;
1356
1357     /* count the parens because an if starts with one, so the
1358      * end of a condition is an unmatched closing paren
1359      */
1360     int parens = 0;
1361     int ternaries = 0;
1362
1363     sy.out = NULL;
1364     sy.ops = NULL;
1365
1366     parser->lex->flags.noops = false;
1367
1368     parser_reclassify_token(parser);
1369
1370     while (true)
1371     {
1372         if (gotmemberof)
1373             gotmemberof = false;
1374         else
1375             parser->memberof = 0;
1376
1377         if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1378             parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1379         {
1380             /* a translatable string */
1381             ast_value *val;
1382
1383             if (wantop) {
1384                 parseerror(parser, "expected operator or end of statement, got constant");
1385                 goto onerr;
1386             }
1387
1388             parser->lex->flags.noops = true;
1389             if (!parser_next(parser) || parser->tok != '(') {
1390                 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1391                 goto onerr;
1392             }
1393             parser->lex->flags.noops = false;
1394             if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1395                 parseerror(parser, "expected a constant string in translatable-string extension");
1396                 goto onerr;
1397             }
1398             val = parser_const_string(parser, parser_tokval(parser), true);
1399             wantop = true;
1400             if (!val)
1401                 return false;
1402             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1403             DEBUGSHUNTDO(con_out("push string\n"));
1404
1405             if (!parser_next(parser) || parser->tok != ')') {
1406                 parseerror(parser, "expected closing paren after translatable string");
1407                 goto onerr;
1408             }
1409         }
1410         else if (parser->tok == TOKEN_IDENT)
1411         {
1412             ast_expression *var;
1413             if (wantop) {
1414                 parseerror(parser, "expected operator or end of statement");
1415                 goto onerr;
1416             }
1417             wantop = true;
1418             /* variable */
1419             if (opts_standard == COMPILER_GMQCC)
1420             {
1421                 if (parser->memberof == TYPE_ENTITY) {
1422                     /* still get vars first since there could be a fieldpointer */
1423                     var = parser_find_var(parser, parser_tokval(parser));
1424                     if (!var)
1425                         var = parser_find_field(parser, parser_tokval(parser));
1426                 }
1427                 else if (parser->memberof == TYPE_VECTOR)
1428                 {
1429                     parseerror(parser, "TODO: implement effective vector member access");
1430                     goto onerr;
1431                 }
1432                 else if (parser->memberof) {
1433                     parseerror(parser, "namespace for member not found");
1434                     goto onerr;
1435                 }
1436                 else
1437                     var = parser_find_var(parser, parser_tokval(parser));
1438             } else {
1439                 var = parser_find_var(parser, parser_tokval(parser));
1440                 if (!var)
1441                     var = parser_find_field(parser, parser_tokval(parser));
1442             }
1443             if (!var) {
1444                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1445                 goto onerr;
1446             }
1447             if (ast_istype(var, ast_value)) {
1448                 ((ast_value*)var)->uses++;
1449             }
1450             else if (ast_istype(var, ast_member)) {
1451                 ast_member *mem = (ast_member*)var;
1452                 if (ast_istype(mem->owner, ast_value))
1453                     ((ast_value*)(mem->owner))->uses++;
1454             }
1455             vec_push(sy.out, syexp(parser_ctx(parser), var));
1456             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1457         }
1458         else if (parser->tok == TOKEN_FLOATCONST) {
1459             ast_value *val;
1460             if (wantop) {
1461                 parseerror(parser, "expected operator or end of statement, got constant");
1462                 goto onerr;
1463             }
1464             wantop = true;
1465             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1466             if (!val)
1467                 return false;
1468             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1469             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1470         }
1471         else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1472             ast_value *val;
1473             if (wantop) {
1474                 parseerror(parser, "expected operator or end of statement, got constant");
1475                 goto onerr;
1476             }
1477             wantop = true;
1478             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1479             if (!val)
1480                 return false;
1481             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1482             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1483         }
1484         else if (parser->tok == TOKEN_STRINGCONST) {
1485             ast_value *val;
1486             if (wantop) {
1487                 parseerror(parser, "expected operator or end of statement, got constant");
1488                 goto onerr;
1489             }
1490             wantop = true;
1491             val = parser_const_string(parser, parser_tokval(parser), false);
1492             if (!val)
1493                 return false;
1494             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1495             DEBUGSHUNTDO(con_out("push string\n"));
1496         }
1497         else if (parser->tok == TOKEN_VECTORCONST) {
1498             ast_value *val;
1499             if (wantop) {
1500                 parseerror(parser, "expected operator or end of statement, got constant");
1501                 goto onerr;
1502             }
1503             wantop = true;
1504             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1505             if (!val)
1506                 return false;
1507             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1508             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1509                                 parser_token(parser)->constval.v.x,
1510                                 parser_token(parser)->constval.v.y,
1511                                 parser_token(parser)->constval.v.z));
1512         }
1513         else if (parser->tok == '(') {
1514             parseerror(parser, "internal error: '(' should be classified as operator");
1515             goto onerr;
1516         }
1517         else if (parser->tok == '[') {
1518             parseerror(parser, "internal error: '[' should be classified as operator");
1519             goto onerr;
1520         }
1521         else if (parser->tok == ')') {
1522             if (wantop) {
1523                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1524                 --parens;
1525                 if (parens < 0)
1526                     break;
1527                 /* we do expect an operator next */
1528                 /* closing an opening paren */
1529                 if (!parser_close_paren(parser, &sy, false))
1530                     goto onerr;
1531                 if (vec_last(parser->pot) != POT_PAREN) {
1532                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1533                     goto onerr;
1534                 }
1535                 vec_pop(parser->pot);
1536             } else {
1537                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1538                 --parens;
1539                 if (parens < 0)
1540                     break;
1541                 /* allowed for function calls */
1542                 if (!parser_close_paren(parser, &sy, true))
1543                     goto onerr;
1544                 if (vec_last(parser->pot) != POT_PAREN) {
1545                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1546                     goto onerr;
1547                 }
1548                 vec_pop(parser->pot);
1549             }
1550             wantop = true;
1551         }
1552         else if (parser->tok == ']') {
1553             if (!wantop)
1554                 parseerror(parser, "operand expected");
1555             --parens;
1556             if (parens < 0)
1557                 break;
1558             if (!parser_close_paren(parser, &sy, false))
1559                 goto onerr;
1560             if (vec_last(parser->pot) != POT_PAREN) {
1561                 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1562                 goto onerr;
1563             }
1564             vec_pop(parser->pot);
1565             wantop = true;
1566         }
1567         else if (parser->tok != TOKEN_OPERATOR) {
1568             if (wantop) {
1569                 parseerror(parser, "expected operator or end of statement");
1570                 goto onerr;
1571             }
1572             break;
1573         }
1574         else
1575         {
1576             /* classify the operator */
1577             const oper_info *op;
1578             const oper_info *olast = NULL;
1579             size_t o;
1580             for (o = 0; o < operator_count; ++o) {
1581                 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1582                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1583                     !strcmp(parser_tokval(parser), operators[o].op))
1584                 {
1585                     break;
1586                 }
1587             }
1588             if (o == operator_count) {
1589                 /* no operator found... must be the end of the statement */
1590                 break;
1591             }
1592             /* found an operator */
1593             op = &operators[o];
1594
1595             /* when declaring variables, a comma starts a new variable */
1596             if (op->id == opid1(',') && !parens && stopatcomma) {
1597                 /* fixup the token */
1598                 parser->tok = ',';
1599                 break;
1600             }
1601
1602             /* a colon without a pervious question mark cannot be a ternary */
1603             if (!ternaries && op->id == opid2(':','?')) {
1604                 parser->tok = ':';
1605                 break;
1606             }
1607
1608             if (op->id == opid1(',')) {
1609                 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1610                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1611                 }
1612             }
1613
1614             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1615                 olast = &operators[vec_last(sy.ops).etype-1];
1616
1617             while (olast && (
1618                     (op->prec < olast->prec) ||
1619                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1620             {
1621                 if (!parser_sy_pop(parser, &sy))
1622                     goto onerr;
1623                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1624                     olast = &operators[vec_last(sy.ops).etype-1];
1625                 else
1626                     olast = NULL;
1627             }
1628
1629             if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1630                 /* for gmqcc standard: open up the namespace of the previous type */
1631                 ast_expression *prevex = vec_last(sy.out).out;
1632                 if (!prevex) {
1633                     parseerror(parser, "unexpected member operator");
1634                     goto onerr;
1635                 }
1636                 if (prevex->expression.vtype == TYPE_ENTITY)
1637                     parser->memberof = TYPE_ENTITY;
1638                 else if (prevex->expression.vtype == TYPE_VECTOR)
1639                     parser->memberof = TYPE_VECTOR;
1640                 else {
1641                     parseerror(parser, "type error: type has no members");
1642                     goto onerr;
1643                 }
1644                 gotmemberof = true;
1645             }
1646
1647             if (op->id == opid1('(')) {
1648                 if (wantop) {
1649                     size_t sycount = vec_size(sy.out);
1650                     DEBUGSHUNTDO(con_out("push [op] (\n"));
1651                     ++parens; vec_push(parser->pot, POT_PAREN);
1652                     /* we expected an operator, this is the function-call operator */
1653                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1654                 } else {
1655                     ++parens; vec_push(parser->pot, POT_PAREN);
1656                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1657                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
1658                 }
1659                 wantop = false;
1660             } else if (op->id == opid1('[')) {
1661                 if (!wantop) {
1662                     parseerror(parser, "unexpected array subscript");
1663                     goto onerr;
1664                 }
1665                 ++parens; vec_push(parser->pot, POT_PAREN);
1666                 /* push both the operator and the paren, this makes life easier */
1667                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1668                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1669                 wantop = false;
1670             } else if (op->id == opid2('?',':')) {
1671                 wantop = false;
1672                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1673                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1674                 wantop = false;
1675                 ++ternaries;
1676                 vec_push(parser->pot, POT_TERNARY1);
1677             } else if (op->id == opid2(':','?')) {
1678                 if (!vec_size(parser->pot)) {
1679                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1680                     goto onerr;
1681                 }
1682                 if (vec_last(parser->pot) != POT_TERNARY1) {
1683                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1684                     goto onerr;
1685                 }
1686                 if (!parser_close_paren(parser, &sy, false))
1687                     goto onerr;
1688                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1689                 wantop = false;
1690                 --ternaries;
1691             } else {
1692                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1693                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1694                 wantop = !!(op->flags & OP_SUFFIX);
1695             }
1696         }
1697         if (!parser_next(parser)) {
1698             goto onerr;
1699         }
1700         if (parser->tok == ';' ||
1701             (!parens && parser->tok == ']'))
1702         {
1703             break;
1704         }
1705     }
1706
1707     while (vec_size(sy.ops)) {
1708         if (!parser_sy_pop(parser, &sy))
1709             goto onerr;
1710     }
1711
1712     parser->lex->flags.noops = true;
1713     if (!vec_size(sy.out)) {
1714         parseerror(parser, "empty expression");
1715         expr = NULL;
1716     } else
1717         expr = sy.out[0].out;
1718     vec_free(sy.out);
1719     vec_free(sy.ops);
1720     DEBUGSHUNTDO(con_out("shunt done\n"));
1721     return expr;
1722
1723 onerr:
1724     parser->lex->flags.noops = true;
1725     vec_free(sy.out);
1726     vec_free(sy.ops);
1727     return NULL;
1728 }
1729
1730 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1731 {
1732     ast_expression *e = parse_expression_leave(parser, stopatcomma);
1733     if (!e)
1734         return NULL;
1735     if (!parser_next(parser)) {
1736         ast_delete(e);
1737         return NULL;
1738     }
1739     return e;
1740 }
1741
1742 static void parser_enterblock(parser_t *parser)
1743 {
1744     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1745     vec_push(parser->_blocklocals, vec_size(parser->_locals));
1746     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1747     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1748     vec_push(parser->_block_ctx, parser_ctx(parser));
1749 }
1750
1751 static bool parser_leaveblock(parser_t *parser)
1752 {
1753     bool   rv = true;
1754     size_t locals, typedefs;
1755
1756     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1757         parseerror(parser, "internal error: parser_leaveblock with no block");
1758         return false;
1759     }
1760
1761     util_htdel(vec_last(parser->variables));
1762     vec_pop(parser->variables);
1763     if (!vec_size(parser->_blocklocals)) {
1764         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1765         return false;
1766     }
1767
1768     locals = vec_last(parser->_blocklocals);
1769     vec_pop(parser->_blocklocals);
1770     while (vec_size(parser->_locals) != locals) {
1771         ast_expression *e = vec_last(parser->_locals);
1772         ast_value      *v = (ast_value*)e;
1773         vec_pop(parser->_locals);
1774         if (ast_istype(e, ast_value) && !v->uses) {
1775             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1776                 parser->errors++;
1777                 rv = false;
1778             }
1779         }
1780     }
1781
1782     typedefs = vec_last(parser->_blocktypedefs);
1783     while (vec_size(parser->_typedefs) != typedefs) {
1784         ast_delete(vec_last(parser->_typedefs));
1785         vec_pop(parser->_typedefs);
1786     }
1787     util_htdel(vec_last(parser->typedefs));
1788     vec_pop(parser->typedefs);
1789
1790     vec_pop(parser->_block_ctx);
1791     return rv;
1792 }
1793
1794 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1795 {
1796     vec_push(parser->_locals, e);
1797     util_htset(vec_last(parser->variables), name, (void*)e);
1798 }
1799
1800 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1801 {
1802     ast_ifthen *ifthen;
1803     ast_expression *cond, *ontrue, *onfalse = NULL;
1804     bool ifnot = false;
1805
1806     lex_ctx ctx = parser_ctx(parser);
1807
1808     (void)block; /* not touching */
1809
1810     /* skip the 'if', parse an optional 'not' and check for an opening paren */
1811     if (!parser_next(parser)) {
1812         parseerror(parser, "expected condition or 'not'");
1813         return false;
1814     }
1815     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1816         ifnot = true;
1817         if (!parser_next(parser)) {
1818             parseerror(parser, "expected condition in parenthesis");
1819             return false;
1820         }
1821     }
1822     if (parser->tok != '(') {
1823         parseerror(parser, "expected 'if' condition in parenthesis");
1824         return false;
1825     }
1826     /* parse into the expression */
1827     if (!parser_next(parser)) {
1828         parseerror(parser, "expected 'if' condition after opening paren");
1829         return false;
1830     }
1831     /* parse the condition */
1832     cond = parse_expression_leave(parser, false);
1833     if (!cond)
1834         return false;
1835     /* closing paren */
1836     if (parser->tok != ')') {
1837         parseerror(parser, "expected closing paren after 'if' condition");
1838         ast_delete(cond);
1839         return false;
1840     }
1841     /* parse into the 'then' branch */
1842     if (!parser_next(parser)) {
1843         parseerror(parser, "expected statement for on-true branch of 'if'");
1844         ast_delete(cond);
1845         return false;
1846     }
1847     if (!parse_statement_or_block(parser, &ontrue)) {
1848         ast_delete(cond);
1849         return false;
1850     }
1851     /* check for an else */
1852     if (!strcmp(parser_tokval(parser), "else")) {
1853         /* parse into the 'else' branch */
1854         if (!parser_next(parser)) {
1855             parseerror(parser, "expected on-false branch after 'else'");
1856             ast_delete(ontrue);
1857             ast_delete(cond);
1858             return false;
1859         }
1860         if (!parse_statement_or_block(parser, &onfalse)) {
1861             ast_delete(ontrue);
1862             ast_delete(cond);
1863             return false;
1864         }
1865     }
1866
1867     if (ifnot)
1868         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1869     else
1870         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1871     *out = (ast_expression*)ifthen;
1872     return true;
1873 }
1874
1875 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1876 {
1877     ast_loop *aloop;
1878     ast_expression *cond, *ontrue;
1879
1880     lex_ctx ctx = parser_ctx(parser);
1881
1882     (void)block; /* not touching */
1883
1884     /* skip the 'while' and check for opening paren */
1885     if (!parser_next(parser) || parser->tok != '(') {
1886         parseerror(parser, "expected 'while' condition in parenthesis");
1887         return false;
1888     }
1889     /* parse into the expression */
1890     if (!parser_next(parser)) {
1891         parseerror(parser, "expected 'while' condition after opening paren");
1892         return false;
1893     }
1894     /* parse the condition */
1895     cond = parse_expression_leave(parser, false);
1896     if (!cond)
1897         return false;
1898     /* closing paren */
1899     if (parser->tok != ')') {
1900         parseerror(parser, "expected closing paren after 'while' condition");
1901         ast_delete(cond);
1902         return false;
1903     }
1904     /* parse into the 'then' branch */
1905     if (!parser_next(parser)) {
1906         parseerror(parser, "expected while-loop body");
1907         ast_delete(cond);
1908         return false;
1909     }
1910     if (!parse_statement_or_block(parser, &ontrue)) {
1911         ast_delete(cond);
1912         return false;
1913     }
1914
1915     aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1916     *out = (ast_expression*)aloop;
1917     return true;
1918 }
1919
1920 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1921 {
1922     ast_loop *aloop;
1923     ast_expression *cond, *ontrue;
1924
1925     lex_ctx ctx = parser_ctx(parser);
1926
1927     (void)block; /* not touching */
1928
1929     /* skip the 'do' and get the body */
1930     if (!parser_next(parser)) {
1931         parseerror(parser, "expected loop body");
1932         return false;
1933     }
1934     if (!parse_statement_or_block(parser, &ontrue))
1935         return false;
1936
1937     /* expect the "while" */
1938     if (parser->tok != TOKEN_KEYWORD ||
1939         strcmp(parser_tokval(parser), "while"))
1940     {
1941         parseerror(parser, "expected 'while' and condition");
1942         ast_delete(ontrue);
1943         return false;
1944     }
1945
1946     /* skip the 'while' and check for opening paren */
1947     if (!parser_next(parser) || parser->tok != '(') {
1948         parseerror(parser, "expected 'while' condition in parenthesis");
1949         ast_delete(ontrue);
1950         return false;
1951     }
1952     /* parse into the expression */
1953     if (!parser_next(parser)) {
1954         parseerror(parser, "expected 'while' condition after opening paren");
1955         ast_delete(ontrue);
1956         return false;
1957     }
1958     /* parse the condition */
1959     cond = parse_expression_leave(parser, false);
1960     if (!cond)
1961         return false;
1962     /* closing paren */
1963     if (parser->tok != ')') {
1964         parseerror(parser, "expected closing paren after 'while' condition");
1965         ast_delete(ontrue);
1966         ast_delete(cond);
1967         return false;
1968     }
1969     /* parse on */
1970     if (!parser_next(parser) || parser->tok != ';') {
1971         parseerror(parser, "expected semicolon after condition");
1972         ast_delete(ontrue);
1973         ast_delete(cond);
1974         return false;
1975     }
1976
1977     if (!parser_next(parser)) {
1978         parseerror(parser, "parse error");
1979         ast_delete(ontrue);
1980         ast_delete(cond);
1981         return false;
1982     }
1983
1984     aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1985     *out = (ast_expression*)aloop;
1986     return true;
1987 }
1988
1989 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1990 {
1991     ast_loop       *aloop;
1992     ast_expression *initexpr, *cond, *increment, *ontrue;
1993     ast_value      *typevar;
1994     bool   retval = true;
1995
1996     lex_ctx ctx = parser_ctx(parser);
1997
1998     parser_enterblock(parser);
1999
2000     initexpr  = NULL;
2001     cond      = NULL;
2002     increment = NULL;
2003     ontrue    = NULL;
2004
2005     /* skip the 'while' and check for opening paren */
2006     if (!parser_next(parser) || parser->tok != '(') {
2007         parseerror(parser, "expected 'for' expressions in parenthesis");
2008         goto onerr;
2009     }
2010     /* parse into the expression */
2011     if (!parser_next(parser)) {
2012         parseerror(parser, "expected 'for' initializer after opening paren");
2013         goto onerr;
2014     }
2015
2016     typevar = NULL;
2017     if (parser->tok == TOKEN_IDENT)
2018         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2019
2020     if (typevar || parser->tok == TOKEN_TYPENAME) {
2021         if (opts_standard != COMPILER_GMQCC) {
2022             if (parsewarning(parser, WARN_EXTENSIONS,
2023                              "current standard does not allow variable declarations in for-loop initializers"))
2024                 goto onerr;
2025         }
2026         if (!parse_variable(parser, block, true, CV_VAR, typevar))
2027             goto onerr;
2028     }
2029     else if (parser->tok != ';')
2030     {
2031         initexpr = parse_expression_leave(parser, false);
2032         if (!initexpr)
2033             goto onerr;
2034     }
2035
2036     /* move on to condition */
2037     if (parser->tok != ';') {
2038         parseerror(parser, "expected semicolon after for-loop initializer");
2039         goto onerr;
2040     }
2041     if (!parser_next(parser)) {
2042         parseerror(parser, "expected for-loop condition");
2043         goto onerr;
2044     }
2045
2046     /* parse the condition */
2047     if (parser->tok != ';') {
2048         cond = parse_expression_leave(parser, false);
2049         if (!cond)
2050             goto onerr;
2051     }
2052
2053     /* move on to incrementor */
2054     if (parser->tok != ';') {
2055         parseerror(parser, "expected semicolon after for-loop initializer");
2056         goto onerr;
2057     }
2058     if (!parser_next(parser)) {
2059         parseerror(parser, "expected for-loop condition");
2060         goto onerr;
2061     }
2062
2063     /* parse the incrementor */
2064     if (parser->tok != ')') {
2065         increment = parse_expression_leave(parser, false);
2066         if (!increment)
2067             goto onerr;
2068         if (!ast_side_effects(increment)) {
2069             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2070                 goto onerr;
2071         }
2072     }
2073
2074     /* closing paren */
2075     if (parser->tok != ')') {
2076         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2077         goto onerr;
2078     }
2079     /* parse into the 'then' branch */
2080     if (!parser_next(parser)) {
2081         parseerror(parser, "expected for-loop body");
2082         goto onerr;
2083     }
2084     if (!parse_statement_or_block(parser, &ontrue))
2085         goto onerr;
2086
2087     aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
2088     *out = (ast_expression*)aloop;
2089
2090     if (!parser_leaveblock(parser))
2091         retval = false;
2092     return retval;
2093 onerr:
2094     if (initexpr)  ast_delete(initexpr);
2095     if (cond)      ast_delete(cond);
2096     if (increment) ast_delete(increment);
2097     (void)!parser_leaveblock(parser);
2098     return false;
2099 }
2100
2101 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2102 {
2103     ast_expression *exp = NULL;
2104     ast_return     *ret = NULL;
2105     ast_value      *expected = parser->function->vtype;
2106
2107     lex_ctx ctx = parser_ctx(parser);
2108
2109     (void)block; /* not touching */
2110
2111     if (!parser_next(parser)) {
2112         parseerror(parser, "expected return expression");
2113         return false;
2114     }
2115
2116     if (parser->tok != ';') {
2117         exp = parse_expression(parser, false);
2118         if (!exp)
2119             return false;
2120
2121         if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2122             parseerror(parser, "return with invalid expression");
2123         }
2124
2125         ret = ast_return_new(exp->expression.node.context, exp);
2126         if (!ret) {
2127             ast_delete(exp);
2128             return false;
2129         }
2130     } else {
2131         if (!parser_next(parser))
2132             parseerror(parser, "parse error");
2133         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2134             if (opts_standard != COMPILER_GMQCC)
2135                 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2136             else
2137                 parseerror(parser, "return without value");
2138         }
2139         ret = ast_return_new(ctx, NULL);
2140     }
2141     *out = (ast_expression*)ret;
2142     return true;
2143 }
2144
2145 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2146 {
2147     lex_ctx ctx = parser_ctx(parser);
2148
2149     (void)block; /* not touching */
2150
2151     if (!parser_next(parser) || parser->tok != ';') {
2152         parseerror(parser, "expected semicolon");
2153         return false;
2154     }
2155
2156     if (!parser_next(parser))
2157         parseerror(parser, "parse error");
2158
2159     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2160     return true;
2161 }
2162
2163 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2164 {
2165     ast_expression *operand;
2166     ast_value      *opval;
2167     ast_value      *typevar;
2168     ast_switch     *switchnode;
2169     ast_switch_case swcase;
2170
2171     lex_ctx ctx = parser_ctx(parser);
2172
2173     (void)block; /* not touching */
2174     (void)opval;
2175
2176     /* parse over the opening paren */
2177     if (!parser_next(parser) || parser->tok != '(') {
2178         parseerror(parser, "expected switch operand in parenthesis");
2179         return false;
2180     }
2181
2182     /* parse into the expression */
2183     if (!parser_next(parser)) {
2184         parseerror(parser, "expected switch operand");
2185         return false;
2186     }
2187     /* parse the operand */
2188     operand = parse_expression_leave(parser, false);
2189     if (!operand)
2190         return false;
2191
2192     switchnode = ast_switch_new(ctx, operand);
2193
2194     /* closing paren */
2195     if (parser->tok != ')') {
2196         ast_delete(switchnode);
2197         parseerror(parser, "expected closing paren after 'switch' operand");
2198         return false;
2199     }
2200
2201     /* parse over the opening paren */
2202     if (!parser_next(parser) || parser->tok != '{') {
2203         ast_delete(switchnode);
2204         parseerror(parser, "expected list of cases");
2205         return false;
2206     }
2207
2208     if (!parser_next(parser)) {
2209         ast_delete(switchnode);
2210         parseerror(parser, "expected 'case' or 'default'");
2211         return false;
2212     }
2213
2214     /* new block; allow some variables to be declared here */
2215     parser_enterblock(parser);
2216     while (true) {
2217         typevar = NULL;
2218         if (parser->tok == TOKEN_IDENT)
2219             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2220         if (typevar || parser->tok == TOKEN_TYPENAME) {
2221             if (!parse_variable(parser, block, false, CV_NONE, typevar)) {
2222                 ast_delete(switchnode);
2223                 return false;
2224             }
2225             continue;
2226         }
2227         if (!strcmp(parser_tokval(parser), "var") ||
2228             !strcmp(parser_tokval(parser), "local"))
2229         {
2230             if (!parser_next(parser)) {
2231                 parseerror(parser, "expected variable declaration");
2232                 ast_delete(switchnode);
2233                 return false;
2234             }
2235             if (!parse_variable(parser, block, false, CV_VAR, NULL)) {
2236                 ast_delete(switchnode);
2237                 return false;
2238             }
2239             continue;
2240         }
2241         if (!strcmp(parser_tokval(parser), "const")) {
2242             if (!parser_next(parser)) {
2243                 parseerror(parser, "expected variable declaration");
2244                 ast_delete(switchnode);
2245                 return false;
2246             }
2247             if (!strcmp(parser_tokval(parser), "var")) {
2248                 if (!parser_next(parser)) {
2249                     parseerror(parser, "expected variable declaration");
2250                     ast_delete(switchnode);
2251                     return false;
2252                 }
2253             }
2254             if (!parse_variable(parser, block, false, CV_CONST, NULL)) {
2255                 ast_delete(switchnode);
2256                 return false;
2257             }
2258             continue;
2259         }
2260         break;
2261     }
2262
2263     /* case list! */
2264     while (parser->tok != '}') {
2265         ast_block *caseblock;
2266
2267         if (parser->tok != TOKEN_KEYWORD) {
2268             ast_delete(switchnode);
2269             parseerror(parser, "expected 'case' or 'default'");
2270             return false;
2271         }
2272         if (!strcmp(parser_tokval(parser), "case")) {
2273             if (!parser_next(parser)) {
2274                 ast_delete(switchnode);
2275                 parseerror(parser, "expected expression for case");
2276                 return false;
2277             }
2278             swcase.value = parse_expression_leave(parser, false);
2279             if (!swcase.value) {
2280                 ast_delete(switchnode);
2281                 parseerror(parser, "expected expression for case");
2282                 return false;
2283             }
2284             if (!OPTS_FLAG(RELAXED_SWITCH)) {
2285                 opval = (ast_value*)swcase.value;
2286                 if (!ast_istype(swcase.value, ast_value)) { /* || opval->cvq != CV_CONST) { */
2287                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2288                     ast_unref(operand);
2289                     return false;
2290                 }
2291             }
2292         }
2293         else if (!strcmp(parser_tokval(parser), "default")) {
2294             swcase.value = NULL;
2295             if (!parser_next(parser)) {
2296                 ast_delete(switchnode);
2297                 parseerror(parser, "expected colon");
2298                 return false;
2299             }
2300         }
2301
2302         /* Now the colon and body */
2303         if (parser->tok != ':') {
2304             if (swcase.value) ast_unref(swcase.value);
2305             ast_delete(switchnode);
2306             parseerror(parser, "expected colon");
2307             return false;
2308         }
2309
2310         if (!parser_next(parser)) {
2311             if (swcase.value) ast_unref(swcase.value);
2312             ast_delete(switchnode);
2313             parseerror(parser, "expected statements or case");
2314             return false;
2315         }
2316         caseblock = ast_block_new(parser_ctx(parser));
2317         if (!caseblock) {
2318             if (swcase.value) ast_unref(swcase.value);
2319             ast_delete(switchnode);
2320             return false;
2321         }
2322         swcase.code = (ast_expression*)caseblock;
2323         vec_push(switchnode->cases, swcase);
2324         while (true) {
2325             ast_expression *expr;
2326             if (parser->tok == '}')
2327                 break;
2328             if (parser->tok == TOKEN_KEYWORD) {
2329                 if (!strcmp(parser_tokval(parser), "case") ||
2330                     !strcmp(parser_tokval(parser), "default"))
2331                 {
2332                     break;
2333                 }
2334             }
2335             if (!parse_statement(parser, caseblock, &expr, true)) {
2336                 ast_delete(switchnode);
2337                 return false;
2338             }
2339             if (!expr)
2340                 continue;
2341             ast_block_add_expr(caseblock, expr);
2342         }
2343     }
2344
2345     parser_leaveblock(parser);
2346
2347     /* closing paren */
2348     if (parser->tok != '}') {
2349         ast_delete(switchnode);
2350         parseerror(parser, "expected closing paren of case list");
2351         return false;
2352     }
2353     if (!parser_next(parser)) {
2354         ast_delete(switchnode);
2355         parseerror(parser, "parse error after switch");
2356         return false;
2357     }
2358     *out = (ast_expression*)switchnode;
2359     return true;
2360 }
2361
2362 static bool parse_goto(parser_t *parser, ast_expression **out)
2363 {
2364     size_t    i;
2365     ast_goto *gt;
2366
2367     if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2368         parseerror(parser, "expected label name after `goto`");
2369         return false;
2370     }
2371
2372     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2373
2374     for (i = 0; i < vec_size(parser->labels); ++i) {
2375         if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2376             ast_goto_set_label(gt, parser->labels[i]);
2377             break;
2378         }
2379     }
2380     if (i == vec_size(parser->labels))
2381         vec_push(parser->gotos, gt);
2382
2383     if (!parser_next(parser) || parser->tok != ';') {
2384         parseerror(parser, "semicolon expected after goto label");
2385         return false;
2386     }
2387     if (!parser_next(parser)) {
2388         parseerror(parser, "parse error after goto");
2389         return false;
2390     }
2391
2392     *out = (ast_expression*)gt;
2393     return true;
2394 }
2395
2396 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2397 {
2398     int cvq;
2399     ast_value *typevar = NULL;
2400     *out = NULL;
2401
2402     if (parser->tok == TOKEN_IDENT)
2403         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2404
2405     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2406     {
2407         /* local variable */
2408         if (!block) {
2409             parseerror(parser, "cannot declare a variable from here");
2410             return false;
2411         }
2412         if (opts_standard == COMPILER_QCC) {
2413             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2414                 return false;
2415         }
2416         if (!parse_variable(parser, block, false, CV_NONE, typevar))
2417             return false;
2418         *out = NULL;
2419         return true;
2420     }
2421     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
2422     {
2423         goto ident_var;
2424     }
2425     else if (parser->tok == TOKEN_KEYWORD)
2426     {
2427         if (!strcmp(parser_tokval(parser), "local") ||
2428             !strcmp(parser_tokval(parser), "const") ||
2429             !strcmp(parser_tokval(parser), "var"))
2430         {
2431 ident_var:
2432             if (parser_tokval(parser)[0] == 'c')
2433                 cvq = CV_CONST;
2434             else if (parser_tokval(parser)[0] == 'v')
2435                 cvq = CV_VAR;
2436             else
2437                 cvq = CV_NONE;
2438
2439             if (!block) {
2440                 parseerror(parser, "cannot declare a local variable here");
2441                 return false;
2442             }
2443             if (!parser_next(parser)) {
2444                 parseerror(parser, "expected variable declaration");
2445                 return false;
2446             }
2447             if (!parse_variable(parser, block, true, cvq, NULL))
2448                 return false;
2449             *out = NULL;
2450             return true;
2451         }
2452         else if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2453         {
2454             char ty[1024];
2455             ast_value *tdef;
2456
2457             if (!parser_next(parser)) {
2458                 parseerror(parser, "parse error after __builtin_debug_printtype");
2459                 return false;
2460             }
2461
2462             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2463             {
2464                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2465                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2466                 if (!parser_next(parser)) {
2467                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2468                     return false;
2469                 }
2470             }
2471             else
2472             {
2473                 if (!parse_statement(parser, block, out, allow_cases))
2474                     return false;
2475                 if (!*out)
2476                     con_out("__builtin_debug_printtype: got no output node\n");
2477                 else
2478                 {
2479                     ast_type_to_string(*out, ty, sizeof(ty));
2480                     con_out("__builtin_debug_printtype: `%s`\n", ty);
2481                 }
2482             }
2483             return true;
2484         }
2485         else if (!strcmp(parser_tokval(parser), "return"))
2486         {
2487             return parse_return(parser, block, out);
2488         }
2489         else if (!strcmp(parser_tokval(parser), "if"))
2490         {
2491             return parse_if(parser, block, out);
2492         }
2493         else if (!strcmp(parser_tokval(parser), "while"))
2494         {
2495             return parse_while(parser, block, out);
2496         }
2497         else if (!strcmp(parser_tokval(parser), "do"))
2498         {
2499             return parse_dowhile(parser, block, out);
2500         }
2501         else if (!strcmp(parser_tokval(parser), "for"))
2502         {
2503             if (opts_standard == COMPILER_QCC) {
2504                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2505                     return false;
2506             }
2507             return parse_for(parser, block, out);
2508         }
2509         else if (!strcmp(parser_tokval(parser), "break"))
2510         {
2511             return parse_break_continue(parser, block, out, false);
2512         }
2513         else if (!strcmp(parser_tokval(parser), "continue"))
2514         {
2515             return parse_break_continue(parser, block, out, true);
2516         }
2517         else if (!strcmp(parser_tokval(parser), "switch"))
2518         {
2519             return parse_switch(parser, block, out);
2520         }
2521         else if (!strcmp(parser_tokval(parser), "case") ||
2522                  !strcmp(parser_tokval(parser), "default"))
2523         {
2524             if (!allow_cases) {
2525                 parseerror(parser, "unexpected 'case' label");
2526                 return false;
2527             }
2528             return true;
2529         }
2530         else if (!strcmp(parser_tokval(parser), "goto"))
2531         {
2532             return parse_goto(parser, out);
2533         }
2534         else if (!strcmp(parser_tokval(parser), "typedef"))
2535         {
2536             if (!parser_next(parser)) {
2537                 parseerror(parser, "expected type definition after 'typedef'");
2538                 return false;
2539             }
2540             return parse_typedef(parser);
2541         }
2542         parseerror(parser, "Unexpected keyword");
2543         return false;
2544     }
2545     else if (parser->tok == '{')
2546     {
2547         ast_block *inner;
2548         inner = parse_block(parser);
2549         if (!inner)
2550             return false;
2551         *out = (ast_expression*)inner;
2552         return true;
2553     }
2554     else if (parser->tok == ':')
2555     {
2556         size_t i;
2557         ast_label *label;
2558         if (!parser_next(parser)) {
2559             parseerror(parser, "expected label name");
2560             return false;
2561         }
2562         if (parser->tok != TOKEN_IDENT) {
2563             parseerror(parser, "label must be an identifier");
2564             return false;
2565         }
2566         label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2567         if (!label)
2568             return false;
2569         vec_push(parser->labels, label);
2570         *out = (ast_expression*)label;
2571         if (!parser_next(parser)) {
2572             parseerror(parser, "parse error after label");
2573             return false;
2574         }
2575         for (i = 0; i < vec_size(parser->gotos); ++i) {
2576             if (!strcmp(parser->gotos[i]->name, label->name)) {
2577                 ast_goto_set_label(parser->gotos[i], label);
2578                 vec_remove(parser->gotos, i, 1);
2579                 --i;
2580             }
2581         }
2582         return true;
2583     }
2584     else if (parser->tok == ';')
2585     {
2586         if (!parser_next(parser)) {
2587             parseerror(parser, "parse error after empty statement");
2588             return false;
2589         }
2590         return true;
2591     }
2592     else
2593     {
2594         ast_expression *exp = parse_expression(parser, false);
2595         if (!exp)
2596             return false;
2597         *out = exp;
2598         if (!ast_side_effects(exp)) {
2599             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2600                 return false;
2601         }
2602         return true;
2603     }
2604 }
2605
2606 static bool parse_block_into(parser_t *parser, ast_block *block)
2607 {
2608     bool   retval = true;
2609
2610     parser_enterblock(parser);
2611
2612     if (!parser_next(parser)) { /* skip the '{' */
2613         parseerror(parser, "expected function body");
2614         goto cleanup;
2615     }
2616
2617     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2618     {
2619         ast_expression *expr = NULL;
2620         if (parser->tok == '}')
2621             break;
2622
2623         if (!parse_statement(parser, block, &expr, false)) {
2624             /* parseerror(parser, "parse error"); */
2625             block = NULL;
2626             goto cleanup;
2627         }
2628         if (!expr)
2629             continue;
2630         ast_block_add_expr(block, expr);
2631     }
2632
2633     if (parser->tok != '}') {
2634         block = NULL;
2635     } else {
2636         (void)parser_next(parser);
2637     }
2638
2639 cleanup:
2640     if (!parser_leaveblock(parser))
2641         retval = false;
2642     return retval && !!block;
2643 }
2644
2645 static ast_block* parse_block(parser_t *parser)
2646 {
2647     ast_block *block;
2648     block = ast_block_new(parser_ctx(parser));
2649     if (!block)
2650         return NULL;
2651     if (!parse_block_into(parser, block)) {
2652         ast_block_delete(block);
2653         return NULL;
2654     }
2655     return block;
2656 }
2657
2658 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2659 {
2660     if (parser->tok == '{') {
2661         *out = (ast_expression*)parse_block(parser);
2662         return !!*out;
2663     }
2664     return parse_statement(parser, NULL, out, false);
2665 }
2666
2667 static bool create_vector_members(ast_value *var, ast_member **me)
2668 {
2669     size_t i;
2670     size_t len = strlen(var->name);
2671
2672     for (i = 0; i < 3; ++i) {
2673         char *name = mem_a(len+3);
2674         memcpy(name, var->name, len);
2675         name[len+0] = '_';
2676         name[len+1] = 'x'+i;
2677         name[len+2] = 0;
2678         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2679         mem_d(name);
2680         if (!me[i])
2681             break;
2682     }
2683     if (i == 3)
2684         return true;
2685
2686     /* unroll */
2687     do { ast_member_delete(me[--i]); } while(i);
2688     return false;
2689 }
2690
2691 static bool parse_function_body(parser_t *parser, ast_value *var)
2692 {
2693     ast_block      *block = NULL;
2694     ast_function   *func;
2695     ast_function   *old;
2696     size_t          parami;
2697
2698     ast_expression *framenum  = NULL;
2699     ast_expression *nextthink = NULL;
2700     /* None of the following have to be deleted */
2701     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2702     ast_expression *gbl_time = NULL, *gbl_self = NULL;
2703     bool            has_frame_think;
2704
2705     bool retval = true;
2706
2707     has_frame_think = false;
2708     old = parser->function;
2709
2710     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
2711         parseerror(parser, "gotos/labels leaking");
2712         return false;
2713     }
2714
2715     if (var->expression.variadic) {
2716         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2717                          "variadic function with implementation will not be able to access additional parameters"))
2718         {
2719             return false;
2720         }
2721     }
2722
2723     if (parser->tok == '[') {
2724         /* got a frame definition: [ framenum, nextthink ]
2725          * this translates to:
2726          * self.frame = framenum;
2727          * self.nextthink = time + 0.1;
2728          * self.think = nextthink;
2729          */
2730         nextthink = NULL;
2731
2732         fld_think     = parser_find_field(parser, "think");
2733         fld_nextthink = parser_find_field(parser, "nextthink");
2734         fld_frame     = parser_find_field(parser, "frame");
2735         if (!fld_think || !fld_nextthink || !fld_frame) {
2736             parseerror(parser, "cannot use [frame,think] notation without the required fields");
2737             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2738             return false;
2739         }
2740         gbl_time      = parser_find_global(parser, "time");
2741         gbl_self      = parser_find_global(parser, "self");
2742         if (!gbl_time || !gbl_self) {
2743             parseerror(parser, "cannot use [frame,think] notation without the required globals");
2744             parseerror(parser, "please declare the following globals: `time`, `self`");
2745             return false;
2746         }
2747
2748         if (!parser_next(parser))
2749             return false;
2750
2751         framenum = parse_expression_leave(parser, true);
2752         if (!framenum) {
2753             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2754             return false;
2755         }
2756         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
2757             ast_unref(framenum);
2758             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2759             return false;
2760         }
2761
2762         if (parser->tok != ',') {
2763             ast_unref(framenum);
2764             parseerror(parser, "expected comma after frame number in [frame,think] notation");
2765             parseerror(parser, "Got a %i\n", parser->tok);
2766             return false;
2767         }
2768
2769         if (!parser_next(parser)) {
2770             ast_unref(framenum);
2771             return false;
2772         }
2773
2774         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2775         {
2776             /* qc allows the use of not-yet-declared functions here
2777              * - this automatically creates a prototype */
2778             ast_value      *thinkfunc;
2779             ast_expression *functype = fld_think->expression.next;
2780
2781             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2782             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2783                 ast_unref(framenum);
2784                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2785                 return false;
2786             }
2787
2788             if (!parser_next(parser)) {
2789                 ast_unref(framenum);
2790                 ast_delete(thinkfunc);
2791                 return false;
2792             }
2793
2794             vec_push(parser->globals, (ast_expression*)thinkfunc);
2795             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2796             nextthink = (ast_expression*)thinkfunc;
2797
2798         } else {
2799             nextthink = parse_expression_leave(parser, true);
2800             if (!nextthink) {
2801                 ast_unref(framenum);
2802                 parseerror(parser, "expected a think-function in [frame,think] notation");
2803                 return false;
2804             }
2805         }
2806
2807         if (!ast_istype(nextthink, ast_value)) {
2808             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2809             retval = false;
2810         }
2811
2812         if (retval && parser->tok != ']') {
2813             parseerror(parser, "expected closing `]` for [frame,think] notation");
2814             retval = false;
2815         }
2816
2817         if (retval && !parser_next(parser)) {
2818             retval = false;
2819         }
2820
2821         if (retval && parser->tok != '{') {
2822             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2823             retval = false;
2824         }
2825
2826         if (!retval) {
2827             ast_unref(nextthink);
2828             ast_unref(framenum);
2829             return false;
2830         }
2831
2832         has_frame_think = true;
2833     }
2834
2835     block = ast_block_new(parser_ctx(parser));
2836     if (!block) {
2837         parseerror(parser, "failed to allocate block");
2838         if (has_frame_think) {
2839             ast_unref(nextthink);
2840             ast_unref(framenum);
2841         }
2842         return false;
2843     }
2844
2845     if (has_frame_think) {
2846         lex_ctx ctx;
2847         ast_expression *self_frame;
2848         ast_expression *self_nextthink;
2849         ast_expression *self_think;
2850         ast_expression *time_plus_1;
2851         ast_store *store_frame;
2852         ast_store *store_nextthink;
2853         ast_store *store_think;
2854
2855         ctx = parser_ctx(parser);
2856         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2857         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2858         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2859
2860         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2861                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2862
2863         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2864             if (self_frame)     ast_delete(self_frame);
2865             if (self_nextthink) ast_delete(self_nextthink);
2866             if (self_think)     ast_delete(self_think);
2867             if (time_plus_1)    ast_delete(time_plus_1);
2868             retval = false;
2869         }
2870
2871         if (retval)
2872         {
2873             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2874             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2875             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2876
2877             if (!store_frame) {
2878                 ast_delete(self_frame);
2879                 retval = false;
2880             }
2881             if (!store_nextthink) {
2882                 ast_delete(self_nextthink);
2883                 retval = false;
2884             }
2885             if (!store_think) {
2886                 ast_delete(self_think);
2887                 retval = false;
2888             }
2889             if (!retval) {
2890                 if (store_frame)     ast_delete(store_frame);
2891                 if (store_nextthink) ast_delete(store_nextthink);
2892                 if (store_think)     ast_delete(store_think);
2893                 retval = false;
2894             }
2895             ast_block_add_expr(block, (ast_expression*)store_frame);
2896             ast_block_add_expr(block, (ast_expression*)store_nextthink);
2897             ast_block_add_expr(block, (ast_expression*)store_think);
2898         }
2899
2900         if (!retval) {
2901             parseerror(parser, "failed to generate code for [frame,think]");
2902             ast_unref(nextthink);
2903             ast_unref(framenum);
2904             ast_delete(block);
2905             return false;
2906         }
2907     }
2908
2909     parser_enterblock(parser);
2910
2911     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2912         size_t     e;
2913         ast_value *param = var->expression.params[parami];
2914         ast_member *me[3];
2915
2916         if (param->expression.vtype != TYPE_VECTOR &&
2917             (param->expression.vtype != TYPE_FIELD ||
2918              param->expression.next->expression.vtype != TYPE_VECTOR))
2919         {
2920             continue;
2921         }
2922
2923         if (!create_vector_members(param, me)) {
2924             ast_block_delete(block);
2925             return false;
2926         }
2927
2928         for (e = 0; e < 3; ++e) {
2929             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2930             ast_block_collect(block, (ast_expression*)me[e]);
2931         }
2932     }
2933
2934     func = ast_function_new(ast_ctx(var), var->name, var);
2935     if (!func) {
2936         parseerror(parser, "failed to allocate function for `%s`", var->name);
2937         ast_block_delete(block);
2938         goto enderr;
2939     }
2940     vec_push(parser->functions, func);
2941
2942     parser->function = func;
2943     if (!parse_block_into(parser, block)) {
2944         ast_block_delete(block);
2945         goto enderrfn;
2946     }
2947
2948     vec_push(func->blocks, block);
2949
2950     parser->function = old;
2951     if (!parser_leaveblock(parser))
2952         retval = false;
2953     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2954         parseerror(parser, "internal error: local scopes left");
2955         retval = false;
2956     }
2957
2958     if (parser->tok == ';')
2959         return parser_next(parser);
2960     else if (opts_standard == COMPILER_QCC)
2961         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2962     return retval;
2963
2964 enderrfn:
2965     vec_pop(parser->functions);
2966     ast_function_delete(func);
2967     var->constval.vfunc = NULL;
2968
2969 enderr:
2970     (void)!parser_leaveblock(parser);
2971     parser->function = old;
2972     return false;
2973 }
2974
2975 static ast_expression *array_accessor_split(
2976     parser_t  *parser,
2977     ast_value *array,
2978     ast_value *index,
2979     size_t     middle,
2980     ast_expression *left,
2981     ast_expression *right
2982     )
2983 {
2984     ast_ifthen *ifthen;
2985     ast_binary *cmp;
2986
2987     lex_ctx ctx = ast_ctx(array);
2988
2989     if (!left || !right) {
2990         if (left)  ast_delete(left);
2991         if (right) ast_delete(right);
2992         return NULL;
2993     }
2994
2995     cmp = ast_binary_new(ctx, INSTR_LT,
2996                          (ast_expression*)index,
2997                          (ast_expression*)parser_const_float(parser, middle));
2998     if (!cmp) {
2999         ast_delete(left);
3000         ast_delete(right);
3001         parseerror(parser, "internal error: failed to create comparison for array setter");
3002         return NULL;
3003     }
3004
3005     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3006     if (!ifthen) {
3007         ast_delete(cmp); /* will delete left and right */
3008         parseerror(parser, "internal error: failed to create conditional jump for array setter");
3009         return NULL;
3010     }
3011
3012     return (ast_expression*)ifthen;
3013 }
3014
3015 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3016 {
3017     lex_ctx ctx = ast_ctx(array);
3018
3019     if (from+1 == afterend) {
3020         /* set this value */
3021         ast_block       *block;
3022         ast_return      *ret;
3023         ast_array_index *subscript;
3024         ast_store       *st;
3025         int assignop = type_store_instr[value->expression.vtype];
3026
3027         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3028             assignop = INSTR_STORE_V;
3029
3030         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3031         if (!subscript)
3032             return NULL;
3033
3034         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3035         if (!st) {
3036             ast_delete(subscript);
3037             return NULL;
3038         }
3039
3040         block = ast_block_new(ctx);
3041         if (!block) {
3042             ast_delete(st);
3043             return NULL;
3044         }
3045
3046         ast_block_add_expr(block, (ast_expression*)st);
3047
3048         ret = ast_return_new(ctx, NULL);
3049         if (!ret) {
3050             ast_delete(block);
3051             return NULL;
3052         }
3053
3054         ast_block_add_expr(block, (ast_expression*)ret);
3055
3056         return (ast_expression*)block;
3057     } else {
3058         ast_expression *left, *right;
3059         size_t diff = afterend - from;
3060         size_t middle = from + diff/2;
3061         left  = array_setter_node(parser, array, index, value, from, middle);
3062         right = array_setter_node(parser, array, index, value, middle, afterend);
3063         return array_accessor_split(parser, array, index, middle, left, right);
3064     }
3065 }
3066
3067 static ast_expression *array_field_setter_node(
3068     parser_t  *parser,
3069     ast_value *array,
3070     ast_value *entity,
3071     ast_value *index,
3072     ast_value *value,
3073     size_t     from,
3074     size_t     afterend)
3075 {
3076     lex_ctx ctx = ast_ctx(array);
3077
3078     if (from+1 == afterend) {
3079         /* set this value */
3080         ast_block       *block;
3081         ast_return      *ret;
3082         ast_entfield    *entfield;
3083         ast_array_index *subscript;
3084         ast_store       *st;
3085         int assignop = type_storep_instr[value->expression.vtype];
3086
3087         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3088             assignop = INSTR_STOREP_V;
3089
3090         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3091         if (!subscript)
3092             return NULL;
3093
3094         entfield = ast_entfield_new_force(ctx,
3095                                           (ast_expression*)entity,
3096                                           (ast_expression*)subscript,
3097                                           (ast_expression*)subscript);
3098         if (!entfield) {
3099             ast_delete(subscript);
3100             return NULL;
3101         }
3102
3103         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3104         if (!st) {
3105             ast_delete(entfield);
3106             return NULL;
3107         }
3108
3109         block = ast_block_new(ctx);
3110         if (!block) {
3111             ast_delete(st);
3112             return NULL;
3113         }
3114
3115         ast_block_add_expr(block, (ast_expression*)st);
3116
3117         ret = ast_return_new(ctx, NULL);
3118         if (!ret) {
3119             ast_delete(block);
3120             return NULL;
3121         }
3122
3123         ast_block_add_expr(block, (ast_expression*)ret);
3124
3125         return (ast_expression*)block;
3126     } else {
3127         ast_expression *left, *right;
3128         size_t diff = afterend - from;
3129         size_t middle = from + diff/2;
3130         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
3131         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3132         return array_accessor_split(parser, array, index, middle, left, right);
3133     }
3134 }
3135
3136 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3137 {
3138     lex_ctx ctx = ast_ctx(array);
3139
3140     if (from+1 == afterend) {
3141         ast_return      *ret;
3142         ast_array_index *subscript;
3143
3144         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3145         if (!subscript)
3146             return NULL;
3147
3148         ret = ast_return_new(ctx, (ast_expression*)subscript);
3149         if (!ret) {
3150             ast_delete(subscript);
3151             return NULL;
3152         }
3153
3154         return (ast_expression*)ret;
3155     } else {
3156         ast_expression *left, *right;
3157         size_t diff = afterend - from;
3158         size_t middle = from + diff/2;
3159         left  = array_getter_node(parser, array, index, from, middle);
3160         right = array_getter_node(parser, array, index, middle, afterend);
3161         return array_accessor_split(parser, array, index, middle, left, right);
3162     }
3163 }
3164
3165 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3166 {
3167     ast_function   *func = NULL;
3168     ast_value      *fval = NULL;
3169     ast_block      *body = NULL;
3170
3171     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3172     if (!fval) {
3173         parseerror(parser, "failed to create accessor function value");
3174         return false;
3175     }
3176
3177     func = ast_function_new(ast_ctx(array), funcname, fval);
3178     if (!func) {
3179         ast_delete(fval);
3180         parseerror(parser, "failed to create accessor function node");
3181         return false;
3182     }
3183
3184     body = ast_block_new(ast_ctx(array));
3185     if (!body) {
3186         parseerror(parser, "failed to create block for array accessor");
3187         ast_delete(fval);
3188         ast_delete(func);
3189         return false;
3190     }
3191
3192     vec_push(func->blocks, body);
3193     *out = fval;
3194
3195     vec_push(parser->accessors, fval);
3196
3197     return true;
3198 }
3199
3200 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3201 {
3202     ast_expression *root = NULL;
3203     ast_value      *index = NULL;
3204     ast_value      *value = NULL;
3205     ast_function   *func;
3206     ast_value      *fval;
3207
3208     if (!ast_istype(array->expression.next, ast_value)) {
3209         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3210         return false;
3211     }
3212
3213     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3214         return false;
3215     func = fval->constval.vfunc;
3216     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3217
3218     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3219     value = ast_value_copy((ast_value*)array->expression.next);
3220
3221     if (!index || !value) {
3222         parseerror(parser, "failed to create locals for array accessor");
3223         goto cleanup;
3224     }
3225     (void)!ast_value_set_name(value, "value"); /* not important */
3226     vec_push(fval->expression.params, index);
3227     vec_push(fval->expression.params, value);
3228
3229     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3230     if (!root) {
3231         parseerror(parser, "failed to build accessor search tree");
3232         goto cleanup;
3233     }
3234
3235     ast_block_add_expr(func->blocks[0], root);
3236     array->setter = fval;
3237     return true;
3238 cleanup:
3239     if (index) ast_delete(index);
3240     if (value) ast_delete(value);
3241     if (root)  ast_delete(root);
3242     ast_delete(func);
3243     ast_delete(fval);
3244     return false;
3245 }
3246
3247 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3248 {
3249     ast_expression *root = NULL;
3250     ast_value      *entity = NULL;
3251     ast_value      *index = NULL;
3252     ast_value      *value = NULL;
3253     ast_function   *func;
3254     ast_value      *fval;
3255
3256     if (!ast_istype(array->expression.next, ast_value)) {
3257         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3258         return false;
3259     }
3260
3261     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3262         return false;
3263     func = fval->constval.vfunc;
3264     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3265
3266     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3267     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
3268     value  = ast_value_copy((ast_value*)array->expression.next);
3269     if (!entity || !index || !value) {
3270         parseerror(parser, "failed to create locals for array accessor");
3271         goto cleanup;
3272     }
3273     (void)!ast_value_set_name(value, "value"); /* not important */
3274     vec_push(fval->expression.params, entity);
3275     vec_push(fval->expression.params, index);
3276     vec_push(fval->expression.params, value);
3277
3278     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3279     if (!root) {
3280         parseerror(parser, "failed to build accessor search tree");
3281         goto cleanup;
3282     }
3283
3284     ast_block_add_expr(func->blocks[0], root);
3285     array->setter = fval;
3286     return true;
3287 cleanup:
3288     if (entity) ast_delete(entity);
3289     if (index)  ast_delete(index);
3290     if (value)  ast_delete(value);
3291     if (root)   ast_delete(root);
3292     ast_delete(func);
3293     ast_delete(fval);
3294     return false;
3295 }
3296
3297 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3298 {
3299     ast_expression *root = NULL;
3300     ast_value      *index = NULL;
3301     ast_value      *fval;
3302     ast_function   *func;
3303
3304     /* NOTE: checking array->expression.next rather than elemtype since
3305      * for fields elemtype is a temporary fieldtype.
3306      */
3307     if (!ast_istype(array->expression.next, ast_value)) {
3308         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3309         return false;
3310     }
3311
3312     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3313         return false;
3314     func = fval->constval.vfunc;
3315     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3316
3317     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3318
3319     if (!index) {
3320         parseerror(parser, "failed to create locals for array accessor");
3321         goto cleanup;
3322     }
3323     vec_push(fval->expression.params, index);
3324
3325     root = array_getter_node(parser, array, index, 0, array->expression.count);
3326     if (!root) {
3327         parseerror(parser, "failed to build accessor search tree");
3328         goto cleanup;
3329     }
3330
3331     ast_block_add_expr(func->blocks[0], root);
3332     array->getter = fval;
3333     return true;
3334 cleanup:
3335     if (index) ast_delete(index);
3336     if (root)  ast_delete(root);
3337     ast_delete(func);
3338     ast_delete(fval);
3339     return false;
3340 }
3341
3342 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3343 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3344 {
3345     lex_ctx     ctx;
3346     size_t      i;
3347     ast_value **params;
3348     ast_value  *param;
3349     ast_value  *fval;
3350     bool        first = true;
3351     bool        variadic = false;
3352
3353     ctx = parser_ctx(parser);
3354
3355     /* for the sake of less code we parse-in in this function */
3356     if (!parser_next(parser)) {
3357         parseerror(parser, "expected parameter list");
3358         return NULL;
3359     }
3360
3361     params = NULL;
3362
3363     /* parse variables until we hit a closing paren */
3364     while (parser->tok != ')') {
3365         if (!first) {
3366             /* there must be commas between them */
3367             if (parser->tok != ',') {
3368                 parseerror(parser, "expected comma or end of parameter list");
3369                 goto on_error;
3370             }
3371             if (!parser_next(parser)) {
3372                 parseerror(parser, "expected parameter");
3373                 goto on_error;
3374             }
3375         }
3376         first = false;
3377
3378         if (parser->tok == TOKEN_DOTS) {
3379             /* '...' indicates a varargs function */
3380             variadic = true;
3381             if (!parser_next(parser)) {
3382                 parseerror(parser, "expected parameter");
3383                 return NULL;
3384             }
3385             if (parser->tok != ')') {
3386                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3387                 goto on_error;
3388             }
3389         }
3390         else
3391         {
3392             /* for anything else just parse a typename */
3393             param = parse_typename(parser, NULL, NULL);
3394             if (!param)
3395                 goto on_error;
3396             vec_push(params, param);
3397             if (param->expression.vtype >= TYPE_VARIANT) {
3398                 char typename[1024];
3399                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3400                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3401                 goto on_error;
3402             }
3403         }
3404     }
3405
3406     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3407         vec_free(params);
3408
3409     /* sanity check */
3410     if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3411         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3412
3413     /* parse-out */
3414     if (!parser_next(parser)) {
3415         parseerror(parser, "parse error after typename");
3416         goto on_error;
3417     }
3418
3419     /* now turn 'var' into a function type */
3420     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3421     fval->expression.next     = (ast_expression*)var;
3422     fval->expression.variadic = variadic;
3423     var = fval;
3424
3425     var->expression.params = params;
3426     params = NULL;
3427
3428     return var;
3429
3430 on_error:
3431     ast_delete(var);
3432     for (i = 0; i < vec_size(params); ++i)
3433         ast_delete(params[i]);
3434     vec_free(params);
3435     return NULL;
3436 }
3437
3438 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3439 {
3440     ast_expression *cexp;
3441     ast_value      *cval, *tmp;
3442     lex_ctx ctx;
3443
3444     ctx = parser_ctx(parser);
3445
3446     if (!parser_next(parser)) {
3447         ast_delete(var);
3448         parseerror(parser, "expected array-size");
3449         return NULL;
3450     }
3451
3452     cexp = parse_expression_leave(parser, true);
3453
3454     if (!cexp || !ast_istype(cexp, ast_value)) {
3455         if (cexp)
3456             ast_unref(cexp);
3457         ast_delete(var);
3458         parseerror(parser, "expected array-size as constant positive integer");
3459         return NULL;
3460     }
3461     cval = (ast_value*)cexp;
3462
3463     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3464     tmp->expression.next = (ast_expression*)var;
3465     var = tmp;
3466
3467     if (cval->expression.vtype == TYPE_INTEGER)
3468         tmp->expression.count = cval->constval.vint;
3469     else if (cval->expression.vtype == TYPE_FLOAT)
3470         tmp->expression.count = cval->constval.vfloat;
3471     else {
3472         ast_unref(cexp);
3473         ast_delete(var);
3474         parseerror(parser, "array-size must be a positive integer constant");
3475         return NULL;
3476     }
3477     ast_unref(cexp);
3478
3479     if (parser->tok != ']') {
3480         ast_delete(var);
3481         parseerror(parser, "expected ']' after array-size");
3482         return NULL;
3483     }
3484     if (!parser_next(parser)) {
3485         ast_delete(var);
3486         parseerror(parser, "error after parsing array size");
3487         return NULL;
3488     }
3489     return var;
3490 }
3491
3492 /* Parse a complete typename.
3493  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3494  * but when parsing variables separated by comma
3495  * 'storebase' should point to where the base-type should be kept.
3496  * The base type makes up every bit of type information which comes *before* the
3497  * variable name.
3498  *
3499  * The following will be parsed in its entirety:
3500  *     void() foo()
3501  * The 'basetype' in this case is 'void()'
3502  * and if there's a comma after it, say:
3503  *     void() foo(), bar
3504  * then the type-information 'void()' can be stored in 'storebase'
3505  */
3506 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3507 {
3508     ast_value *var, *tmp;
3509     lex_ctx    ctx;
3510
3511     const char *name = NULL;
3512     bool        isfield  = false;
3513     bool        wasarray = false;
3514     size_t      morefields = 0;
3515
3516     ctx = parser_ctx(parser);
3517
3518     /* types may start with a dot */
3519     if (parser->tok == '.') {
3520         isfield = true;
3521         /* if we parsed a dot we need a typename now */
3522         if (!parser_next(parser)) {
3523             parseerror(parser, "expected typename for field definition");
3524             return NULL;
3525         }
3526
3527         /* Further dots are handled seperately because they won't be part of the
3528          * basetype
3529          */
3530         while (parser->tok == '.') {
3531             ++morefields;
3532             if (!parser_next(parser)) {
3533                 parseerror(parser, "expected typename for field definition");
3534                 return NULL;
3535             }
3536         }
3537     }
3538     if (parser->tok == TOKEN_IDENT)
3539         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3540     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3541         parseerror(parser, "expected typename");
3542         return NULL;
3543     }
3544
3545     /* generate the basic type value */
3546     if (cached_typedef) {
3547         var = ast_value_copy(cached_typedef);
3548         ast_value_set_name(var, "<type(from_def)>");
3549     } else
3550         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3551
3552     for (; morefields; --morefields) {
3553         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3554         tmp->expression.next = (ast_expression*)var;
3555         var = tmp;
3556     }
3557
3558     /* do not yet turn into a field - remember:
3559      * .void() foo; is a field too
3560      * .void()() foo; is a function
3561      */
3562
3563     /* parse on */
3564     if (!parser_next(parser)) {
3565         ast_delete(var);
3566         parseerror(parser, "parse error after typename");
3567         return NULL;
3568     }
3569
3570     /* an opening paren now starts the parameter-list of a function
3571      * this is where original-QC has parameter lists.
3572      * We allow a single parameter list here.
3573      * Much like fteqcc we don't allow `float()() x`
3574      */
3575     if (parser->tok == '(') {
3576         var = parse_parameter_list(parser, var);
3577         if (!var)
3578             return NULL;
3579     }
3580
3581     /* store the base if requested */
3582     if (storebase) {
3583         *storebase = ast_value_copy(var);
3584         if (isfield) {
3585             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3586             tmp->expression.next = (ast_expression*)*storebase;
3587             *storebase = tmp;
3588         }
3589     }
3590
3591     /* there may be a name now */
3592     if (parser->tok == TOKEN_IDENT) {
3593         name = util_strdup(parser_tokval(parser));
3594         /* parse on */
3595         if (!parser_next(parser)) {
3596             ast_delete(var);
3597             parseerror(parser, "error after variable or field declaration");
3598             return NULL;
3599         }
3600     }
3601
3602     /* now this may be an array */
3603     if (parser->tok == '[') {
3604         wasarray = true;
3605         var = parse_arraysize(parser, var);
3606         if (!var)
3607             return NULL;
3608     }
3609
3610     /* This is the point where we can turn it into a field */
3611     if (isfield) {
3612         /* turn it into a field if desired */
3613         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3614         tmp->expression.next = (ast_expression*)var;
3615         var = tmp;
3616     }
3617
3618     /* now there may be function parens again */
3619     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3620         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3621     if (parser->tok == '(' && wasarray)
3622         parseerror(parser, "arrays as part of a return type is not supported");
3623     while (parser->tok == '(') {
3624         var = parse_parameter_list(parser, var);
3625         if (!var) {
3626             if (name)
3627                 mem_d((void*)name);
3628             ast_delete(var);
3629             return NULL;
3630         }
3631     }
3632
3633     /* finally name it */
3634     if (name) {
3635         if (!ast_value_set_name(var, name)) {
3636             ast_delete(var);
3637             parseerror(parser, "internal error: failed to set name");
3638             return NULL;
3639         }
3640         /* free the name, ast_value_set_name duplicates */
3641         mem_d((void*)name);
3642     }
3643
3644     return var;
3645 }
3646
3647 static bool parse_typedef(parser_t *parser)
3648 {
3649     ast_value      *typevar, *oldtype;
3650     ast_expression *old;
3651
3652     typevar = parse_typename(parser, NULL, NULL);
3653
3654     if (!typevar)
3655         return false;
3656
3657     if ( (old = parser_find_var(parser, typevar->name)) ) {
3658         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3659                    " -> `%s` has been declared here: %s:%i",
3660                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3661         ast_delete(typevar);
3662         return false;
3663     }
3664
3665     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3666         parseerror(parser, "type `%s` has already been declared here: %s:%i",
3667                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3668         ast_delete(typevar);
3669         return false;
3670     }
3671
3672     vec_push(parser->_typedefs, typevar);
3673     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3674
3675     if (parser->tok != ';') {
3676         parseerror(parser, "expected semicolon after typedef");
3677         return false;
3678     }
3679     if (!parser_next(parser)) {
3680         parseerror(parser, "parse error after typedef");
3681         return false;
3682     }
3683
3684     return true;
3685 }
3686
3687 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef)
3688 {
3689     ast_value *var;
3690     ast_value *proto;
3691     ast_expression *old;
3692     bool       was_end;
3693     size_t     i;
3694
3695     ast_value *basetype = NULL;
3696     bool      retval    = true;
3697     bool      isparam   = false;
3698     bool      isvector  = false;
3699     bool      cleanvar  = true;
3700     bool      wasarray  = false;
3701
3702     ast_member *me[3];
3703
3704     /* get the first complete variable */
3705     var = parse_typename(parser, &basetype, cached_typedef);
3706     if (!var) {
3707         if (basetype)
3708             ast_delete(basetype);
3709         return false;
3710     }
3711
3712     while (true) {
3713         proto = NULL;
3714         wasarray = false;
3715
3716         /* Part 0: finish the type */
3717         if (parser->tok == '(') {
3718             if (opts_standard == COMPILER_QCC)
3719                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3720             var = parse_parameter_list(parser, var);
3721             if (!var) {
3722                 retval = false;
3723                 goto cleanup;
3724             }
3725         }
3726         /* we only allow 1-dimensional arrays */
3727         if (parser->tok == '[') {
3728             wasarray = true;
3729             var = parse_arraysize(parser, var);
3730             if (!var) {
3731                 retval = false;
3732                 goto cleanup;
3733             }
3734         }
3735         if (parser->tok == '(' && wasarray) {
3736             parseerror(parser, "arrays as part of a return type is not supported");
3737             /* we'll still parse the type completely for now */
3738         }
3739         /* for functions returning functions */
3740         while (parser->tok == '(') {
3741             if (opts_standard == COMPILER_QCC)
3742                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3743             var = parse_parameter_list(parser, var);
3744             if (!var) {
3745                 retval = false;
3746                 goto cleanup;
3747             }
3748         }
3749
3750         var->cvq = qualifier;
3751
3752         /* Part 1:
3753          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3754          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3755          * is then filled with the previous definition and the parameter-names replaced.
3756          */
3757         if (!localblock) {
3758             /* Deal with end_sys_ vars */
3759             was_end = false;
3760             if (!strcmp(var->name, "end_sys_globals")) {
3761                 parser->crc_globals = vec_size(parser->globals);
3762                 was_end = true;
3763             }
3764             else if (!strcmp(var->name, "end_sys_fields")) {
3765                 parser->crc_fields = vec_size(parser->fields);
3766                 was_end = true;
3767             }
3768             if (was_end && var->expression.vtype == TYPE_FIELD) {
3769                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3770                                  "global '%s' hint should not be a field",
3771                                  parser_tokval(parser)))
3772                 {
3773                     retval = false;
3774                     goto cleanup;
3775                 }
3776             }
3777
3778             if (!nofields && var->expression.vtype == TYPE_FIELD)
3779             {
3780                 /* deal with field declarations */
3781                 old = parser_find_field(parser, var->name);
3782                 if (old) {
3783                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3784                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3785                     {
3786                         retval = false;
3787                         goto cleanup;
3788                     }
3789                     ast_delete(var);
3790                     var = NULL;
3791                     goto skipvar;
3792                     /*
3793                     parseerror(parser, "field `%s` already declared here: %s:%i",
3794                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3795                     retval = false;
3796                     goto cleanup;
3797                     */
3798                 }
3799                 if (opts_standard == COMPILER_QCC &&
3800                     (old = parser_find_global(parser, var->name)))
3801                 {
3802                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3803                     parseerror(parser, "field `%s` already declared here: %s:%i",
3804                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3805                     retval = false;
3806                     goto cleanup;
3807                 }
3808             }
3809             else
3810             {
3811                 /* deal with other globals */
3812                 old = parser_find_global(parser, var->name);
3813                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3814                 {
3815                     /* This is a function which had a prototype */
3816                     if (!ast_istype(old, ast_value)) {
3817                         parseerror(parser, "internal error: prototype is not an ast_value");
3818                         retval = false;
3819                         goto cleanup;
3820                     }
3821                     proto = (ast_value*)old;
3822                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3823                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3824                                    proto->name,
3825                                    ast_ctx(proto).file, ast_ctx(proto).line);
3826                         retval = false;
3827                         goto cleanup;
3828                     }
3829                     /* we need the new parameter-names */
3830                     for (i = 0; i < vec_size(proto->expression.params); ++i)
3831                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3832                     ast_delete(var);
3833                     var = proto;
3834                 }
3835                 else
3836                 {
3837                     /* other globals */
3838                     if (old) {
3839                         if (opts_standard == COMPILER_GMQCC) {
3840                             parseerror(parser, "global `%s` already declared here: %s:%i",
3841                                        var->name, ast_ctx(old).file, ast_ctx(old).line);
3842                             retval = false;
3843                             goto cleanup;
3844                         } else {
3845                             if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3846                                              "global `%s` already declared here: %s:%i",
3847                                              var->name, ast_ctx(old).file, ast_ctx(old).line))
3848                             {
3849                                 retval = false;
3850                                 goto cleanup;
3851                             }
3852                             proto = (ast_value*)old;
3853                             if (!ast_istype(old, ast_value)) {
3854                                 parseerror(parser, "internal error: not an ast_value");
3855                                 retval = false;
3856                                 proto = NULL;
3857                                 goto cleanup;
3858                             }
3859                             ast_delete(var);
3860                             var = proto;
3861                         }
3862                     }
3863                     if (opts_standard == COMPILER_QCC &&
3864                         (old = parser_find_field(parser, var->name)))
3865                     {
3866                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3867                         parseerror(parser, "global `%s` already declared here: %s:%i",
3868                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3869                         retval = false;
3870                         goto cleanup;
3871                     }
3872                 }
3873             }
3874         }
3875         else /* it's not a global */
3876         {
3877             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3878             if (old && !isparam) {
3879                 parseerror(parser, "local `%s` already declared here: %s:%i",
3880                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3881                 retval = false;
3882                 goto cleanup;
3883             }
3884             old = parser_find_local(parser, var->name, 0, &isparam);
3885             if (old && isparam) {
3886                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3887                                  "local `%s` is shadowing a parameter", var->name))
3888                 {
3889                     parseerror(parser, "local `%s` already declared here: %s:%i",
3890                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3891                     retval = false;
3892                     goto cleanup;
3893                 }
3894                 if (opts_standard != COMPILER_GMQCC) {
3895                     ast_delete(var);
3896                     var = NULL;
3897                     goto skipvar;
3898                 }
3899             }
3900         }
3901
3902         /* Part 2:
3903          * Create the global/local, and deal with vector types.
3904          */
3905         if (!proto) {
3906             if (var->expression.vtype == TYPE_VECTOR)
3907                 isvector = true;
3908             else if (var->expression.vtype == TYPE_FIELD &&
3909                      var->expression.next->expression.vtype == TYPE_VECTOR)
3910                 isvector = true;
3911
3912             if (isvector) {
3913                 if (!create_vector_members(var, me)) {
3914                     retval = false;
3915                     goto cleanup;
3916                 }
3917             }
3918
3919             if (!localblock) {
3920                 /* deal with global variables, fields, functions */
3921                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
3922                     var->isfield = true;
3923                     vec_push(parser->fields, (ast_expression*)var);
3924                     util_htset(parser->htfields, var->name, var);
3925                     if (isvector) {
3926                         for (i = 0; i < 3; ++i) {
3927                             vec_push(parser->fields, (ast_expression*)me[i]);
3928                             util_htset(parser->htfields, me[i]->name, me[i]);
3929                         }
3930                     }
3931                 }
3932                 else {
3933                     vec_push(parser->globals, (ast_expression*)var);
3934                     util_htset(parser->htglobals, var->name, var);
3935                     if (isvector) {
3936                         for (i = 0; i < 3; ++i) {
3937                             vec_push(parser->globals, (ast_expression*)me[i]);
3938                             util_htset(parser->htglobals, me[i]->name, me[i]);
3939                         }
3940                     }
3941                 }
3942             } else {
3943                 vec_push(localblock->locals, var);
3944                 parser_addlocal(parser, var->name, (ast_expression*)var);
3945                 if (isvector) {
3946                     for (i = 0; i < 3; ++i) {
3947                         parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3948                         ast_block_collect(localblock, (ast_expression*)me[i]);
3949                     }
3950                 }
3951             }
3952
3953         }
3954         me[0] = me[1] = me[2] = NULL;
3955         cleanvar = false;
3956         /* Part 2.2
3957          * deal with arrays
3958          */
3959         if (var->expression.vtype == TYPE_ARRAY) {
3960             char name[1024];
3961             snprintf(name, sizeof(name), "%s##SET", var->name);
3962             if (!parser_create_array_setter(parser, var, name))
3963                 goto cleanup;
3964             snprintf(name, sizeof(name), "%s##GET", var->name);
3965             if (!parser_create_array_getter(parser, var, var->expression.next, name))
3966                 goto cleanup;
3967         }
3968         else if (!localblock && !nofields &&
3969                  var->expression.vtype == TYPE_FIELD &&
3970                  var->expression.next->expression.vtype == TYPE_ARRAY)
3971         {
3972             char name[1024];
3973             ast_expression *telem;
3974             ast_value      *tfield;
3975             ast_value      *array = (ast_value*)var->expression.next;
3976
3977             if (!ast_istype(var->expression.next, ast_value)) {
3978                 parseerror(parser, "internal error: field element type must be an ast_value");
3979                 goto cleanup;
3980             }
3981
3982             snprintf(name, sizeof(name), "%s##SETF", var->name);
3983             if (!parser_create_array_field_setter(parser, array, name))
3984                 goto cleanup;
3985
3986             telem = ast_type_copy(ast_ctx(var), array->expression.next);
3987             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3988             tfield->expression.next = telem;
3989             snprintf(name, sizeof(name), "%s##GETFP", var->name);
3990             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3991                 ast_delete(tfield);
3992                 goto cleanup;
3993             }
3994             ast_delete(tfield);
3995         }
3996
3997 skipvar:
3998         if (parser->tok == ';') {
3999             ast_delete(basetype);
4000             if (!parser_next(parser)) {
4001                 parseerror(parser, "error after variable declaration");
4002                 return false;
4003             }
4004             return true;
4005         }
4006
4007         if (parser->tok == ',')
4008             goto another;
4009
4010         /*
4011         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4012         */
4013         if (!var) {
4014             parseerror(parser, "missing comma or semicolon while parsing variables");
4015             break;
4016         }
4017
4018         if (localblock && opts_standard == COMPILER_QCC) {
4019             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4020                              "initializing expression turns variable `%s` into a constant in this standard",
4021                              var->name) )
4022             {
4023                 break;
4024             }
4025         }
4026
4027         if (parser->tok != '{') {
4028             if (parser->tok != '=') {
4029                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4030                 break;
4031             }
4032
4033             if (!parser_next(parser)) {
4034                 parseerror(parser, "error parsing initializer");
4035                 break;
4036             }
4037         }
4038         else if (opts_standard == COMPILER_QCC) {
4039             parseerror(parser, "expected '=' before function body in this standard");
4040         }
4041
4042         if (parser->tok == '#') {
4043             ast_function *func = NULL;
4044
4045             if (localblock) {
4046                 parseerror(parser, "cannot declare builtins within functions");
4047                 break;
4048             }
4049             if (var->expression.vtype != TYPE_FUNCTION) {
4050                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4051                 break;
4052             }
4053             if (!parser_next(parser)) {
4054                 parseerror(parser, "expected builtin number");
4055                 break;
4056             }
4057             if (parser->tok != TOKEN_INTCONST) {
4058                 parseerror(parser, "builtin number must be an integer constant");
4059                 break;
4060             }
4061             if (parser_token(parser)->constval.i < 0) {
4062                 parseerror(parser, "builtin number must be an integer greater than zero");
4063                 break;
4064             }
4065
4066             if (var->hasvalue) {
4067                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4068                                     "builtin `%s` has already been defined\n"
4069                                     " -> previous declaration here: %s:%i",
4070                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4071             }
4072             else
4073             {
4074                 func = ast_function_new(ast_ctx(var), var->name, var);
4075                 if (!func) {
4076                     parseerror(parser, "failed to allocate function for `%s`", var->name);
4077                     break;
4078                 }
4079                 vec_push(parser->functions, func);
4080
4081                 func->builtin = -parser_token(parser)->constval.i-1;
4082             }
4083
4084             if (!parser_next(parser)) {
4085                 parseerror(parser, "expected comma or semicolon");
4086                 if (func)
4087                     ast_function_delete(func);
4088                 var->constval.vfunc = NULL;
4089                 break;
4090             }
4091         }
4092         else if (parser->tok == '{' || parser->tok == '[')
4093         {
4094             size_t i;
4095             if (localblock) {
4096                 parseerror(parser, "cannot declare functions within functions");
4097                 break;
4098             }
4099
4100             if (proto)
4101                 ast_ctx(proto) = parser_ctx(parser);
4102
4103             if (!parse_function_body(parser, var))
4104                 break;
4105             ast_delete(basetype);
4106             for (i = 0; i < vec_size(parser->gotos); ++i)
4107                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4108             vec_free(parser->gotos);
4109             vec_free(parser->labels);
4110             return true;
4111         } else {
4112             ast_expression *cexp;
4113             ast_value      *cval;
4114
4115             cexp = parse_expression_leave(parser, true);
4116             if (!cexp)
4117                 break;
4118
4119             if (!localblock) {
4120                 cval = (ast_value*)cexp;
4121                 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4122                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4123                 else
4124                 {
4125                     if (opts_standard != COMPILER_GMQCC &&
4126                         !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4127                         qualifier != CV_VAR)
4128                     {
4129                         var->cvq = CV_CONST;
4130                     }
4131                     var->hasvalue = true;
4132                     if (cval->expression.vtype == TYPE_STRING)
4133                         var->constval.vstring = parser_strdup(cval->constval.vstring);
4134                     else if (cval->expression.vtype == TYPE_FIELD)
4135                         var->constval.vfield = cval;
4136                     else
4137                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4138                     ast_unref(cval);
4139                 }
4140             } else {
4141                 bool cvq;
4142                 shunt sy = { NULL, NULL };
4143                 cvq = var->cvq;
4144                 var->cvq = CV_NONE;
4145                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4146                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4147                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4148                 if (!parser_sy_pop(parser, &sy))
4149                     ast_unref(cexp);
4150                 else {
4151                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4152                         parseerror(parser, "internal error: leaked operands");
4153                     ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out);
4154                 }
4155                 vec_free(sy.out);
4156                 vec_free(sy.ops);
4157                 var->cvq = cvq;
4158             }
4159         }
4160
4161 another:
4162         if (parser->tok == ',') {
4163             if (!parser_next(parser)) {
4164                 parseerror(parser, "expected another variable");
4165                 break;
4166             }
4167
4168             if (parser->tok != TOKEN_IDENT) {
4169                 parseerror(parser, "expected another variable");
4170                 break;
4171             }
4172             var = ast_value_copy(basetype);
4173             cleanvar = true;
4174             ast_value_set_name(var, parser_tokval(parser));
4175             if (!parser_next(parser)) {
4176                 parseerror(parser, "error parsing variable declaration");
4177                 break;
4178             }
4179             continue;
4180         }
4181
4182         if (parser->tok != ';') {
4183             parseerror(parser, "missing semicolon after variables");
4184             break;
4185         }
4186
4187         if (!parser_next(parser)) {
4188             parseerror(parser, "parse error after variable declaration");
4189             break;
4190         }
4191
4192         ast_delete(basetype);
4193         return true;
4194     }
4195
4196     if (cleanvar && var)
4197         ast_delete(var);
4198     ast_delete(basetype);
4199     return false;
4200
4201 cleanup:
4202     ast_delete(basetype);
4203     if (cleanvar && var)
4204         ast_delete(var);
4205     if (me[0]) ast_member_delete(me[0]);
4206     if (me[1]) ast_member_delete(me[1]);
4207     if (me[2]) ast_member_delete(me[2]);
4208     return retval;
4209 }
4210
4211 static bool parser_global_statement(parser_t *parser)
4212 {
4213     ast_value *istype = NULL;
4214     if (parser->tok == TOKEN_IDENT)
4215         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4216
4217     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4218     {
4219         return parse_variable(parser, NULL, false, CV_NONE, istype);
4220     }
4221     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
4222     {
4223         if (!strcmp(parser_tokval(parser), "var")) {
4224             if (!parser_next(parser)) {
4225                 parseerror(parser, "expected variable declaration after 'var'");
4226                 return false;
4227             }
4228             if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "const")) {
4229                 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `const` after 'var' qualifier");
4230                 if (!parser_next(parser)) {
4231                     parseerror(parser, "expected variable declaration after 'const var'");
4232                     return false;
4233                 }
4234             }
4235             return parse_variable(parser, NULL, true, CV_VAR, NULL);
4236         }
4237     }
4238     else if (parser->tok == TOKEN_KEYWORD)
4239     {
4240         if (!strcmp(parser_tokval(parser), "const")) {
4241             if (!parser_next(parser)) {
4242                 parseerror(parser, "expected variable declaration after 'const'");
4243                 return false;
4244             }
4245             if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var")) {
4246                 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `var` after const qualifier");
4247                 if (!parser_next(parser)) {
4248                     parseerror(parser, "expected variable declaration after 'const var'");
4249                     return false;
4250                 }
4251             }
4252             return parse_variable(parser, NULL, true, CV_CONST, NULL);
4253         }
4254         else if (!strcmp(parser_tokval(parser), "typedef")) {
4255             if (!parser_next(parser)) {
4256                 parseerror(parser, "expected type definition after 'typedef'");
4257                 return false;
4258             }
4259             return parse_typedef(parser);
4260         }
4261         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4262         return false;
4263     }
4264     else if (parser->tok == '$')
4265     {
4266         if (!parser_next(parser)) {
4267             parseerror(parser, "parse error");
4268             return false;
4269         }
4270     }
4271     else
4272     {
4273         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4274         return false;
4275     }
4276     return true;
4277 }
4278
4279 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4280 {
4281     return util_crc16(old, str, strlen(str));
4282 }
4283
4284 static void progdefs_crc_file(const char *str)
4285 {
4286     /* write to progdefs.h here */
4287     (void)str;
4288 }
4289
4290 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4291 {
4292     old = progdefs_crc_sum(old, str);
4293     progdefs_crc_file(str);
4294     return old;
4295 }
4296
4297 static void generate_checksum(parser_t *parser)
4298 {
4299     uint16_t   crc = 0xFFFF;
4300     size_t     i;
4301     ast_value *value;
4302
4303         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4304         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4305         /*
4306         progdefs_crc_file("\tint\tpad;\n");
4307         progdefs_crc_file("\tint\tofs_return[3];\n");
4308         progdefs_crc_file("\tint\tofs_parm0[3];\n");
4309         progdefs_crc_file("\tint\tofs_parm1[3];\n");
4310         progdefs_crc_file("\tint\tofs_parm2[3];\n");
4311         progdefs_crc_file("\tint\tofs_parm3[3];\n");
4312         progdefs_crc_file("\tint\tofs_parm4[3];\n");
4313         progdefs_crc_file("\tint\tofs_parm5[3];\n");
4314         progdefs_crc_file("\tint\tofs_parm6[3];\n");
4315         progdefs_crc_file("\tint\tofs_parm7[3];\n");
4316         */
4317         for (i = 0; i < parser->crc_globals; ++i) {
4318             if (!ast_istype(parser->globals[i], ast_value))
4319                 continue;
4320             value = (ast_value*)(parser->globals[i]);
4321             switch (value->expression.vtype) {
4322                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4323                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4324                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4325                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4326                 default:
4327                     crc = progdefs_crc_both(crc, "\tint\t");
4328                     break;
4329             }
4330             crc = progdefs_crc_both(crc, value->name);
4331             crc = progdefs_crc_both(crc, ";\n");
4332         }
4333         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4334         for (i = 0; i < parser->crc_fields; ++i) {
4335             if (!ast_istype(parser->fields[i], ast_value))
4336                 continue;
4337             value = (ast_value*)(parser->fields[i]);
4338             switch (value->expression.next->expression.vtype) {
4339                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4340                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4341                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4342                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4343                 default:
4344                     crc = progdefs_crc_both(crc, "\tint\t");
4345                     break;
4346             }
4347             crc = progdefs_crc_both(crc, value->name);
4348             crc = progdefs_crc_both(crc, ";\n");
4349         }
4350         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4351
4352         code_crc = crc;
4353 }
4354
4355 static parser_t *parser;
4356
4357 bool parser_init()
4358 {
4359     size_t i;
4360
4361     parser = (parser_t*)mem_a(sizeof(parser_t));
4362     if (!parser)
4363         return false;
4364
4365     memset(parser, 0, sizeof(*parser));
4366
4367     for (i = 0; i < operator_count; ++i) {
4368         if (operators[i].id == opid1('=')) {
4369             parser->assign_op = operators+i;
4370             break;
4371         }
4372     }
4373     if (!parser->assign_op) {
4374         printf("internal error: initializing parser: failed to find assign operator\n");
4375         mem_d(parser);
4376         return false;
4377     }
4378
4379     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
4380     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4381     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4382     vec_push(parser->_blocktypedefs, 0);
4383     return true;
4384 }
4385
4386 bool parser_compile()
4387 {
4388     /* initial lexer/parser state */
4389     parser->lex->flags.noops = true;
4390
4391     if (parser_next(parser))
4392     {
4393         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4394         {
4395             if (!parser_global_statement(parser)) {
4396                 if (parser->tok == TOKEN_EOF)
4397                     parseerror(parser, "unexpected eof");
4398                 else if (!parser->errors)
4399                     parseerror(parser, "there have been errors, bailing out");
4400                 lex_close(parser->lex);
4401                 parser->lex = NULL;
4402                 return false;
4403             }
4404         }
4405     } else {
4406         parseerror(parser, "parse error");
4407         lex_close(parser->lex);
4408         parser->lex = NULL;
4409         return false;
4410     }
4411
4412     lex_close(parser->lex);
4413     parser->lex = NULL;
4414
4415     return !parser->errors;
4416 }
4417
4418 bool parser_compile_file(const char *filename)
4419 {
4420     parser->lex = lex_open(filename);
4421     if (!parser->lex) {
4422         con_err("failed to open file \"%s\"\n", filename);
4423         return false;
4424     }
4425     return parser_compile();
4426 }
4427
4428 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4429 {
4430     parser->lex = lex_open_string(str, len, name);
4431     if (!parser->lex) {
4432         con_err("failed to create lexer for string \"%s\"\n", name);
4433         return false;
4434     }
4435     return parser_compile();
4436 }
4437
4438 bool parser_compile_string(const char *name, const char *str)
4439 {
4440     parser->lex = lex_open_string(str, strlen(str), name);
4441     if (!parser->lex) {
4442         con_err("failed to create lexer for string \"%s\"\n", name);
4443         return false;
4444     }
4445     return parser_compile();
4446 }
4447
4448 void parser_cleanup()
4449 {
4450     size_t i;
4451     for (i = 0; i < vec_size(parser->accessors); ++i) {
4452         ast_delete(parser->accessors[i]->constval.vfunc);
4453         parser->accessors[i]->constval.vfunc = NULL;
4454         ast_delete(parser->accessors[i]);
4455     }
4456     for (i = 0; i < vec_size(parser->functions); ++i) {
4457         ast_delete(parser->functions[i]);
4458     }
4459     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4460         ast_delete(parser->imm_vector[i]);
4461     }
4462     for (i = 0; i < vec_size(parser->imm_string); ++i) {
4463         ast_delete(parser->imm_string[i]);
4464     }
4465     for (i = 0; i < vec_size(parser->imm_float); ++i) {
4466         ast_delete(parser->imm_float[i]);
4467     }
4468     for (i = 0; i < vec_size(parser->fields); ++i) {
4469         ast_delete(parser->fields[i]);
4470     }
4471     for (i = 0; i < vec_size(parser->globals); ++i) {
4472         ast_delete(parser->globals[i]);
4473     }
4474     vec_free(parser->accessors);
4475     vec_free(parser->functions);
4476     vec_free(parser->imm_vector);
4477     vec_free(parser->imm_string);
4478     vec_free(parser->imm_float);
4479     vec_free(parser->globals);
4480     vec_free(parser->fields);
4481
4482     for (i = 0; i < vec_size(parser->variables); ++i)
4483         util_htdel(parser->variables[i]);
4484     vec_free(parser->variables);
4485     vec_free(parser->_blocklocals);
4486     vec_free(parser->_locals);
4487
4488     for (i = 0; i < vec_size(parser->_typedefs); ++i)
4489         ast_delete(parser->_typedefs[i]);
4490     vec_free(parser->_typedefs);
4491     for (i = 0; i < vec_size(parser->typedefs); ++i)
4492         util_htdel(parser->typedefs[i]);
4493     vec_free(parser->typedefs);
4494     vec_free(parser->_blocktypedefs);
4495
4496     vec_free(parser->_block_ctx);
4497
4498     vec_free(parser->labels);
4499     vec_free(parser->gotos);
4500
4501     mem_d(parser);
4502 }
4503
4504 bool parser_finish(const char *output)
4505 {
4506     size_t i;
4507     ir_builder *ir;
4508     bool retval = true;
4509
4510     if (!parser->errors)
4511     {
4512         ir = ir_builder_new("gmqcc_out");
4513         if (!ir) {
4514             con_out("failed to allocate builder\n");
4515             return false;
4516         }
4517
4518         for (i = 0; i < vec_size(parser->fields); ++i) {
4519             ast_value *field;
4520             bool hasvalue;
4521             if (!ast_istype(parser->fields[i], ast_value))
4522                 continue;
4523             field = (ast_value*)parser->fields[i];
4524             hasvalue = field->hasvalue;
4525             field->hasvalue = false;
4526             if (!ast_global_codegen((ast_value*)field, ir, true)) {
4527                 con_out("failed to generate field %s\n", field->name);
4528                 ir_builder_delete(ir);
4529                 return false;
4530             }
4531             if (hasvalue) {
4532                 ir_value *ifld;
4533                 ast_expression *subtype;
4534                 field->hasvalue = true;
4535                 subtype = field->expression.next;
4536                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4537                 if (subtype->expression.vtype == TYPE_FIELD)
4538                     ifld->fieldtype = subtype->expression.next->expression.vtype;
4539                 else if (subtype->expression.vtype == TYPE_FUNCTION)
4540                     ifld->outtype = subtype->expression.next->expression.vtype;
4541                 (void)!ir_value_set_field(field->ir_v, ifld);
4542             }
4543         }
4544         for (i = 0; i < vec_size(parser->globals); ++i) {
4545             ast_value *asvalue;
4546             if (!ast_istype(parser->globals[i], ast_value))
4547                 continue;
4548             asvalue = (ast_value*)(parser->globals[i]);
4549             if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4550                 if (strcmp(asvalue->name, "end_sys_globals") &&
4551                     strcmp(asvalue->name, "end_sys_fields"))
4552                 {
4553                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4554                                                    "unused global: `%s`", asvalue->name);
4555                 }
4556             }
4557             if (!ast_global_codegen(asvalue, ir, false)) {
4558                 con_out("failed to generate global %s\n", asvalue->name);
4559                 ir_builder_delete(ir);
4560                 return false;
4561             }
4562         }
4563         for (i = 0; i < vec_size(parser->imm_float); ++i) {
4564             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4565                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4566                 ir_builder_delete(ir);
4567                 return false;
4568             }
4569         }
4570         for (i = 0; i < vec_size(parser->imm_string); ++i) {
4571             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4572                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4573                 ir_builder_delete(ir);
4574                 return false;
4575             }
4576         }
4577         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4578             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4579                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4580                 ir_builder_delete(ir);
4581                 return false;
4582             }
4583         }
4584         for (i = 0; i < vec_size(parser->globals); ++i) {
4585             ast_value *asvalue;
4586             if (!ast_istype(parser->globals[i], ast_value))
4587                 continue;
4588             asvalue = (ast_value*)(parser->globals[i]);
4589             if (asvalue->setter) {
4590                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4591                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4592                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4593                 {
4594                     printf("failed to generate setter for %s\n", asvalue->name);
4595                     ir_builder_delete(ir);
4596                     return false;
4597                 }
4598             }
4599             if (asvalue->getter) {
4600                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4601                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4602                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4603                 {
4604                     printf("failed to generate getter for %s\n", asvalue->name);
4605                     ir_builder_delete(ir);
4606                     return false;
4607                 }
4608             }
4609         }
4610         for (i = 0; i < vec_size(parser->fields); ++i) {
4611             ast_value *asvalue;
4612             asvalue = (ast_value*)(parser->fields[i]->expression.next);
4613
4614             if (!ast_istype((ast_expression*)asvalue, ast_value))
4615                 continue;
4616             if (asvalue->expression.vtype != TYPE_ARRAY)
4617                 continue;
4618             if (asvalue->setter) {
4619                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4620                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4621                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4622                 {
4623                     printf("failed to generate setter for %s\n", asvalue->name);
4624                     ir_builder_delete(ir);
4625                     return false;
4626                 }
4627             }
4628             if (asvalue->getter) {
4629                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4630                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4631                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4632                 {
4633                     printf("failed to generate getter for %s\n", asvalue->name);
4634                     ir_builder_delete(ir);
4635                     return false;
4636                 }
4637             }
4638         }
4639         for (i = 0; i < vec_size(parser->functions); ++i) {
4640             if (!ast_function_codegen(parser->functions[i], ir)) {
4641                 con_out("failed to generate function %s\n", parser->functions[i]->name);
4642                 ir_builder_delete(ir);
4643                 return false;
4644             }
4645         }
4646         if (opts_dump)
4647             ir_builder_dump(ir, con_out);
4648         for (i = 0; i < vec_size(parser->functions); ++i) {
4649             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4650                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4651                 ir_builder_delete(ir);
4652                 return false;
4653             }
4654         }
4655
4656         if (retval) {
4657             if (opts_dumpfin)
4658                 ir_builder_dump(ir, con_out);
4659
4660             generate_checksum(parser);
4661
4662             if (!ir_builder_generate(ir, output)) {
4663                 con_out("*** failed to generate output file\n");
4664                 ir_builder_delete(ir);
4665                 return false;
4666             }
4667         }
4668
4669         ir_builder_delete(ir);
4670         return retval;
4671     }
4672
4673     con_out("*** there were compile errors\n");
4674     return false;
4675 }