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