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