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