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