]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
425668225f2ee37c21be88d8c1ab4bbf40bc17b1
[xonotic/gmqcc.git] / parser.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Wolfgang Bumiller
4  *     Dale Weiler
5  * 
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include <stdio.h>
25 #include <stdarg.h>
26
27 #include "gmqcc.h"
28 #include "lexer.h"
29 #include "ast.h"
30
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS  2
33
34 #define PARSER_HT_SIZE    1024
35 #define TYPEDEF_HT_SIZE   16
36
37 enum parser_pot { POT_PAREN, POT_TERNARY1, POT_TERNARY2 };
38 typedef struct {
39     lex_file *lex;
40     int      tok;
41
42     ast_expression **globals;
43     ast_expression **fields;
44     ast_function **functions;
45     ast_value    **imm_float;
46     ast_value    **imm_string;
47     ast_value    **imm_vector;
48     size_t         translated;
49
50     /* must be deleted first, they reference immediates and values */
51     ast_value    **accessors;
52
53     ast_value *imm_float_zero;
54     ast_value *imm_float_one;
55     ast_value *imm_vector_zero;
56     ast_value *nil;
57
58     size_t crc_globals;
59     size_t crc_fields;
60
61     ast_function *function;
62
63     /* All the labels the function defined...
64      * Should they be in ast_function instead?
65      */
66     ast_label  **labels;
67     ast_goto   **gotos;
68     const char **breaks;
69     const char **continues;
70
71     /* A list of hashtables for each scope */
72     ht *variables;
73     ht htfields;
74     ht htglobals;
75     ht *typedefs;
76
77     /* not to be used directly, we use the hash table */
78     ast_expression **_locals;
79     size_t          *_blocklocals;
80     ast_value      **_typedefs;
81     size_t          *_blocktypedefs;
82     lex_ctx         *_block_ctx;
83
84     /* we store the '=' operator info */
85     const oper_info *assign_op;
86
87     /* TYPE_FIELD -> parser_find_fields is used instead of find_var
88      * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
89      * anything else: type error
90      */
91     qcint  memberof;
92
93     /* Keep track of our ternary vs parenthesis nesting state.
94      * If we reach a 'comma' operator in a ternary without a paren,
95      * we shall trigger -Wternary-precedence.
96      */
97     enum parser_pot *pot;
98
99     /* pragma flags */
100     bool noref;
101 } parser_t;
102
103 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
104
105 static void parser_enterblock(parser_t *parser);
106 static bool parser_leaveblock(parser_t *parser);
107 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
108 static bool parse_typedef(parser_t *parser);
109 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
110 static ast_block* parse_block(parser_t *parser);
111 static bool parse_block_into(parser_t *parser, ast_block *block);
112 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
113 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
114 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue);
115 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
116
117 static void parseerror(parser_t *parser, const char *fmt, ...)
118 {
119     va_list ap;
120     va_start(ap, fmt);
121     vcompile_error(parser->lex->tok.ctx, 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[1]->expression.vtype == TYPE_FLOAT) &&
767                 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
768                   exprs[0]->expression.vtype == TYPE_FLOAT)
769                 )
770             {
771                 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
772                            type_name[exprs[1]->expression.vtype],
773                            type_name[exprs[0]->expression.vtype]);
774                 return false;
775             }
776             switch (exprs[0]->expression.vtype) {
777                 case TYPE_FLOAT:
778                     if (exprs[1]->expression.vtype == TYPE_VECTOR)
779                     {
780                         if (CanConstFold(exprs[0], exprs[1]))
781                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
782                         else
783                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
784                     }
785                     else
786                     {
787                         if (CanConstFold(exprs[0], exprs[1]))
788                             out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
789                         else
790                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
791                     }
792                     break;
793                 case TYPE_VECTOR:
794                     if (exprs[1]->expression.vtype == TYPE_FLOAT)
795                     {
796                         if (CanConstFold(exprs[0], exprs[1]))
797                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
798                         else
799                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
800                     }
801                     else
802                     {
803                         if (CanConstFold(exprs[0], exprs[1]))
804                             out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
805                         else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
806                             vector vec = ConstV(0);
807                             if (!vec.y && !vec.z) { /* 'n 0 0' * v */
808                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
809                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
810                                 out->expression.node.keep = false;
811                                 ((ast_member*)out)->rvalue = true;
812                                 if (vec.x != 1)
813                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
814                             }
815                             else if (!vec.x && !vec.z) { /* '0 n 0' * v */
816                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
817                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
818                                 out->expression.node.keep = false;
819                                 ((ast_member*)out)->rvalue = true;
820                                 if (vec.y != 1)
821                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
822                             }
823                             else if (!vec.x && !vec.y) { /* '0 n 0' * v */
824                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
825                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
826                                 out->expression.node.keep = false;
827                                 ((ast_member*)out)->rvalue = true;
828                                 if (vec.z != 1)
829                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
830                             }
831                             else
832                                 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
833                         }
834                         else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
835                             vector vec = ConstV(1);
836                             if (!vec.y && !vec.z) { /* v * 'n 0 0' */
837                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
838                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
839                                 out->expression.node.keep = false;
840                                 ((ast_member*)out)->rvalue = true;
841                                 if (vec.x != 1)
842                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
843                             }
844                             else if (!vec.x && !vec.z) { /* v * '0 n 0' */
845                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
846                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
847                                 out->expression.node.keep = false;
848                                 ((ast_member*)out)->rvalue = true;
849                                 if (vec.y != 1)
850                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
851                             }
852                             else if (!vec.x && !vec.y) { /* v * '0 n 0' */
853                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
854                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
855                                 out->expression.node.keep = false;
856                                 ((ast_member*)out)->rvalue = true;
857                                 if (vec.z != 1)
858                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
859                             }
860                             else
861                                 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
862                         }
863                         else
864                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
865                     }
866                     break;
867                 default:
868                     parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
869                                type_name[exprs[1]->expression.vtype],
870                                type_name[exprs[0]->expression.vtype]);
871                     return false;
872             };
873             break;
874         case opid1('/'):
875             if (NotSameType(TYPE_FLOAT)) {
876                 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
877                            type_name[exprs[0]->expression.vtype],
878                            type_name[exprs[1]->expression.vtype]);
879                 return false;
880             }
881             if (CanConstFold(exprs[0], exprs[1]))
882                 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
883             else
884                 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
885             break;
886         case opid1('%'):
887         case opid2('%','='):
888             parseerror(parser, "qc does not have a modulo operator");
889             return false;
890         case opid1('|'):
891         case opid1('&'):
892             if (NotSameType(TYPE_FLOAT)) {
893                 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
894                            type_name[exprs[0]->expression.vtype],
895                            type_name[exprs[1]->expression.vtype]);
896                 return false;
897             }
898             if (CanConstFold(exprs[0], exprs[1]))
899                 out = (ast_expression*)parser_const_float(parser,
900                     (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
901                                             (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
902             else
903                 out = (ast_expression*)ast_binary_new(ctx,
904                     (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
905                     exprs[0], exprs[1]);
906             break;
907         case opid1('^'):
908             parseerror(parser, "TODO: bitxor");
909             return false;
910
911         case opid2('<','<'):
912         case opid2('>','>'):
913         case opid3('<','<','='):
914         case opid3('>','>','='):
915             parseerror(parser, "TODO: shifts");
916             return false;
917
918         case opid2('|','|'):
919             generated_op += 1; /* INSTR_OR */
920         case opid2('&','&'):
921             generated_op += INSTR_AND;
922 #if 0
923             if (NotSameType(TYPE_FLOAT)) {
924                 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
925                            type_name[exprs[0]->expression.vtype],
926                            type_name[exprs[1]->expression.vtype]);
927                 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
928                 parseerror(parser, "TODO: optional early out");
929                 return false;
930             }
931 #endif
932             if (CanConstFold(exprs[0], exprs[1]))
933             {
934                 if (OPTS_FLAG(PERL_LOGIC)) {
935                     if (immediate_is_true(ctx, asvalue[0]))
936                         out = exprs[1];
937                 }
938                 else
939                     out = (ast_expression*)parser_const_float(parser,
940                           ( (generated_op == INSTR_OR)
941                             ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
942                             : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
943                           ? 1 : 0);
944             }
945             else
946             {
947                 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
948                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
949                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
950                     parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
951                     return false;
952                 }
953                 for (i = 0; i < 2; ++i) {
954                     if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
955                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
956                         if (!out) break;
957                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
958                         if (!out) break;
959                         exprs[i] = out; out = NULL;
960                         if (OPTS_FLAG(PERL_LOGIC)) {
961                             /* here we want to keep the right expressions' type */
962                             break;
963                         }
964                     }
965                     else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
966                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
967                         if (!out) break;
968                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
969                         if (!out) break;
970                         exprs[i] = out; out = NULL;
971                         if (OPTS_FLAG(PERL_LOGIC)) {
972                             /* here we want to keep the right expressions' type */
973                             break;
974                         }
975                     }
976                 }
977                 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
978             }
979             break;
980
981         case opid2('?',':'):
982             if (vec_last(parser->pot) != POT_TERNARY2) {
983                 parseerror(parser, "mismatched parenthesis/ternary");
984                 return false;
985             }
986             vec_pop(parser->pot);
987             if (!ast_compare_type(exprs[1], exprs[2])) {
988                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
989                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
990                 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
991                 return false;
992             }
993             if (CanConstFold1(exprs[0]))
994                 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
995             else
996                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
997             break;
998
999         case opid1('>'):
1000             generated_op += 1; /* INSTR_GT */
1001         case opid1('<'):
1002             generated_op += 1; /* INSTR_LT */
1003         case opid2('>', '='):
1004             generated_op += 1; /* INSTR_GE */
1005         case opid2('<', '='):
1006             generated_op += INSTR_LE;
1007             if (NotSameType(TYPE_FLOAT)) {
1008                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1009                            type_name[exprs[0]->expression.vtype],
1010                            type_name[exprs[1]->expression.vtype]);
1011                 return false;
1012             }
1013             out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1014             break;
1015         case opid2('!', '='):
1016             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1017                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1018                            type_name[exprs[0]->expression.vtype],
1019                            type_name[exprs[1]->expression.vtype]);
1020                 return false;
1021             }
1022             out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1023             break;
1024         case opid2('=', '='):
1025             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1026                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1027                            type_name[exprs[0]->expression.vtype],
1028                            type_name[exprs[1]->expression.vtype]);
1029                 return false;
1030             }
1031             out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1032             break;
1033
1034         case opid1('='):
1035             if (ast_istype(exprs[0], ast_entfield)) {
1036                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1037                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1038                     exprs[0]->expression.vtype == TYPE_FIELD &&
1039                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1040                 {
1041                     assignop = type_storep_instr[TYPE_VECTOR];
1042                 }
1043                 else
1044                     assignop = type_storep_instr[exprs[0]->expression.vtype];
1045                 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1046                 {
1047                     ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1048                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1049                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1050                         field->expression.next->expression.vtype == TYPE_FUNCTION &&
1051                         exprs[1]->expression.vtype == TYPE_FUNCTION)
1052                     {
1053                         (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1054                                             "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1055                     }
1056                     else
1057                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1058                 }
1059             }
1060             else
1061             {
1062                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1063                     exprs[0]->expression.vtype == TYPE_FIELD &&
1064                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1065                 {
1066                     assignop = type_store_instr[TYPE_VECTOR];
1067                 }
1068                 else {
1069                     assignop = type_store_instr[exprs[0]->expression.vtype];
1070                 }
1071
1072                 if (assignop == AINSTR_END) {
1073                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1074                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1075                     parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1076                 }
1077                 else if (!ast_compare_type(exprs[0], exprs[1]))
1078                 {
1079                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1080                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1081                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1082                         exprs[0]->expression.vtype == TYPE_FUNCTION &&
1083                         exprs[1]->expression.vtype == TYPE_FUNCTION)
1084                     {
1085                         (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1086                                             "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1087                     }
1088                     else
1089                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1090                 }
1091             }
1092             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1093                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1094             }
1095             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1096             break;
1097         case opid3('+','+','P'):
1098         case opid3('-','-','P'):
1099             /* prefix ++ */
1100             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1101                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1102                 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1103                 return false;
1104             }
1105             if (op->id == opid3('+','+','P'))
1106                 addop = INSTR_ADD_F;
1107             else
1108                 addop = INSTR_SUB_F;
1109             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1110                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1111             }
1112             if (ast_istype(exprs[0], ast_entfield)) {
1113                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1114                                                         exprs[0],
1115                                                         (ast_expression*)parser_const_float_1(parser));
1116             } else {
1117                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1118                                                         exprs[0],
1119                                                         (ast_expression*)parser_const_float_1(parser));
1120             }
1121             break;
1122         case opid3('S','+','+'):
1123         case opid3('S','-','-'):
1124             /* prefix ++ */
1125             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1126                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1127                 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1128                 return false;
1129             }
1130             if (op->id == opid3('S','+','+')) {
1131                 addop = INSTR_ADD_F;
1132                 subop = INSTR_SUB_F;
1133             } else {
1134                 addop = INSTR_SUB_F;
1135                 subop = INSTR_ADD_F;
1136             }
1137             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1138                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1139             }
1140             if (ast_istype(exprs[0], ast_entfield)) {
1141                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1142                                                         exprs[0],
1143                                                         (ast_expression*)parser_const_float_1(parser));
1144             } else {
1145                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1146                                                         exprs[0],
1147                                                         (ast_expression*)parser_const_float_1(parser));
1148             }
1149             if (!out)
1150                 return false;
1151             out = (ast_expression*)ast_binary_new(ctx, subop,
1152                                                   out,
1153                                                   (ast_expression*)parser_const_float_1(parser));
1154             break;
1155         case opid2('+','='):
1156         case opid2('-','='):
1157             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1158                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1159             {
1160                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1161                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1162                 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1163                            ty1, ty2);
1164                 return false;
1165             }
1166             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1167                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1168             }
1169             if (ast_istype(exprs[0], ast_entfield))
1170                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1171             else
1172                 assignop = type_store_instr[exprs[0]->expression.vtype];
1173             switch (exprs[0]->expression.vtype) {
1174                 case TYPE_FLOAT:
1175                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1176                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1177                                                             exprs[0], exprs[1]);
1178                     break;
1179                 case TYPE_VECTOR:
1180                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1181                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1182                                                             exprs[0], exprs[1]);
1183                     break;
1184                 default:
1185                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1186                                type_name[exprs[0]->expression.vtype],
1187                                type_name[exprs[1]->expression.vtype]);
1188                     return false;
1189             };
1190             break;
1191         case opid2('*','='):
1192         case opid2('/','='):
1193             if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1194                 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1195                   exprs[0]->expression.vtype == TYPE_VECTOR))
1196             {
1197                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1198                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1199                 parseerror(parser, "invalid types used in expression: %s and %s",
1200                            ty1, ty2);
1201                 return false;
1202             }
1203             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1204                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1205             }
1206             if (ast_istype(exprs[0], ast_entfield))
1207                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1208             else
1209                 assignop = type_store_instr[exprs[0]->expression.vtype];
1210             switch (exprs[0]->expression.vtype) {
1211                 case TYPE_FLOAT:
1212                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1213                                                             (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1214                                                             exprs[0], exprs[1]);
1215                     break;
1216                 case TYPE_VECTOR:
1217                     if (op->id == opid2('*','=')) {
1218                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1219                                                                 exprs[0], exprs[1]);
1220                     } else {
1221                         /* there's no DIV_VF */
1222                         out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1223                                                               (ast_expression*)parser_const_float_1(parser),
1224                                                               exprs[1]);
1225                         if (!out)
1226                             return false;
1227                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1228                                                                 exprs[0], out);
1229                     }
1230                     break;
1231                 default:
1232                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1233                                type_name[exprs[0]->expression.vtype],
1234                                type_name[exprs[1]->expression.vtype]);
1235                     return false;
1236             };
1237             break;
1238         case opid2('&','='):
1239         case opid2('|','='):
1240             if (NotSameType(TYPE_FLOAT)) {
1241                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1242                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1243                 parseerror(parser, "invalid types used in expression: %s and %s",
1244                            ty1, ty2);
1245                 return false;
1246             }
1247             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1248                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1249             }
1250             if (ast_istype(exprs[0], ast_entfield))
1251                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1252             else
1253                 assignop = type_store_instr[exprs[0]->expression.vtype];
1254             out = (ast_expression*)ast_binstore_new(ctx, assignop,
1255                                                     (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1256                                                     exprs[0], exprs[1]);
1257             break;
1258         case opid3('&','~','='):
1259             /* This is like: a &= ~(b);
1260              * But QC has no bitwise-not, so we implement it as
1261              * a -= a & (b);
1262              */
1263             if (NotSameType(TYPE_FLOAT)) {
1264                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1265                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1266                 parseerror(parser, "invalid types used in expression: %s and %s",
1267                            ty1, ty2);
1268                 return false;
1269             }
1270             if (ast_istype(exprs[0], ast_entfield))
1271                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1272             else
1273                 assignop = type_store_instr[exprs[0]->expression.vtype];
1274             out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1275             if (!out)
1276                 return false;
1277             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1278                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1279             }
1280             asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1281             asbinstore->keep_dest = true;
1282             out = (ast_expression*)asbinstore;
1283             break;
1284     }
1285 #undef NotSameType
1286
1287     if (!out) {
1288         parseerror(parser, "failed to apply operand %s", op->op);
1289         return false;
1290     }
1291
1292     DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1293     vec_push(sy->out, syexp(ctx, out));
1294     return true;
1295 }
1296
1297 static bool parser_close_call(parser_t *parser, shunt *sy)
1298 {
1299     /* was a function call */
1300     ast_expression *fun;
1301     ast_call       *call;
1302
1303     size_t          fid;
1304     size_t          paramcount;
1305
1306     vec_shrinkby(sy->ops, 1);
1307     fid = sy->ops[vec_size(sy->ops)].off;
1308
1309     /* out[fid] is the function
1310      * everything above is parameters...
1311      * 0 params = nothing
1312      * 1 params = ast_expression
1313      * more = ast_block
1314      */
1315
1316     if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1317         parseerror(parser, "internal error: function call needs function and parameter list...");
1318         return false;
1319     }
1320
1321     fun = sy->out[fid].out;
1322
1323     if (fun == intrinsic_debug_typestring) {
1324         char ty[1024];
1325         if (fid+2 != vec_size(sy->out) ||
1326             vec_last(sy->out).block)
1327         {
1328             parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1329             return false;
1330         }
1331         ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1332         ast_unref(vec_last(sy->out).out);
1333         sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1334                              (ast_expression*)parser_const_string(parser, ty, false));
1335         vec_shrinkby(sy->out, 1);
1336         return true;
1337     }
1338
1339     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1340     if (!call) {
1341         parseerror(parser, "internal error: failed to create ast_call node");
1342         return false;
1343     }
1344
1345     if (fid+1 == vec_size(sy->out)) {
1346         /* no arguments */
1347         paramcount = 0;
1348     } else if (fid+2 == vec_size(sy->out)) {
1349         ast_block *params;
1350         vec_shrinkby(sy->out, 1);
1351         params = sy->out[vec_size(sy->out)].block;
1352         if (!params) {
1353             /* 1 param */
1354             paramcount = 1;
1355             vec_push(call->params, sy->out[vec_size(sy->out)].out);
1356         } else {
1357             paramcount = vec_size(params->exprs);
1358             call->params = params->exprs;
1359             params->exprs = NULL;
1360             ast_delete(params);
1361         }
1362         (void)!ast_call_check_types(call);
1363     } else {
1364         parseerror(parser, "invalid function call");
1365         return false;
1366     }
1367
1368     /* overwrite fid, the function, with a call */
1369     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1370
1371     if (fun->expression.vtype != TYPE_FUNCTION) {
1372         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1373         return false;
1374     }
1375
1376     if (!fun->expression.next) {
1377         parseerror(parser, "could not determine function return type");
1378         return false;
1379     } else {
1380         ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1381
1382         if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1383             if (!fval) {
1384                 return !parsewarning(parser, WARN_DEPRECATED,
1385                         "call to function (which is marked deprecated)\n",
1386                         "-> it has been declared here: %s:%i",
1387                         ast_ctx(fun).file, ast_ctx(fun).line);
1388             }
1389             if (!fval->desc) {
1390                 return !parsewarning(parser, WARN_DEPRECATED,
1391                         "call to `%s` (which is marked deprecated)\n"
1392                         "-> `%s` declared here: %s:%i",
1393                         fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1394             }
1395             return !parsewarning(parser, WARN_DEPRECATED,
1396                     "call to `%s` (deprecated: %s)\n"
1397                     "-> `%s` declared here: %s:%i",
1398                     fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1399                     ast_ctx(fun).line);
1400         }
1401
1402         if (vec_size(fun->expression.params) != paramcount &&
1403             !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1404               vec_size(fun->expression.params) < paramcount))
1405         {
1406             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1407             if (fval)
1408                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1409                                      "too %s parameters for call to %s: expected %i, got %i\n"
1410                                      " -> `%s` has been declared here: %s:%i",
1411                                      fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1412                                      fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1413             else
1414                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1415                                      "too %s parameters for function call: expected %i, got %i\n"
1416                                      " -> it has been declared here: %s:%i",
1417                                      fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1418                                      ast_ctx(fun).file, (int)ast_ctx(fun).line);
1419         }
1420     }
1421
1422     return true;
1423 }
1424
1425 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1426 {
1427     if (!vec_size(sy->ops)) {
1428         parseerror(parser, "unmatched closing paren");
1429         return false;
1430     }
1431     /* this would for bit a + (x) because there are no operators inside (x)
1432     if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1433         parseerror(parser, "empty parenthesis expression");
1434         return false;
1435     }
1436     */
1437     while (vec_size(sy->ops)) {
1438         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1439             if (!parser_close_call(parser, sy))
1440                 return false;
1441             break;
1442         }
1443         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1444             vec_shrinkby(sy->ops, 1);
1445             return !functions_only;
1446         }
1447         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1448             if (functions_only)
1449                 return false;
1450             /* pop off the parenthesis */
1451             vec_shrinkby(sy->ops, 1);
1452             /* then apply the index operator */
1453             if (!parser_sy_apply_operator(parser, sy))
1454                 return false;
1455             return true;
1456         }
1457         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1458             if (functions_only)
1459                 return false;
1460             if (vec_last(parser->pot) != POT_TERNARY1) {
1461                 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1462                 return false;
1463             }
1464             vec_last(parser->pot) = POT_TERNARY2;
1465             /* pop off the parenthesis */
1466             vec_shrinkby(sy->ops, 1);
1467             return true;
1468         }
1469         if (!parser_sy_apply_operator(parser, sy))
1470             return false;
1471     }
1472     return true;
1473 }
1474
1475 static void parser_reclassify_token(parser_t *parser)
1476 {
1477     size_t i;
1478     for (i = 0; i < operator_count; ++i) {
1479         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1480             parser->tok = TOKEN_OPERATOR;
1481             return;
1482         }
1483     }
1484 }
1485
1486 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue)
1487 {
1488     ast_expression *expr = NULL;
1489     shunt sy;
1490     bool wantop = false;
1491     bool gotmemberof = false;
1492     /* only warn once about an assignment in a truth value because the current code
1493      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1494      */
1495     bool warn_truthvalue = true;
1496
1497     /* count the parens because an if starts with one, so the
1498      * end of a condition is an unmatched closing paren
1499      */
1500     int parens = 0;
1501     int ternaries = 0;
1502
1503     sy.out = NULL;
1504     sy.ops = NULL;
1505
1506     parser->lex->flags.noops = false;
1507
1508     parser_reclassify_token(parser);
1509
1510     while (true)
1511     {
1512         if (gotmemberof)
1513             gotmemberof = false;
1514         else
1515             parser->memberof = 0;
1516
1517         if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1518             parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1519         {
1520             /* a translatable string */
1521             ast_value *val;
1522
1523             if (wantop) {
1524                 parseerror(parser, "expected operator or end of statement, got constant");
1525                 goto onerr;
1526             }
1527
1528             parser->lex->flags.noops = true;
1529             if (!parser_next(parser) || parser->tok != '(') {
1530                 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1531                 goto onerr;
1532             }
1533             parser->lex->flags.noops = false;
1534             if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1535                 parseerror(parser, "expected a constant string in translatable-string extension");
1536                 goto onerr;
1537             }
1538             val = parser_const_string(parser, parser_tokval(parser), true);
1539             wantop = true;
1540             if (!val)
1541                 return NULL;
1542             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1543             DEBUGSHUNTDO(con_out("push string\n"));
1544
1545             if (!parser_next(parser) || parser->tok != ')') {
1546                 parseerror(parser, "expected closing paren after translatable string");
1547                 goto onerr;
1548             }
1549         }
1550         else if (parser->tok == TOKEN_IDENT)
1551         {
1552             ast_expression *var;
1553             if (wantop) {
1554                 parseerror(parser, "expected operator or end of statement");
1555                 goto onerr;
1556             }
1557             wantop = true;
1558             /* variable */
1559             if (opts.standard == COMPILER_GMQCC)
1560             {
1561                 if (parser->memberof == TYPE_ENTITY) {
1562                     /* still get vars first since there could be a fieldpointer */
1563                     var = parser_find_var(parser, parser_tokval(parser));
1564                     if (!var)
1565                         var = parser_find_field(parser, parser_tokval(parser));
1566                 }
1567                 else if (parser->memberof == TYPE_VECTOR)
1568                 {
1569                     parseerror(parser, "TODO: implement effective vector member access");
1570                     goto onerr;
1571                 }
1572                 else if (parser->memberof) {
1573                     parseerror(parser, "namespace for member not found");
1574                     goto onerr;
1575                 }
1576                 else
1577                     var = parser_find_var(parser, parser_tokval(parser));
1578             } else {
1579                 var = parser_find_var(parser, parser_tokval(parser));
1580                 if (!var)
1581                     var = parser_find_field(parser, parser_tokval(parser));
1582             }
1583             if (!var) {
1584                 /* intrinsics */
1585                 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1586                     var = (ast_expression*)intrinsic_debug_typestring;
1587
1588                 }
1589                 else
1590                 {
1591                     parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1592                     goto onerr;
1593                 }
1594             }
1595             else
1596             {
1597                 if (ast_istype(var, ast_value)) {
1598                     ((ast_value*)var)->uses++;
1599                 }
1600                 else if (ast_istype(var, ast_member)) {
1601                     ast_member *mem = (ast_member*)var;
1602                     if (ast_istype(mem->owner, ast_value))
1603                         ((ast_value*)(mem->owner))->uses++;
1604                 }
1605             }
1606             vec_push(sy.out, syexp(parser_ctx(parser), var));
1607             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1608         }
1609         else if (parser->tok == TOKEN_FLOATCONST) {
1610             ast_value *val;
1611             if (wantop) {
1612                 parseerror(parser, "expected operator or end of statement, got constant");
1613                 goto onerr;
1614             }
1615             wantop = true;
1616             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1617             if (!val)
1618                 return NULL;
1619             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1620             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1621         }
1622         else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1623             ast_value *val;
1624             if (wantop) {
1625                 parseerror(parser, "expected operator or end of statement, got constant");
1626                 goto onerr;
1627             }
1628             wantop = true;
1629             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1630             if (!val)
1631                 return NULL;
1632             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1633             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1634         }
1635         else if (parser->tok == TOKEN_STRINGCONST) {
1636             ast_value *val;
1637             if (wantop) {
1638                 parseerror(parser, "expected operator or end of statement, got constant");
1639                 goto onerr;
1640             }
1641             wantop = true;
1642             val = parser_const_string(parser, parser_tokval(parser), false);
1643             if (!val)
1644                 return NULL;
1645             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1646             DEBUGSHUNTDO(con_out("push string\n"));
1647         }
1648         else if (parser->tok == TOKEN_VECTORCONST) {
1649             ast_value *val;
1650             if (wantop) {
1651                 parseerror(parser, "expected operator or end of statement, got constant");
1652                 goto onerr;
1653             }
1654             wantop = true;
1655             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1656             if (!val)
1657                 return NULL;
1658             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1659             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1660                                 parser_token(parser)->constval.v.x,
1661                                 parser_token(parser)->constval.v.y,
1662                                 parser_token(parser)->constval.v.z));
1663         }
1664         else if (parser->tok == '(') {
1665             parseerror(parser, "internal error: '(' should be classified as operator");
1666             goto onerr;
1667         }
1668         else if (parser->tok == '[') {
1669             parseerror(parser, "internal error: '[' should be classified as operator");
1670             goto onerr;
1671         }
1672         else if (parser->tok == ')') {
1673             if (wantop) {
1674                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1675                 --parens;
1676                 if (parens < 0)
1677                     break;
1678                 /* we do expect an operator next */
1679                 /* closing an opening paren */
1680                 if (!parser_close_paren(parser, &sy, false))
1681                     goto onerr;
1682                 if (vec_last(parser->pot) != POT_PAREN) {
1683                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1684                     goto onerr;
1685                 }
1686                 vec_pop(parser->pot);
1687             } else {
1688                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1689                 --parens;
1690                 if (parens < 0)
1691                     break;
1692                 /* allowed for function calls */
1693                 if (!parser_close_paren(parser, &sy, true))
1694                     goto onerr;
1695                 if (vec_last(parser->pot) != POT_PAREN) {
1696                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1697                     goto onerr;
1698                 }
1699                 vec_pop(parser->pot);
1700             }
1701             wantop = true;
1702         }
1703         else if (parser->tok == ']') {
1704             if (!wantop)
1705                 parseerror(parser, "operand expected");
1706             --parens;
1707             if (parens < 0)
1708                 break;
1709             if (!parser_close_paren(parser, &sy, false))
1710                 goto onerr;
1711             if (vec_last(parser->pot) != POT_PAREN) {
1712                 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1713                 goto onerr;
1714             }
1715             vec_pop(parser->pot);
1716             wantop = true;
1717         }
1718         else if (parser->tok == TOKEN_TYPENAME) {
1719             parseerror(parser, "unexpected typename");
1720             goto onerr;
1721         }
1722         else if (parser->tok != TOKEN_OPERATOR) {
1723             if (wantop) {
1724                 parseerror(parser, "expected operator or end of statement");
1725                 goto onerr;
1726             }
1727             break;
1728         }
1729         else
1730         {
1731             /* classify the operator */
1732             const oper_info *op;
1733             const oper_info *olast = NULL;
1734             size_t o;
1735             for (o = 0; o < operator_count; ++o) {
1736                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1737                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1738                     !strcmp(parser_tokval(parser), operators[o].op))
1739                 {
1740                     break;
1741                 }
1742             }
1743             if (o == operator_count) {
1744                 /* no operator found... must be the end of the statement */
1745                 break;
1746             }
1747             /* found an operator */
1748             op = &operators[o];
1749
1750             /* when declaring variables, a comma starts a new variable */
1751             if (op->id == opid1(',') && !parens && stopatcomma) {
1752                 /* fixup the token */
1753                 parser->tok = ',';
1754                 break;
1755             }
1756
1757             /* a colon without a pervious question mark cannot be a ternary */
1758             if (!ternaries && op->id == opid2(':','?')) {
1759                 parser->tok = ':';
1760                 break;
1761             }
1762
1763             if (op->id == opid1(',')) {
1764                 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1765                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1766                 }
1767             }
1768
1769             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1770                 olast = &operators[vec_last(sy.ops).etype-1];
1771
1772 #define IsAssignOp(x) (\
1773                 (x) == opid1('=') || \
1774                 (x) == opid2('+','=') || \
1775                 (x) == opid2('-','=') || \
1776                 (x) == opid2('*','=') || \
1777                 (x) == opid2('/','=') || \
1778                 (x) == opid2('%','=') || \
1779                 (x) == opid2('&','=') || \
1780                 (x) == opid2('|','=') || \
1781                 (x) == opid3('&','~','=') \
1782                 )
1783             if (warn_truthvalue) {
1784                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1785                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1786                      (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1787                    )
1788                 {
1789                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1790                     warn_truthvalue = false;
1791                 }
1792             }
1793
1794             while (olast && (
1795                     (op->prec < olast->prec) ||
1796                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1797             {
1798                 if (!parser_sy_apply_operator(parser, &sy))
1799                     goto onerr;
1800                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1801                     olast = &operators[vec_last(sy.ops).etype-1];
1802                 else
1803                     olast = NULL;
1804             }
1805
1806             if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1807                 /* for gmqcc standard: open up the namespace of the previous type */
1808                 ast_expression *prevex = vec_last(sy.out).out;
1809                 if (!prevex) {
1810                     parseerror(parser, "unexpected member operator");
1811                     goto onerr;
1812                 }
1813                 if (prevex->expression.vtype == TYPE_ENTITY)
1814                     parser->memberof = TYPE_ENTITY;
1815                 else if (prevex->expression.vtype == TYPE_VECTOR)
1816                     parser->memberof = TYPE_VECTOR;
1817                 else {
1818                     parseerror(parser, "type error: type has no members");
1819                     goto onerr;
1820                 }
1821                 gotmemberof = true;
1822             }
1823
1824             if (op->id == opid1('(')) {
1825                 if (wantop) {
1826                     size_t sycount = vec_size(sy.out);
1827                     DEBUGSHUNTDO(con_out("push [op] (\n"));
1828                     ++parens; vec_push(parser->pot, POT_PAREN);
1829                     /* we expected an operator, this is the function-call operator */
1830                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1831                 } else {
1832                     ++parens; vec_push(parser->pot, POT_PAREN);
1833                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1834                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
1835                 }
1836                 wantop = false;
1837             } else if (op->id == opid1('[')) {
1838                 if (!wantop) {
1839                     parseerror(parser, "unexpected array subscript");
1840                     goto onerr;
1841                 }
1842                 ++parens; vec_push(parser->pot, POT_PAREN);
1843                 /* push both the operator and the paren, this makes life easier */
1844                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1845                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1846                 wantop = false;
1847             } else if (op->id == opid2('?',':')) {
1848                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1849                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1850                 wantop = false;
1851                 ++ternaries;
1852                 vec_push(parser->pot, POT_TERNARY1);
1853             } else if (op->id == opid2(':','?')) {
1854                 if (!vec_size(parser->pot)) {
1855                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1856                     goto onerr;
1857                 }
1858                 if (vec_last(parser->pot) != POT_TERNARY1) {
1859                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1860                     goto onerr;
1861                 }
1862                 if (!parser_close_paren(parser, &sy, false))
1863                     goto onerr;
1864                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1865                 wantop = false;
1866                 --ternaries;
1867             } else {
1868                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1869                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1870                 wantop = !!(op->flags & OP_SUFFIX);
1871             }
1872         }
1873         if (!parser_next(parser)) {
1874             goto onerr;
1875         }
1876         if (parser->tok == ';' ||
1877             (!parens && parser->tok == ']'))
1878         {
1879             break;
1880         }
1881     }
1882
1883     while (vec_size(sy.ops)) {
1884         if (!parser_sy_apply_operator(parser, &sy))
1885             goto onerr;
1886     }
1887
1888     parser->lex->flags.noops = true;
1889     if (!vec_size(sy.out)) {
1890         parseerror(parser, "empty expression");
1891         expr = NULL;
1892     } else
1893         expr = sy.out[0].out;
1894     vec_free(sy.out);
1895     vec_free(sy.ops);
1896     DEBUGSHUNTDO(con_out("shunt done\n"));
1897     if (vec_size(parser->pot)) {
1898         parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1899         return NULL;
1900     }
1901     vec_free(parser->pot);
1902     return expr;
1903
1904 onerr:
1905     parser->lex->flags.noops = true;
1906     vec_free(sy.out);
1907     vec_free(sy.ops);
1908     return NULL;
1909 }
1910
1911 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1912 {
1913     ast_expression *e = parse_expression_leave(parser, stopatcomma, false);
1914     if (!e)
1915         return NULL;
1916     if (!parser_next(parser)) {
1917         ast_delete(e);
1918         return NULL;
1919     }
1920     return e;
1921 }
1922
1923 static void parser_enterblock(parser_t *parser)
1924 {
1925     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1926     vec_push(parser->_blocklocals, vec_size(parser->_locals));
1927     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1928     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1929     vec_push(parser->_block_ctx, parser_ctx(parser));
1930 }
1931
1932 static bool parser_leaveblock(parser_t *parser)
1933 {
1934     bool   rv = true;
1935     size_t locals, typedefs;
1936
1937     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1938         parseerror(parser, "internal error: parser_leaveblock with no block");
1939         return false;
1940     }
1941
1942     util_htdel(vec_last(parser->variables));
1943     vec_pop(parser->variables);
1944     if (!vec_size(parser->_blocklocals)) {
1945         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1946         return false;
1947     }
1948
1949     locals = vec_last(parser->_blocklocals);
1950     vec_pop(parser->_blocklocals);
1951     while (vec_size(parser->_locals) != locals) {
1952         ast_expression *e = vec_last(parser->_locals);
1953         ast_value      *v = (ast_value*)e;
1954         vec_pop(parser->_locals);
1955         if (ast_istype(e, ast_value) && !v->uses) {
1956             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1957                 rv = false;
1958         }
1959     }
1960
1961     typedefs = vec_last(parser->_blocktypedefs);
1962     while (vec_size(parser->_typedefs) != typedefs) {
1963         ast_delete(vec_last(parser->_typedefs));
1964         vec_pop(parser->_typedefs);
1965     }
1966     util_htdel(vec_last(parser->typedefs));
1967     vec_pop(parser->typedefs);
1968
1969     vec_pop(parser->_block_ctx);
1970     return rv;
1971 }
1972
1973 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1974 {
1975     vec_push(parser->_locals, e);
1976     util_htset(vec_last(parser->variables), name, (void*)e);
1977 }
1978
1979 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1980 {
1981     bool       ifnot = false;
1982     ast_unary *unary;
1983     ast_expression *prev;
1984
1985     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
1986     {
1987         prev = cond;
1988         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1989         if (!cond) {
1990             ast_unref(prev);
1991             parseerror(parser, "internal error: failed to process condition");
1992             return NULL;
1993         }
1994         ifnot = !ifnot;
1995     }
1996     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
1997     {
1998         /* vector types need to be cast to true booleans */
1999         ast_binary *bin = (ast_binary*)cond;
2000         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2001         {
2002             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2003             prev = cond;
2004             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2005             if (!cond) {
2006                 ast_unref(prev);
2007                 parseerror(parser, "internal error: failed to process condition");
2008                 return NULL;
2009             }
2010             ifnot = !ifnot;
2011         }
2012     }
2013
2014     unary = (ast_unary*)cond;
2015     while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2016     {
2017         cond = unary->operand;
2018         unary->operand = NULL;
2019         ast_delete(unary);
2020         ifnot = !ifnot;
2021         unary = (ast_unary*)cond;
2022     }
2023
2024     if (!cond)
2025         parseerror(parser, "internal error: failed to process condition");
2026
2027     if (ifnot) *_ifnot = !*_ifnot;
2028     return cond;
2029 }
2030
2031 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2032 {
2033     ast_ifthen *ifthen;
2034     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2035     bool ifnot = false;
2036
2037     lex_ctx ctx = parser_ctx(parser);
2038
2039     (void)block; /* not touching */
2040
2041     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2042     if (!parser_next(parser)) {
2043         parseerror(parser, "expected condition or 'not'");
2044         return false;
2045     }
2046     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2047         ifnot = true;
2048         if (!parser_next(parser)) {
2049             parseerror(parser, "expected condition in parenthesis");
2050             return false;
2051         }
2052     }
2053     if (parser->tok != '(') {
2054         parseerror(parser, "expected 'if' condition in parenthesis");
2055         return false;
2056     }
2057     /* parse into the expression */
2058     if (!parser_next(parser)) {
2059         parseerror(parser, "expected 'if' condition after opening paren");
2060         return false;
2061     }
2062     /* parse the condition */
2063     cond = parse_expression_leave(parser, false, true);
2064     if (!cond)
2065         return false;
2066     /* closing paren */
2067     if (parser->tok != ')') {
2068         parseerror(parser, "expected closing paren after 'if' condition");
2069         ast_delete(cond);
2070         return false;
2071     }
2072     /* parse into the 'then' branch */
2073     if (!parser_next(parser)) {
2074         parseerror(parser, "expected statement for on-true branch of 'if'");
2075         ast_delete(cond);
2076         return false;
2077     }
2078     if (!parse_statement_or_block(parser, &ontrue)) {
2079         ast_delete(cond);
2080         return false;
2081     }
2082     /* check for an else */
2083     if (!strcmp(parser_tokval(parser), "else")) {
2084         /* parse into the 'else' branch */
2085         if (!parser_next(parser)) {
2086             parseerror(parser, "expected on-false branch after 'else'");
2087             ast_delete(ontrue);
2088             ast_delete(cond);
2089             return false;
2090         }
2091         if (!parse_statement_or_block(parser, &onfalse)) {
2092             ast_delete(ontrue);
2093             ast_delete(cond);
2094             return false;
2095         }
2096     }
2097
2098     cond = process_condition(parser, cond, &ifnot);
2099     if (!cond) {
2100         if (ontrue)  ast_delete(ontrue);
2101         if (onfalse) ast_delete(onfalse);
2102         return false;
2103     }
2104
2105     if (ifnot)
2106         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2107     else
2108         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2109     *out = (ast_expression*)ifthen;
2110     return true;
2111 }
2112
2113 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2114 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2115 {
2116     bool rv;
2117     char *label = NULL;
2118
2119     /* skip the 'while' and get the body */
2120     if (!parser_next(parser)) {
2121         if (OPTS_FLAG(LOOP_LABELS))
2122             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2123         else
2124             parseerror(parser, "expected 'while' condition in parenthesis");
2125         return false;
2126     }
2127
2128     if (parser->tok == ':') {
2129         if (!OPTS_FLAG(LOOP_LABELS))
2130             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2131         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2132             parseerror(parser, "expected loop label");
2133             return false;
2134         }
2135         label = util_strdup(parser_tokval(parser));
2136         if (!parser_next(parser)) {
2137             mem_d(label);
2138             parseerror(parser, "expected 'while' condition in parenthesis");
2139             return false;
2140         }
2141     }
2142
2143     if (parser->tok != '(') {
2144         parseerror(parser, "expected 'while' condition in parenthesis");
2145         return false;
2146     }
2147
2148     vec_push(parser->breaks, label);
2149     vec_push(parser->continues, label);
2150
2151     rv = parse_while_go(parser, block, out);
2152     if (label)
2153         mem_d(label);
2154     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2155         parseerror(parser, "internal error: label stack corrupted");
2156         rv = false;
2157         ast_delete(*out);
2158         *out = NULL;
2159     }
2160     else {
2161         vec_pop(parser->breaks);
2162         vec_pop(parser->continues);
2163     }
2164     return rv;
2165 }
2166
2167 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2168 {
2169     ast_loop *aloop;
2170     ast_expression *cond, *ontrue;
2171
2172     bool ifnot = false;
2173
2174     lex_ctx ctx = parser_ctx(parser);
2175
2176     (void)block; /* not touching */
2177
2178     /* parse into the expression */
2179     if (!parser_next(parser)) {
2180         parseerror(parser, "expected 'while' condition after opening paren");
2181         return false;
2182     }
2183     /* parse the condition */
2184     cond = parse_expression_leave(parser, false, true);
2185     if (!cond)
2186         return false;
2187     /* closing paren */
2188     if (parser->tok != ')') {
2189         parseerror(parser, "expected closing paren after 'while' condition");
2190         ast_delete(cond);
2191         return false;
2192     }
2193     /* parse into the 'then' branch */
2194     if (!parser_next(parser)) {
2195         parseerror(parser, "expected while-loop body");
2196         ast_delete(cond);
2197         return false;
2198     }
2199     if (!parse_statement_or_block(parser, &ontrue)) {
2200         ast_delete(cond);
2201         return false;
2202     }
2203
2204     cond = process_condition(parser, cond, &ifnot);
2205     if (!cond) {
2206         ast_delete(ontrue);
2207         return false;
2208     }
2209     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2210     *out = (ast_expression*)aloop;
2211     return true;
2212 }
2213
2214 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2215 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2216 {
2217     bool rv;
2218     char *label = NULL;
2219
2220     /* skip the 'do' and get the body */
2221     if (!parser_next(parser)) {
2222         if (OPTS_FLAG(LOOP_LABELS))
2223             parseerror(parser, "expected loop label or body");
2224         else
2225             parseerror(parser, "expected loop body");
2226         return false;
2227     }
2228
2229     if (parser->tok == ':') {
2230         if (!OPTS_FLAG(LOOP_LABELS))
2231             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2232         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2233             parseerror(parser, "expected loop label");
2234             return false;
2235         }
2236         label = util_strdup(parser_tokval(parser));
2237         if (!parser_next(parser)) {
2238             mem_d(label);
2239             parseerror(parser, "expected loop body");
2240             return false;
2241         }
2242     }
2243
2244     vec_push(parser->breaks, label);
2245     vec_push(parser->continues, label);
2246
2247     rv = parse_dowhile_go(parser, block, out);
2248     if (label)
2249         mem_d(label);
2250     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2251         parseerror(parser, "internal error: label stack corrupted");
2252         rv = false;
2253         ast_delete(*out);
2254         *out = NULL;
2255     }
2256     else {
2257         vec_pop(parser->breaks);
2258         vec_pop(parser->continues);
2259     }
2260     return rv;
2261 }
2262
2263 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2264 {
2265     ast_loop *aloop;
2266     ast_expression *cond, *ontrue;
2267
2268     bool ifnot = false;
2269
2270     lex_ctx ctx = parser_ctx(parser);
2271
2272     (void)block; /* not touching */
2273
2274     if (!parse_statement_or_block(parser, &ontrue))
2275         return false;
2276
2277     /* expect the "while" */
2278     if (parser->tok != TOKEN_KEYWORD ||
2279         strcmp(parser_tokval(parser), "while"))
2280     {
2281         parseerror(parser, "expected 'while' and condition");
2282         ast_delete(ontrue);
2283         return false;
2284     }
2285
2286     /* skip the 'while' and check for opening paren */
2287     if (!parser_next(parser) || parser->tok != '(') {
2288         parseerror(parser, "expected 'while' condition in parenthesis");
2289         ast_delete(ontrue);
2290         return false;
2291     }
2292     /* parse into the expression */
2293     if (!parser_next(parser)) {
2294         parseerror(parser, "expected 'while' condition after opening paren");
2295         ast_delete(ontrue);
2296         return false;
2297     }
2298     /* parse the condition */
2299     cond = parse_expression_leave(parser, false, true);
2300     if (!cond)
2301         return false;
2302     /* closing paren */
2303     if (parser->tok != ')') {
2304         parseerror(parser, "expected closing paren after 'while' condition");
2305         ast_delete(ontrue);
2306         ast_delete(cond);
2307         return false;
2308     }
2309     /* parse on */
2310     if (!parser_next(parser) || parser->tok != ';') {
2311         parseerror(parser, "expected semicolon after condition");
2312         ast_delete(ontrue);
2313         ast_delete(cond);
2314         return false;
2315     }
2316
2317     if (!parser_next(parser)) {
2318         parseerror(parser, "parse error");
2319         ast_delete(ontrue);
2320         ast_delete(cond);
2321         return false;
2322     }
2323
2324     cond = process_condition(parser, cond, &ifnot);
2325     if (!cond) {
2326         ast_delete(ontrue);
2327         return false;
2328     }
2329     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2330     *out = (ast_expression*)aloop;
2331     return true;
2332 }
2333
2334 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2335 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2336 {
2337     bool rv;
2338     char *label = NULL;
2339
2340     /* skip the 'for' and check for opening paren */
2341     if (!parser_next(parser)) {
2342         if (OPTS_FLAG(LOOP_LABELS))
2343             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2344         else
2345             parseerror(parser, "expected 'for' expressions in parenthesis");
2346         return false;
2347     }
2348
2349     if (parser->tok == ':') {
2350         if (!OPTS_FLAG(LOOP_LABELS))
2351             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2352         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2353             parseerror(parser, "expected loop label");
2354             return false;
2355         }
2356         label = util_strdup(parser_tokval(parser));
2357         if (!parser_next(parser)) {
2358             mem_d(label);
2359             parseerror(parser, "expected 'for' expressions in parenthesis");
2360             return false;
2361         }
2362     }
2363
2364     if (parser->tok != '(') {
2365         parseerror(parser, "expected 'for' expressions in parenthesis");
2366         return false;
2367     }
2368
2369     vec_push(parser->breaks, label);
2370     vec_push(parser->continues, label);
2371
2372     rv = parse_for_go(parser, block, out);
2373     if (label)
2374         mem_d(label);
2375     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2376         parseerror(parser, "internal error: label stack corrupted");
2377         rv = false;
2378         ast_delete(*out);
2379         *out = NULL;
2380     }
2381     else {
2382         vec_pop(parser->breaks);
2383         vec_pop(parser->continues);
2384     }
2385     return rv;
2386 }
2387 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2388 {
2389     ast_loop       *aloop;
2390     ast_expression *initexpr, *cond, *increment, *ontrue;
2391     ast_value      *typevar;
2392
2393     bool retval = true;
2394     bool ifnot  = false;
2395
2396     lex_ctx ctx = parser_ctx(parser);
2397
2398     parser_enterblock(parser);
2399
2400     initexpr  = NULL;
2401     cond      = NULL;
2402     increment = NULL;
2403     ontrue    = NULL;
2404
2405     /* parse into the expression */
2406     if (!parser_next(parser)) {
2407         parseerror(parser, "expected 'for' initializer after opening paren");
2408         goto onerr;
2409     }
2410
2411     typevar = NULL;
2412     if (parser->tok == TOKEN_IDENT)
2413         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2414
2415     if (typevar || parser->tok == TOKEN_TYPENAME) {
2416 #if 0
2417         if (opts.standard != COMPILER_GMQCC) {
2418             if (parsewarning(parser, WARN_EXTENSIONS,
2419                              "current standard does not allow variable declarations in for-loop initializers"))
2420                 goto onerr;
2421         }
2422 #endif
2423         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2424             goto onerr;
2425     }
2426     else if (parser->tok != ';')
2427     {
2428         initexpr = parse_expression_leave(parser, false, false);
2429         if (!initexpr)
2430             goto onerr;
2431     }
2432
2433     /* move on to condition */
2434     if (parser->tok != ';') {
2435         parseerror(parser, "expected semicolon after for-loop initializer");
2436         goto onerr;
2437     }
2438     if (!parser_next(parser)) {
2439         parseerror(parser, "expected for-loop condition");
2440         goto onerr;
2441     }
2442
2443     /* parse the condition */
2444     if (parser->tok != ';') {
2445         cond = parse_expression_leave(parser, false, true);
2446         if (!cond)
2447             goto onerr;
2448     }
2449
2450     /* move on to incrementor */
2451     if (parser->tok != ';') {
2452         parseerror(parser, "expected semicolon after for-loop initializer");
2453         goto onerr;
2454     }
2455     if (!parser_next(parser)) {
2456         parseerror(parser, "expected for-loop condition");
2457         goto onerr;
2458     }
2459
2460     /* parse the incrementor */
2461     if (parser->tok != ')') {
2462         increment = parse_expression_leave(parser, false, false);
2463         if (!increment)
2464             goto onerr;
2465         if (!ast_side_effects(increment)) {
2466             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2467                 goto onerr;
2468         }
2469     }
2470
2471     /* closing paren */
2472     if (parser->tok != ')') {
2473         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2474         goto onerr;
2475     }
2476     /* parse into the 'then' branch */
2477     if (!parser_next(parser)) {
2478         parseerror(parser, "expected for-loop body");
2479         goto onerr;
2480     }
2481     if (!parse_statement_or_block(parser, &ontrue))
2482         goto onerr;
2483
2484     if (cond) {
2485         cond = process_condition(parser, cond, &ifnot);
2486         if (!cond)
2487             goto onerr;
2488     }
2489     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2490     *out = (ast_expression*)aloop;
2491
2492     if (!parser_leaveblock(parser))
2493         retval = false;
2494     return retval;
2495 onerr:
2496     if (initexpr)  ast_delete(initexpr);
2497     if (cond)      ast_delete(cond);
2498     if (increment) ast_delete(increment);
2499     (void)!parser_leaveblock(parser);
2500     return false;
2501 }
2502
2503 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2504 {
2505     ast_expression *exp = NULL;
2506     ast_return     *ret = NULL;
2507     ast_value      *expected = parser->function->vtype;
2508
2509     lex_ctx ctx = parser_ctx(parser);
2510
2511     (void)block; /* not touching */
2512
2513     if (!parser_next(parser)) {
2514         parseerror(parser, "expected return expression");
2515         return false;
2516     }
2517
2518     if (parser->tok != ';') {
2519         exp = parse_expression(parser, false);
2520         if (!exp)
2521             return false;
2522
2523         if (exp->expression.vtype != TYPE_NIL &&
2524             exp->expression.vtype != expected->expression.next->expression.vtype)
2525         {
2526             parseerror(parser, "return with invalid expression");
2527         }
2528
2529         ret = ast_return_new(ctx, exp);
2530         if (!ret) {
2531             ast_delete(exp);
2532             return false;
2533         }
2534     } else {
2535         if (!parser_next(parser))
2536             parseerror(parser, "parse error");
2537         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2538             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2539         }
2540         ret = ast_return_new(ctx, NULL);
2541     }
2542     *out = (ast_expression*)ret;
2543     return true;
2544 }
2545
2546 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2547 {
2548     size_t       i;
2549     unsigned int levels = 0;
2550     lex_ctx      ctx = parser_ctx(parser);
2551     const char **loops = (is_continue ? parser->continues : parser->breaks);
2552
2553     (void)block; /* not touching */
2554     if (!parser_next(parser)) {
2555         parseerror(parser, "expected semicolon or loop label");
2556         return false;
2557     }
2558
2559     if (parser->tok == TOKEN_IDENT) {
2560         if (!OPTS_FLAG(LOOP_LABELS))
2561             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2562         i = vec_size(loops);
2563         while (i--) {
2564             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2565                 break;
2566             if (!i) {
2567                 parseerror(parser, "no such loop to %s: `%s`",
2568                            (is_continue ? "continue" : "break out of"),
2569                            parser_tokval(parser));
2570                 return false;
2571             }
2572             ++levels;
2573         }
2574         if (!parser_next(parser)) {
2575             parseerror(parser, "expected semicolon");
2576             return false;
2577         }
2578     }
2579
2580     if (parser->tok != ';') {
2581         parseerror(parser, "expected semicolon");
2582         return false;
2583     }
2584
2585     if (!parser_next(parser))
2586         parseerror(parser, "parse error");
2587
2588     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2589     return true;
2590 }
2591
2592 /* returns true when it was a variable qualifier, false otherwise!
2593  * on error, cvq is set to CV_WRONG
2594  */
2595 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2596 {
2597     bool had_const    = false;
2598     bool had_var      = false;
2599     bool had_noref    = false;
2600     bool had_attrib   = false;
2601     bool had_static   = false;
2602     uint32_t flags    = 0;
2603
2604     *cvq = CV_NONE;
2605     for (;;) {
2606         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2607             had_attrib = true;
2608             /* parse an attribute */
2609             if (!parser_next(parser)) {
2610                 parseerror(parser, "expected attribute after `[[`");
2611                 *cvq = CV_WRONG;
2612                 return false;
2613             }
2614             if (!strcmp(parser_tokval(parser), "noreturn")) {
2615                 flags |= AST_FLAG_NORETURN;
2616                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2617                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2618                     *cvq = CV_WRONG;
2619                     return false;
2620                 }
2621             }
2622             else if (!strcmp(parser_tokval(parser), "noref")) {
2623                 had_noref = true;
2624                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2625                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2626                     *cvq = CV_WRONG;
2627                     return false;
2628                 }
2629             }
2630             else if (!strcmp(parser_tokval(parser), "inline")) {
2631                 flags |= AST_FLAG_INLINE;
2632                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2633                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2634                     *cvq = CV_WRONG;
2635                     return false;
2636                 }
2637             }
2638
2639
2640             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2641                 flags   |= AST_FLAG_DEPRECATED;
2642                 *message = NULL;
2643                 
2644                 if (!parser_next(parser)) {
2645                     parseerror(parser, "parse error in attribute");
2646                     goto argerr;
2647                 }
2648
2649                 if (parser->tok == '(') {
2650                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2651                         parseerror(parser, "`deprecated` attribute missing parameter");
2652                         goto argerr;
2653                     }
2654
2655                     *message = util_strdup(parser_tokval(parser));
2656
2657                     if (!parser_next(parser)) {
2658                         parseerror(parser, "parse error in attribute");
2659                         goto argerr;
2660                     }
2661
2662                     if(parser->tok != ')') {
2663                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2664                         goto argerr;
2665                     }
2666
2667                     if (!parser_next(parser)) {
2668                         parseerror(parser, "parse error in attribute");
2669                         goto argerr;
2670                     }
2671                 }
2672                 /* no message */
2673                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2674                     parseerror(parser, "`deprecated` attribute expected `]]`");
2675
2676                     argerr: /* ugly */
2677                     if (*message) mem_d(*message);
2678                     *message = NULL;
2679                     *cvq     = CV_WRONG;
2680                     return false;
2681                 }
2682             }
2683             else
2684             {
2685                 /* Skip tokens until we hit a ]] */
2686                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2687                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2688                     if (!parser_next(parser)) {
2689                         parseerror(parser, "error inside attribute");
2690                         *cvq = CV_WRONG;
2691                         return false;
2692                     }
2693                 }
2694             }
2695         }
2696         else if (!strcmp(parser_tokval(parser), "static"))
2697             had_static = true;
2698         else if (!strcmp(parser_tokval(parser), "const"))
2699             had_const = true;
2700         else if (!strcmp(parser_tokval(parser), "var"))
2701             had_var = true;
2702         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2703             had_var = true;
2704         else if (!strcmp(parser_tokval(parser), "noref"))
2705             had_noref = true;
2706         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2707             return false;
2708         }
2709         else
2710             break;
2711         if (!parser_next(parser))
2712             goto onerr;
2713     }
2714     if (had_const)
2715         *cvq = CV_CONST;
2716     else if (had_var)
2717         *cvq = CV_VAR;
2718     else
2719         *cvq = CV_NONE;
2720     *noref     = had_noref;
2721     *is_static = had_static;
2722     *_flags    = flags;
2723     return true;
2724 onerr:
2725     parseerror(parser, "parse error after variable qualifier");
2726     *cvq = CV_WRONG;
2727     return true;
2728 }
2729
2730 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2731 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2732 {
2733     bool rv;
2734     char *label = NULL;
2735
2736     /* skip the 'while' and get the body */
2737     if (!parser_next(parser)) {
2738         if (OPTS_FLAG(LOOP_LABELS))
2739             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2740         else
2741             parseerror(parser, "expected 'switch' operand in parenthesis");
2742         return false;
2743     }
2744
2745     if (parser->tok == ':') {
2746         if (!OPTS_FLAG(LOOP_LABELS))
2747             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2748         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2749             parseerror(parser, "expected loop label");
2750             return false;
2751         }
2752         label = util_strdup(parser_tokval(parser));
2753         if (!parser_next(parser)) {
2754             mem_d(label);
2755             parseerror(parser, "expected 'switch' operand in parenthesis");
2756             return false;
2757         }
2758     }
2759
2760     if (parser->tok != '(') {
2761         parseerror(parser, "expected 'switch' operand in parenthesis");
2762         return false;
2763     }
2764
2765     vec_push(parser->breaks, label);
2766
2767     rv = parse_switch_go(parser, block, out);
2768     if (label)
2769         mem_d(label);
2770     if (vec_last(parser->breaks) != label) {
2771         parseerror(parser, "internal error: label stack corrupted");
2772         rv = false;
2773         ast_delete(*out);
2774         *out = NULL;
2775     }
2776     else {
2777         vec_pop(parser->breaks);
2778     }
2779     return rv;
2780 }
2781
2782 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2783 {
2784     ast_expression *operand;
2785     ast_value      *opval;
2786     ast_value      *typevar;
2787     ast_switch     *switchnode;
2788     ast_switch_case swcase;
2789
2790     int  cvq;
2791     bool noref, is_static;
2792     uint32_t qflags = 0;
2793
2794     lex_ctx ctx = parser_ctx(parser);
2795
2796     (void)block; /* not touching */
2797     (void)opval;
2798
2799     /* parse into the expression */
2800     if (!parser_next(parser)) {
2801         parseerror(parser, "expected switch operand");
2802         return false;
2803     }
2804     /* parse the operand */
2805     operand = parse_expression_leave(parser, false, false);
2806     if (!operand)
2807         return false;
2808
2809     switchnode = ast_switch_new(ctx, operand);
2810
2811     /* closing paren */
2812     if (parser->tok != ')') {
2813         ast_delete(switchnode);
2814         parseerror(parser, "expected closing paren after 'switch' operand");
2815         return false;
2816     }
2817
2818     /* parse over the opening paren */
2819     if (!parser_next(parser) || parser->tok != '{') {
2820         ast_delete(switchnode);
2821         parseerror(parser, "expected list of cases");
2822         return false;
2823     }
2824
2825     if (!parser_next(parser)) {
2826         ast_delete(switchnode);
2827         parseerror(parser, "expected 'case' or 'default'");
2828         return false;
2829     }
2830
2831     /* new block; allow some variables to be declared here */
2832     parser_enterblock(parser);
2833     while (true) {
2834         typevar = NULL;
2835         if (parser->tok == TOKEN_IDENT)
2836             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2837         if (typevar || parser->tok == TOKEN_TYPENAME) {
2838             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2839                 ast_delete(switchnode);
2840                 return false;
2841             }
2842             continue;
2843         }
2844         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2845         {
2846             if (cvq == CV_WRONG) {
2847                 ast_delete(switchnode);
2848                 return false;
2849             }
2850             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2851                 ast_delete(switchnode);
2852                 return false;
2853             }
2854             continue;
2855         }
2856         break;
2857     }
2858
2859     /* case list! */
2860     while (parser->tok != '}') {
2861         ast_block *caseblock;
2862
2863         if (!strcmp(parser_tokval(parser), "case")) {
2864             if (!parser_next(parser)) {
2865                 ast_delete(switchnode);
2866                 parseerror(parser, "expected expression for case");
2867                 return false;
2868             }
2869             swcase.value = parse_expression_leave(parser, false, false);
2870             if (!swcase.value) {
2871                 ast_delete(switchnode);
2872                 parseerror(parser, "expected expression for case");
2873                 return false;
2874             }
2875             if (!OPTS_FLAG(RELAXED_SWITCH)) {
2876                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2877                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2878                     ast_unref(operand);
2879                     return false;
2880                 }
2881             }
2882         }
2883         else if (!strcmp(parser_tokval(parser), "default")) {
2884             swcase.value = NULL;
2885             if (!parser_next(parser)) {
2886                 ast_delete(switchnode);
2887                 parseerror(parser, "expected colon");
2888                 return false;
2889             }
2890         }
2891         else {
2892             ast_delete(switchnode);
2893             parseerror(parser, "expected 'case' or 'default'");
2894             return false;
2895         }
2896
2897         /* Now the colon and body */
2898         if (parser->tok != ':') {
2899             if (swcase.value) ast_unref(swcase.value);
2900             ast_delete(switchnode);
2901             parseerror(parser, "expected colon");
2902             return false;
2903         }
2904
2905         if (!parser_next(parser)) {
2906             if (swcase.value) ast_unref(swcase.value);
2907             ast_delete(switchnode);
2908             parseerror(parser, "expected statements or case");
2909             return false;
2910         }
2911         caseblock = ast_block_new(parser_ctx(parser));
2912         if (!caseblock) {
2913             if (swcase.value) ast_unref(swcase.value);
2914             ast_delete(switchnode);
2915             return false;
2916         }
2917         swcase.code = (ast_expression*)caseblock;
2918         vec_push(switchnode->cases, swcase);
2919         while (true) {
2920             ast_expression *expr;
2921             if (parser->tok == '}')
2922                 break;
2923             if (parser->tok == TOKEN_KEYWORD) {
2924                 if (!strcmp(parser_tokval(parser), "case") ||
2925                     !strcmp(parser_tokval(parser), "default"))
2926                 {
2927                     break;
2928                 }
2929             }
2930             if (!parse_statement(parser, caseblock, &expr, true)) {
2931                 ast_delete(switchnode);
2932                 return false;
2933             }
2934             if (!expr)
2935                 continue;
2936             if (!ast_block_add_expr(caseblock, expr)) {
2937                 ast_delete(switchnode);
2938                 return false;
2939             }
2940         }
2941     }
2942
2943     parser_leaveblock(parser);
2944
2945     /* closing paren */
2946     if (parser->tok != '}') {
2947         ast_delete(switchnode);
2948         parseerror(parser, "expected closing paren of case list");
2949         return false;
2950     }
2951     if (!parser_next(parser)) {
2952         ast_delete(switchnode);
2953         parseerror(parser, "parse error after switch");
2954         return false;
2955     }
2956     *out = (ast_expression*)switchnode;
2957     return true;
2958 }
2959
2960 static bool parse_goto(parser_t *parser, ast_expression **out)
2961 {
2962     size_t    i;
2963     ast_goto *gt;
2964
2965     if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2966         parseerror(parser, "expected label name after `goto`");
2967         return false;
2968     }
2969
2970     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2971
2972     for (i = 0; i < vec_size(parser->labels); ++i) {
2973         if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2974             ast_goto_set_label(gt, parser->labels[i]);
2975             break;
2976         }
2977     }
2978     if (i == vec_size(parser->labels))
2979         vec_push(parser->gotos, gt);
2980
2981     if (!parser_next(parser) || parser->tok != ';') {
2982         parseerror(parser, "semicolon expected after goto label");
2983         return false;
2984     }
2985     if (!parser_next(parser)) {
2986         parseerror(parser, "parse error after goto");
2987         return false;
2988     }
2989
2990     *out = (ast_expression*)gt;
2991     return true;
2992 }
2993
2994 static bool parse_skipwhite(parser_t *parser)
2995 {
2996     do {
2997         if (!parser_next(parser))
2998             return false;
2999     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3000     return parser->tok < TOKEN_ERROR;
3001 }
3002
3003 static bool parse_eol(parser_t *parser)
3004 {
3005     if (!parse_skipwhite(parser))
3006         return false;
3007     return parser->tok == TOKEN_EOL;
3008 }
3009
3010 static bool parse_pragma_do(parser_t *parser)
3011 {
3012     if (!parser_next(parser) ||
3013         parser->tok != TOKEN_IDENT ||
3014         strcmp(parser_tokval(parser), "pragma"))
3015     {
3016         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3017         return false;
3018     }
3019     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3020         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3021         return false;
3022     }
3023
3024     if (!strcmp(parser_tokval(parser), "noref")) {
3025         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3026             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3027             return false;
3028         }
3029         parser->noref = !!parser_token(parser)->constval.i;
3030         if (!parse_eol(parser)) {
3031             parseerror(parser, "parse error after `noref` pragma");
3032             return false;
3033         }
3034     }
3035     else
3036     {
3037         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3038         return false;
3039     }
3040
3041     return true;
3042 }
3043
3044 static bool parse_pragma(parser_t *parser)
3045 {
3046     bool rv;
3047     parser->lex->flags.preprocessing = true;
3048     parser->lex->flags.mergelines = true;
3049     rv = parse_pragma_do(parser);
3050     if (parser->tok != TOKEN_EOL) {
3051         parseerror(parser, "junk after pragma");
3052         rv = false;
3053     }
3054     parser->lex->flags.preprocessing = false;
3055     parser->lex->flags.mergelines = false;
3056     if (!parser_next(parser)) {
3057         parseerror(parser, "parse error after pragma");
3058         rv = false;
3059     }
3060     return rv;
3061 }
3062
3063 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3064 {
3065     bool       noref, is_static;
3066     int        cvq     = CV_NONE;
3067     uint32_t   qflags  = 0;
3068     ast_value *typevar = NULL;
3069     char      *vstring = NULL;
3070
3071     *out = NULL;
3072
3073     if (parser->tok == TOKEN_IDENT)
3074         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3075
3076     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3077     {
3078         /* local variable */
3079         if (!block) {
3080             parseerror(parser, "cannot declare a variable from here");
3081             return false;
3082         }
3083         if (opts.standard == COMPILER_QCC) {
3084             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3085                 return false;
3086         }
3087         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3088             return false;
3089         return true;
3090     }
3091     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3092     {
3093         if (cvq == CV_WRONG)
3094             return false;
3095         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3096     }
3097     else if (parser->tok == TOKEN_KEYWORD)
3098     {
3099         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3100         {
3101             char ty[1024];
3102             ast_value *tdef;
3103
3104             if (!parser_next(parser)) {
3105                 parseerror(parser, "parse error after __builtin_debug_printtype");
3106                 return false;
3107             }
3108
3109             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3110             {
3111                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3112                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3113                 if (!parser_next(parser)) {
3114                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3115                     return false;
3116                 }
3117             }
3118             else
3119             {
3120                 if (!parse_statement(parser, block, out, allow_cases))
3121                     return false;
3122                 if (!*out)
3123                     con_out("__builtin_debug_printtype: got no output node\n");
3124                 else
3125                 {
3126                     ast_type_to_string(*out, ty, sizeof(ty));
3127                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3128                 }
3129             }
3130             return true;
3131         }
3132         else if (!strcmp(parser_tokval(parser), "return"))
3133         {
3134             return parse_return(parser, block, out);
3135         }
3136         else if (!strcmp(parser_tokval(parser), "if"))
3137         {
3138             return parse_if(parser, block, out);
3139         }
3140         else if (!strcmp(parser_tokval(parser), "while"))
3141         {
3142             return parse_while(parser, block, out);
3143         }
3144         else if (!strcmp(parser_tokval(parser), "do"))
3145         {
3146             return parse_dowhile(parser, block, out);
3147         }
3148         else if (!strcmp(parser_tokval(parser), "for"))
3149         {
3150             if (opts.standard == COMPILER_QCC) {
3151                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3152                     return false;
3153             }
3154             return parse_for(parser, block, out);
3155         }
3156         else if (!strcmp(parser_tokval(parser), "break"))
3157         {
3158             return parse_break_continue(parser, block, out, false);
3159         }
3160         else if (!strcmp(parser_tokval(parser), "continue"))
3161         {
3162             return parse_break_continue(parser, block, out, true);
3163         }
3164         else if (!strcmp(parser_tokval(parser), "switch"))
3165         {
3166             return parse_switch(parser, block, out);
3167         }
3168         else if (!strcmp(parser_tokval(parser), "case") ||
3169                  !strcmp(parser_tokval(parser), "default"))
3170         {
3171             if (!allow_cases) {
3172                 parseerror(parser, "unexpected 'case' label");
3173                 return false;
3174             }
3175             return true;
3176         }
3177         else if (!strcmp(parser_tokval(parser), "goto"))
3178         {
3179             return parse_goto(parser, out);
3180         }
3181         else if (!strcmp(parser_tokval(parser), "typedef"))
3182         {
3183             if (!parser_next(parser)) {
3184                 parseerror(parser, "expected type definition after 'typedef'");
3185                 return false;
3186             }
3187             return parse_typedef(parser);
3188         }
3189         parseerror(parser, "Unexpected keyword");
3190         return false;
3191     }
3192     else if (parser->tok == '{')
3193     {
3194         ast_block *inner;
3195         inner = parse_block(parser);
3196         if (!inner)
3197             return false;
3198         *out = (ast_expression*)inner;
3199         return true;
3200     }
3201     else if (parser->tok == ':')
3202     {
3203         size_t i;
3204         ast_label *label;
3205         if (!parser_next(parser)) {
3206             parseerror(parser, "expected label name");
3207             return false;
3208         }
3209         if (parser->tok != TOKEN_IDENT) {
3210             parseerror(parser, "label must be an identifier");
3211             return false;
3212         }
3213         label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
3214         if (!label)
3215             return false;
3216         vec_push(parser->labels, label);
3217         *out = (ast_expression*)label;
3218         if (!parser_next(parser)) {
3219             parseerror(parser, "parse error after label");
3220             return false;
3221         }
3222         for (i = 0; i < vec_size(parser->gotos); ++i) {
3223             if (!strcmp(parser->gotos[i]->name, label->name)) {
3224                 ast_goto_set_label(parser->gotos[i], label);
3225                 vec_remove(parser->gotos, i, 1);
3226                 --i;
3227             }
3228         }
3229         return true;
3230     }
3231     else if (parser->tok == ';')
3232     {
3233         if (!parser_next(parser)) {
3234             parseerror(parser, "parse error after empty statement");
3235             return false;
3236         }
3237         return true;
3238     }
3239     else
3240     {
3241         ast_expression *exp = parse_expression(parser, false);
3242         if (!exp)
3243             return false;
3244         *out = exp;
3245         if (!ast_side_effects(exp)) {
3246             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3247                 return false;
3248         }
3249         return true;
3250     }
3251 }
3252
3253 static bool parse_block_into(parser_t *parser, ast_block *block)
3254 {
3255     bool   retval = true;
3256
3257     parser_enterblock(parser);
3258
3259     if (!parser_next(parser)) { /* skip the '{' */
3260         parseerror(parser, "expected function body");
3261         goto cleanup;
3262     }
3263
3264     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3265     {
3266         ast_expression *expr = NULL;
3267         if (parser->tok == '}')
3268             break;
3269
3270         if (!parse_statement(parser, block, &expr, false)) {
3271             /* parseerror(parser, "parse error"); */
3272             block = NULL;
3273             goto cleanup;
3274         }
3275         if (!expr)
3276             continue;
3277         if (!ast_block_add_expr(block, expr)) {
3278             ast_delete(block);
3279             block = NULL;
3280             goto cleanup;
3281         }
3282     }
3283
3284     if (parser->tok != '}') {
3285         block = NULL;
3286     } else {
3287         (void)parser_next(parser);
3288     }
3289
3290 cleanup:
3291     if (!parser_leaveblock(parser))
3292         retval = false;
3293     return retval && !!block;
3294 }
3295
3296 static ast_block* parse_block(parser_t *parser)
3297 {
3298     ast_block *block;
3299     block = ast_block_new(parser_ctx(parser));
3300     if (!block)
3301         return NULL;
3302     if (!parse_block_into(parser, block)) {
3303         ast_block_delete(block);
3304         return NULL;
3305     }
3306     return block;
3307 }
3308
3309 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3310 {
3311     if (parser->tok == '{') {
3312         *out = (ast_expression*)parse_block(parser);
3313         return !!*out;
3314     }
3315     return parse_statement(parser, NULL, out, false);
3316 }
3317
3318 static bool create_vector_members(ast_value *var, ast_member **me)
3319 {
3320     size_t i;
3321     size_t len = strlen(var->name);
3322
3323     for (i = 0; i < 3; ++i) {
3324         char *name = (char*)mem_a(len+3);
3325         memcpy(name, var->name, len);
3326         name[len+0] = '_';
3327         name[len+1] = 'x'+i;
3328         name[len+2] = 0;
3329         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3330         mem_d(name);
3331         if (!me[i])
3332             break;
3333     }
3334     if (i == 3)
3335         return true;
3336
3337     /* unroll */
3338     do { ast_member_delete(me[--i]); } while(i);
3339     return false;
3340 }
3341
3342 static bool parse_function_body(parser_t *parser, ast_value *var)
3343 {
3344     ast_block      *block = NULL;
3345     ast_function   *func;
3346     ast_function   *old;
3347     size_t          parami;
3348
3349     ast_expression *framenum  = NULL;
3350     ast_expression *nextthink = NULL;
3351     /* None of the following have to be deleted */
3352     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3353     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3354     bool            has_frame_think;
3355
3356     bool retval = true;
3357
3358     has_frame_think = false;
3359     old = parser->function;
3360
3361     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3362         parseerror(parser, "gotos/labels leaking");
3363         return false;
3364     }
3365
3366     if (var->expression.flags & AST_FLAG_VARIADIC) {
3367         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3368                          "variadic function with implementation will not be able to access additional parameters"))
3369         {
3370             return false;
3371         }
3372     }
3373
3374     if (parser->tok == '[') {
3375         /* got a frame definition: [ framenum, nextthink ]
3376          * this translates to:
3377          * self.frame = framenum;
3378          * self.nextthink = time + 0.1;
3379          * self.think = nextthink;
3380          */
3381         nextthink = NULL;
3382
3383         fld_think     = parser_find_field(parser, "think");
3384         fld_nextthink = parser_find_field(parser, "nextthink");
3385         fld_frame     = parser_find_field(parser, "frame");
3386         if (!fld_think || !fld_nextthink || !fld_frame) {
3387             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3388             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3389             return false;
3390         }
3391         gbl_time      = parser_find_global(parser, "time");
3392         gbl_self      = parser_find_global(parser, "self");
3393         if (!gbl_time || !gbl_self) {
3394             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3395             parseerror(parser, "please declare the following globals: `time`, `self`");
3396             return false;
3397         }
3398
3399         if (!parser_next(parser))
3400             return false;
3401
3402         framenum = parse_expression_leave(parser, true, false);
3403         if (!framenum) {
3404             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3405             return false;
3406         }
3407         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3408             ast_unref(framenum);
3409             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3410             return false;
3411         }
3412
3413         if (parser->tok != ',') {
3414             ast_unref(framenum);
3415             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3416             parseerror(parser, "Got a %i\n", parser->tok);
3417             return false;
3418         }
3419
3420         if (!parser_next(parser)) {
3421             ast_unref(framenum);
3422             return false;
3423         }
3424
3425         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3426         {
3427             /* qc allows the use of not-yet-declared functions here
3428              * - this automatically creates a prototype */
3429             ast_value      *thinkfunc;
3430             ast_expression *functype = fld_think->expression.next;
3431
3432             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3433             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3434                 ast_unref(framenum);
3435                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3436                 return false;
3437             }
3438
3439             if (!parser_next(parser)) {
3440                 ast_unref(framenum);
3441                 ast_delete(thinkfunc);
3442                 return false;
3443             }
3444
3445             vec_push(parser->globals, (ast_expression*)thinkfunc);
3446             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3447             nextthink = (ast_expression*)thinkfunc;
3448
3449         } else {
3450             nextthink = parse_expression_leave(parser, true, false);
3451             if (!nextthink) {
3452                 ast_unref(framenum);
3453                 parseerror(parser, "expected a think-function in [frame,think] notation");
3454                 return false;
3455             }
3456         }
3457
3458         if (!ast_istype(nextthink, ast_value)) {
3459             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3460             retval = false;
3461         }
3462
3463         if (retval && parser->tok != ']') {
3464             parseerror(parser, "expected closing `]` for [frame,think] notation");
3465             retval = false;
3466         }
3467
3468         if (retval && !parser_next(parser)) {
3469             retval = false;
3470         }
3471
3472         if (retval && parser->tok != '{') {
3473             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3474             retval = false;
3475         }
3476
3477         if (!retval) {
3478             ast_unref(nextthink);
3479             ast_unref(framenum);
3480             return false;
3481         }
3482
3483         has_frame_think = true;
3484     }
3485
3486     block = ast_block_new(parser_ctx(parser));
3487     if (!block) {
3488         parseerror(parser, "failed to allocate block");
3489         if (has_frame_think) {
3490             ast_unref(nextthink);
3491             ast_unref(framenum);
3492         }
3493         return false;
3494     }
3495
3496     if (has_frame_think) {
3497         lex_ctx ctx;
3498         ast_expression *self_frame;
3499         ast_expression *self_nextthink;
3500         ast_expression *self_think;
3501         ast_expression *time_plus_1;
3502         ast_store *store_frame;
3503         ast_store *store_nextthink;
3504         ast_store *store_think;
3505
3506         ctx = parser_ctx(parser);
3507         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3508         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3509         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3510
3511         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3512                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3513
3514         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3515             if (self_frame)     ast_delete(self_frame);
3516             if (self_nextthink) ast_delete(self_nextthink);
3517             if (self_think)     ast_delete(self_think);
3518             if (time_plus_1)    ast_delete(time_plus_1);
3519             retval = false;
3520         }
3521
3522         if (retval)
3523         {
3524             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3525             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3526             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3527
3528             if (!store_frame) {
3529                 ast_delete(self_frame);
3530                 retval = false;
3531             }
3532             if (!store_nextthink) {
3533                 ast_delete(self_nextthink);
3534                 retval = false;
3535             }
3536             if (!store_think) {
3537                 ast_delete(self_think);
3538                 retval = false;
3539             }
3540             if (!retval) {
3541                 if (store_frame)     ast_delete(store_frame);
3542                 if (store_nextthink) ast_delete(store_nextthink);
3543                 if (store_think)     ast_delete(store_think);
3544                 retval = false;
3545             }
3546             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3547                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3548                 !ast_block_add_expr(block, (ast_expression*)store_think))
3549             {
3550                 retval = false;
3551             }
3552         }
3553
3554         if (!retval) {
3555             parseerror(parser, "failed to generate code for [frame,think]");
3556             ast_unref(nextthink);
3557             ast_unref(framenum);
3558             ast_delete(block);
3559             return false;
3560         }
3561     }
3562
3563     parser_enterblock(parser);
3564
3565     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3566         size_t     e;
3567         ast_value *param = var->expression.params[parami];
3568         ast_member *me[3];
3569
3570         if (param->expression.vtype != TYPE_VECTOR &&
3571             (param->expression.vtype != TYPE_FIELD ||
3572              param->expression.next->expression.vtype != TYPE_VECTOR))
3573         {
3574             continue;
3575         }
3576
3577         if (!create_vector_members(param, me)) {
3578             ast_block_delete(block);
3579             return false;
3580         }
3581
3582         for (e = 0; e < 3; ++e) {
3583             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3584             ast_block_collect(block, (ast_expression*)me[e]);
3585         }
3586     }
3587
3588     func = ast_function_new(ast_ctx(var), var->name, var);
3589     if (!func) {
3590         parseerror(parser, "failed to allocate function for `%s`", var->name);
3591         ast_block_delete(block);
3592         goto enderr;
3593     }
3594     vec_push(parser->functions, func);
3595
3596     parser->function = func;
3597     if (!parse_block_into(parser, block)) {
3598         ast_block_delete(block);
3599         goto enderrfn;
3600     }
3601
3602     vec_push(func->blocks, block);
3603
3604     parser->function = old;
3605     if (!parser_leaveblock(parser))
3606         retval = false;
3607     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3608         parseerror(parser, "internal error: local scopes left");
3609         retval = false;
3610     }
3611
3612     if (parser->tok == ';')
3613         return parser_next(parser);
3614     else if (opts.standard == COMPILER_QCC)
3615         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3616     return retval;
3617
3618 enderrfn:
3619     vec_pop(parser->functions);
3620     ast_function_delete(func);
3621     var->constval.vfunc = NULL;
3622
3623 enderr:
3624     (void)!parser_leaveblock(parser);
3625     parser->function = old;
3626     return false;
3627 }
3628
3629 static ast_expression *array_accessor_split(
3630     parser_t  *parser,
3631     ast_value *array,
3632     ast_value *index,
3633     size_t     middle,
3634     ast_expression *left,
3635     ast_expression *right
3636     )
3637 {
3638     ast_ifthen *ifthen;
3639     ast_binary *cmp;
3640
3641     lex_ctx ctx = ast_ctx(array);
3642
3643     if (!left || !right) {
3644         if (left)  ast_delete(left);
3645         if (right) ast_delete(right);
3646         return NULL;
3647     }
3648
3649     cmp = ast_binary_new(ctx, INSTR_LT,
3650                          (ast_expression*)index,
3651                          (ast_expression*)parser_const_float(parser, middle));
3652     if (!cmp) {
3653         ast_delete(left);
3654         ast_delete(right);
3655         parseerror(parser, "internal error: failed to create comparison for array setter");
3656         return NULL;
3657     }
3658
3659     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3660     if (!ifthen) {
3661         ast_delete(cmp); /* will delete left and right */
3662         parseerror(parser, "internal error: failed to create conditional jump for array setter");
3663         return NULL;
3664     }
3665
3666     return (ast_expression*)ifthen;
3667 }
3668
3669 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3670 {
3671     lex_ctx ctx = ast_ctx(array);
3672
3673     if (from+1 == afterend) {
3674         /* set this value */
3675         ast_block       *block;
3676         ast_return      *ret;
3677         ast_array_index *subscript;
3678         ast_store       *st;
3679         int assignop = type_store_instr[value->expression.vtype];
3680
3681         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3682             assignop = INSTR_STORE_V;
3683
3684         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3685         if (!subscript)
3686             return NULL;
3687
3688         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3689         if (!st) {
3690             ast_delete(subscript);
3691             return NULL;
3692         }
3693
3694         block = ast_block_new(ctx);
3695         if (!block) {
3696             ast_delete(st);
3697             return NULL;
3698         }
3699
3700         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3701             ast_delete(block);
3702             return NULL;
3703         }
3704
3705         ret = ast_return_new(ctx, NULL);
3706         if (!ret) {
3707             ast_delete(block);
3708             return NULL;
3709         }
3710
3711         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3712             ast_delete(block);
3713             return NULL;
3714         }
3715
3716         return (ast_expression*)block;
3717     } else {
3718         ast_expression *left, *right;
3719         size_t diff = afterend - from;
3720         size_t middle = from + diff/2;
3721         left  = array_setter_node(parser, array, index, value, from, middle);
3722         right = array_setter_node(parser, array, index, value, middle, afterend);
3723         return array_accessor_split(parser, array, index, middle, left, right);
3724     }
3725 }
3726
3727 static ast_expression *array_field_setter_node(
3728     parser_t  *parser,
3729     ast_value *array,
3730     ast_value *entity,
3731     ast_value *index,
3732     ast_value *value,
3733     size_t     from,
3734     size_t     afterend)
3735 {
3736     lex_ctx ctx = ast_ctx(array);
3737
3738     if (from+1 == afterend) {
3739         /* set this value */
3740         ast_block       *block;
3741         ast_return      *ret;
3742         ast_entfield    *entfield;
3743         ast_array_index *subscript;
3744         ast_store       *st;
3745         int assignop = type_storep_instr[value->expression.vtype];
3746
3747         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3748             assignop = INSTR_STOREP_V;
3749
3750         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3751         if (!subscript)
3752             return NULL;
3753
3754         entfield = ast_entfield_new_force(ctx,
3755                                           (ast_expression*)entity,
3756                                           (ast_expression*)subscript,
3757                                           (ast_expression*)subscript);
3758         if (!entfield) {
3759             ast_delete(subscript);
3760             return NULL;
3761         }
3762
3763         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3764         if (!st) {
3765             ast_delete(entfield);
3766             return NULL;
3767         }
3768
3769         block = ast_block_new(ctx);
3770         if (!block) {
3771             ast_delete(st);
3772             return NULL;
3773         }
3774
3775         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3776             ast_delete(block);
3777             return NULL;
3778         }
3779
3780         ret = ast_return_new(ctx, NULL);
3781         if (!ret) {
3782             ast_delete(block);
3783             return NULL;
3784         }
3785
3786         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3787             ast_delete(block);
3788             return NULL;
3789         }
3790
3791         return (ast_expression*)block;
3792     } else {
3793         ast_expression *left, *right;
3794         size_t diff = afterend - from;
3795         size_t middle = from + diff/2;
3796         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
3797         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3798         return array_accessor_split(parser, array, index, middle, left, right);
3799     }
3800 }
3801
3802 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3803 {
3804     lex_ctx ctx = ast_ctx(array);
3805
3806     if (from+1 == afterend) {
3807         ast_return      *ret;
3808         ast_array_index *subscript;
3809
3810         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3811         if (!subscript)
3812             return NULL;
3813
3814         ret = ast_return_new(ctx, (ast_expression*)subscript);
3815         if (!ret) {
3816             ast_delete(subscript);
3817             return NULL;
3818         }
3819
3820         return (ast_expression*)ret;
3821     } else {
3822         ast_expression *left, *right;
3823         size_t diff = afterend - from;
3824         size_t middle = from + diff/2;
3825         left  = array_getter_node(parser, array, index, from, middle);
3826         right = array_getter_node(parser, array, index, middle, afterend);
3827         return array_accessor_split(parser, array, index, middle, left, right);
3828     }
3829 }
3830
3831 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3832 {
3833     ast_function   *func = NULL;
3834     ast_value      *fval = NULL;
3835     ast_block      *body = NULL;
3836
3837     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3838     if (!fval) {
3839         parseerror(parser, "failed to create accessor function value");
3840         return false;
3841     }
3842
3843     func = ast_function_new(ast_ctx(array), funcname, fval);
3844     if (!func) {
3845         ast_delete(fval);
3846         parseerror(parser, "failed to create accessor function node");
3847         return false;
3848     }
3849
3850     body = ast_block_new(ast_ctx(array));
3851     if (!body) {
3852         parseerror(parser, "failed to create block for array accessor");
3853         ast_delete(fval);
3854         ast_delete(func);
3855         return false;
3856     }
3857
3858     vec_push(func->blocks, body);
3859     *out = fval;
3860
3861     vec_push(parser->accessors, fval);
3862
3863     return true;
3864 }
3865
3866 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3867 {
3868     ast_expression *root = NULL;
3869     ast_value      *index = NULL;
3870     ast_value      *value = NULL;
3871     ast_function   *func;
3872     ast_value      *fval;
3873
3874     if (!ast_istype(array->expression.next, ast_value)) {
3875         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3876         return false;
3877     }
3878
3879     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3880         return false;
3881     func = fval->constval.vfunc;
3882     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3883
3884     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3885     value = ast_value_copy((ast_value*)array->expression.next);
3886
3887     if (!index || !value) {
3888         parseerror(parser, "failed to create locals for array accessor");
3889         goto cleanup;
3890     }
3891     (void)!ast_value_set_name(value, "value"); /* not important */
3892     vec_push(fval->expression.params, index);
3893     vec_push(fval->expression.params, value);
3894
3895     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3896     if (!root) {
3897         parseerror(parser, "failed to build accessor search tree");
3898         goto cleanup;
3899     }
3900
3901     array->setter = fval;
3902     return ast_block_add_expr(func->blocks[0], root);
3903 cleanup:
3904     if (index) ast_delete(index);
3905     if (value) ast_delete(value);
3906     if (root)  ast_delete(root);
3907     ast_delete(func);
3908     ast_delete(fval);
3909     return false;
3910 }
3911
3912 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3913 {
3914     ast_expression *root = NULL;
3915     ast_value      *entity = NULL;
3916     ast_value      *index = NULL;
3917     ast_value      *value = NULL;
3918     ast_function   *func;
3919     ast_value      *fval;
3920
3921     if (!ast_istype(array->expression.next, ast_value)) {
3922         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3923         return false;
3924     }
3925
3926     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3927         return false;
3928     func = fval->constval.vfunc;
3929     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3930
3931     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3932     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
3933     value  = ast_value_copy((ast_value*)array->expression.next);
3934     if (!entity || !index || !value) {
3935         parseerror(parser, "failed to create locals for array accessor");
3936         goto cleanup;
3937     }
3938     (void)!ast_value_set_name(value, "value"); /* not important */
3939     vec_push(fval->expression.params, entity);
3940     vec_push(fval->expression.params, index);
3941     vec_push(fval->expression.params, value);
3942
3943     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3944     if (!root) {
3945         parseerror(parser, "failed to build accessor search tree");
3946         goto cleanup;
3947     }
3948
3949     array->setter = fval;
3950     return ast_block_add_expr(func->blocks[0], root);
3951 cleanup:
3952     if (entity) ast_delete(entity);
3953     if (index)  ast_delete(index);
3954     if (value)  ast_delete(value);
3955     if (root)   ast_delete(root);
3956     ast_delete(func);
3957     ast_delete(fval);
3958     return false;
3959 }
3960
3961 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3962 {
3963     ast_expression *root = NULL;
3964     ast_value      *index = NULL;
3965     ast_value      *fval;
3966     ast_function   *func;
3967
3968     /* NOTE: checking array->expression.next rather than elemtype since
3969      * for fields elemtype is a temporary fieldtype.
3970      */
3971     if (!ast_istype(array->expression.next, ast_value)) {
3972         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3973         return false;
3974     }
3975
3976     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3977         return false;
3978     func = fval->constval.vfunc;
3979     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3980
3981     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3982
3983     if (!index) {
3984         parseerror(parser, "failed to create locals for array accessor");
3985         goto cleanup;
3986     }
3987     vec_push(fval->expression.params, index);
3988
3989     root = array_getter_node(parser, array, index, 0, array->expression.count);
3990     if (!root) {
3991         parseerror(parser, "failed to build accessor search tree");
3992         goto cleanup;
3993     }
3994
3995     array->getter = fval;
3996     return ast_block_add_expr(func->blocks[0], root);
3997 cleanup:
3998     if (index) ast_delete(index);
3999     if (root)  ast_delete(root);
4000     ast_delete(func);
4001     ast_delete(fval);
4002     return false;
4003 }
4004
4005 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4006 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4007 {
4008     lex_ctx     ctx;
4009     size_t      i;
4010     ast_value **params;
4011     ast_value  *param;
4012     ast_value  *fval;
4013     bool        first = true;
4014     bool        variadic = false;
4015
4016     ctx = parser_ctx(parser);
4017
4018     /* for the sake of less code we parse-in in this function */
4019     if (!parser_next(parser)) {
4020         parseerror(parser, "expected parameter list");
4021         return NULL;
4022     }
4023
4024     params = NULL;
4025
4026     /* parse variables until we hit a closing paren */
4027     while (parser->tok != ')') {
4028         if (!first) {
4029             /* there must be commas between them */
4030             if (parser->tok != ',') {
4031                 parseerror(parser, "expected comma or end of parameter list");
4032                 goto on_error;
4033             }
4034             if (!parser_next(parser)) {
4035                 parseerror(parser, "expected parameter");
4036                 goto on_error;
4037             }
4038         }
4039         first = false;
4040
4041         if (parser->tok == TOKEN_DOTS) {
4042             /* '...' indicates a varargs function */
4043             variadic = true;
4044             if (!parser_next(parser)) {
4045                 parseerror(parser, "expected parameter");
4046                 return NULL;
4047             }
4048             if (parser->tok != ')') {
4049                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4050                 goto on_error;
4051             }
4052         }
4053         else
4054         {
4055             /* for anything else just parse a typename */
4056             param = parse_typename(parser, NULL, NULL);
4057             if (!param)
4058                 goto on_error;
4059             vec_push(params, param);
4060             if (param->expression.vtype >= TYPE_VARIANT) {
4061                 char tname[1024]; /* typename is reserved in C++ */
4062                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4063                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4064                 goto on_error;
4065             }
4066         }
4067     }
4068
4069     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4070         vec_free(params);
4071
4072     /* sanity check */
4073     if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4074         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4075
4076     /* parse-out */
4077     if (!parser_next(parser)) {
4078         parseerror(parser, "parse error after typename");
4079         goto on_error;
4080     }
4081
4082     /* now turn 'var' into a function type */
4083     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4084     fval->expression.next     = (ast_expression*)var;
4085     if (variadic)
4086         fval->expression.flags |= AST_FLAG_VARIADIC;
4087     var = fval;
4088
4089     var->expression.params = params;
4090     params = NULL;
4091
4092     return var;
4093
4094 on_error:
4095     ast_delete(var);
4096     for (i = 0; i < vec_size(params); ++i)
4097         ast_delete(params[i]);
4098     vec_free(params);
4099     return NULL;
4100 }
4101
4102 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4103 {
4104     ast_expression *cexp;
4105     ast_value      *cval, *tmp;
4106     lex_ctx ctx;
4107
4108     ctx = parser_ctx(parser);
4109
4110     if (!parser_next(parser)) {
4111         ast_delete(var);
4112         parseerror(parser, "expected array-size");
4113         return NULL;
4114     }
4115
4116     cexp = parse_expression_leave(parser, true, false);
4117
4118     if (!cexp || !ast_istype(cexp, ast_value)) {
4119         if (cexp)
4120             ast_unref(cexp);
4121         ast_delete(var);
4122         parseerror(parser, "expected array-size as constant positive integer");
4123         return NULL;
4124     }
4125     cval = (ast_value*)cexp;
4126
4127     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4128     tmp->expression.next = (ast_expression*)var;
4129     var = tmp;
4130
4131     if (cval->expression.vtype == TYPE_INTEGER)
4132         tmp->expression.count = cval->constval.vint;
4133     else if (cval->expression.vtype == TYPE_FLOAT)
4134         tmp->expression.count = cval->constval.vfloat;
4135     else {
4136         ast_unref(cexp);
4137         ast_delete(var);
4138         parseerror(parser, "array-size must be a positive integer constant");
4139         return NULL;
4140     }
4141     ast_unref(cexp);
4142
4143     if (parser->tok != ']') {
4144         ast_delete(var);
4145         parseerror(parser, "expected ']' after array-size");
4146         return NULL;
4147     }
4148     if (!parser_next(parser)) {
4149         ast_delete(var);
4150         parseerror(parser, "error after parsing array size");
4151         return NULL;
4152     }
4153     return var;
4154 }
4155
4156 /* Parse a complete typename.
4157  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4158  * but when parsing variables separated by comma
4159  * 'storebase' should point to where the base-type should be kept.
4160  * The base type makes up every bit of type information which comes *before* the
4161  * variable name.
4162  *
4163  * The following will be parsed in its entirety:
4164  *     void() foo()
4165  * The 'basetype' in this case is 'void()'
4166  * and if there's a comma after it, say:
4167  *     void() foo(), bar
4168  * then the type-information 'void()' can be stored in 'storebase'
4169  */
4170 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4171 {
4172     ast_value *var, *tmp;
4173     lex_ctx    ctx;
4174
4175     const char *name = NULL;
4176     bool        isfield  = false;
4177     bool        wasarray = false;
4178     size_t      morefields = 0;
4179
4180     ctx = parser_ctx(parser);
4181
4182     /* types may start with a dot */
4183     if (parser->tok == '.') {
4184         isfield = true;
4185         /* if we parsed a dot we need a typename now */
4186         if (!parser_next(parser)) {
4187             parseerror(parser, "expected typename for field definition");
4188             return NULL;
4189         }
4190
4191         /* Further dots are handled seperately because they won't be part of the
4192          * basetype
4193          */
4194         while (parser->tok == '.') {
4195             ++morefields;
4196             if (!parser_next(parser)) {
4197                 parseerror(parser, "expected typename for field definition");
4198                 return NULL;
4199             }
4200         }
4201     }
4202     if (parser->tok == TOKEN_IDENT)
4203         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4204     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4205         parseerror(parser, "expected typename");
4206         return NULL;
4207     }
4208
4209     /* generate the basic type value */
4210     if (cached_typedef) {
4211         var = ast_value_copy(cached_typedef);
4212         ast_value_set_name(var, "<type(from_def)>");
4213     } else
4214         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4215
4216     for (; morefields; --morefields) {
4217         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4218         tmp->expression.next = (ast_expression*)var;
4219         var = tmp;
4220     }
4221
4222     /* do not yet turn into a field - remember:
4223      * .void() foo; is a field too
4224      * .void()() foo; is a function
4225      */
4226
4227     /* parse on */
4228     if (!parser_next(parser)) {
4229         ast_delete(var);
4230         parseerror(parser, "parse error after typename");
4231         return NULL;
4232     }
4233
4234     /* an opening paren now starts the parameter-list of a function
4235      * this is where original-QC has parameter lists.
4236      * We allow a single parameter list here.
4237      * Much like fteqcc we don't allow `float()() x`
4238      */
4239     if (parser->tok == '(') {
4240         var = parse_parameter_list(parser, var);
4241         if (!var)
4242             return NULL;
4243     }
4244
4245     /* store the base if requested */
4246     if (storebase) {
4247         *storebase = ast_value_copy(var);
4248         if (isfield) {
4249             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4250             tmp->expression.next = (ast_expression*)*storebase;
4251             *storebase = tmp;
4252         }
4253     }
4254
4255     /* there may be a name now */
4256     if (parser->tok == TOKEN_IDENT) {
4257         name = util_strdup(parser_tokval(parser));
4258         /* parse on */
4259         if (!parser_next(parser)) {
4260             ast_delete(var);
4261             parseerror(parser, "error after variable or field declaration");
4262             return NULL;
4263         }
4264     }
4265
4266     /* now this may be an array */
4267     if (parser->tok == '[') {
4268         wasarray = true;
4269         var = parse_arraysize(parser, var);
4270         if (!var)
4271             return NULL;
4272     }
4273
4274     /* This is the point where we can turn it into a field */
4275     if (isfield) {
4276         /* turn it into a field if desired */
4277         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4278         tmp->expression.next = (ast_expression*)var;
4279         var = tmp;
4280     }
4281
4282     /* now there may be function parens again */
4283     if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4284         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4285     if (parser->tok == '(' && wasarray)
4286         parseerror(parser, "arrays as part of a return type is not supported");
4287     while (parser->tok == '(') {
4288         var = parse_parameter_list(parser, var);
4289         if (!var) {
4290             if (name)
4291                 mem_d((void*)name);
4292             ast_delete(var);
4293             return NULL;
4294         }
4295     }
4296
4297     /* finally name it */
4298     if (name) {
4299         if (!ast_value_set_name(var, name)) {
4300             ast_delete(var);
4301             parseerror(parser, "internal error: failed to set name");
4302             return NULL;
4303         }
4304         /* free the name, ast_value_set_name duplicates */
4305         mem_d((void*)name);
4306     }
4307
4308     return var;
4309 }
4310
4311 static bool parse_typedef(parser_t *parser)
4312 {
4313     ast_value      *typevar, *oldtype;
4314     ast_expression *old;
4315
4316     typevar = parse_typename(parser, NULL, NULL);
4317
4318     if (!typevar)
4319         return false;
4320
4321     if ( (old = parser_find_var(parser, typevar->name)) ) {
4322         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4323                    " -> `%s` has been declared here: %s:%i",
4324                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4325         ast_delete(typevar);
4326         return false;
4327     }
4328
4329     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4330         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4331                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4332         ast_delete(typevar);
4333         return false;
4334     }
4335
4336     vec_push(parser->_typedefs, typevar);
4337     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4338
4339     if (parser->tok != ';') {
4340         parseerror(parser, "expected semicolon after typedef");
4341         return false;
4342     }
4343     if (!parser_next(parser)) {
4344         parseerror(parser, "parse error after typedef");
4345         return false;
4346     }
4347
4348     return true;
4349 }
4350
4351 static const char *cvq_to_str(int cvq) {
4352     switch (cvq) {
4353         case CV_NONE:  return "none";
4354         case CV_VAR:   return "`var`";
4355         case CV_CONST: return "`const`";
4356         default:       return "<INVALID>";
4357     }
4358 }
4359
4360 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4361 {
4362     bool av, ao;
4363     if (proto->cvq != var->cvq) {
4364         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4365               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4366               parser->tok == '='))
4367         {
4368             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4369                                  "`%s` declared with different qualifiers: %s\n"
4370                                  " -> previous declaration here: %s:%i uses %s",
4371                                  var->name, cvq_to_str(var->cvq),
4372                                  ast_ctx(proto).file, ast_ctx(proto).line,
4373                                  cvq_to_str(proto->cvq));
4374         }
4375     }
4376     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4377     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4378     if (!av != !ao) {
4379         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4380                              "`%s` declared with different attributes%s\n"
4381                              " -> previous declaration here: %s:%i",
4382                              var->name, (av ? ": noreturn" : ""),
4383                              ast_ctx(proto).file, ast_ctx(proto).line,
4384                              (ao ? ": noreturn" : ""));
4385     }
4386     return true;
4387 }
4388
4389 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring)
4390 {
4391     ast_value *var;
4392     ast_value *proto;
4393     ast_expression *old;
4394     bool       was_end;
4395     size_t     i;
4396
4397     ast_value *basetype = NULL;
4398     bool      retval    = true;
4399     bool      isparam   = false;
4400     bool      isvector  = false;
4401     bool      cleanvar  = true;
4402     bool      wasarray  = false;
4403
4404     ast_member *me[3];
4405
4406     if (!localblock && is_static)
4407         parseerror(parser, "`static` qualifier is not supported in global scope");
4408
4409     /* get the first complete variable */
4410     var = parse_typename(parser, &basetype, cached_typedef);
4411     if (!var) {
4412         if (basetype)
4413             ast_delete(basetype);
4414         return false;
4415     }
4416
4417     while (true) {
4418         proto = NULL;
4419         wasarray = false;
4420
4421         /* Part 0: finish the type */
4422         if (parser->tok == '(') {
4423             if (opts.standard == COMPILER_QCC)
4424                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4425             var = parse_parameter_list(parser, var);
4426             if (!var) {
4427                 retval = false;
4428                 goto cleanup;
4429             }
4430         }
4431         /* we only allow 1-dimensional arrays */
4432         if (parser->tok == '[') {
4433             wasarray = true;
4434             var = parse_arraysize(parser, var);
4435             if (!var) {
4436                 retval = false;
4437                 goto cleanup;
4438             }
4439         }
4440         if (parser->tok == '(' && wasarray) {
4441             parseerror(parser, "arrays as part of a return type is not supported");
4442             /* we'll still parse the type completely for now */
4443         }
4444         /* for functions returning functions */
4445         while (parser->tok == '(') {
4446             if (opts.standard == COMPILER_QCC)
4447                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4448             var = parse_parameter_list(parser, var);
4449             if (!var) {
4450                 retval = false;
4451                 goto cleanup;
4452             }
4453         }
4454
4455         var->cvq = qualifier;
4456         var->expression.flags |= qflags;
4457         if (var->expression.flags & AST_FLAG_DEPRECATED)
4458             var->desc = vstring;
4459
4460         /* Part 1:
4461          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4462          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4463          * is then filled with the previous definition and the parameter-names replaced.
4464          */
4465         if (!strcmp(var->name, "nil")) {
4466             if (OPTS_FLAG(UNTYPED_NIL)) {
4467                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4468                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4469             } else
4470                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4471         }
4472         if (!localblock) {
4473             /* Deal with end_sys_ vars */
4474             was_end = false;
4475             if (!strcmp(var->name, "end_sys_globals")) {
4476                 var->uses++;
4477                 parser->crc_globals = vec_size(parser->globals);
4478                 was_end = true;
4479             }
4480             else if (!strcmp(var->name, "end_sys_fields")) {
4481                 var->uses++;
4482                 parser->crc_fields = vec_size(parser->fields);
4483                 was_end = true;
4484             }
4485             if (was_end && var->expression.vtype == TYPE_FIELD) {
4486                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4487                                  "global '%s' hint should not be a field",
4488                                  parser_tokval(parser)))
4489                 {
4490                     retval = false;
4491                     goto cleanup;
4492                 }
4493             }
4494
4495             if (!nofields && var->expression.vtype == TYPE_FIELD)
4496             {
4497                 /* deal with field declarations */
4498                 old = parser_find_field(parser, var->name);
4499                 if (old) {
4500                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4501                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4502                     {
4503                         retval = false;
4504                         goto cleanup;
4505                     }
4506                     ast_delete(var);
4507                     var = NULL;
4508                     goto skipvar;
4509                     /*
4510                     parseerror(parser, "field `%s` already declared here: %s:%i",
4511                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4512                     retval = false;
4513                     goto cleanup;
4514                     */
4515                 }
4516                 if (opts.standard == COMPILER_QCC &&
4517                     (old = parser_find_global(parser, var->name)))
4518                 {
4519                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4520                     parseerror(parser, "field `%s` already declared here: %s:%i",
4521                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4522                     retval = false;
4523                     goto cleanup;
4524                 }
4525             }
4526             else
4527             {
4528                 /* deal with other globals */
4529                 old = parser_find_global(parser, var->name);
4530                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4531                 {
4532                     /* This is a function which had a prototype */
4533                     if (!ast_istype(old, ast_value)) {
4534                         parseerror(parser, "internal error: prototype is not an ast_value");
4535                         retval = false;
4536                         goto cleanup;
4537                     }
4538                     proto = (ast_value*)old;
4539                     proto->desc = var->desc;
4540                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4541                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4542                                    proto->name,
4543                                    ast_ctx(proto).file, ast_ctx(proto).line);
4544                         retval = false;
4545                         goto cleanup;
4546                     }
4547                     /* we need the new parameter-names */
4548                     for (i = 0; i < vec_size(proto->expression.params); ++i)
4549                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4550                     if (!parser_check_qualifiers(parser, var, proto)) {
4551                         retval = false;
4552                         if (proto->desc) 
4553                             mem_d(proto->desc);
4554                         proto = NULL;
4555                         goto cleanup;
4556                     }
4557                     proto->expression.flags |= var->expression.flags;
4558                     ast_delete(var);
4559                     var = proto;
4560                 }
4561                 else
4562                 {
4563                     /* other globals */
4564                     if (old) {
4565                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4566                                          "global `%s` already declared here: %s:%i",
4567                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
4568                         {
4569                             retval = false;
4570                             goto cleanup;
4571                         }
4572                         proto = (ast_value*)old;
4573                         if (!ast_istype(old, ast_value)) {
4574                             parseerror(parser, "internal error: not an ast_value");
4575                             retval = false;
4576                             proto = NULL;
4577                             goto cleanup;
4578                         }
4579                         if (!parser_check_qualifiers(parser, var, proto)) {
4580                             retval = false;
4581                             proto = NULL;
4582                             goto cleanup;
4583                         }
4584                         proto->expression.flags |= var->expression.flags;
4585                         ast_delete(var);
4586                         var = proto;
4587                     }
4588                     if (opts.standard == COMPILER_QCC &&
4589                         (old = parser_find_field(parser, var->name)))
4590                     {
4591                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4592                         parseerror(parser, "global `%s` already declared here: %s:%i",
4593                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
4594                         retval = false;
4595                         goto cleanup;
4596                     }
4597                 }
4598             }
4599         }
4600         else /* it's not a global */
4601         {
4602             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4603             if (old && !isparam) {
4604                 parseerror(parser, "local `%s` already declared here: %s:%i",
4605                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4606                 retval = false;
4607                 goto cleanup;
4608             }
4609             old = parser_find_local(parser, var->name, 0, &isparam);
4610             if (old && isparam) {
4611                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4612                                  "local `%s` is shadowing a parameter", var->name))
4613                 {
4614                     parseerror(parser, "local `%s` already declared here: %s:%i",
4615                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4616                     retval = false;
4617                     goto cleanup;
4618                 }
4619                 if (opts.standard != COMPILER_GMQCC) {
4620                     ast_delete(var);
4621                     var = NULL;
4622                     goto skipvar;
4623                 }
4624             }
4625         }
4626
4627         /* in a noref section we simply bump the usecount */
4628         if (noref || parser->noref)
4629             var->uses++;
4630
4631         /* Part 2:
4632          * Create the global/local, and deal with vector types.
4633          */
4634         if (!proto) {
4635             if (var->expression.vtype == TYPE_VECTOR)
4636                 isvector = true;
4637             else if (var->expression.vtype == TYPE_FIELD &&
4638                      var->expression.next->expression.vtype == TYPE_VECTOR)
4639                 isvector = true;
4640
4641             if (isvector) {
4642                 if (!create_vector_members(var, me)) {
4643                     retval = false;
4644                     goto cleanup;
4645                 }
4646             }
4647
4648             if (!localblock) {
4649                 /* deal with global variables, fields, functions */
4650                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4651                     var->isfield = true;
4652                     vec_push(parser->fields, (ast_expression*)var);
4653                     util_htset(parser->htfields, var->name, var);
4654                     if (isvector) {
4655                         for (i = 0; i < 3; ++i) {
4656                             vec_push(parser->fields, (ast_expression*)me[i]);
4657                             util_htset(parser->htfields, me[i]->name, me[i]);
4658                         }
4659                     }
4660                 }
4661                 else {
4662                     vec_push(parser->globals, (ast_expression*)var);
4663                     util_htset(parser->htglobals, var->name, var);
4664                     if (isvector) {
4665                         for (i = 0; i < 3; ++i) {
4666                             vec_push(parser->globals, (ast_expression*)me[i]);
4667                             util_htset(parser->htglobals, me[i]->name, me[i]);
4668                         }
4669                     }
4670                 }
4671             } else {
4672                 if (is_static) {
4673                     /* a static adds itself to be generated like any other global
4674                      * but is added to the local namespace instead
4675                      */
4676                     char   *defname = NULL;
4677                     size_t  prefix_len, ln;
4678
4679                     ln = strlen(parser->function->name);
4680                     vec_append(defname, ln, parser->function->name);
4681
4682                     vec_append(defname, 2, "::");
4683                     /* remember the length up to here */
4684                     prefix_len = vec_size(defname);
4685
4686                     /* Add it to the local scope */
4687                     util_htset(vec_last(parser->variables), var->name, (void*)var);
4688                     /* now rename the global */
4689                     ln = strlen(var->name);
4690                     vec_append(defname, ln, var->name);
4691                     ast_value_set_name(var, defname);
4692
4693                     /* push it to the to-be-generated globals */
4694                     vec_push(parser->globals, (ast_expression*)var);
4695
4696                     /* same game for the vector members */
4697                     if (isvector) {
4698                         for (i = 0; i < 3; ++i) {
4699                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4700
4701                             vec_shrinkto(defname, prefix_len);
4702                             ln = strlen(me[i]->name);
4703                             vec_append(defname, ln, me[i]->name);
4704                             ast_member_set_name(me[i], defname);
4705
4706                             vec_push(parser->globals, (ast_expression*)me[i]);
4707                         }
4708                     }
4709                     vec_free(defname);
4710                 } else {
4711                     vec_push(localblock->locals, var);
4712                     parser_addlocal(parser, var->name, (ast_expression*)var);
4713                     if (isvector) {
4714                         for (i = 0; i < 3; ++i) {
4715                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4716                             ast_block_collect(localblock, (ast_expression*)me[i]);
4717                         }
4718                     }
4719                 }
4720             }
4721         }
4722         me[0] = me[1] = me[2] = NULL;
4723         cleanvar = false;
4724         /* Part 2.2
4725          * deal with arrays
4726          */
4727         if (var->expression.vtype == TYPE_ARRAY) {
4728             char name[1024];
4729             snprintf(name, sizeof(name), "%s##SET", var->name);
4730             if (!parser_create_array_setter(parser, var, name))
4731                 goto cleanup;
4732             snprintf(name, sizeof(name), "%s##GET", var->name);
4733             if (!parser_create_array_getter(parser, var, var->expression.next, name))
4734                 goto cleanup;
4735         }
4736         else if (!localblock && !nofields &&
4737                  var->expression.vtype == TYPE_FIELD &&
4738                  var->expression.next->expression.vtype == TYPE_ARRAY)
4739         {
4740             char name[1024];
4741             ast_expression *telem;
4742             ast_value      *tfield;
4743             ast_value      *array = (ast_value*)var->expression.next;
4744
4745             if (!ast_istype(var->expression.next, ast_value)) {
4746                 parseerror(parser, "internal error: field element type must be an ast_value");
4747                 goto cleanup;
4748             }
4749
4750             snprintf(name, sizeof(name), "%s##SETF", var->name);
4751             if (!parser_create_array_field_setter(parser, array, name))
4752                 goto cleanup;
4753
4754             telem = ast_type_copy(ast_ctx(var), array->expression.next);
4755             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4756             tfield->expression.next = telem;
4757             snprintf(name, sizeof(name), "%s##GETFP", var->name);
4758             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4759                 ast_delete(tfield);
4760                 goto cleanup;
4761             }
4762             ast_delete(tfield);
4763         }
4764
4765 skipvar:
4766         if (parser->tok == ';') {
4767             ast_delete(basetype);
4768             if (!parser_next(parser)) {
4769                 parseerror(parser, "error after variable declaration");
4770                 return false;
4771             }
4772             return true;
4773         }
4774
4775         if (parser->tok == ',')
4776             goto another;
4777
4778         /*
4779         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4780         */
4781         if (!var) {
4782             parseerror(parser, "missing comma or semicolon while parsing variables");
4783             break;
4784         }
4785
4786         if (localblock && opts.standard == COMPILER_QCC) {
4787             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4788                              "initializing expression turns variable `%s` into a constant in this standard",
4789                              var->name) )
4790             {
4791                 break;
4792             }
4793         }
4794
4795         if (parser->tok != '{') {
4796             if (parser->tok != '=') {
4797                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4798                 break;
4799             }
4800
4801             if (!parser_next(parser)) {
4802                 parseerror(parser, "error parsing initializer");
4803                 break;
4804             }
4805         }
4806         else if (opts.standard == COMPILER_QCC) {
4807             parseerror(parser, "expected '=' before function body in this standard");
4808         }
4809
4810         if (parser->tok == '#') {
4811             ast_function *func = NULL;
4812
4813             if (localblock) {
4814                 parseerror(parser, "cannot declare builtins within functions");
4815                 break;
4816             }
4817             if (var->expression.vtype != TYPE_FUNCTION) {
4818                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4819                 break;
4820             }
4821             if (!parser_next(parser)) {
4822                 parseerror(parser, "expected builtin number");
4823                 break;
4824             }
4825             if (parser->tok != TOKEN_INTCONST) {
4826                 parseerror(parser, "builtin number must be an integer constant");
4827                 break;
4828             }
4829             if (parser_token(parser)->constval.i < 0) {
4830                 parseerror(parser, "builtin number must be an integer greater than zero");
4831                 break;
4832             }
4833
4834             if (var->hasvalue) {
4835                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4836                                     "builtin `%s` has already been defined\n"
4837                                     " -> previous declaration here: %s:%i",
4838                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4839             }
4840             else
4841             {
4842                 func = ast_function_new(ast_ctx(var), var->name, var);
4843                 if (!func) {
4844                     parseerror(parser, "failed to allocate function for `%s`", var->name);
4845                     break;
4846                 }
4847                 vec_push(parser->functions, func);
4848
4849                 func->builtin = -parser_token(parser)->constval.i-1;
4850             }
4851
4852             if (!parser_next(parser)) {
4853                 parseerror(parser, "expected comma or semicolon");
4854                 if (func)
4855                     ast_function_delete(func);
4856                 var->constval.vfunc = NULL;
4857                 break;
4858             }
4859         }
4860         else if (parser->tok == '{' || parser->tok == '[')
4861         {
4862             if (localblock) {
4863                 parseerror(parser, "cannot declare functions within functions");
4864                 break;
4865             }
4866
4867             if (proto)
4868                 ast_ctx(proto) = parser_ctx(parser);
4869
4870             if (!parse_function_body(parser, var))
4871                 break;
4872             ast_delete(basetype);
4873             for (i = 0; i < vec_size(parser->gotos); ++i)
4874                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4875             vec_free(parser->gotos);
4876             vec_free(parser->labels);
4877             return true;
4878         } else {
4879             ast_expression *cexp;
4880             ast_value      *cval;
4881
4882             cexp = parse_expression_leave(parser, true, false);
4883             if (!cexp)
4884                 break;
4885
4886             if (!localblock) {
4887                 cval = (ast_value*)cexp;
4888                 if (cval != parser->nil &&
4889                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4890                    )
4891                 {
4892                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4893                 }
4894                 else
4895                 {
4896                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4897                         qualifier != CV_VAR)
4898                     {
4899                         var->cvq = CV_CONST;
4900                     }
4901                     if (cval == parser->nil)
4902                         var->expression.flags |= AST_FLAG_INITIALIZED;
4903                     else
4904                     {
4905                         var->hasvalue = true;
4906                         if (cval->expression.vtype == TYPE_STRING)
4907                             var->constval.vstring = parser_strdup(cval->constval.vstring);
4908                         else if (cval->expression.vtype == TYPE_FIELD)
4909                             var->constval.vfield = cval;
4910                         else
4911                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4912                         ast_unref(cval);
4913                     }
4914                 }
4915             } else {
4916                 int cvq;
4917                 shunt sy = { NULL, NULL };
4918                 cvq = var->cvq;
4919                 var->cvq = CV_NONE;
4920                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4921                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4922                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4923                 if (!parser_sy_apply_operator(parser, &sy))
4924                     ast_unref(cexp);
4925                 else {
4926                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4927                         parseerror(parser, "internal error: leaked operands");
4928                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4929                         break;
4930                 }
4931                 vec_free(sy.out);
4932                 vec_free(sy.ops);
4933                 var->cvq = cvq;
4934             }
4935         }
4936
4937 another:
4938         if (parser->tok == ',') {
4939             if (!parser_next(parser)) {
4940                 parseerror(parser, "expected another variable");
4941                 break;
4942             }
4943
4944             if (parser->tok != TOKEN_IDENT) {
4945                 parseerror(parser, "expected another variable");
4946                 break;
4947             }
4948             var = ast_value_copy(basetype);
4949             cleanvar = true;
4950             ast_value_set_name(var, parser_tokval(parser));
4951             if (!parser_next(parser)) {
4952                 parseerror(parser, "error parsing variable declaration");
4953                 break;
4954             }
4955             continue;
4956         }
4957
4958         if (parser->tok != ';') {
4959             parseerror(parser, "missing semicolon after variables");
4960             break;
4961         }
4962
4963         if (!parser_next(parser)) {
4964             parseerror(parser, "parse error after variable declaration");
4965             break;
4966         }
4967
4968         ast_delete(basetype);
4969         return true;
4970     }
4971
4972     if (cleanvar && var)
4973         ast_delete(var);
4974     ast_delete(basetype);
4975     return false;
4976
4977 cleanup:
4978     ast_delete(basetype);
4979     if (cleanvar && var)
4980         ast_delete(var);
4981     if (me[0]) ast_member_delete(me[0]);
4982     if (me[1]) ast_member_delete(me[1]);
4983     if (me[2]) ast_member_delete(me[2]);
4984     return retval;
4985 }
4986
4987 static bool parser_global_statement(parser_t *parser)
4988 {
4989     int        cvq       = CV_WRONG;
4990     bool       noref     = false;
4991     bool       is_static = false;
4992     uint32_t   qflags    = 0;
4993     ast_value *istype    = NULL;
4994     char      *vstring   = NULL;
4995
4996     if (parser->tok == TOKEN_IDENT)
4997         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4998
4999     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5000     {
5001         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5002     }
5003     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5004     {
5005         if (cvq == CV_WRONG)
5006             return false;
5007         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5008     }
5009     else if (parser->tok == TOKEN_KEYWORD)
5010     {
5011         if (!strcmp(parser_tokval(parser), "typedef")) {
5012             if (!parser_next(parser)) {
5013                 parseerror(parser, "expected type definition after 'typedef'");
5014                 return false;
5015             }
5016             return parse_typedef(parser);
5017         }
5018         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5019         return false;
5020     }
5021     else if (parser->tok == '#')
5022     {
5023         return parse_pragma(parser);
5024     }
5025     else if (parser->tok == '$')
5026     {
5027         if (!parser_next(parser)) {
5028             parseerror(parser, "parse error");
5029             return false;
5030         }
5031     }
5032     else
5033     {
5034         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5035         return false;
5036     }
5037     return true;
5038 }
5039
5040 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5041 {
5042     return util_crc16(old, str, strlen(str));
5043 }
5044
5045 static void progdefs_crc_file(const char *str)
5046 {
5047     /* write to progdefs.h here */
5048     (void)str;
5049 }
5050
5051 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5052 {
5053     old = progdefs_crc_sum(old, str);
5054     progdefs_crc_file(str);
5055     return old;
5056 }
5057
5058 static void generate_checksum(parser_t *parser)
5059 {
5060     uint16_t   crc = 0xFFFF;
5061     size_t     i;
5062     ast_value *value;
5063
5064     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5065     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5066     /*
5067     progdefs_crc_file("\tint\tpad;\n");
5068     progdefs_crc_file("\tint\tofs_return[3];\n");
5069     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5070     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5071     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5072     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5073     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5074     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5075     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5076     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5077     */
5078     for (i = 0; i < parser->crc_globals; ++i) {
5079         if (!ast_istype(parser->globals[i], ast_value))
5080             continue;
5081         value = (ast_value*)(parser->globals[i]);
5082         switch (value->expression.vtype) {
5083             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5084             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5085             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5086             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5087             default:
5088                 crc = progdefs_crc_both(crc, "\tint\t");
5089                 break;
5090         }
5091         crc = progdefs_crc_both(crc, value->name);
5092         crc = progdefs_crc_both(crc, ";\n");
5093     }
5094     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5095     for (i = 0; i < parser->crc_fields; ++i) {
5096         if (!ast_istype(parser->fields[i], ast_value))
5097             continue;
5098         value = (ast_value*)(parser->fields[i]);
5099         switch (value->expression.next->expression.vtype) {
5100             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5101             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5102             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5103             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5104             default:
5105                 crc = progdefs_crc_both(crc, "\tint\t");
5106                 break;
5107         }
5108         crc = progdefs_crc_both(crc, value->name);
5109         crc = progdefs_crc_both(crc, ";\n");
5110     }
5111     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5112
5113     code_crc = crc;
5114 }
5115
5116 static parser_t *parser;
5117
5118 bool parser_init()
5119 {
5120     lex_ctx empty_ctx;
5121     size_t i;
5122
5123     parser = (parser_t*)mem_a(sizeof(parser_t));
5124     if (!parser)
5125         return false;
5126
5127     memset(parser, 0, sizeof(*parser));
5128
5129     for (i = 0; i < operator_count; ++i) {
5130         if (operators[i].id == opid1('=')) {
5131             parser->assign_op = operators+i;
5132             break;
5133         }
5134     }
5135     if (!parser->assign_op) {
5136         printf("internal error: initializing parser: failed to find assign operator\n");
5137         mem_d(parser);
5138         return false;
5139     }
5140
5141     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5142     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5143     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5144     vec_push(parser->_blocktypedefs, 0);
5145
5146     empty_ctx.file = "<internal>";
5147     empty_ctx.line = 0;
5148     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5149     parser->nil->cvq = CV_CONST;
5150     if (OPTS_FLAG(UNTYPED_NIL))
5151         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5152     return true;
5153 }
5154
5155 bool parser_compile()
5156 {
5157     /* initial lexer/parser state */
5158     parser->lex->flags.noops = true;
5159
5160     if (parser_next(parser))
5161     {
5162         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5163         {
5164             if (!parser_global_statement(parser)) {
5165                 if (parser->tok == TOKEN_EOF)
5166                     parseerror(parser, "unexpected eof");
5167                 else if (compile_errors)
5168                     parseerror(parser, "there have been errors, bailing out");
5169                 lex_close(parser->lex);
5170                 parser->lex = NULL;
5171                 return false;
5172             }
5173         }
5174     } else {
5175         parseerror(parser, "parse error");
5176         lex_close(parser->lex);
5177         parser->lex = NULL;
5178         return false;
5179     }
5180
5181     lex_close(parser->lex);
5182     parser->lex = NULL;
5183
5184     return !compile_errors;
5185 }
5186
5187 bool parser_compile_file(const char *filename)
5188 {
5189     parser->lex = lex_open(filename);
5190     if (!parser->lex) {
5191         con_err("failed to open file \"%s\"\n", filename);
5192         return false;
5193     }
5194     return parser_compile();
5195 }
5196
5197 bool parser_compile_string(const char *name, const char *str, size_t len)
5198 {
5199     parser->lex = lex_open_string(str, len, name);
5200     if (!parser->lex) {
5201         con_err("failed to create lexer for string \"%s\"\n", name);
5202         return false;
5203     }
5204     return parser_compile();
5205 }
5206
5207 void parser_cleanup()
5208 {
5209     size_t i;
5210     for (i = 0; i < vec_size(parser->accessors); ++i) {
5211         ast_delete(parser->accessors[i]->constval.vfunc);
5212         parser->accessors[i]->constval.vfunc = NULL;
5213         ast_delete(parser->accessors[i]);
5214     }
5215     for (i = 0; i < vec_size(parser->functions); ++i) {
5216         ast_delete(parser->functions[i]);
5217     }
5218     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5219         ast_delete(parser->imm_vector[i]);
5220     }
5221     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5222         ast_delete(parser->imm_string[i]);
5223     }
5224     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5225         ast_delete(parser->imm_float[i]);
5226     }
5227     for (i = 0; i < vec_size(parser->fields); ++i) {
5228         ast_delete(parser->fields[i]);
5229     }
5230     for (i = 0; i < vec_size(parser->globals); ++i) {
5231         ast_delete(parser->globals[i]);
5232     }
5233     vec_free(parser->accessors);
5234     vec_free(parser->functions);
5235     vec_free(parser->imm_vector);
5236     vec_free(parser->imm_string);
5237     vec_free(parser->imm_float);
5238     vec_free(parser->globals);
5239     vec_free(parser->fields);
5240
5241     for (i = 0; i < vec_size(parser->variables); ++i)
5242         util_htdel(parser->variables[i]);
5243     vec_free(parser->variables);
5244     vec_free(parser->_blocklocals);
5245     vec_free(parser->_locals);
5246
5247     for (i = 0; i < vec_size(parser->_typedefs); ++i)
5248         ast_delete(parser->_typedefs[i]);
5249     vec_free(parser->_typedefs);
5250     for (i = 0; i < vec_size(parser->typedefs); ++i)
5251         util_htdel(parser->typedefs[i]);
5252     vec_free(parser->typedefs);
5253     vec_free(parser->_blocktypedefs);
5254
5255     vec_free(parser->_block_ctx);
5256
5257     vec_free(parser->labels);
5258     vec_free(parser->gotos);
5259     vec_free(parser->breaks);
5260     vec_free(parser->continues);
5261
5262     ast_value_delete(parser->nil);
5263
5264     mem_d(parser);
5265 }
5266
5267 bool parser_finish(const char *output)
5268 {
5269     size_t i;
5270     ir_builder *ir;
5271     bool retval = true;
5272
5273     if (compile_errors) {
5274         con_out("*** there were compile errors\n");
5275         return false;
5276     }
5277
5278     ir = ir_builder_new("gmqcc_out");
5279     if (!ir) {
5280         con_out("failed to allocate builder\n");
5281         return false;
5282     }
5283
5284     for (i = 0; i < vec_size(parser->fields); ++i) {
5285         ast_value *field;
5286         bool hasvalue;
5287         if (!ast_istype(parser->fields[i], ast_value))
5288             continue;
5289         field = (ast_value*)parser->fields[i];
5290         hasvalue = field->hasvalue;
5291         field->hasvalue = false;
5292         if (!ast_global_codegen((ast_value*)field, ir, true)) {
5293             con_out("failed to generate field %s\n", field->name);
5294             ir_builder_delete(ir);
5295             return false;
5296         }
5297         if (hasvalue) {
5298             ir_value *ifld;
5299             ast_expression *subtype;
5300             field->hasvalue = true;
5301             subtype = field->expression.next;
5302             ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5303             if (subtype->expression.vtype == TYPE_FIELD)
5304                 ifld->fieldtype = subtype->expression.next->expression.vtype;
5305             else if (subtype->expression.vtype == TYPE_FUNCTION)
5306                 ifld->outtype = subtype->expression.next->expression.vtype;
5307             (void)!ir_value_set_field(field->ir_v, ifld);
5308         }
5309     }
5310     for (i = 0; i < vec_size(parser->globals); ++i) {
5311         ast_value *asvalue;
5312         if (!ast_istype(parser->globals[i], ast_value))
5313             continue;
5314         asvalue = (ast_value*)(parser->globals[i]);
5315         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5316             retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5317                                            "unused global: `%s`", asvalue->name);
5318         }
5319         if (!ast_global_codegen(asvalue, ir, false)) {
5320             con_out("failed to generate global %s\n", asvalue->name);
5321             ir_builder_delete(ir);
5322             return false;
5323         }
5324     }
5325     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5326         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5327             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5328             ir_builder_delete(ir);
5329             return false;
5330         }
5331     }
5332     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5333         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5334             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5335             ir_builder_delete(ir);
5336             return false;
5337         }
5338     }
5339     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5340         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5341             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5342             ir_builder_delete(ir);
5343             return false;
5344         }
5345     }
5346     for (i = 0; i < vec_size(parser->globals); ++i) {
5347         ast_value *asvalue;
5348         if (!ast_istype(parser->globals[i], ast_value))
5349             continue;
5350         asvalue = (ast_value*)(parser->globals[i]);
5351         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5352         {
5353             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5354                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5355                                        "uninitialized constant: `%s`",
5356                                        asvalue->name);
5357             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5358                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5359                                        "uninitialized global: `%s`",
5360                                        asvalue->name);
5361         }
5362         if (!ast_generate_accessors(asvalue, ir)) {
5363             ir_builder_delete(ir);
5364             return false;
5365         }
5366     }
5367     for (i = 0; i < vec_size(parser->fields); ++i) {
5368         ast_value *asvalue;
5369         asvalue = (ast_value*)(parser->fields[i]->expression.next);
5370
5371         if (!ast_istype((ast_expression*)asvalue, ast_value))
5372             continue;
5373         if (asvalue->expression.vtype != TYPE_ARRAY)
5374             continue;
5375         if (!ast_generate_accessors(asvalue, ir)) {
5376             ir_builder_delete(ir);
5377             return false;
5378         }
5379     }
5380     for (i = 0; i < vec_size(parser->functions); ++i) {
5381         if (!ast_function_codegen(parser->functions[i], ir)) {
5382             con_out("failed to generate function %s\n", parser->functions[i]->name);
5383             ir_builder_delete(ir);
5384             return false;
5385         }
5386     }
5387     if (opts.dump)
5388         ir_builder_dump(ir, con_out);
5389     for (i = 0; i < vec_size(parser->functions); ++i) {
5390         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5391             con_out("failed to finalize function %s\n", parser->functions[i]->name);
5392             ir_builder_delete(ir);
5393             return false;
5394         }
5395     }
5396
5397     if (compile_Werrors) {
5398         con_out("*** there were warnings treated as errors\n");
5399         compile_show_werrors();
5400         retval = false;
5401     }
5402
5403     if (retval) {
5404         if (opts.dumpfin)
5405             ir_builder_dump(ir, con_out);
5406
5407         generate_checksum(parser);
5408
5409         if (!ir_builder_generate(ir, output)) {
5410             con_out("*** failed to generate output file\n");
5411             ir_builder_delete(ir);
5412             return false;
5413         }
5414     }
5415
5416     ir_builder_delete(ir);
5417     return retval;
5418 }