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