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