]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
a11c70955878c248adbef9c0bd7b48307abaafd2
[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, bool is_static);
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, 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, bool *is_static)
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     bool had_static   = false;
2355
2356     *cvq = CV_NONE;
2357     for (;;) {
2358         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2359             had_attrib = true;
2360             /* parse an attribute */
2361             if (!parser_next(parser)) {
2362                 parseerror(parser, "expected attribute after `[[`");
2363                 *cvq = CV_WRONG;
2364                 return false;
2365             }
2366             if (!strcmp(parser_tokval(parser), "noreturn")) {
2367                 had_noreturn = true;
2368                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2369                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2370                     *cvq = CV_WRONG;
2371                     return false;
2372                 }
2373             }
2374             else if (!strcmp(parser_tokval(parser), "noref")) {
2375                 had_noref = true;
2376                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2377                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2378                     *cvq = CV_WRONG;
2379                     return false;
2380                 }
2381             }
2382             else
2383             {
2384                 /* Skip tokens until we hit a ]] */
2385                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2386                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2387                     if (!parser_next(parser)) {
2388                         parseerror(parser, "error inside attribute");
2389                         *cvq = CV_WRONG;
2390                         return false;
2391                     }
2392                 }
2393             }
2394         }
2395         else if (!strcmp(parser_tokval(parser), "static"))
2396             had_static = true;
2397         else if (!strcmp(parser_tokval(parser), "const"))
2398             had_const = true;
2399         else if (!strcmp(parser_tokval(parser), "var"))
2400             had_var = true;
2401         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2402             had_var = true;
2403         else if (!strcmp(parser_tokval(parser), "noref"))
2404             had_noref = true;
2405         else if (!had_const && !had_var && !had_noref && !had_noreturn && !had_attrib && !had_static) {
2406             return false;
2407         }
2408         else
2409             break;
2410         if (!parser_next(parser))
2411             goto onerr;
2412     }
2413     if (had_const)
2414         *cvq = CV_CONST;
2415     else if (had_var)
2416         *cvq = CV_VAR;
2417     else
2418         *cvq = CV_NONE;
2419     *noref     = had_noref;
2420     *noreturn  = had_noreturn;
2421     *is_static = had_static;
2422     return true;
2423 onerr:
2424     parseerror(parser, "parse error after variable qualifier");
2425     *cvq = CV_WRONG;
2426     return true;
2427 }
2428
2429 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2430 {
2431     ast_expression *operand;
2432     ast_value      *opval;
2433     ast_value      *typevar;
2434     ast_switch     *switchnode;
2435     ast_switch_case swcase;
2436
2437     int  cvq;
2438     bool noref, noreturn, is_static;
2439
2440     lex_ctx ctx = parser_ctx(parser);
2441
2442     (void)block; /* not touching */
2443     (void)opval;
2444
2445     /* parse over the opening paren */
2446     if (!parser_next(parser) || parser->tok != '(') {
2447         parseerror(parser, "expected switch operand in parenthesis");
2448         return false;
2449     }
2450
2451     /* parse into the expression */
2452     if (!parser_next(parser)) {
2453         parseerror(parser, "expected switch operand");
2454         return false;
2455     }
2456     /* parse the operand */
2457     operand = parse_expression_leave(parser, false);
2458     if (!operand)
2459         return false;
2460
2461     switchnode = ast_switch_new(ctx, operand);
2462
2463     /* closing paren */
2464     if (parser->tok != ')') {
2465         ast_delete(switchnode);
2466         parseerror(parser, "expected closing paren after 'switch' operand");
2467         return false;
2468     }
2469
2470     /* parse over the opening paren */
2471     if (!parser_next(parser) || parser->tok != '{') {
2472         ast_delete(switchnode);
2473         parseerror(parser, "expected list of cases");
2474         return false;
2475     }
2476
2477     if (!parser_next(parser)) {
2478         ast_delete(switchnode);
2479         parseerror(parser, "expected 'case' or 'default'");
2480         return false;
2481     }
2482
2483     /* new block; allow some variables to be declared here */
2484     parser_enterblock(parser);
2485     while (true) {
2486         typevar = NULL;
2487         if (parser->tok == TOKEN_IDENT)
2488             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2489         if (typevar || parser->tok == TOKEN_TYPENAME) {
2490             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false)) {
2491                 ast_delete(switchnode);
2492                 return false;
2493             }
2494             continue;
2495         }
2496         if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn, &is_static))
2497         {
2498             if (cvq == CV_WRONG) {
2499                 ast_delete(switchnode);
2500                 return false;
2501             }
2502             if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn, is_static)) {
2503                 ast_delete(switchnode);
2504                 return false;
2505             }
2506             continue;
2507         }
2508         break;
2509     }
2510
2511     /* case list! */
2512     while (parser->tok != '}') {
2513         ast_block *caseblock;
2514
2515         if (!strcmp(parser_tokval(parser), "case")) {
2516             if (!parser_next(parser)) {
2517                 ast_delete(switchnode);
2518                 parseerror(parser, "expected expression for case");
2519                 return false;
2520             }
2521             swcase.value = parse_expression_leave(parser, false);
2522             if (!swcase.value) {
2523                 ast_delete(switchnode);
2524                 parseerror(parser, "expected expression for case");
2525                 return false;
2526             }
2527             if (!OPTS_FLAG(RELAXED_SWITCH)) {
2528                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2529                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2530                     ast_unref(operand);
2531                     return false;
2532                 }
2533             }
2534         }
2535         else if (!strcmp(parser_tokval(parser), "default")) {
2536             swcase.value = NULL;
2537             if (!parser_next(parser)) {
2538                 ast_delete(switchnode);
2539                 parseerror(parser, "expected colon");
2540                 return false;
2541             }
2542         }
2543         else {
2544             ast_delete(switchnode);
2545             parseerror(parser, "expected 'case' or 'default'");
2546             return false;
2547         }
2548
2549         /* Now the colon and body */
2550         if (parser->tok != ':') {
2551             if (swcase.value) ast_unref(swcase.value);
2552             ast_delete(switchnode);
2553             parseerror(parser, "expected colon");
2554             return false;
2555         }
2556
2557         if (!parser_next(parser)) {
2558             if (swcase.value) ast_unref(swcase.value);
2559             ast_delete(switchnode);
2560             parseerror(parser, "expected statements or case");
2561             return false;
2562         }
2563         caseblock = ast_block_new(parser_ctx(parser));
2564         if (!caseblock) {
2565             if (swcase.value) ast_unref(swcase.value);
2566             ast_delete(switchnode);
2567             return false;
2568         }
2569         swcase.code = (ast_expression*)caseblock;
2570         vec_push(switchnode->cases, swcase);
2571         while (true) {
2572             ast_expression *expr;
2573             if (parser->tok == '}')
2574                 break;
2575             if (parser->tok == TOKEN_KEYWORD) {
2576                 if (!strcmp(parser_tokval(parser), "case") ||
2577                     !strcmp(parser_tokval(parser), "default"))
2578                 {
2579                     break;
2580                 }
2581             }
2582             if (!parse_statement(parser, caseblock, &expr, true)) {
2583                 ast_delete(switchnode);
2584                 return false;
2585             }
2586             if (!expr)
2587                 continue;
2588             if (!ast_block_add_expr(caseblock, expr)) {
2589                 ast_delete(switchnode);
2590                 return false;
2591             }
2592         }
2593     }
2594
2595     parser_leaveblock(parser);
2596
2597     /* closing paren */
2598     if (parser->tok != '}') {
2599         ast_delete(switchnode);
2600         parseerror(parser, "expected closing paren of case list");
2601         return false;
2602     }
2603     if (!parser_next(parser)) {
2604         ast_delete(switchnode);
2605         parseerror(parser, "parse error after switch");
2606         return false;
2607     }
2608     *out = (ast_expression*)switchnode;
2609     return true;
2610 }
2611
2612 static bool parse_goto(parser_t *parser, ast_expression **out)
2613 {
2614     size_t    i;
2615     ast_goto *gt;
2616
2617     if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2618         parseerror(parser, "expected label name after `goto`");
2619         return false;
2620     }
2621
2622     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2623
2624     for (i = 0; i < vec_size(parser->labels); ++i) {
2625         if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2626             ast_goto_set_label(gt, parser->labels[i]);
2627             break;
2628         }
2629     }
2630     if (i == vec_size(parser->labels))
2631         vec_push(parser->gotos, gt);
2632
2633     if (!parser_next(parser) || parser->tok != ';') {
2634         parseerror(parser, "semicolon expected after goto label");
2635         return false;
2636     }
2637     if (!parser_next(parser)) {
2638         parseerror(parser, "parse error after goto");
2639         return false;
2640     }
2641
2642     *out = (ast_expression*)gt;
2643     return true;
2644 }
2645
2646 static bool parse_skipwhite(parser_t *parser)
2647 {
2648     do {
2649         if (!parser_next(parser))
2650             return false;
2651     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2652     return parser->tok < TOKEN_ERROR;
2653 }
2654
2655 static bool parse_eol(parser_t *parser)
2656 {
2657     if (!parse_skipwhite(parser))
2658         return false;
2659     return parser->tok == TOKEN_EOL;
2660 }
2661
2662 static bool parse_pragma_do(parser_t *parser)
2663 {
2664     if (!parser_next(parser) ||
2665         parser->tok != TOKEN_IDENT ||
2666         strcmp(parser_tokval(parser), "pragma"))
2667     {
2668         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2669         return false;
2670     }
2671     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2672         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2673         return false;
2674     }
2675
2676     if (!strcmp(parser_tokval(parser), "noref")) {
2677         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2678             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2679             return false;
2680         }
2681         parser->noref = !!parser_token(parser)->constval.i;
2682         if (!parse_eol(parser)) {
2683             parseerror(parser, "parse error after `noref` pragma");
2684             return false;
2685         }
2686     }
2687     else
2688     {
2689         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2690         return false;
2691     }
2692
2693     return true;
2694 }
2695
2696 static bool parse_pragma(parser_t *parser)
2697 {
2698     bool rv;
2699     parser->lex->flags.preprocessing = true;
2700     parser->lex->flags.mergelines = true;
2701     rv = parse_pragma_do(parser);
2702     if (parser->tok != TOKEN_EOL) {
2703         parseerror(parser, "junk after pragma");
2704         rv = false;
2705     }
2706     parser->lex->flags.preprocessing = false;
2707     parser->lex->flags.mergelines = false;
2708     if (!parser_next(parser)) {
2709         parseerror(parser, "parse error after pragma");
2710         rv = false;
2711     }
2712     return rv;
2713 }
2714
2715 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2716 {
2717     bool       noref, noreturn, is_static;
2718     int        cvq = CV_NONE;
2719     ast_value *typevar = NULL;
2720
2721     *out = NULL;
2722
2723     if (parser->tok == TOKEN_IDENT)
2724         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2725
2726     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2727     {
2728         /* local variable */
2729         if (!block) {
2730             parseerror(parser, "cannot declare a variable from here");
2731             return false;
2732         }
2733         if (opts.standard == COMPILER_QCC) {
2734             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2735                 return false;
2736         }
2737         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false))
2738             return false;
2739         return true;
2740     }
2741     else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn, &is_static))
2742     {
2743         if (cvq == CV_WRONG)
2744             return false;
2745         return parse_variable(parser, block, true, cvq, NULL, noref, noreturn, is_static);
2746     }
2747     else if (parser->tok == TOKEN_KEYWORD)
2748     {
2749         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2750         {
2751             char ty[1024];
2752             ast_value *tdef;
2753
2754             if (!parser_next(parser)) {
2755                 parseerror(parser, "parse error after __builtin_debug_printtype");
2756                 return false;
2757             }
2758
2759             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2760             {
2761                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2762                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2763                 if (!parser_next(parser)) {
2764                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2765                     return false;
2766                 }
2767             }
2768             else
2769             {
2770                 if (!parse_statement(parser, block, out, allow_cases))
2771                     return false;
2772                 if (!*out)
2773                     con_out("__builtin_debug_printtype: got no output node\n");
2774                 else
2775                 {
2776                     ast_type_to_string(*out, ty, sizeof(ty));
2777                     con_out("__builtin_debug_printtype: `%s`\n", ty);
2778                 }
2779             }
2780             return true;
2781         }
2782         else if (!strcmp(parser_tokval(parser), "return"))
2783         {
2784             return parse_return(parser, block, out);
2785         }
2786         else if (!strcmp(parser_tokval(parser), "if"))
2787         {
2788             return parse_if(parser, block, out);
2789         }
2790         else if (!strcmp(parser_tokval(parser), "while"))
2791         {
2792             return parse_while(parser, block, out);
2793         }
2794         else if (!strcmp(parser_tokval(parser), "do"))
2795         {
2796             return parse_dowhile(parser, block, out);
2797         }
2798         else if (!strcmp(parser_tokval(parser), "for"))
2799         {
2800             if (opts.standard == COMPILER_QCC) {
2801                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2802                     return false;
2803             }
2804             return parse_for(parser, block, out);
2805         }
2806         else if (!strcmp(parser_tokval(parser), "break"))
2807         {
2808             return parse_break_continue(parser, block, out, false);
2809         }
2810         else if (!strcmp(parser_tokval(parser), "continue"))
2811         {
2812             return parse_break_continue(parser, block, out, true);
2813         }
2814         else if (!strcmp(parser_tokval(parser), "switch"))
2815         {
2816             return parse_switch(parser, block, out);
2817         }
2818         else if (!strcmp(parser_tokval(parser), "case") ||
2819                  !strcmp(parser_tokval(parser), "default"))
2820         {
2821             if (!allow_cases) {
2822                 parseerror(parser, "unexpected 'case' label");
2823                 return false;
2824             }
2825             return true;
2826         }
2827         else if (!strcmp(parser_tokval(parser), "goto"))
2828         {
2829             return parse_goto(parser, out);
2830         }
2831         else if (!strcmp(parser_tokval(parser), "typedef"))
2832         {
2833             if (!parser_next(parser)) {
2834                 parseerror(parser, "expected type definition after 'typedef'");
2835                 return false;
2836             }
2837             return parse_typedef(parser);
2838         }
2839         parseerror(parser, "Unexpected keyword");
2840         return false;
2841     }
2842     else if (parser->tok == '{')
2843     {
2844         ast_block *inner;
2845         inner = parse_block(parser);
2846         if (!inner)
2847             return false;
2848         *out = (ast_expression*)inner;
2849         return true;
2850     }
2851     else if (parser->tok == ':')
2852     {
2853         size_t i;
2854         ast_label *label;
2855         if (!parser_next(parser)) {
2856             parseerror(parser, "expected label name");
2857             return false;
2858         }
2859         if (parser->tok != TOKEN_IDENT) {
2860             parseerror(parser, "label must be an identifier");
2861             return false;
2862         }
2863         label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2864         if (!label)
2865             return false;
2866         vec_push(parser->labels, label);
2867         *out = (ast_expression*)label;
2868         if (!parser_next(parser)) {
2869             parseerror(parser, "parse error after label");
2870             return false;
2871         }
2872         for (i = 0; i < vec_size(parser->gotos); ++i) {
2873             if (!strcmp(parser->gotos[i]->name, label->name)) {
2874                 ast_goto_set_label(parser->gotos[i], label);
2875                 vec_remove(parser->gotos, i, 1);
2876                 --i;
2877             }
2878         }
2879         return true;
2880     }
2881     else if (parser->tok == ';')
2882     {
2883         if (!parser_next(parser)) {
2884             parseerror(parser, "parse error after empty statement");
2885             return false;
2886         }
2887         return true;
2888     }
2889     else
2890     {
2891         ast_expression *exp = parse_expression(parser, false);
2892         if (!exp)
2893             return false;
2894         *out = exp;
2895         if (!ast_side_effects(exp)) {
2896             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2897                 return false;
2898         }
2899         return true;
2900     }
2901 }
2902
2903 static bool parse_block_into(parser_t *parser, ast_block *block)
2904 {
2905     bool   retval = true;
2906
2907     parser_enterblock(parser);
2908
2909     if (!parser_next(parser)) { /* skip the '{' */
2910         parseerror(parser, "expected function body");
2911         goto cleanup;
2912     }
2913
2914     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2915     {
2916         ast_expression *expr = NULL;
2917         if (parser->tok == '}')
2918             break;
2919
2920         if (!parse_statement(parser, block, &expr, false)) {
2921             /* parseerror(parser, "parse error"); */
2922             block = NULL;
2923             goto cleanup;
2924         }
2925         if (!expr)
2926             continue;
2927         if (!ast_block_add_expr(block, expr)) {
2928             ast_delete(block);
2929             block = NULL;
2930             goto cleanup;
2931         }
2932     }
2933
2934     if (parser->tok != '}') {
2935         block = NULL;
2936     } else {
2937         (void)parser_next(parser);
2938     }
2939
2940 cleanup:
2941     if (!parser_leaveblock(parser))
2942         retval = false;
2943     return retval && !!block;
2944 }
2945
2946 static ast_block* parse_block(parser_t *parser)
2947 {
2948     ast_block *block;
2949     block = ast_block_new(parser_ctx(parser));
2950     if (!block)
2951         return NULL;
2952     if (!parse_block_into(parser, block)) {
2953         ast_block_delete(block);
2954         return NULL;
2955     }
2956     return block;
2957 }
2958
2959 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2960 {
2961     if (parser->tok == '{') {
2962         *out = (ast_expression*)parse_block(parser);
2963         return !!*out;
2964     }
2965     return parse_statement(parser, NULL, out, false);
2966 }
2967
2968 static bool create_vector_members(ast_value *var, ast_member **me)
2969 {
2970     size_t i;
2971     size_t len = strlen(var->name);
2972
2973     for (i = 0; i < 3; ++i) {
2974         char *name = (char*)mem_a(len+3);
2975         memcpy(name, var->name, len);
2976         name[len+0] = '_';
2977         name[len+1] = 'x'+i;
2978         name[len+2] = 0;
2979         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2980         mem_d(name);
2981         if (!me[i])
2982             break;
2983     }
2984     if (i == 3)
2985         return true;
2986
2987     /* unroll */
2988     do { ast_member_delete(me[--i]); } while(i);
2989     return false;
2990 }
2991
2992 static bool parse_function_body(parser_t *parser, ast_value *var)
2993 {
2994     ast_block      *block = NULL;
2995     ast_function   *func;
2996     ast_function   *old;
2997     size_t          parami;
2998
2999     ast_expression *framenum  = NULL;
3000     ast_expression *nextthink = NULL;
3001     /* None of the following have to be deleted */
3002     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3003     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3004     bool            has_frame_think;
3005
3006     bool retval = true;
3007
3008     has_frame_think = false;
3009     old = parser->function;
3010
3011     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3012         parseerror(parser, "gotos/labels leaking");
3013         return false;
3014     }
3015
3016     if (var->expression.flags & AST_FLAG_VARIADIC) {
3017         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3018                          "variadic function with implementation will not be able to access additional parameters"))
3019         {
3020             return false;
3021         }
3022     }
3023
3024     if (parser->tok == '[') {
3025         /* got a frame definition: [ framenum, nextthink ]
3026          * this translates to:
3027          * self.frame = framenum;
3028          * self.nextthink = time + 0.1;
3029          * self.think = nextthink;
3030          */
3031         nextthink = NULL;
3032
3033         fld_think     = parser_find_field(parser, "think");
3034         fld_nextthink = parser_find_field(parser, "nextthink");
3035         fld_frame     = parser_find_field(parser, "frame");
3036         if (!fld_think || !fld_nextthink || !fld_frame) {
3037             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3038             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3039             return false;
3040         }
3041         gbl_time      = parser_find_global(parser, "time");
3042         gbl_self      = parser_find_global(parser, "self");
3043         if (!gbl_time || !gbl_self) {
3044             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3045             parseerror(parser, "please declare the following globals: `time`, `self`");
3046             return false;
3047         }
3048
3049         if (!parser_next(parser))
3050             return false;
3051
3052         framenum = parse_expression_leave(parser, true);
3053         if (!framenum) {
3054             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3055             return false;
3056         }
3057         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3058             ast_unref(framenum);
3059             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3060             return false;
3061         }
3062
3063         if (parser->tok != ',') {
3064             ast_unref(framenum);
3065             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3066             parseerror(parser, "Got a %i\n", parser->tok);
3067             return false;
3068         }
3069
3070         if (!parser_next(parser)) {
3071             ast_unref(framenum);
3072             return false;
3073         }
3074
3075         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3076         {
3077             /* qc allows the use of not-yet-declared functions here
3078              * - this automatically creates a prototype */
3079             ast_value      *thinkfunc;
3080             ast_expression *functype = fld_think->expression.next;
3081
3082             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3083             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3084                 ast_unref(framenum);
3085                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3086                 return false;
3087             }
3088
3089             if (!parser_next(parser)) {
3090                 ast_unref(framenum);
3091                 ast_delete(thinkfunc);
3092                 return false;
3093             }
3094
3095             vec_push(parser->globals, (ast_expression*)thinkfunc);
3096             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3097             nextthink = (ast_expression*)thinkfunc;
3098
3099         } else {
3100             nextthink = parse_expression_leave(parser, true);
3101             if (!nextthink) {
3102                 ast_unref(framenum);
3103                 parseerror(parser, "expected a think-function in [frame,think] notation");
3104                 return false;
3105             }
3106         }
3107
3108         if (!ast_istype(nextthink, ast_value)) {
3109             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3110             retval = false;
3111         }
3112
3113         if (retval && parser->tok != ']') {
3114             parseerror(parser, "expected closing `]` for [frame,think] notation");
3115             retval = false;
3116         }
3117
3118         if (retval && !parser_next(parser)) {
3119             retval = false;
3120         }
3121
3122         if (retval && parser->tok != '{') {
3123             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3124             retval = false;
3125         }
3126
3127         if (!retval) {
3128             ast_unref(nextthink);
3129             ast_unref(framenum);
3130             return false;
3131         }
3132
3133         has_frame_think = true;
3134     }
3135
3136     block = ast_block_new(parser_ctx(parser));
3137     if (!block) {
3138         parseerror(parser, "failed to allocate block");
3139         if (has_frame_think) {
3140             ast_unref(nextthink);
3141             ast_unref(framenum);
3142         }
3143         return false;
3144     }
3145
3146     if (has_frame_think) {
3147         lex_ctx ctx;
3148         ast_expression *self_frame;
3149         ast_expression *self_nextthink;
3150         ast_expression *self_think;
3151         ast_expression *time_plus_1;
3152         ast_store *store_frame;
3153         ast_store *store_nextthink;
3154         ast_store *store_think;
3155
3156         ctx = parser_ctx(parser);
3157         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3158         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3159         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3160
3161         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3162                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3163
3164         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3165             if (self_frame)     ast_delete(self_frame);
3166             if (self_nextthink) ast_delete(self_nextthink);
3167             if (self_think)     ast_delete(self_think);
3168             if (time_plus_1)    ast_delete(time_plus_1);
3169             retval = false;
3170         }
3171
3172         if (retval)
3173         {
3174             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3175             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3176             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3177
3178             if (!store_frame) {
3179                 ast_delete(self_frame);
3180                 retval = false;
3181             }
3182             if (!store_nextthink) {
3183                 ast_delete(self_nextthink);
3184                 retval = false;
3185             }
3186             if (!store_think) {
3187                 ast_delete(self_think);
3188                 retval = false;
3189             }
3190             if (!retval) {
3191                 if (store_frame)     ast_delete(store_frame);
3192                 if (store_nextthink) ast_delete(store_nextthink);
3193                 if (store_think)     ast_delete(store_think);
3194                 retval = false;
3195             }
3196             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3197                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3198                 !ast_block_add_expr(block, (ast_expression*)store_think))
3199             {
3200                 retval = false;
3201             }
3202         }
3203
3204         if (!retval) {
3205             parseerror(parser, "failed to generate code for [frame,think]");
3206             ast_unref(nextthink);
3207             ast_unref(framenum);
3208             ast_delete(block);
3209             return false;
3210         }
3211     }
3212
3213     parser_enterblock(parser);
3214
3215     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3216         size_t     e;
3217         ast_value *param = var->expression.params[parami];
3218         ast_member *me[3];
3219
3220         if (param->expression.vtype != TYPE_VECTOR &&
3221             (param->expression.vtype != TYPE_FIELD ||
3222              param->expression.next->expression.vtype != TYPE_VECTOR))
3223         {
3224             continue;
3225         }
3226
3227         if (!create_vector_members(param, me)) {
3228             ast_block_delete(block);
3229             return false;
3230         }
3231
3232         for (e = 0; e < 3; ++e) {
3233             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3234             ast_block_collect(block, (ast_expression*)me[e]);
3235         }
3236     }
3237
3238     func = ast_function_new(ast_ctx(var), var->name, var);
3239     if (!func) {
3240         parseerror(parser, "failed to allocate function for `%s`", var->name);
3241         ast_block_delete(block);
3242         goto enderr;
3243     }
3244     vec_push(parser->functions, func);
3245
3246     parser->function = func;
3247     if (!parse_block_into(parser, block)) {
3248         ast_block_delete(block);
3249         goto enderrfn;
3250     }
3251
3252     vec_push(func->blocks, block);
3253
3254     parser->function = old;
3255     if (!parser_leaveblock(parser))
3256         retval = false;
3257     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3258         parseerror(parser, "internal error: local scopes left");
3259         retval = false;
3260     }
3261
3262     if (parser->tok == ';')
3263         return parser_next(parser);
3264     else if (opts.standard == COMPILER_QCC)
3265         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3266     return retval;
3267
3268 enderrfn:
3269     vec_pop(parser->functions);
3270     ast_function_delete(func);
3271     var->constval.vfunc = NULL;
3272
3273 enderr:
3274     (void)!parser_leaveblock(parser);
3275     parser->function = old;
3276     return false;
3277 }
3278
3279 static ast_expression *array_accessor_split(
3280     parser_t  *parser,
3281     ast_value *array,
3282     ast_value *index,
3283     size_t     middle,
3284     ast_expression *left,
3285     ast_expression *right
3286     )
3287 {
3288     ast_ifthen *ifthen;
3289     ast_binary *cmp;
3290
3291     lex_ctx ctx = ast_ctx(array);
3292
3293     if (!left || !right) {
3294         if (left)  ast_delete(left);
3295         if (right) ast_delete(right);
3296         return NULL;
3297     }
3298
3299     cmp = ast_binary_new(ctx, INSTR_LT,
3300                          (ast_expression*)index,
3301                          (ast_expression*)parser_const_float(parser, middle));
3302     if (!cmp) {
3303         ast_delete(left);
3304         ast_delete(right);
3305         parseerror(parser, "internal error: failed to create comparison for array setter");
3306         return NULL;
3307     }
3308
3309     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3310     if (!ifthen) {
3311         ast_delete(cmp); /* will delete left and right */
3312         parseerror(parser, "internal error: failed to create conditional jump for array setter");
3313         return NULL;
3314     }
3315
3316     return (ast_expression*)ifthen;
3317 }
3318
3319 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3320 {
3321     lex_ctx ctx = ast_ctx(array);
3322
3323     if (from+1 == afterend) {
3324         /* set this value */
3325         ast_block       *block;
3326         ast_return      *ret;
3327         ast_array_index *subscript;
3328         ast_store       *st;
3329         int assignop = type_store_instr[value->expression.vtype];
3330
3331         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3332             assignop = INSTR_STORE_V;
3333
3334         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3335         if (!subscript)
3336             return NULL;
3337
3338         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3339         if (!st) {
3340             ast_delete(subscript);
3341             return NULL;
3342         }
3343
3344         block = ast_block_new(ctx);
3345         if (!block) {
3346             ast_delete(st);
3347             return NULL;
3348         }
3349
3350         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3351             ast_delete(block);
3352             return NULL;
3353         }
3354
3355         ret = ast_return_new(ctx, NULL);
3356         if (!ret) {
3357             ast_delete(block);
3358             return NULL;
3359         }
3360
3361         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3362             ast_delete(block);
3363             return NULL;
3364         }
3365
3366         return (ast_expression*)block;
3367     } else {
3368         ast_expression *left, *right;
3369         size_t diff = afterend - from;
3370         size_t middle = from + diff/2;
3371         left  = array_setter_node(parser, array, index, value, from, middle);
3372         right = array_setter_node(parser, array, index, value, middle, afterend);
3373         return array_accessor_split(parser, array, index, middle, left, right);
3374     }
3375 }
3376
3377 static ast_expression *array_field_setter_node(
3378     parser_t  *parser,
3379     ast_value *array,
3380     ast_value *entity,
3381     ast_value *index,
3382     ast_value *value,
3383     size_t     from,
3384     size_t     afterend)
3385 {
3386     lex_ctx ctx = ast_ctx(array);
3387
3388     if (from+1 == afterend) {
3389         /* set this value */
3390         ast_block       *block;
3391         ast_return      *ret;
3392         ast_entfield    *entfield;
3393         ast_array_index *subscript;
3394         ast_store       *st;
3395         int assignop = type_storep_instr[value->expression.vtype];
3396
3397         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3398             assignop = INSTR_STOREP_V;
3399
3400         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3401         if (!subscript)
3402             return NULL;
3403
3404         entfield = ast_entfield_new_force(ctx,
3405                                           (ast_expression*)entity,
3406                                           (ast_expression*)subscript,
3407                                           (ast_expression*)subscript);
3408         if (!entfield) {
3409             ast_delete(subscript);
3410             return NULL;
3411         }
3412
3413         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3414         if (!st) {
3415             ast_delete(entfield);
3416             return NULL;
3417         }
3418
3419         block = ast_block_new(ctx);
3420         if (!block) {
3421             ast_delete(st);
3422             return NULL;
3423         }
3424
3425         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3426             ast_delete(block);
3427             return NULL;
3428         }
3429
3430         ret = ast_return_new(ctx, NULL);
3431         if (!ret) {
3432             ast_delete(block);
3433             return NULL;
3434         }
3435
3436         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3437             ast_delete(block);
3438             return NULL;
3439         }
3440
3441         return (ast_expression*)block;
3442     } else {
3443         ast_expression *left, *right;
3444         size_t diff = afterend - from;
3445         size_t middle = from + diff/2;
3446         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
3447         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3448         return array_accessor_split(parser, array, index, middle, left, right);
3449     }
3450 }
3451
3452 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3453 {
3454     lex_ctx ctx = ast_ctx(array);
3455
3456     if (from+1 == afterend) {
3457         ast_return      *ret;
3458         ast_array_index *subscript;
3459
3460         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3461         if (!subscript)
3462             return NULL;
3463
3464         ret = ast_return_new(ctx, (ast_expression*)subscript);
3465         if (!ret) {
3466             ast_delete(subscript);
3467             return NULL;
3468         }
3469
3470         return (ast_expression*)ret;
3471     } else {
3472         ast_expression *left, *right;
3473         size_t diff = afterend - from;
3474         size_t middle = from + diff/2;
3475         left  = array_getter_node(parser, array, index, from, middle);
3476         right = array_getter_node(parser, array, index, middle, afterend);
3477         return array_accessor_split(parser, array, index, middle, left, right);
3478     }
3479 }
3480
3481 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3482 {
3483     ast_function   *func = NULL;
3484     ast_value      *fval = NULL;
3485     ast_block      *body = NULL;
3486
3487     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3488     if (!fval) {
3489         parseerror(parser, "failed to create accessor function value");
3490         return false;
3491     }
3492
3493     func = ast_function_new(ast_ctx(array), funcname, fval);
3494     if (!func) {
3495         ast_delete(fval);
3496         parseerror(parser, "failed to create accessor function node");
3497         return false;
3498     }
3499
3500     body = ast_block_new(ast_ctx(array));
3501     if (!body) {
3502         parseerror(parser, "failed to create block for array accessor");
3503         ast_delete(fval);
3504         ast_delete(func);
3505         return false;
3506     }
3507
3508     vec_push(func->blocks, body);
3509     *out = fval;
3510
3511     vec_push(parser->accessors, fval);
3512
3513     return true;
3514 }
3515
3516 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3517 {
3518     ast_expression *root = NULL;
3519     ast_value      *index = NULL;
3520     ast_value      *value = NULL;
3521     ast_function   *func;
3522     ast_value      *fval;
3523
3524     if (!ast_istype(array->expression.next, ast_value)) {
3525         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3526         return false;
3527     }
3528
3529     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3530         return false;
3531     func = fval->constval.vfunc;
3532     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3533
3534     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3535     value = ast_value_copy((ast_value*)array->expression.next);
3536
3537     if (!index || !value) {
3538         parseerror(parser, "failed to create locals for array accessor");
3539         goto cleanup;
3540     }
3541     (void)!ast_value_set_name(value, "value"); /* not important */
3542     vec_push(fval->expression.params, index);
3543     vec_push(fval->expression.params, value);
3544
3545     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3546     if (!root) {
3547         parseerror(parser, "failed to build accessor search tree");
3548         goto cleanup;
3549     }
3550
3551     array->setter = fval;
3552     return ast_block_add_expr(func->blocks[0], root);
3553 cleanup:
3554     if (index) ast_delete(index);
3555     if (value) ast_delete(value);
3556     if (root)  ast_delete(root);
3557     ast_delete(func);
3558     ast_delete(fval);
3559     return false;
3560 }
3561
3562 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3563 {
3564     ast_expression *root = NULL;
3565     ast_value      *entity = NULL;
3566     ast_value      *index = NULL;
3567     ast_value      *value = NULL;
3568     ast_function   *func;
3569     ast_value      *fval;
3570
3571     if (!ast_istype(array->expression.next, ast_value)) {
3572         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3573         return false;
3574     }
3575
3576     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3577         return false;
3578     func = fval->constval.vfunc;
3579     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3580
3581     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3582     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
3583     value  = ast_value_copy((ast_value*)array->expression.next);
3584     if (!entity || !index || !value) {
3585         parseerror(parser, "failed to create locals for array accessor");
3586         goto cleanup;
3587     }
3588     (void)!ast_value_set_name(value, "value"); /* not important */
3589     vec_push(fval->expression.params, entity);
3590     vec_push(fval->expression.params, index);
3591     vec_push(fval->expression.params, value);
3592
3593     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3594     if (!root) {
3595         parseerror(parser, "failed to build accessor search tree");
3596         goto cleanup;
3597     }
3598
3599     array->setter = fval;
3600     return ast_block_add_expr(func->blocks[0], root);
3601 cleanup:
3602     if (entity) ast_delete(entity);
3603     if (index)  ast_delete(index);
3604     if (value)  ast_delete(value);
3605     if (root)   ast_delete(root);
3606     ast_delete(func);
3607     ast_delete(fval);
3608     return false;
3609 }
3610
3611 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3612 {
3613     ast_expression *root = NULL;
3614     ast_value      *index = NULL;
3615     ast_value      *fval;
3616     ast_function   *func;
3617
3618     /* NOTE: checking array->expression.next rather than elemtype since
3619      * for fields elemtype is a temporary fieldtype.
3620      */
3621     if (!ast_istype(array->expression.next, ast_value)) {
3622         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3623         return false;
3624     }
3625
3626     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3627         return false;
3628     func = fval->constval.vfunc;
3629     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3630
3631     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3632
3633     if (!index) {
3634         parseerror(parser, "failed to create locals for array accessor");
3635         goto cleanup;
3636     }
3637     vec_push(fval->expression.params, index);
3638
3639     root = array_getter_node(parser, array, index, 0, array->expression.count);
3640     if (!root) {
3641         parseerror(parser, "failed to build accessor search tree");
3642         goto cleanup;
3643     }
3644
3645     array->getter = fval;
3646     return ast_block_add_expr(func->blocks[0], root);
3647 cleanup:
3648     if (index) ast_delete(index);
3649     if (root)  ast_delete(root);
3650     ast_delete(func);
3651     ast_delete(fval);
3652     return false;
3653 }
3654
3655 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3656 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3657 {
3658     lex_ctx     ctx;
3659     size_t      i;
3660     ast_value **params;
3661     ast_value  *param;
3662     ast_value  *fval;
3663     bool        first = true;
3664     bool        variadic = false;
3665
3666     ctx = parser_ctx(parser);
3667
3668     /* for the sake of less code we parse-in in this function */
3669     if (!parser_next(parser)) {
3670         parseerror(parser, "expected parameter list");
3671         return NULL;
3672     }
3673
3674     params = NULL;
3675
3676     /* parse variables until we hit a closing paren */
3677     while (parser->tok != ')') {
3678         if (!first) {
3679             /* there must be commas between them */
3680             if (parser->tok != ',') {
3681                 parseerror(parser, "expected comma or end of parameter list");
3682                 goto on_error;
3683             }
3684             if (!parser_next(parser)) {
3685                 parseerror(parser, "expected parameter");
3686                 goto on_error;
3687             }
3688         }
3689         first = false;
3690
3691         if (parser->tok == TOKEN_DOTS) {
3692             /* '...' indicates a varargs function */
3693             variadic = true;
3694             if (!parser_next(parser)) {
3695                 parseerror(parser, "expected parameter");
3696                 return NULL;
3697             }
3698             if (parser->tok != ')') {
3699                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3700                 goto on_error;
3701             }
3702         }
3703         else
3704         {
3705             /* for anything else just parse a typename */
3706             param = parse_typename(parser, NULL, NULL);
3707             if (!param)
3708                 goto on_error;
3709             vec_push(params, param);
3710             if (param->expression.vtype >= TYPE_VARIANT) {
3711                 char tname[1024]; /* typename is reserved in C++ */
3712                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
3713                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
3714                 goto on_error;
3715             }
3716         }
3717     }
3718
3719     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3720         vec_free(params);
3721
3722     /* sanity check */
3723     if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3724         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3725
3726     /* parse-out */
3727     if (!parser_next(parser)) {
3728         parseerror(parser, "parse error after typename");
3729         goto on_error;
3730     }
3731
3732     /* now turn 'var' into a function type */
3733     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3734     fval->expression.next     = (ast_expression*)var;
3735     if (variadic)
3736         fval->expression.flags |= AST_FLAG_VARIADIC;
3737     var = fval;
3738
3739     var->expression.params = params;
3740     params = NULL;
3741
3742     return var;
3743
3744 on_error:
3745     ast_delete(var);
3746     for (i = 0; i < vec_size(params); ++i)
3747         ast_delete(params[i]);
3748     vec_free(params);
3749     return NULL;
3750 }
3751
3752 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3753 {
3754     ast_expression *cexp;
3755     ast_value      *cval, *tmp;
3756     lex_ctx ctx;
3757
3758     ctx = parser_ctx(parser);
3759
3760     if (!parser_next(parser)) {
3761         ast_delete(var);
3762         parseerror(parser, "expected array-size");
3763         return NULL;
3764     }
3765
3766     cexp = parse_expression_leave(parser, true);
3767
3768     if (!cexp || !ast_istype(cexp, ast_value)) {
3769         if (cexp)
3770             ast_unref(cexp);
3771         ast_delete(var);
3772         parseerror(parser, "expected array-size as constant positive integer");
3773         return NULL;
3774     }
3775     cval = (ast_value*)cexp;
3776
3777     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3778     tmp->expression.next = (ast_expression*)var;
3779     var = tmp;
3780
3781     if (cval->expression.vtype == TYPE_INTEGER)
3782         tmp->expression.count = cval->constval.vint;
3783     else if (cval->expression.vtype == TYPE_FLOAT)
3784         tmp->expression.count = cval->constval.vfloat;
3785     else {
3786         ast_unref(cexp);
3787         ast_delete(var);
3788         parseerror(parser, "array-size must be a positive integer constant");
3789         return NULL;
3790     }
3791     ast_unref(cexp);
3792
3793     if (parser->tok != ']') {
3794         ast_delete(var);
3795         parseerror(parser, "expected ']' after array-size");
3796         return NULL;
3797     }
3798     if (!parser_next(parser)) {
3799         ast_delete(var);
3800         parseerror(parser, "error after parsing array size");
3801         return NULL;
3802     }
3803     return var;
3804 }
3805
3806 /* Parse a complete typename.
3807  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3808  * but when parsing variables separated by comma
3809  * 'storebase' should point to where the base-type should be kept.
3810  * The base type makes up every bit of type information which comes *before* the
3811  * variable name.
3812  *
3813  * The following will be parsed in its entirety:
3814  *     void() foo()
3815  * The 'basetype' in this case is 'void()'
3816  * and if there's a comma after it, say:
3817  *     void() foo(), bar
3818  * then the type-information 'void()' can be stored in 'storebase'
3819  */
3820 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3821 {
3822     ast_value *var, *tmp;
3823     lex_ctx    ctx;
3824
3825     const char *name = NULL;
3826     bool        isfield  = false;
3827     bool        wasarray = false;
3828     size_t      morefields = 0;
3829
3830     ctx = parser_ctx(parser);
3831
3832     /* types may start with a dot */
3833     if (parser->tok == '.') {
3834         isfield = true;
3835         /* if we parsed a dot we need a typename now */
3836         if (!parser_next(parser)) {
3837             parseerror(parser, "expected typename for field definition");
3838             return NULL;
3839         }
3840
3841         /* Further dots are handled seperately because they won't be part of the
3842          * basetype
3843          */
3844         while (parser->tok == '.') {
3845             ++morefields;
3846             if (!parser_next(parser)) {
3847                 parseerror(parser, "expected typename for field definition");
3848                 return NULL;
3849             }
3850         }
3851     }
3852     if (parser->tok == TOKEN_IDENT)
3853         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3854     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3855         parseerror(parser, "expected typename");
3856         return NULL;
3857     }
3858
3859     /* generate the basic type value */
3860     if (cached_typedef) {
3861         var = ast_value_copy(cached_typedef);
3862         ast_value_set_name(var, "<type(from_def)>");
3863     } else
3864         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3865
3866     for (; morefields; --morefields) {
3867         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3868         tmp->expression.next = (ast_expression*)var;
3869         var = tmp;
3870     }
3871
3872     /* do not yet turn into a field - remember:
3873      * .void() foo; is a field too
3874      * .void()() foo; is a function
3875      */
3876
3877     /* parse on */
3878     if (!parser_next(parser)) {
3879         ast_delete(var);
3880         parseerror(parser, "parse error after typename");
3881         return NULL;
3882     }
3883
3884     /* an opening paren now starts the parameter-list of a function
3885      * this is where original-QC has parameter lists.
3886      * We allow a single parameter list here.
3887      * Much like fteqcc we don't allow `float()() x`
3888      */
3889     if (parser->tok == '(') {
3890         var = parse_parameter_list(parser, var);
3891         if (!var)
3892             return NULL;
3893     }
3894
3895     /* store the base if requested */
3896     if (storebase) {
3897         *storebase = ast_value_copy(var);
3898         if (isfield) {
3899             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3900             tmp->expression.next = (ast_expression*)*storebase;
3901             *storebase = tmp;
3902         }
3903     }
3904
3905     /* there may be a name now */
3906     if (parser->tok == TOKEN_IDENT) {
3907         name = util_strdup(parser_tokval(parser));
3908         /* parse on */
3909         if (!parser_next(parser)) {
3910             ast_delete(var);
3911             parseerror(parser, "error after variable or field declaration");
3912             return NULL;
3913         }
3914     }
3915
3916     /* now this may be an array */
3917     if (parser->tok == '[') {
3918         wasarray = true;
3919         var = parse_arraysize(parser, var);
3920         if (!var)
3921             return NULL;
3922     }
3923
3924     /* This is the point where we can turn it into a field */
3925     if (isfield) {
3926         /* turn it into a field if desired */
3927         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3928         tmp->expression.next = (ast_expression*)var;
3929         var = tmp;
3930     }
3931
3932     /* now there may be function parens again */
3933     if (parser->tok == '(' && opts.standard == COMPILER_QCC)
3934         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3935     if (parser->tok == '(' && wasarray)
3936         parseerror(parser, "arrays as part of a return type is not supported");
3937     while (parser->tok == '(') {
3938         var = parse_parameter_list(parser, var);
3939         if (!var) {
3940             if (name)
3941                 mem_d((void*)name);
3942             ast_delete(var);
3943             return NULL;
3944         }
3945     }
3946
3947     /* finally name it */
3948     if (name) {
3949         if (!ast_value_set_name(var, name)) {
3950             ast_delete(var);
3951             parseerror(parser, "internal error: failed to set name");
3952             return NULL;
3953         }
3954         /* free the name, ast_value_set_name duplicates */
3955         mem_d((void*)name);
3956     }
3957
3958     return var;
3959 }
3960
3961 static bool parse_typedef(parser_t *parser)
3962 {
3963     ast_value      *typevar, *oldtype;
3964     ast_expression *old;
3965
3966     typevar = parse_typename(parser, NULL, NULL);
3967
3968     if (!typevar)
3969         return false;
3970
3971     if ( (old = parser_find_var(parser, typevar->name)) ) {
3972         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3973                    " -> `%s` has been declared here: %s:%i",
3974                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3975         ast_delete(typevar);
3976         return false;
3977     }
3978
3979     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3980         parseerror(parser, "type `%s` has already been declared here: %s:%i",
3981                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3982         ast_delete(typevar);
3983         return false;
3984     }
3985
3986     vec_push(parser->_typedefs, typevar);
3987     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3988
3989     if (parser->tok != ';') {
3990         parseerror(parser, "expected semicolon after typedef");
3991         return false;
3992     }
3993     if (!parser_next(parser)) {
3994         parseerror(parser, "parse error after typedef");
3995         return false;
3996     }
3997
3998     return true;
3999 }
4000
4001 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn, bool is_static)
4002 {
4003     ast_value *var;
4004     ast_value *proto;
4005     ast_expression *old;
4006     bool       was_end;
4007     size_t     i;
4008
4009     ast_value *basetype = NULL;
4010     bool      retval    = true;
4011     bool      isparam   = false;
4012     bool      isvector  = false;
4013     bool      cleanvar  = true;
4014     bool      wasarray  = false;
4015
4016     ast_member *me[3];
4017
4018     if (!localblock && is_static)
4019         parseerror(parser, "`static` qualifier is not supported in global scope");
4020
4021     /* get the first complete variable */
4022     var = parse_typename(parser, &basetype, cached_typedef);
4023     if (!var) {
4024         if (basetype)
4025             ast_delete(basetype);
4026         return false;
4027     }
4028
4029     while (true) {
4030         proto = NULL;
4031         wasarray = false;
4032
4033         /* Part 0: finish the type */
4034         if (parser->tok == '(') {
4035             if (opts.standard == COMPILER_QCC)
4036                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4037             var = parse_parameter_list(parser, var);
4038             if (!var) {
4039                 retval = false;
4040                 goto cleanup;
4041             }
4042         }
4043         /* we only allow 1-dimensional arrays */
4044         if (parser->tok == '[') {
4045             wasarray = true;
4046             var = parse_arraysize(parser, var);
4047             if (!var) {
4048                 retval = false;
4049                 goto cleanup;
4050             }
4051         }
4052         if (parser->tok == '(' && wasarray) {
4053             parseerror(parser, "arrays as part of a return type is not supported");
4054             /* we'll still parse the type completely for now */
4055         }
4056         /* for functions returning functions */
4057         while (parser->tok == '(') {
4058             if (opts.standard == COMPILER_QCC)
4059                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4060             var = parse_parameter_list(parser, var);
4061             if (!var) {
4062                 retval = false;
4063                 goto cleanup;
4064             }
4065         }
4066
4067         var->cvq = qualifier;
4068         /* in a noref section we simply bump the usecount */
4069         if (noref || parser->noref)
4070             var->uses++;
4071         if (noreturn)
4072             var->expression.flags |= AST_FLAG_NORETURN;
4073
4074         /* Part 1:
4075          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4076          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4077          * is then filled with the previous definition and the parameter-names replaced.
4078          */
4079         if (!localblock) {
4080             /* Deal with end_sys_ vars */
4081             was_end = false;
4082             if (!strcmp(var->name, "end_sys_globals")) {
4083                 var->uses++;
4084                 parser->crc_globals = vec_size(parser->globals);
4085                 was_end = true;
4086             }
4087             else if (!strcmp(var->name, "end_sys_fields")) {
4088                 var->uses++;
4089                 parser->crc_fields = vec_size(parser->fields);
4090                 was_end = true;
4091             }
4092             if (was_end && var->expression.vtype == TYPE_FIELD) {
4093                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4094                                  "global '%s' hint should not be a field",
4095                                  parser_tokval(parser)))
4096                 {
4097                     retval = false;
4098                     goto cleanup;
4099                 }
4100             }
4101
4102             if (!nofields && var->expression.vtype == TYPE_FIELD)
4103             {
4104                 /* deal with field declarations */
4105                 old = parser_find_field(parser, var->name);
4106                 if (old) {
4107                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4108                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4109                     {
4110                         retval = false;
4111                         goto cleanup;
4112                     }
4113                     ast_delete(var);
4114                     var = NULL;
4115                     goto skipvar;
4116                     /*
4117                     parseerror(parser, "field `%s` already declared here: %s:%i",
4118                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4119                     retval = false;
4120                     goto cleanup;
4121                     */
4122                 }
4123                 if (opts.standard == COMPILER_QCC &&
4124                     (old = parser_find_global(parser, var->name)))
4125                 {
4126                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4127                     parseerror(parser, "field `%s` already declared here: %s:%i",
4128                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4129                     retval = false;
4130                     goto cleanup;
4131                 }
4132             }
4133             else
4134             {
4135                 /* deal with other globals */
4136                 old = parser_find_global(parser, var->name);
4137                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4138                 {
4139                     /* This is a function which had a prototype */
4140                     if (!ast_istype(old, ast_value)) {
4141                         parseerror(parser, "internal error: prototype is not an ast_value");
4142                         retval = false;
4143                         goto cleanup;
4144                     }
4145                     proto = (ast_value*)old;
4146                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4147                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4148                                    proto->name,
4149                                    ast_ctx(proto).file, ast_ctx(proto).line);
4150                         retval = false;
4151                         goto cleanup;
4152                     }
4153                     /* we need the new parameter-names */
4154                     for (i = 0; i < vec_size(proto->expression.params); ++i)
4155                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4156                     ast_delete(var);
4157                     var = proto;
4158                 }
4159                 else
4160                 {
4161                     /* other globals */
4162                     if (old) {
4163                         if (opts.standard == COMPILER_GMQCC) {
4164                             parseerror(parser, "global `%s` already declared here: %s:%i",
4165                                        var->name, ast_ctx(old).file, ast_ctx(old).line);
4166                             retval = false;
4167                             goto cleanup;
4168                         } else {
4169                             if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4170                                              "global `%s` already declared here: %s:%i",
4171                                              var->name, ast_ctx(old).file, ast_ctx(old).line))
4172                             {
4173                                 retval = false;
4174                                 goto cleanup;
4175                             }
4176                             proto = (ast_value*)old;
4177                             if (!ast_istype(old, ast_value)) {
4178                                 parseerror(parser, "internal error: not an ast_value");
4179                                 retval = false;
4180                                 proto = NULL;
4181                                 goto cleanup;
4182                             }
4183                             ast_delete(var);
4184                             var = proto;
4185                         }
4186                     }
4187                     if (opts.standard == COMPILER_QCC &&
4188                         (old = parser_find_field(parser, var->name)))
4189                     {
4190                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4191                         parseerror(parser, "global `%s` already declared here: %s:%i",
4192                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
4193                         retval = false;
4194                         goto cleanup;
4195                     }
4196                 }
4197             }
4198         }
4199         else /* it's not a global */
4200         {
4201             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4202             if (old && !isparam) {
4203                 parseerror(parser, "local `%s` already declared here: %s:%i",
4204                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4205                 retval = false;
4206                 goto cleanup;
4207             }
4208             old = parser_find_local(parser, var->name, 0, &isparam);
4209             if (old && isparam) {
4210                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4211                                  "local `%s` is shadowing a parameter", var->name))
4212                 {
4213                     parseerror(parser, "local `%s` already declared here: %s:%i",
4214                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4215                     retval = false;
4216                     goto cleanup;
4217                 }
4218                 if (opts.standard != COMPILER_GMQCC) {
4219                     ast_delete(var);
4220                     var = NULL;
4221                     goto skipvar;
4222                 }
4223             }
4224         }
4225
4226         /* Part 2:
4227          * Create the global/local, and deal with vector types.
4228          */
4229         if (!proto) {
4230             if (var->expression.vtype == TYPE_VECTOR)
4231                 isvector = true;
4232             else if (var->expression.vtype == TYPE_FIELD &&
4233                      var->expression.next->expression.vtype == TYPE_VECTOR)
4234                 isvector = true;
4235
4236             if (isvector) {
4237                 if (!create_vector_members(var, me)) {
4238                     retval = false;
4239                     goto cleanup;
4240                 }
4241             }
4242
4243             if (!localblock) {
4244                 /* deal with global variables, fields, functions */
4245                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4246                     var->isfield = true;
4247                     vec_push(parser->fields, (ast_expression*)var);
4248                     util_htset(parser->htfields, var->name, var);
4249                     if (isvector) {
4250                         for (i = 0; i < 3; ++i) {
4251                             vec_push(parser->fields, (ast_expression*)me[i]);
4252                             util_htset(parser->htfields, me[i]->name, me[i]);
4253                         }
4254                     }
4255                 }
4256                 else {
4257                     vec_push(parser->globals, (ast_expression*)var);
4258                     util_htset(parser->htglobals, var->name, var);
4259                     if (isvector) {
4260                         for (i = 0; i < 3; ++i) {
4261                             vec_push(parser->globals, (ast_expression*)me[i]);
4262                             util_htset(parser->htglobals, me[i]->name, me[i]);
4263                         }
4264                     }
4265                 }
4266             } else {
4267                 if (is_static) {
4268                     /* a static adds itself to be generated like any other global
4269                      * but is added to the local namespace instead
4270                      */
4271                     char   *defname = NULL;
4272                     size_t  prefix_len, ln;
4273
4274                     ln = strlen(parser->function->name);
4275                     vec_append(defname, ln, parser->function->name);
4276
4277                     vec_append(defname, 2, "::");
4278                     /* remember the length up to here */
4279                     prefix_len = vec_size(defname);
4280
4281                     /* Add it to the local scope */
4282                     util_htset(vec_last(parser->variables), var->name, (void*)var);
4283                     /* now rename the global */
4284                     ln = strlen(var->name);
4285                     vec_append(defname, ln, var->name);
4286                     ast_value_set_name(var, defname);
4287
4288                     /* push it to the to-be-generated globals */
4289                     vec_push(parser->globals, (ast_expression*)var);
4290
4291                     /* same game for the vector members */
4292                     if (isvector) {
4293                         for (i = 0; i < 3; ++i) {
4294                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4295
4296                             vec_shrinkto(defname, prefix_len);
4297                             ln = strlen(me[i]->name);
4298                             vec_append(defname, ln, me[i]->name);
4299                             ast_member_set_name(me[i], defname);
4300
4301                             vec_push(parser->globals, (ast_expression*)me[i]);
4302                         }
4303                     }
4304                     vec_free(defname);
4305                 } else {
4306                     vec_push(localblock->locals, var);
4307                     parser_addlocal(parser, var->name, (ast_expression*)var);
4308                     if (isvector) {
4309                         for (i = 0; i < 3; ++i) {
4310                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4311                             ast_block_collect(localblock, (ast_expression*)me[i]);
4312                         }
4313                     }
4314                 }
4315             }
4316         }
4317         me[0] = me[1] = me[2] = NULL;
4318         cleanvar = false;
4319         /* Part 2.2
4320          * deal with arrays
4321          */
4322         if (var->expression.vtype == TYPE_ARRAY) {
4323             char name[1024];
4324             snprintf(name, sizeof(name), "%s##SET", var->name);
4325             if (!parser_create_array_setter(parser, var, name))
4326                 goto cleanup;
4327             snprintf(name, sizeof(name), "%s##GET", var->name);
4328             if (!parser_create_array_getter(parser, var, var->expression.next, name))
4329                 goto cleanup;
4330         }
4331         else if (!localblock && !nofields &&
4332                  var->expression.vtype == TYPE_FIELD &&
4333                  var->expression.next->expression.vtype == TYPE_ARRAY)
4334         {
4335             char name[1024];
4336             ast_expression *telem;
4337             ast_value      *tfield;
4338             ast_value      *array = (ast_value*)var->expression.next;
4339
4340             if (!ast_istype(var->expression.next, ast_value)) {
4341                 parseerror(parser, "internal error: field element type must be an ast_value");
4342                 goto cleanup;
4343             }
4344
4345             snprintf(name, sizeof(name), "%s##SETF", var->name);
4346             if (!parser_create_array_field_setter(parser, array, name))
4347                 goto cleanup;
4348
4349             telem = ast_type_copy(ast_ctx(var), array->expression.next);
4350             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4351             tfield->expression.next = telem;
4352             snprintf(name, sizeof(name), "%s##GETFP", var->name);
4353             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4354                 ast_delete(tfield);
4355                 goto cleanup;
4356             }
4357             ast_delete(tfield);
4358         }
4359
4360 skipvar:
4361         if (parser->tok == ';') {
4362             ast_delete(basetype);
4363             if (!parser_next(parser)) {
4364                 parseerror(parser, "error after variable declaration");
4365                 return false;
4366             }
4367             return true;
4368         }
4369
4370         if (parser->tok == ',')
4371             goto another;
4372
4373         /*
4374         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4375         */
4376         if (!var) {
4377             parseerror(parser, "missing comma or semicolon while parsing variables");
4378             break;
4379         }
4380
4381         if (localblock && opts.standard == COMPILER_QCC) {
4382             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4383                              "initializing expression turns variable `%s` into a constant in this standard",
4384                              var->name) )
4385             {
4386                 break;
4387             }
4388         }
4389
4390         if (parser->tok != '{') {
4391             if (parser->tok != '=') {
4392                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4393                 break;
4394             }
4395
4396             if (!parser_next(parser)) {
4397                 parseerror(parser, "error parsing initializer");
4398                 break;
4399             }
4400         }
4401         else if (opts.standard == COMPILER_QCC) {
4402             parseerror(parser, "expected '=' before function body in this standard");
4403         }
4404
4405         if (parser->tok == '#') {
4406             ast_function *func = NULL;
4407
4408             if (localblock) {
4409                 parseerror(parser, "cannot declare builtins within functions");
4410                 break;
4411             }
4412             if (var->expression.vtype != TYPE_FUNCTION) {
4413                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4414                 break;
4415             }
4416             if (!parser_next(parser)) {
4417                 parseerror(parser, "expected builtin number");
4418                 break;
4419             }
4420             if (parser->tok != TOKEN_INTCONST) {
4421                 parseerror(parser, "builtin number must be an integer constant");
4422                 break;
4423             }
4424             if (parser_token(parser)->constval.i < 0) {
4425                 parseerror(parser, "builtin number must be an integer greater than zero");
4426                 break;
4427             }
4428
4429             if (var->hasvalue) {
4430                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4431                                     "builtin `%s` has already been defined\n"
4432                                     " -> previous declaration here: %s:%i",
4433                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4434             }
4435             else
4436             {
4437                 func = ast_function_new(ast_ctx(var), var->name, var);
4438                 if (!func) {
4439                     parseerror(parser, "failed to allocate function for `%s`", var->name);
4440                     break;
4441                 }
4442                 vec_push(parser->functions, func);
4443
4444                 func->builtin = -parser_token(parser)->constval.i-1;
4445             }
4446
4447             if (!parser_next(parser)) {
4448                 parseerror(parser, "expected comma or semicolon");
4449                 if (func)
4450                     ast_function_delete(func);
4451                 var->constval.vfunc = NULL;
4452                 break;
4453             }
4454         }
4455         else if (parser->tok == '{' || parser->tok == '[')
4456         {
4457             if (localblock) {
4458                 parseerror(parser, "cannot declare functions within functions");
4459                 break;
4460             }
4461
4462             if (proto)
4463                 ast_ctx(proto) = parser_ctx(parser);
4464
4465             if (!parse_function_body(parser, var))
4466                 break;
4467             ast_delete(basetype);
4468             for (i = 0; i < vec_size(parser->gotos); ++i)
4469                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4470             vec_free(parser->gotos);
4471             vec_free(parser->labels);
4472             return true;
4473         } else {
4474             ast_expression *cexp;
4475             ast_value      *cval;
4476
4477             cexp = parse_expression_leave(parser, true);
4478             if (!cexp)
4479                 break;
4480
4481             if (!localblock) {
4482                 cval = (ast_value*)cexp;
4483                 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4484                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4485                 else
4486                 {
4487                     if (opts.standard != COMPILER_GMQCC &&
4488                         !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4489                         qualifier != CV_VAR)
4490                     {
4491                         var->cvq = CV_CONST;
4492                     }
4493                     var->hasvalue = true;
4494                     if (cval->expression.vtype == TYPE_STRING)
4495                         var->constval.vstring = parser_strdup(cval->constval.vstring);
4496                     else if (cval->expression.vtype == TYPE_FIELD)
4497                         var->constval.vfield = cval;
4498                     else
4499                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4500                     ast_unref(cval);
4501                 }
4502             } else {
4503                 bool cvq;
4504                 shunt sy = { NULL, NULL };
4505                 cvq = var->cvq;
4506                 var->cvq = CV_NONE;
4507                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4508                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4509                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4510                 if (!parser_sy_apply_operator(parser, &sy))
4511                     ast_unref(cexp);
4512                 else {
4513                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4514                         parseerror(parser, "internal error: leaked operands");
4515                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4516                         break;
4517                 }
4518                 vec_free(sy.out);
4519                 vec_free(sy.ops);
4520                 var->cvq = cvq;
4521             }
4522         }
4523
4524 another:
4525         if (parser->tok == ',') {
4526             if (!parser_next(parser)) {
4527                 parseerror(parser, "expected another variable");
4528                 break;
4529             }
4530
4531             if (parser->tok != TOKEN_IDENT) {
4532                 parseerror(parser, "expected another variable");
4533                 break;
4534             }
4535             var = ast_value_copy(basetype);
4536             cleanvar = true;
4537             ast_value_set_name(var, parser_tokval(parser));
4538             if (!parser_next(parser)) {
4539                 parseerror(parser, "error parsing variable declaration");
4540                 break;
4541             }
4542             continue;
4543         }
4544
4545         if (parser->tok != ';') {
4546             parseerror(parser, "missing semicolon after variables");
4547             break;
4548         }
4549
4550         if (!parser_next(parser)) {
4551             parseerror(parser, "parse error after variable declaration");
4552             break;
4553         }
4554
4555         ast_delete(basetype);
4556         return true;
4557     }
4558
4559     if (cleanvar && var)
4560         ast_delete(var);
4561     ast_delete(basetype);
4562     return false;
4563
4564 cleanup:
4565     ast_delete(basetype);
4566     if (cleanvar && var)
4567         ast_delete(var);
4568     if (me[0]) ast_member_delete(me[0]);
4569     if (me[1]) ast_member_delete(me[1]);
4570     if (me[2]) ast_member_delete(me[2]);
4571     return retval;
4572 }
4573
4574 static bool parser_global_statement(parser_t *parser)
4575 {
4576     int        cvq       = CV_WRONG;
4577     bool       noref     = false;
4578     bool       noreturn  = false;
4579     bool       is_static = false;
4580     ast_value *istype    = NULL;
4581
4582     if (parser->tok == TOKEN_IDENT)
4583         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4584
4585     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4586     {
4587         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, false);
4588     }
4589     else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn, &is_static))
4590     {
4591         if (cvq == CV_WRONG)
4592             return false;
4593         return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn, is_static);
4594     }
4595     else if (parser->tok == TOKEN_KEYWORD)
4596     {
4597         if (!strcmp(parser_tokval(parser), "typedef")) {
4598             if (!parser_next(parser)) {
4599                 parseerror(parser, "expected type definition after 'typedef'");
4600                 return false;
4601             }
4602             return parse_typedef(parser);
4603         }
4604         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4605         return false;
4606     }
4607     else if (parser->tok == '#')
4608     {
4609         return parse_pragma(parser);
4610     }
4611     else if (parser->tok == '$')
4612     {
4613         if (!parser_next(parser)) {
4614             parseerror(parser, "parse error");
4615             return false;
4616         }
4617     }
4618     else
4619     {
4620         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4621         return false;
4622     }
4623     return true;
4624 }
4625
4626 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4627 {
4628     return util_crc16(old, str, strlen(str));
4629 }
4630
4631 static void progdefs_crc_file(const char *str)
4632 {
4633     /* write to progdefs.h here */
4634     (void)str;
4635 }
4636
4637 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4638 {
4639     old = progdefs_crc_sum(old, str);
4640     progdefs_crc_file(str);
4641     return old;
4642 }
4643
4644 static void generate_checksum(parser_t *parser)
4645 {
4646     uint16_t   crc = 0xFFFF;
4647     size_t     i;
4648     ast_value *value;
4649
4650     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4651     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4652     /*
4653     progdefs_crc_file("\tint\tpad;\n");
4654     progdefs_crc_file("\tint\tofs_return[3];\n");
4655     progdefs_crc_file("\tint\tofs_parm0[3];\n");
4656     progdefs_crc_file("\tint\tofs_parm1[3];\n");
4657     progdefs_crc_file("\tint\tofs_parm2[3];\n");
4658     progdefs_crc_file("\tint\tofs_parm3[3];\n");
4659     progdefs_crc_file("\tint\tofs_parm4[3];\n");
4660     progdefs_crc_file("\tint\tofs_parm5[3];\n");
4661     progdefs_crc_file("\tint\tofs_parm6[3];\n");
4662     progdefs_crc_file("\tint\tofs_parm7[3];\n");
4663     */
4664     for (i = 0; i < parser->crc_globals; ++i) {
4665         if (!ast_istype(parser->globals[i], ast_value))
4666             continue;
4667         value = (ast_value*)(parser->globals[i]);
4668         switch (value->expression.vtype) {
4669             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4670             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4671             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4672             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4673             default:
4674                 crc = progdefs_crc_both(crc, "\tint\t");
4675                 break;
4676         }
4677         crc = progdefs_crc_both(crc, value->name);
4678         crc = progdefs_crc_both(crc, ";\n");
4679     }
4680     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4681     for (i = 0; i < parser->crc_fields; ++i) {
4682         if (!ast_istype(parser->fields[i], ast_value))
4683             continue;
4684         value = (ast_value*)(parser->fields[i]);
4685         switch (value->expression.next->expression.vtype) {
4686             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4687             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4688             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4689             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4690             default:
4691                 crc = progdefs_crc_both(crc, "\tint\t");
4692                 break;
4693         }
4694         crc = progdefs_crc_both(crc, value->name);
4695         crc = progdefs_crc_both(crc, ";\n");
4696     }
4697     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4698
4699     code_crc = crc;
4700 }
4701
4702 static parser_t *parser;
4703
4704 bool parser_init()
4705 {
4706     size_t i;
4707
4708     parser = (parser_t*)mem_a(sizeof(parser_t));
4709     if (!parser)
4710         return false;
4711
4712     memset(parser, 0, sizeof(*parser));
4713
4714     for (i = 0; i < operator_count; ++i) {
4715         if (operators[i].id == opid1('=')) {
4716             parser->assign_op = operators+i;
4717             break;
4718         }
4719     }
4720     if (!parser->assign_op) {
4721         printf("internal error: initializing parser: failed to find assign operator\n");
4722         mem_d(parser);
4723         return false;
4724     }
4725
4726     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
4727     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4728     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4729     vec_push(parser->_blocktypedefs, 0);
4730     return true;
4731 }
4732
4733 bool parser_compile()
4734 {
4735     /* initial lexer/parser state */
4736     parser->lex->flags.noops = true;
4737
4738     if (parser_next(parser))
4739     {
4740         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4741         {
4742             if (!parser_global_statement(parser)) {
4743                 if (parser->tok == TOKEN_EOF)
4744                     parseerror(parser, "unexpected eof");
4745                 else if (!parser->errors)
4746                     parseerror(parser, "there have been errors, bailing out");
4747                 lex_close(parser->lex);
4748                 parser->lex = NULL;
4749                 return false;
4750             }
4751         }
4752     } else {
4753         parseerror(parser, "parse error");
4754         lex_close(parser->lex);
4755         parser->lex = NULL;
4756         return false;
4757     }
4758
4759     lex_close(parser->lex);
4760     parser->lex = NULL;
4761
4762     return !parser->errors;
4763 }
4764
4765 bool parser_compile_file(const char *filename)
4766 {
4767     parser->lex = lex_open(filename);
4768     if (!parser->lex) {
4769         con_err("failed to open file \"%s\"\n", filename);
4770         return false;
4771     }
4772     return parser_compile();
4773 }
4774
4775 bool parser_compile_string(const char *name, const char *str, size_t len)
4776 {
4777     parser->lex = lex_open_string(str, len, name);
4778     if (!parser->lex) {
4779         con_err("failed to create lexer for string \"%s\"\n", name);
4780         return false;
4781     }
4782     return parser_compile();
4783 }
4784
4785 void parser_cleanup()
4786 {
4787     size_t i;
4788     for (i = 0; i < vec_size(parser->accessors); ++i) {
4789         ast_delete(parser->accessors[i]->constval.vfunc);
4790         parser->accessors[i]->constval.vfunc = NULL;
4791         ast_delete(parser->accessors[i]);
4792     }
4793     for (i = 0; i < vec_size(parser->functions); ++i) {
4794         ast_delete(parser->functions[i]);
4795     }
4796     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4797         ast_delete(parser->imm_vector[i]);
4798     }
4799     for (i = 0; i < vec_size(parser->imm_string); ++i) {
4800         ast_delete(parser->imm_string[i]);
4801     }
4802     for (i = 0; i < vec_size(parser->imm_float); ++i) {
4803         ast_delete(parser->imm_float[i]);
4804     }
4805     for (i = 0; i < vec_size(parser->fields); ++i) {
4806         ast_delete(parser->fields[i]);
4807     }
4808     for (i = 0; i < vec_size(parser->globals); ++i) {
4809         ast_delete(parser->globals[i]);
4810     }
4811     vec_free(parser->accessors);
4812     vec_free(parser->functions);
4813     vec_free(parser->imm_vector);
4814     vec_free(parser->imm_string);
4815     vec_free(parser->imm_float);
4816     vec_free(parser->globals);
4817     vec_free(parser->fields);
4818
4819     for (i = 0; i < vec_size(parser->variables); ++i)
4820         util_htdel(parser->variables[i]);
4821     vec_free(parser->variables);
4822     vec_free(parser->_blocklocals);
4823     vec_free(parser->_locals);
4824
4825     for (i = 0; i < vec_size(parser->_typedefs); ++i)
4826         ast_delete(parser->_typedefs[i]);
4827     vec_free(parser->_typedefs);
4828     for (i = 0; i < vec_size(parser->typedefs); ++i)
4829         util_htdel(parser->typedefs[i]);
4830     vec_free(parser->typedefs);
4831     vec_free(parser->_blocktypedefs);
4832
4833     vec_free(parser->_block_ctx);
4834
4835     vec_free(parser->labels);
4836     vec_free(parser->gotos);
4837
4838     mem_d(parser);
4839 }
4840
4841 bool parser_finish(const char *output)
4842 {
4843     size_t i;
4844     ir_builder *ir;
4845     bool retval = true;
4846
4847     if (!parser->errors)
4848     {
4849         ir = ir_builder_new("gmqcc_out");
4850         if (!ir) {
4851             con_out("failed to allocate builder\n");
4852             return false;
4853         }
4854
4855         for (i = 0; i < vec_size(parser->fields); ++i) {
4856             ast_value *field;
4857             bool hasvalue;
4858             if (!ast_istype(parser->fields[i], ast_value))
4859                 continue;
4860             field = (ast_value*)parser->fields[i];
4861             hasvalue = field->hasvalue;
4862             field->hasvalue = false;
4863             if (!ast_global_codegen((ast_value*)field, ir, true)) {
4864                 con_out("failed to generate field %s\n", field->name);
4865                 ir_builder_delete(ir);
4866                 return false;
4867             }
4868             if (hasvalue) {
4869                 ir_value *ifld;
4870                 ast_expression *subtype;
4871                 field->hasvalue = true;
4872                 subtype = field->expression.next;
4873                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4874                 if (subtype->expression.vtype == TYPE_FIELD)
4875                     ifld->fieldtype = subtype->expression.next->expression.vtype;
4876                 else if (subtype->expression.vtype == TYPE_FUNCTION)
4877                     ifld->outtype = subtype->expression.next->expression.vtype;
4878                 (void)!ir_value_set_field(field->ir_v, ifld);
4879             }
4880         }
4881         for (i = 0; i < vec_size(parser->globals); ++i) {
4882             ast_value *asvalue;
4883             if (!ast_istype(parser->globals[i], ast_value))
4884                 continue;
4885             asvalue = (ast_value*)(parser->globals[i]);
4886             if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4887                 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4888                                                "unused global: `%s`", asvalue->name);
4889             }
4890             if (!ast_global_codegen(asvalue, ir, false)) {
4891                 con_out("failed to generate global %s\n", asvalue->name);
4892                 ir_builder_delete(ir);
4893                 return false;
4894             }
4895         }
4896         for (i = 0; i < vec_size(parser->imm_float); ++i) {
4897             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4898                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4899                 ir_builder_delete(ir);
4900                 return false;
4901             }
4902         }
4903         for (i = 0; i < vec_size(parser->imm_string); ++i) {
4904             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4905                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4906                 ir_builder_delete(ir);
4907                 return false;
4908             }
4909         }
4910         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4911             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4912                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4913                 ir_builder_delete(ir);
4914                 return false;
4915             }
4916         }
4917         for (i = 0; i < vec_size(parser->globals); ++i) {
4918             ast_value *asvalue;
4919             if (!ast_istype(parser->globals[i], ast_value))
4920                 continue;
4921             asvalue = (ast_value*)(parser->globals[i]);
4922             if (!ast_generate_accessors(asvalue, ir)) {
4923                 ir_builder_delete(ir);
4924                 return false;
4925             }
4926         }
4927         for (i = 0; i < vec_size(parser->fields); ++i) {
4928             ast_value *asvalue;
4929             asvalue = (ast_value*)(parser->fields[i]->expression.next);
4930
4931             if (!ast_istype((ast_expression*)asvalue, ast_value))
4932                 continue;
4933             if (asvalue->expression.vtype != TYPE_ARRAY)
4934                 continue;
4935             if (!ast_generate_accessors(asvalue, ir)) {
4936                 ir_builder_delete(ir);
4937                 return false;
4938             }
4939         }
4940         for (i = 0; i < vec_size(parser->functions); ++i) {
4941             if (!ast_function_codegen(parser->functions[i], ir)) {
4942                 con_out("failed to generate function %s\n", parser->functions[i]->name);
4943                 ir_builder_delete(ir);
4944                 return false;
4945             }
4946         }
4947         if (opts.dump)
4948             ir_builder_dump(ir, con_out);
4949         for (i = 0; i < vec_size(parser->functions); ++i) {
4950             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4951                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4952                 ir_builder_delete(ir);
4953                 return false;
4954             }
4955         }
4956
4957         if (retval) {
4958             if (opts.dumpfin)
4959                 ir_builder_dump(ir, con_out);
4960
4961             generate_checksum(parser);
4962
4963             if (!ir_builder_generate(ir, output)) {
4964                 con_out("*** failed to generate output file\n");
4965                 ir_builder_delete(ir);
4966                 return false;
4967             }
4968         }
4969
4970         ir_builder_delete(ir);
4971         return retval;
4972     }
4973
4974     con_out("*** there were compile errors\n");
4975     return false;
4976 }