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