]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Some error checking for computed goto.
[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) {
2985             parseerror(parser, "expected label or expression in ternary");
2986             ast_unref(((ast_ternary*)side)->on_false);
2987             return NULL;
2988         }
2989
2990         if (!on_false) {
2991             parseerror(parser, "expected label or expression in ternary");
2992             ast_unref(((ast_ternary*)side)->on_true);
2993             return NULL;
2994         }
2995
2996         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), ((ast_ternary*)side)->cond, on_true, on_false);
2997     } else if (ast_istype(side, ast_label)) {
2998         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)side)->name);
2999         ast_goto_set_label(gt, ((ast_label*)side));
3000         return (ast_expression*)gt;
3001     }
3002     return NULL;
3003 }
3004
3005 static bool parse_goto(parser_t *parser, ast_expression **out)
3006 {
3007     size_t    i;
3008     ast_goto *gt = NULL;
3009
3010     if (!parser_next(parser))
3011         return false;
3012
3013     if (parser->tok != TOKEN_IDENT) {
3014         ast_expression *expression;
3015         /* could be an expression i.e computed goto :-) */
3016         if (parser->tok != '(') {
3017             parseerror(parser, "expected label name after `goto`");
3018             return false;
3019         }
3020
3021         /* failed to parse expression for goto */
3022         if (!(expression = parse_expression(parser, false)) ||
3023             !(*out = parse_goto_computed(parser, expression))) {
3024             parseerror(parser, "invalid goto expression");
3025             return false;
3026         }
3027
3028         return true;
3029     }
3030
3031     /* not computed goto */
3032     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3033
3034     for (i = 0; i < vec_size(parser->labels); ++i) {
3035         if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
3036             ast_goto_set_label(gt, parser->labels[i]);
3037             break;
3038         }
3039     }
3040     if (i == vec_size(parser->labels))
3041         vec_push(parser->gotos, gt);
3042
3043     if (!parser_next(parser) || parser->tok != ';') {
3044         parseerror(parser, "semicolon expected after goto label");
3045         return false;
3046     }
3047     if (!parser_next(parser)) {
3048         parseerror(parser, "parse error after goto");
3049         return false;
3050     }
3051
3052     *out = (ast_expression*)gt;
3053     return true;
3054 }
3055
3056 static bool parse_skipwhite(parser_t *parser)
3057 {
3058     do {
3059         if (!parser_next(parser))
3060             return false;
3061     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3062     return parser->tok < TOKEN_ERROR;
3063 }
3064
3065 static bool parse_eol(parser_t *parser)
3066 {
3067     if (!parse_skipwhite(parser))
3068         return false;
3069     return parser->tok == TOKEN_EOL;
3070 }
3071
3072 static bool parse_pragma_do(parser_t *parser)
3073 {
3074     if (!parser_next(parser) ||
3075         parser->tok != TOKEN_IDENT ||
3076         strcmp(parser_tokval(parser), "pragma"))
3077     {
3078         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3079         return false;
3080     }
3081     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3082         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3083         return false;
3084     }
3085
3086     if (!strcmp(parser_tokval(parser), "noref")) {
3087         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3088             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3089             return false;
3090         }
3091         parser->noref = !!parser_token(parser)->constval.i;
3092         if (!parse_eol(parser)) {
3093             parseerror(parser, "parse error after `noref` pragma");
3094             return false;
3095         }
3096     }
3097     else
3098     {
3099         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3100         return false;
3101     }
3102
3103     return true;
3104 }
3105
3106 static bool parse_pragma(parser_t *parser)
3107 {
3108     bool rv;
3109     parser->lex->flags.preprocessing = true;
3110     parser->lex->flags.mergelines = true;
3111     rv = parse_pragma_do(parser);
3112     if (parser->tok != TOKEN_EOL) {
3113         parseerror(parser, "junk after pragma");
3114         rv = false;
3115     }
3116     parser->lex->flags.preprocessing = false;
3117     parser->lex->flags.mergelines = false;
3118     if (!parser_next(parser)) {
3119         parseerror(parser, "parse error after pragma");
3120         rv = false;
3121     }
3122     return rv;
3123 }
3124
3125 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3126 {
3127     bool       noref, is_static;
3128     int        cvq     = CV_NONE;
3129     uint32_t   qflags  = 0;
3130     ast_value *typevar = NULL;
3131     char      *vstring = NULL;
3132
3133     *out = NULL;
3134
3135     if (parser->tok == TOKEN_IDENT)
3136         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3137
3138     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3139     {
3140         /* local variable */
3141         if (!block) {
3142             parseerror(parser, "cannot declare a variable from here");
3143             return false;
3144         }
3145         if (opts.standard == COMPILER_QCC) {
3146             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3147                 return false;
3148         }
3149         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3150             return false;
3151         return true;
3152     }
3153     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3154     {
3155         if (cvq == CV_WRONG)
3156             return false;
3157         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3158     }
3159     else if (parser->tok == TOKEN_KEYWORD)
3160     {
3161         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3162         {
3163             char ty[1024];
3164             ast_value *tdef;
3165
3166             if (!parser_next(parser)) {
3167                 parseerror(parser, "parse error after __builtin_debug_printtype");
3168                 return false;
3169             }
3170
3171             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3172             {
3173                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3174                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3175                 if (!parser_next(parser)) {
3176                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3177                     return false;
3178                 }
3179             }
3180             else
3181             {
3182                 if (!parse_statement(parser, block, out, allow_cases))
3183                     return false;
3184                 if (!*out)
3185                     con_out("__builtin_debug_printtype: got no output node\n");
3186                 else
3187                 {
3188                     ast_type_to_string(*out, ty, sizeof(ty));
3189                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3190                 }
3191             }
3192             return true;
3193         }
3194         else if (!strcmp(parser_tokval(parser), "return"))
3195         {
3196             return parse_return(parser, block, out);
3197         }
3198         else if (!strcmp(parser_tokval(parser), "if"))
3199         {
3200             return parse_if(parser, block, out);
3201         }
3202         else if (!strcmp(parser_tokval(parser), "while"))
3203         {
3204             return parse_while(parser, block, out);
3205         }
3206         else if (!strcmp(parser_tokval(parser), "do"))
3207         {
3208             return parse_dowhile(parser, block, out);
3209         }
3210         else if (!strcmp(parser_tokval(parser), "for"))
3211         {
3212             if (opts.standard == COMPILER_QCC) {
3213                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3214                     return false;
3215             }
3216             return parse_for(parser, block, out);
3217         }
3218         else if (!strcmp(parser_tokval(parser), "break"))
3219         {
3220             return parse_break_continue(parser, block, out, false);
3221         }
3222         else if (!strcmp(parser_tokval(parser), "continue"))
3223         {
3224             return parse_break_continue(parser, block, out, true);
3225         }
3226         else if (!strcmp(parser_tokval(parser), "switch"))
3227         {
3228             return parse_switch(parser, block, out);
3229         }
3230         else if (!strcmp(parser_tokval(parser), "case") ||
3231                  !strcmp(parser_tokval(parser), "default"))
3232         {
3233             if (!allow_cases) {
3234                 parseerror(parser, "unexpected 'case' label");
3235                 return false;
3236             }
3237             return true;
3238         }
3239         else if (!strcmp(parser_tokval(parser), "goto"))
3240         {
3241             return parse_goto(parser, out);
3242         }
3243         else if (!strcmp(parser_tokval(parser), "typedef"))
3244         {
3245             if (!parser_next(parser)) {
3246                 parseerror(parser, "expected type definition after 'typedef'");
3247                 return false;
3248             }
3249             return parse_typedef(parser);
3250         }
3251         parseerror(parser, "Unexpected keyword");
3252         return false;
3253     }
3254     else if (parser->tok == '{')
3255     {
3256         ast_block *inner;
3257         inner = parse_block(parser);
3258         if (!inner)
3259             return false;
3260         *out = (ast_expression*)inner;
3261         return true;
3262     }
3263     else if (parser->tok == ':')
3264     {
3265         size_t i;
3266         ast_label *label;
3267         if (!parser_next(parser)) {
3268             parseerror(parser, "expected label name");
3269             return false;
3270         }
3271         if (parser->tok != TOKEN_IDENT) {
3272             parseerror(parser, "label must be an identifier");
3273             return false;
3274         }
3275         label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
3276         if (!label)
3277             return false;
3278         vec_push(parser->labels, label);
3279         *out = (ast_expression*)label;
3280         if (!parser_next(parser)) {
3281             parseerror(parser, "parse error after label");
3282             return false;
3283         }
3284         for (i = 0; i < vec_size(parser->gotos); ++i) {
3285             if (!strcmp(parser->gotos[i]->name, label->name)) {
3286                 ast_goto_set_label(parser->gotos[i], label);
3287                 vec_remove(parser->gotos, i, 1);
3288                 --i;
3289             }
3290         }
3291         return true;
3292     }
3293     else if (parser->tok == ';')
3294     {
3295         if (!parser_next(parser)) {
3296             parseerror(parser, "parse error after empty statement");
3297             return false;
3298         }
3299         return true;
3300     }
3301     else
3302     {
3303         ast_expression *exp = parse_expression(parser, false);
3304         if (!exp)
3305             return false;
3306         *out = exp;
3307         if (!ast_side_effects(exp)) {
3308             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3309                 return false;
3310         }
3311         return true;
3312     }
3313 }
3314
3315 static bool parse_block_into(parser_t *parser, ast_block *block)
3316 {
3317     bool   retval = true;
3318
3319     parser_enterblock(parser);
3320
3321     if (!parser_next(parser)) { /* skip the '{' */
3322         parseerror(parser, "expected function body");
3323         goto cleanup;
3324     }
3325
3326     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3327     {
3328         ast_expression *expr = NULL;
3329         if (parser->tok == '}')
3330             break;
3331
3332         if (!parse_statement(parser, block, &expr, false)) {
3333             /* parseerror(parser, "parse error"); */
3334             block = NULL;
3335             goto cleanup;
3336         }
3337         if (!expr)
3338             continue;
3339         if (!ast_block_add_expr(block, expr)) {
3340             ast_delete(block);
3341             block = NULL;
3342             goto cleanup;
3343         }
3344     }
3345
3346     if (parser->tok != '}') {
3347         block = NULL;
3348     } else {
3349         (void)parser_next(parser);
3350     }
3351
3352 cleanup:
3353     if (!parser_leaveblock(parser))
3354         retval = false;
3355     return retval && !!block;
3356 }
3357
3358 static ast_block* parse_block(parser_t *parser)
3359 {
3360     ast_block *block;
3361     block = ast_block_new(parser_ctx(parser));
3362     if (!block)
3363         return NULL;
3364     if (!parse_block_into(parser, block)) {
3365         ast_block_delete(block);
3366         return NULL;
3367     }
3368     return block;
3369 }
3370
3371 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3372 {
3373     if (parser->tok == '{') {
3374         *out = (ast_expression*)parse_block(parser);
3375         return !!*out;
3376     }
3377     return parse_statement(parser, NULL, out, false);
3378 }
3379
3380 static bool create_vector_members(ast_value *var, ast_member **me)
3381 {
3382     size_t i;
3383     size_t len = strlen(var->name);
3384
3385     for (i = 0; i < 3; ++i) {
3386         char *name = (char*)mem_a(len+3);
3387         memcpy(name, var->name, len);
3388         name[len+0] = '_';
3389         name[len+1] = 'x'+i;
3390         name[len+2] = 0;
3391         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3392         mem_d(name);
3393         if (!me[i])
3394             break;
3395     }
3396     if (i == 3)
3397         return true;
3398
3399     /* unroll */
3400     do { ast_member_delete(me[--i]); } while(i);
3401     return false;
3402 }
3403
3404 static bool parse_function_body(parser_t *parser, ast_value *var)
3405 {
3406     ast_block      *block = NULL;
3407     ast_function   *func;
3408     ast_function   *old;
3409     size_t          parami;
3410
3411     ast_expression *framenum  = NULL;
3412     ast_expression *nextthink = NULL;
3413     /* None of the following have to be deleted */
3414     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3415     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3416     bool            has_frame_think;
3417
3418     bool retval = true;
3419
3420     has_frame_think = false;
3421     old = parser->function;
3422
3423     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3424         parseerror(parser, "gotos/labels leaking");
3425         return false;
3426     }
3427
3428     if (var->expression.flags & AST_FLAG_VARIADIC) {
3429         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3430                          "variadic function with implementation will not be able to access additional parameters"))
3431         {
3432             return false;
3433         }
3434     }
3435
3436     if (parser->tok == '[') {
3437         /* got a frame definition: [ framenum, nextthink ]
3438          * this translates to:
3439          * self.frame = framenum;
3440          * self.nextthink = time + 0.1;
3441          * self.think = nextthink;
3442          */
3443         nextthink = NULL;
3444
3445         fld_think     = parser_find_field(parser, "think");
3446         fld_nextthink = parser_find_field(parser, "nextthink");
3447         fld_frame     = parser_find_field(parser, "frame");
3448         if (!fld_think || !fld_nextthink || !fld_frame) {
3449             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3450             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3451             return false;
3452         }
3453         gbl_time      = parser_find_global(parser, "time");
3454         gbl_self      = parser_find_global(parser, "self");
3455         if (!gbl_time || !gbl_self) {
3456             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3457             parseerror(parser, "please declare the following globals: `time`, `self`");
3458             return false;
3459         }
3460
3461         if (!parser_next(parser))
3462             return false;
3463
3464         framenum = parse_expression_leave(parser, true, false);
3465         if (!framenum) {
3466             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3467             return false;
3468         }
3469         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3470             ast_unref(framenum);
3471             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3472             return false;
3473         }
3474
3475         if (parser->tok != ',') {
3476             ast_unref(framenum);
3477             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3478             parseerror(parser, "Got a %i\n", parser->tok);
3479             return false;
3480         }
3481
3482         if (!parser_next(parser)) {
3483             ast_unref(framenum);
3484             return false;
3485         }
3486
3487         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3488         {
3489             /* qc allows the use of not-yet-declared functions here
3490              * - this automatically creates a prototype */
3491             ast_value      *thinkfunc;
3492             ast_expression *functype = fld_think->expression.next;
3493
3494             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3495             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3496                 ast_unref(framenum);
3497                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3498                 return false;
3499             }
3500
3501             if (!parser_next(parser)) {
3502                 ast_unref(framenum);
3503                 ast_delete(thinkfunc);
3504                 return false;
3505             }
3506
3507             vec_push(parser->globals, (ast_expression*)thinkfunc);
3508             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3509             nextthink = (ast_expression*)thinkfunc;
3510
3511         } else {
3512             nextthink = parse_expression_leave(parser, true, false);
3513             if (!nextthink) {
3514                 ast_unref(framenum);
3515                 parseerror(parser, "expected a think-function in [frame,think] notation");
3516                 return false;
3517             }
3518         }
3519
3520         if (!ast_istype(nextthink, ast_value)) {
3521             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3522             retval = false;
3523         }
3524
3525         if (retval && parser->tok != ']') {
3526             parseerror(parser, "expected closing `]` for [frame,think] notation");
3527             retval = false;
3528         }
3529
3530         if (retval && !parser_next(parser)) {
3531             retval = false;
3532         }
3533
3534         if (retval && parser->tok != '{') {
3535             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3536             retval = false;
3537         }
3538
3539         if (!retval) {
3540             ast_unref(nextthink);
3541             ast_unref(framenum);
3542             return false;
3543         }
3544
3545         has_frame_think = true;
3546     }
3547
3548     block = ast_block_new(parser_ctx(parser));
3549     if (!block) {
3550         parseerror(parser, "failed to allocate block");
3551         if (has_frame_think) {
3552             ast_unref(nextthink);
3553             ast_unref(framenum);
3554         }
3555         return false;
3556     }
3557
3558     if (has_frame_think) {
3559         lex_ctx ctx;
3560         ast_expression *self_frame;
3561         ast_expression *self_nextthink;
3562         ast_expression *self_think;
3563         ast_expression *time_plus_1;
3564         ast_store *store_frame;
3565         ast_store *store_nextthink;
3566         ast_store *store_think;
3567
3568         ctx = parser_ctx(parser);
3569         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3570         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3571         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3572
3573         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3574                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3575
3576         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3577             if (self_frame)     ast_delete(self_frame);
3578             if (self_nextthink) ast_delete(self_nextthink);
3579             if (self_think)     ast_delete(self_think);
3580             if (time_plus_1)    ast_delete(time_plus_1);
3581             retval = false;
3582         }
3583
3584         if (retval)
3585         {
3586             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3587             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3588             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3589
3590             if (!store_frame) {
3591                 ast_delete(self_frame);
3592                 retval = false;
3593             }
3594             if (!store_nextthink) {
3595                 ast_delete(self_nextthink);
3596                 retval = false;
3597             }
3598             if (!store_think) {
3599                 ast_delete(self_think);
3600                 retval = false;
3601             }
3602             if (!retval) {
3603                 if (store_frame)     ast_delete(store_frame);
3604                 if (store_nextthink) ast_delete(store_nextthink);
3605                 if (store_think)     ast_delete(store_think);
3606                 retval = false;
3607             }
3608             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3609                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3610                 !ast_block_add_expr(block, (ast_expression*)store_think))
3611             {
3612                 retval = false;
3613             }
3614         }
3615
3616         if (!retval) {
3617             parseerror(parser, "failed to generate code for [frame,think]");
3618             ast_unref(nextthink);
3619             ast_unref(framenum);
3620             ast_delete(block);
3621             return false;
3622         }
3623     }
3624
3625     parser_enterblock(parser);
3626
3627     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3628         size_t     e;
3629         ast_value *param = var->expression.params[parami];
3630         ast_member *me[3];
3631
3632         if (param->expression.vtype != TYPE_VECTOR &&
3633             (param->expression.vtype != TYPE_FIELD ||
3634              param->expression.next->expression.vtype != TYPE_VECTOR))
3635         {
3636             continue;
3637         }
3638
3639         if (!create_vector_members(param, me)) {
3640             ast_block_delete(block);
3641             return false;
3642         }
3643
3644         for (e = 0; e < 3; ++e) {
3645             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3646             ast_block_collect(block, (ast_expression*)me[e]);
3647         }
3648     }
3649
3650     func = ast_function_new(ast_ctx(var), var->name, var);
3651     if (!func) {
3652         parseerror(parser, "failed to allocate function for `%s`", var->name);
3653         ast_block_delete(block);
3654         goto enderr;
3655     }
3656     vec_push(parser->functions, func);
3657
3658     parser->function = func;
3659     if (!parse_block_into(parser, block)) {
3660         ast_block_delete(block);
3661         goto enderrfn;
3662     }
3663
3664     vec_push(func->blocks, block);
3665
3666     parser->function = old;
3667     if (!parser_leaveblock(parser))
3668         retval = false;
3669     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3670         parseerror(parser, "internal error: local scopes left");
3671         retval = false;
3672     }
3673
3674     if (parser->tok == ';')
3675         return parser_next(parser);
3676     else if (opts.standard == COMPILER_QCC)
3677         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3678     return retval;
3679
3680 enderrfn:
3681     vec_pop(parser->functions);
3682     ast_function_delete(func);
3683     var->constval.vfunc = NULL;
3684
3685 enderr:
3686     (void)!parser_leaveblock(parser);
3687     parser->function = old;
3688     return false;
3689 }
3690
3691 static ast_expression *array_accessor_split(
3692     parser_t  *parser,
3693     ast_value *array,
3694     ast_value *index,
3695     size_t     middle,
3696     ast_expression *left,
3697     ast_expression *right
3698     )
3699 {
3700     ast_ifthen *ifthen;
3701     ast_binary *cmp;
3702
3703     lex_ctx ctx = ast_ctx(array);
3704
3705     if (!left || !right) {
3706         if (left)  ast_delete(left);
3707         if (right) ast_delete(right);
3708         return NULL;
3709     }
3710
3711     cmp = ast_binary_new(ctx, INSTR_LT,
3712                          (ast_expression*)index,
3713                          (ast_expression*)parser_const_float(parser, middle));
3714     if (!cmp) {
3715         ast_delete(left);
3716         ast_delete(right);
3717         parseerror(parser, "internal error: failed to create comparison for array setter");
3718         return NULL;
3719     }
3720
3721     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3722     if (!ifthen) {
3723         ast_delete(cmp); /* will delete left and right */
3724         parseerror(parser, "internal error: failed to create conditional jump for array setter");
3725         return NULL;
3726     }
3727
3728     return (ast_expression*)ifthen;
3729 }
3730
3731 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3732 {
3733     lex_ctx ctx = ast_ctx(array);
3734
3735     if (from+1 == afterend) {
3736         /* set this value */
3737         ast_block       *block;
3738         ast_return      *ret;
3739         ast_array_index *subscript;
3740         ast_store       *st;
3741         int assignop = type_store_instr[value->expression.vtype];
3742
3743         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3744             assignop = INSTR_STORE_V;
3745
3746         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3747         if (!subscript)
3748             return NULL;
3749
3750         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3751         if (!st) {
3752             ast_delete(subscript);
3753             return NULL;
3754         }
3755
3756         block = ast_block_new(ctx);
3757         if (!block) {
3758             ast_delete(st);
3759             return NULL;
3760         }
3761
3762         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3763             ast_delete(block);
3764             return NULL;
3765         }
3766
3767         ret = ast_return_new(ctx, NULL);
3768         if (!ret) {
3769             ast_delete(block);
3770             return NULL;
3771         }
3772
3773         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3774             ast_delete(block);
3775             return NULL;
3776         }
3777
3778         return (ast_expression*)block;
3779     } else {
3780         ast_expression *left, *right;
3781         size_t diff = afterend - from;
3782         size_t middle = from + diff/2;
3783         left  = array_setter_node(parser, array, index, value, from, middle);
3784         right = array_setter_node(parser, array, index, value, middle, afterend);
3785         return array_accessor_split(parser, array, index, middle, left, right);
3786     }
3787 }
3788
3789 static ast_expression *array_field_setter_node(
3790     parser_t  *parser,
3791     ast_value *array,
3792     ast_value *entity,
3793     ast_value *index,
3794     ast_value *value,
3795     size_t     from,
3796     size_t     afterend)
3797 {
3798     lex_ctx ctx = ast_ctx(array);
3799
3800     if (from+1 == afterend) {
3801         /* set this value */
3802         ast_block       *block;
3803         ast_return      *ret;
3804         ast_entfield    *entfield;
3805         ast_array_index *subscript;
3806         ast_store       *st;
3807         int assignop = type_storep_instr[value->expression.vtype];
3808
3809         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3810             assignop = INSTR_STOREP_V;
3811
3812         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3813         if (!subscript)
3814             return NULL;
3815
3816         entfield = ast_entfield_new_force(ctx,
3817                                           (ast_expression*)entity,
3818                                           (ast_expression*)subscript,
3819                                           (ast_expression*)subscript);
3820         if (!entfield) {
3821             ast_delete(subscript);
3822             return NULL;
3823         }
3824
3825         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3826         if (!st) {
3827             ast_delete(entfield);
3828             return NULL;
3829         }
3830
3831         block = ast_block_new(ctx);
3832         if (!block) {
3833             ast_delete(st);
3834             return NULL;
3835         }
3836
3837         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3838             ast_delete(block);
3839             return NULL;
3840         }
3841
3842         ret = ast_return_new(ctx, NULL);
3843         if (!ret) {
3844             ast_delete(block);
3845             return NULL;
3846         }
3847
3848         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3849             ast_delete(block);
3850             return NULL;
3851         }
3852
3853         return (ast_expression*)block;
3854     } else {
3855         ast_expression *left, *right;
3856         size_t diff = afterend - from;
3857         size_t middle = from + diff/2;
3858         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
3859         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3860         return array_accessor_split(parser, array, index, middle, left, right);
3861     }
3862 }
3863
3864 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3865 {
3866     lex_ctx ctx = ast_ctx(array);
3867
3868     if (from+1 == afterend) {
3869         ast_return      *ret;
3870         ast_array_index *subscript;
3871
3872         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3873         if (!subscript)
3874             return NULL;
3875
3876         ret = ast_return_new(ctx, (ast_expression*)subscript);
3877         if (!ret) {
3878             ast_delete(subscript);
3879             return NULL;
3880         }
3881
3882         return (ast_expression*)ret;
3883     } else {
3884         ast_expression *left, *right;
3885         size_t diff = afterend - from;
3886         size_t middle = from + diff/2;
3887         left  = array_getter_node(parser, array, index, from, middle);
3888         right = array_getter_node(parser, array, index, middle, afterend);
3889         return array_accessor_split(parser, array, index, middle, left, right);
3890     }
3891 }
3892
3893 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3894 {
3895     ast_function   *func = NULL;
3896     ast_value      *fval = NULL;
3897     ast_block      *body = NULL;
3898
3899     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3900     if (!fval) {
3901         parseerror(parser, "failed to create accessor function value");
3902         return false;
3903     }
3904
3905     func = ast_function_new(ast_ctx(array), funcname, fval);
3906     if (!func) {
3907         ast_delete(fval);
3908         parseerror(parser, "failed to create accessor function node");
3909         return false;
3910     }
3911
3912     body = ast_block_new(ast_ctx(array));
3913     if (!body) {
3914         parseerror(parser, "failed to create block for array accessor");
3915         ast_delete(fval);
3916         ast_delete(func);
3917         return false;
3918     }
3919
3920     vec_push(func->blocks, body);
3921     *out = fval;
3922
3923     vec_push(parser->accessors, fval);
3924
3925     return true;
3926 }
3927
3928 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3929 {
3930     ast_expression *root = NULL;
3931     ast_value      *index = NULL;
3932     ast_value      *value = NULL;
3933     ast_function   *func;
3934     ast_value      *fval;
3935
3936     if (!ast_istype(array->expression.next, ast_value)) {
3937         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3938         return false;
3939     }
3940
3941     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3942         return false;
3943     func = fval->constval.vfunc;
3944     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3945
3946     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3947     value = ast_value_copy((ast_value*)array->expression.next);
3948
3949     if (!index || !value) {
3950         parseerror(parser, "failed to create locals for array accessor");
3951         goto cleanup;
3952     }
3953     (void)!ast_value_set_name(value, "value"); /* not important */
3954     vec_push(fval->expression.params, index);
3955     vec_push(fval->expression.params, value);
3956
3957     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3958     if (!root) {
3959         parseerror(parser, "failed to build accessor search tree");
3960         goto cleanup;
3961     }
3962
3963     array->setter = fval;
3964     return ast_block_add_expr(func->blocks[0], root);
3965 cleanup:
3966     if (index) ast_delete(index);
3967     if (value) ast_delete(value);
3968     if (root)  ast_delete(root);
3969     ast_delete(func);
3970     ast_delete(fval);
3971     return false;
3972 }
3973
3974 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3975 {
3976     ast_expression *root = NULL;
3977     ast_value      *entity = NULL;
3978     ast_value      *index = NULL;
3979     ast_value      *value = NULL;
3980     ast_function   *func;
3981     ast_value      *fval;
3982
3983     if (!ast_istype(array->expression.next, ast_value)) {
3984         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3985         return false;
3986     }
3987
3988     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3989         return false;
3990     func = fval->constval.vfunc;
3991     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3992
3993     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3994     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
3995     value  = ast_value_copy((ast_value*)array->expression.next);
3996     if (!entity || !index || !value) {
3997         parseerror(parser, "failed to create locals for array accessor");
3998         goto cleanup;
3999     }
4000     (void)!ast_value_set_name(value, "value"); /* not important */
4001     vec_push(fval->expression.params, entity);
4002     vec_push(fval->expression.params, index);
4003     vec_push(fval->expression.params, value);
4004
4005     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4006     if (!root) {
4007         parseerror(parser, "failed to build accessor search tree");
4008         goto cleanup;
4009     }
4010
4011     array->setter = fval;
4012     return ast_block_add_expr(func->blocks[0], root);
4013 cleanup:
4014     if (entity) ast_delete(entity);
4015     if (index)  ast_delete(index);
4016     if (value)  ast_delete(value);
4017     if (root)   ast_delete(root);
4018     ast_delete(func);
4019     ast_delete(fval);
4020     return false;
4021 }
4022
4023 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4024 {
4025     ast_expression *root = NULL;
4026     ast_value      *index = NULL;
4027     ast_value      *fval;
4028     ast_function   *func;
4029
4030     /* NOTE: checking array->expression.next rather than elemtype since
4031      * for fields elemtype is a temporary fieldtype.
4032      */
4033     if (!ast_istype(array->expression.next, ast_value)) {
4034         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4035         return false;
4036     }
4037
4038     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4039         return false;
4040     func = fval->constval.vfunc;
4041     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4042
4043     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4044
4045     if (!index) {
4046         parseerror(parser, "failed to create locals for array accessor");
4047         goto cleanup;
4048     }
4049     vec_push(fval->expression.params, index);
4050
4051     root = array_getter_node(parser, array, index, 0, array->expression.count);
4052     if (!root) {
4053         parseerror(parser, "failed to build accessor search tree");
4054         goto cleanup;
4055     }
4056
4057     array->getter = fval;
4058     return ast_block_add_expr(func->blocks[0], root);
4059 cleanup:
4060     if (index) ast_delete(index);
4061     if (root)  ast_delete(root);
4062     ast_delete(func);
4063     ast_delete(fval);
4064     return false;
4065 }
4066
4067 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4068 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4069 {
4070     lex_ctx     ctx;
4071     size_t      i;
4072     ast_value **params;
4073     ast_value  *param;
4074     ast_value  *fval;
4075     bool        first = true;
4076     bool        variadic = false;
4077
4078     ctx = parser_ctx(parser);
4079
4080     /* for the sake of less code we parse-in in this function */
4081     if (!parser_next(parser)) {
4082         parseerror(parser, "expected parameter list");
4083         return NULL;
4084     }
4085
4086     params = NULL;
4087
4088     /* parse variables until we hit a closing paren */
4089     while (parser->tok != ')') {
4090         if (!first) {
4091             /* there must be commas between them */
4092             if (parser->tok != ',') {
4093                 parseerror(parser, "expected comma or end of parameter list");
4094                 goto on_error;
4095             }
4096             if (!parser_next(parser)) {
4097                 parseerror(parser, "expected parameter");
4098                 goto on_error;
4099             }
4100         }
4101         first = false;
4102
4103         if (parser->tok == TOKEN_DOTS) {
4104             /* '...' indicates a varargs function */
4105             variadic = true;
4106             if (!parser_next(parser)) {
4107                 parseerror(parser, "expected parameter");
4108                 return NULL;
4109             }
4110             if (parser->tok != ')') {
4111                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4112                 goto on_error;
4113             }
4114         }
4115         else
4116         {
4117             /* for anything else just parse a typename */
4118             param = parse_typename(parser, NULL, NULL);
4119             if (!param)
4120                 goto on_error;
4121             vec_push(params, param);
4122             if (param->expression.vtype >= TYPE_VARIANT) {
4123                 char tname[1024]; /* typename is reserved in C++ */
4124                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4125                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4126                 goto on_error;
4127             }
4128         }
4129     }
4130
4131     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4132         vec_free(params);
4133
4134     /* sanity check */
4135     if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4136         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4137
4138     /* parse-out */
4139     if (!parser_next(parser)) {
4140         parseerror(parser, "parse error after typename");
4141         goto on_error;
4142     }
4143
4144     /* now turn 'var' into a function type */
4145     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4146     fval->expression.next     = (ast_expression*)var;
4147     if (variadic)
4148         fval->expression.flags |= AST_FLAG_VARIADIC;
4149     var = fval;
4150
4151     var->expression.params = params;
4152     params = NULL;
4153
4154     return var;
4155
4156 on_error:
4157     ast_delete(var);
4158     for (i = 0; i < vec_size(params); ++i)
4159         ast_delete(params[i]);
4160     vec_free(params);
4161     return NULL;
4162 }
4163
4164 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4165 {
4166     ast_expression *cexp;
4167     ast_value      *cval, *tmp;
4168     lex_ctx ctx;
4169
4170     ctx = parser_ctx(parser);
4171
4172     if (!parser_next(parser)) {
4173         ast_delete(var);
4174         parseerror(parser, "expected array-size");
4175         return NULL;
4176     }
4177
4178     cexp = parse_expression_leave(parser, true, false);
4179
4180     if (!cexp || !ast_istype(cexp, ast_value)) {
4181         if (cexp)
4182             ast_unref(cexp);
4183         ast_delete(var);
4184         parseerror(parser, "expected array-size as constant positive integer");
4185         return NULL;
4186     }
4187     cval = (ast_value*)cexp;
4188
4189     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4190     tmp->expression.next = (ast_expression*)var;
4191     var = tmp;
4192
4193     if (cval->expression.vtype == TYPE_INTEGER)
4194         tmp->expression.count = cval->constval.vint;
4195     else if (cval->expression.vtype == TYPE_FLOAT)
4196         tmp->expression.count = cval->constval.vfloat;
4197     else {
4198         ast_unref(cexp);
4199         ast_delete(var);
4200         parseerror(parser, "array-size must be a positive integer constant");
4201         return NULL;
4202     }
4203     ast_unref(cexp);
4204
4205     if (parser->tok != ']') {
4206         ast_delete(var);
4207         parseerror(parser, "expected ']' after array-size");
4208         return NULL;
4209     }
4210     if (!parser_next(parser)) {
4211         ast_delete(var);
4212         parseerror(parser, "error after parsing array size");
4213         return NULL;
4214     }
4215     return var;
4216 }
4217
4218 /* Parse a complete typename.
4219  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4220  * but when parsing variables separated by comma
4221  * 'storebase' should point to where the base-type should be kept.
4222  * The base type makes up every bit of type information which comes *before* the
4223  * variable name.
4224  *
4225  * The following will be parsed in its entirety:
4226  *     void() foo()
4227  * The 'basetype' in this case is 'void()'
4228  * and if there's a comma after it, say:
4229  *     void() foo(), bar
4230  * then the type-information 'void()' can be stored in 'storebase'
4231  */
4232 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4233 {
4234     ast_value *var, *tmp;
4235     lex_ctx    ctx;
4236
4237     const char *name = NULL;
4238     bool        isfield  = false;
4239     bool        wasarray = false;
4240     size_t      morefields = 0;
4241
4242     ctx = parser_ctx(parser);
4243
4244     /* types may start with a dot */
4245     if (parser->tok == '.') {
4246         isfield = true;
4247         /* if we parsed a dot we need a typename now */
4248         if (!parser_next(parser)) {
4249             parseerror(parser, "expected typename for field definition");
4250             return NULL;
4251         }
4252
4253         /* Further dots are handled seperately because they won't be part of the
4254          * basetype
4255          */
4256         while (parser->tok == '.') {
4257             ++morefields;
4258             if (!parser_next(parser)) {
4259                 parseerror(parser, "expected typename for field definition");
4260                 return NULL;
4261             }
4262         }
4263     }
4264     if (parser->tok == TOKEN_IDENT)
4265         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4266     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4267         parseerror(parser, "expected typename");
4268         return NULL;
4269     }
4270
4271     /* generate the basic type value */
4272     if (cached_typedef) {
4273         var = ast_value_copy(cached_typedef);
4274         ast_value_set_name(var, "<type(from_def)>");
4275     } else
4276         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4277
4278     for (; morefields; --morefields) {
4279         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4280         tmp->expression.next = (ast_expression*)var;
4281         var = tmp;
4282     }
4283
4284     /* do not yet turn into a field - remember:
4285      * .void() foo; is a field too
4286      * .void()() foo; is a function
4287      */
4288
4289     /* parse on */
4290     if (!parser_next(parser)) {
4291         ast_delete(var);
4292         parseerror(parser, "parse error after typename");
4293         return NULL;
4294     }
4295
4296     /* an opening paren now starts the parameter-list of a function
4297      * this is where original-QC has parameter lists.
4298      * We allow a single parameter list here.
4299      * Much like fteqcc we don't allow `float()() x`
4300      */
4301     if (parser->tok == '(') {
4302         var = parse_parameter_list(parser, var);
4303         if (!var)
4304             return NULL;
4305     }
4306
4307     /* store the base if requested */
4308     if (storebase) {
4309         *storebase = ast_value_copy(var);
4310         if (isfield) {
4311             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4312             tmp->expression.next = (ast_expression*)*storebase;
4313             *storebase = tmp;
4314         }
4315     }
4316
4317     /* there may be a name now */
4318     if (parser->tok == TOKEN_IDENT) {
4319         name = util_strdup(parser_tokval(parser));
4320         /* parse on */
4321         if (!parser_next(parser)) {
4322             ast_delete(var);
4323             parseerror(parser, "error after variable or field declaration");
4324             return NULL;
4325         }
4326     }
4327
4328     /* now this may be an array */
4329     if (parser->tok == '[') {
4330         wasarray = true;
4331         var = parse_arraysize(parser, var);
4332         if (!var)
4333             return NULL;
4334     }
4335
4336     /* This is the point where we can turn it into a field */
4337     if (isfield) {
4338         /* turn it into a field if desired */
4339         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4340         tmp->expression.next = (ast_expression*)var;
4341         var = tmp;
4342     }
4343
4344     /* now there may be function parens again */
4345     if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4346         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4347     if (parser->tok == '(' && wasarray)
4348         parseerror(parser, "arrays as part of a return type is not supported");
4349     while (parser->tok == '(') {
4350         var = parse_parameter_list(parser, var);
4351         if (!var) {
4352             if (name)
4353                 mem_d((void*)name);
4354             ast_delete(var);
4355             return NULL;
4356         }
4357     }
4358
4359     /* finally name it */
4360     if (name) {
4361         if (!ast_value_set_name(var, name)) {
4362             ast_delete(var);
4363             parseerror(parser, "internal error: failed to set name");
4364             return NULL;
4365         }
4366         /* free the name, ast_value_set_name duplicates */
4367         mem_d((void*)name);
4368     }
4369
4370     return var;
4371 }
4372
4373 static bool parse_typedef(parser_t *parser)
4374 {
4375     ast_value      *typevar, *oldtype;
4376     ast_expression *old;
4377
4378     typevar = parse_typename(parser, NULL, NULL);
4379
4380     if (!typevar)
4381         return false;
4382
4383     if ( (old = parser_find_var(parser, typevar->name)) ) {
4384         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4385                    " -> `%s` has been declared here: %s:%i",
4386                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4387         ast_delete(typevar);
4388         return false;
4389     }
4390
4391     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4392         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4393                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4394         ast_delete(typevar);
4395         return false;
4396     }
4397
4398     vec_push(parser->_typedefs, typevar);
4399     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4400
4401     if (parser->tok != ';') {
4402         parseerror(parser, "expected semicolon after typedef");
4403         return false;
4404     }
4405     if (!parser_next(parser)) {
4406         parseerror(parser, "parse error after typedef");
4407         return false;
4408     }
4409
4410     return true;
4411 }
4412
4413 static const char *cvq_to_str(int cvq) {
4414     switch (cvq) {
4415         case CV_NONE:  return "none";
4416         case CV_VAR:   return "`var`";
4417         case CV_CONST: return "`const`";
4418         default:       return "<INVALID>";
4419     }
4420 }
4421
4422 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4423 {
4424     bool av, ao;
4425     if (proto->cvq != var->cvq) {
4426         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4427               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4428               parser->tok == '='))
4429         {
4430             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4431                                  "`%s` declared with different qualifiers: %s\n"
4432                                  " -> previous declaration here: %s:%i uses %s",
4433                                  var->name, cvq_to_str(var->cvq),
4434                                  ast_ctx(proto).file, ast_ctx(proto).line,
4435                                  cvq_to_str(proto->cvq));
4436         }
4437     }
4438     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4439     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4440     if (!av != !ao) {
4441         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4442                              "`%s` declared with different attributes%s\n"
4443                              " -> previous declaration here: %s:%i",
4444                              var->name, (av ? ": noreturn" : ""),
4445                              ast_ctx(proto).file, ast_ctx(proto).line,
4446                              (ao ? ": noreturn" : ""));
4447     }
4448     return true;
4449 }
4450
4451 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)
4452 {
4453     ast_value *var;
4454     ast_value *proto;
4455     ast_expression *old;
4456     bool       was_end;
4457     size_t     i;
4458
4459     ast_value *basetype = NULL;
4460     bool      retval    = true;
4461     bool      isparam   = false;
4462     bool      isvector  = false;
4463     bool      cleanvar  = true;
4464     bool      wasarray  = false;
4465
4466     ast_member *me[3];
4467
4468     if (!localblock && is_static)
4469         parseerror(parser, "`static` qualifier is not supported in global scope");
4470
4471     /* get the first complete variable */
4472     var = parse_typename(parser, &basetype, cached_typedef);
4473     if (!var) {
4474         if (basetype)
4475             ast_delete(basetype);
4476         return false;
4477     }
4478
4479     while (true) {
4480         proto = NULL;
4481         wasarray = false;
4482
4483         /* Part 0: finish the type */
4484         if (parser->tok == '(') {
4485             if (opts.standard == COMPILER_QCC)
4486                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4487             var = parse_parameter_list(parser, var);
4488             if (!var) {
4489                 retval = false;
4490                 goto cleanup;
4491             }
4492         }
4493         /* we only allow 1-dimensional arrays */
4494         if (parser->tok == '[') {
4495             wasarray = true;
4496             var = parse_arraysize(parser, var);
4497             if (!var) {
4498                 retval = false;
4499                 goto cleanup;
4500             }
4501         }
4502         if (parser->tok == '(' && wasarray) {
4503             parseerror(parser, "arrays as part of a return type is not supported");
4504             /* we'll still parse the type completely for now */
4505         }
4506         /* for functions returning functions */
4507         while (parser->tok == '(') {
4508             if (opts.standard == COMPILER_QCC)
4509                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4510             var = parse_parameter_list(parser, var);
4511             if (!var) {
4512                 retval = false;
4513                 goto cleanup;
4514             }
4515         }
4516
4517         var->cvq = qualifier;
4518         var->expression.flags |= qflags;
4519         if (var->expression.flags & AST_FLAG_DEPRECATED)
4520             var->desc = vstring;
4521
4522         /* Part 1:
4523          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4524          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4525          * is then filled with the previous definition and the parameter-names replaced.
4526          */
4527         if (!strcmp(var->name, "nil")) {
4528             if (OPTS_FLAG(UNTYPED_NIL)) {
4529                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4530                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4531             } else
4532                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4533         }
4534         if (!localblock) {
4535             /* Deal with end_sys_ vars */
4536             was_end = false;
4537             if (!strcmp(var->name, "end_sys_globals")) {
4538                 var->uses++;
4539                 parser->crc_globals = vec_size(parser->globals);
4540                 was_end = true;
4541             }
4542             else if (!strcmp(var->name, "end_sys_fields")) {
4543                 var->uses++;
4544                 parser->crc_fields = vec_size(parser->fields);
4545                 was_end = true;
4546             }
4547             if (was_end && var->expression.vtype == TYPE_FIELD) {
4548                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4549                                  "global '%s' hint should not be a field",
4550                                  parser_tokval(parser)))
4551                 {
4552                     retval = false;
4553                     goto cleanup;
4554                 }
4555             }
4556
4557             if (!nofields && var->expression.vtype == TYPE_FIELD)
4558             {
4559                 /* deal with field declarations */
4560                 old = parser_find_field(parser, var->name);
4561                 if (old) {
4562                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4563                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4564                     {
4565                         retval = false;
4566                         goto cleanup;
4567                     }
4568                     ast_delete(var);
4569                     var = NULL;
4570                     goto skipvar;
4571                     /*
4572                     parseerror(parser, "field `%s` already declared here: %s:%i",
4573                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4574                     retval = false;
4575                     goto cleanup;
4576                     */
4577                 }
4578                 if (opts.standard == COMPILER_QCC &&
4579                     (old = parser_find_global(parser, var->name)))
4580                 {
4581                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4582                     parseerror(parser, "field `%s` already declared here: %s:%i",
4583                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4584                     retval = false;
4585                     goto cleanup;
4586                 }
4587             }
4588             else
4589             {
4590                 /* deal with other globals */
4591                 old = parser_find_global(parser, var->name);
4592                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4593                 {
4594                     /* This is a function which had a prototype */
4595                     if (!ast_istype(old, ast_value)) {
4596                         parseerror(parser, "internal error: prototype is not an ast_value");
4597                         retval = false;
4598                         goto cleanup;
4599                     }
4600                     proto = (ast_value*)old;
4601                     proto->desc = var->desc;
4602                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4603                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4604                                    proto->name,
4605                                    ast_ctx(proto).file, ast_ctx(proto).line);
4606                         retval = false;
4607                         goto cleanup;
4608                     }
4609                     /* we need the new parameter-names */
4610                     for (i = 0; i < vec_size(proto->expression.params); ++i)
4611                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4612                     if (!parser_check_qualifiers(parser, var, proto)) {
4613                         retval = false;
4614                         if (proto->desc) 
4615                             mem_d(proto->desc);
4616                         proto = NULL;
4617                         goto cleanup;
4618                     }
4619                     proto->expression.flags |= var->expression.flags;
4620                     ast_delete(var);
4621                     var = proto;
4622                 }
4623                 else
4624                 {
4625                     /* other globals */
4626                     if (old) {
4627                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4628                                          "global `%s` already declared here: %s:%i",
4629                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
4630                         {
4631                             retval = false;
4632                             goto cleanup;
4633                         }
4634                         proto = (ast_value*)old;
4635                         if (!ast_istype(old, ast_value)) {
4636                             parseerror(parser, "internal error: not an ast_value");
4637                             retval = false;
4638                             proto = NULL;
4639                             goto cleanup;
4640                         }
4641                         if (!parser_check_qualifiers(parser, var, proto)) {
4642                             retval = false;
4643                             proto = NULL;
4644                             goto cleanup;
4645                         }
4646                         proto->expression.flags |= var->expression.flags;
4647                         ast_delete(var);
4648                         var = proto;
4649                     }
4650                     if (opts.standard == COMPILER_QCC &&
4651                         (old = parser_find_field(parser, var->name)))
4652                     {
4653                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4654                         parseerror(parser, "global `%s` already declared here: %s:%i",
4655                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
4656                         retval = false;
4657                         goto cleanup;
4658                     }
4659                 }
4660             }
4661         }
4662         else /* it's not a global */
4663         {
4664             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4665             if (old && !isparam) {
4666                 parseerror(parser, "local `%s` already declared here: %s:%i",
4667                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4668                 retval = false;
4669                 goto cleanup;
4670             }
4671             old = parser_find_local(parser, var->name, 0, &isparam);
4672             if (old && isparam) {
4673                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4674                                  "local `%s` is shadowing a parameter", var->name))
4675                 {
4676                     parseerror(parser, "local `%s` already declared here: %s:%i",
4677                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4678                     retval = false;
4679                     goto cleanup;
4680                 }
4681                 if (opts.standard != COMPILER_GMQCC) {
4682                     ast_delete(var);
4683                     var = NULL;
4684                     goto skipvar;
4685                 }
4686             }
4687         }
4688
4689         /* in a noref section we simply bump the usecount */
4690         if (noref || parser->noref)
4691             var->uses++;
4692
4693         /* Part 2:
4694          * Create the global/local, and deal with vector types.
4695          */
4696         if (!proto) {
4697             if (var->expression.vtype == TYPE_VECTOR)
4698                 isvector = true;
4699             else if (var->expression.vtype == TYPE_FIELD &&
4700                      var->expression.next->expression.vtype == TYPE_VECTOR)
4701                 isvector = true;
4702
4703             if (isvector) {
4704                 if (!create_vector_members(var, me)) {
4705                     retval = false;
4706                     goto cleanup;
4707                 }
4708             }
4709
4710             if (!localblock) {
4711                 /* deal with global variables, fields, functions */
4712                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4713                     var->isfield = true;
4714                     vec_push(parser->fields, (ast_expression*)var);
4715                     util_htset(parser->htfields, var->name, var);
4716                     if (isvector) {
4717                         for (i = 0; i < 3; ++i) {
4718                             vec_push(parser->fields, (ast_expression*)me[i]);
4719                             util_htset(parser->htfields, me[i]->name, me[i]);
4720                         }
4721                     }
4722                 }
4723                 else {
4724                     vec_push(parser->globals, (ast_expression*)var);
4725                     util_htset(parser->htglobals, var->name, var);
4726                     if (isvector) {
4727                         for (i = 0; i < 3; ++i) {
4728                             vec_push(parser->globals, (ast_expression*)me[i]);
4729                             util_htset(parser->htglobals, me[i]->name, me[i]);
4730                         }
4731                     }
4732                 }
4733             } else {
4734                 if (is_static) {
4735                     /* a static adds itself to be generated like any other global
4736                      * but is added to the local namespace instead
4737                      */
4738                     char   *defname = NULL;
4739                     size_t  prefix_len, ln;
4740
4741                     ln = strlen(parser->function->name);
4742                     vec_append(defname, ln, parser->function->name);
4743
4744                     vec_append(defname, 2, "::");
4745                     /* remember the length up to here */
4746                     prefix_len = vec_size(defname);
4747
4748                     /* Add it to the local scope */
4749                     util_htset(vec_last(parser->variables), var->name, (void*)var);
4750                     /* now rename the global */
4751                     ln = strlen(var->name);
4752                     vec_append(defname, ln, var->name);
4753                     ast_value_set_name(var, defname);
4754
4755                     /* push it to the to-be-generated globals */
4756                     vec_push(parser->globals, (ast_expression*)var);
4757
4758                     /* same game for the vector members */
4759                     if (isvector) {
4760                         for (i = 0; i < 3; ++i) {
4761                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4762
4763                             vec_shrinkto(defname, prefix_len);
4764                             ln = strlen(me[i]->name);
4765                             vec_append(defname, ln, me[i]->name);
4766                             ast_member_set_name(me[i], defname);
4767
4768                             vec_push(parser->globals, (ast_expression*)me[i]);
4769                         }
4770                     }
4771                     vec_free(defname);
4772                 } else {
4773                     vec_push(localblock->locals, var);
4774                     parser_addlocal(parser, var->name, (ast_expression*)var);
4775                     if (isvector) {
4776                         for (i = 0; i < 3; ++i) {
4777                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4778                             ast_block_collect(localblock, (ast_expression*)me[i]);
4779                         }
4780                     }
4781                 }
4782             }
4783         }
4784         me[0] = me[1] = me[2] = NULL;
4785         cleanvar = false;
4786         /* Part 2.2
4787          * deal with arrays
4788          */
4789         if (var->expression.vtype == TYPE_ARRAY) {
4790             char name[1024];
4791             snprintf(name, sizeof(name), "%s##SET", var->name);
4792             if (!parser_create_array_setter(parser, var, name))
4793                 goto cleanup;
4794             snprintf(name, sizeof(name), "%s##GET", var->name);
4795             if (!parser_create_array_getter(parser, var, var->expression.next, name))
4796                 goto cleanup;
4797         }
4798         else if (!localblock && !nofields &&
4799                  var->expression.vtype == TYPE_FIELD &&
4800                  var->expression.next->expression.vtype == TYPE_ARRAY)
4801         {
4802             char name[1024];
4803             ast_expression *telem;
4804             ast_value      *tfield;
4805             ast_value      *array = (ast_value*)var->expression.next;
4806
4807             if (!ast_istype(var->expression.next, ast_value)) {
4808                 parseerror(parser, "internal error: field element type must be an ast_value");
4809                 goto cleanup;
4810             }
4811
4812             snprintf(name, sizeof(name), "%s##SETF", var->name);
4813             if (!parser_create_array_field_setter(parser, array, name))
4814                 goto cleanup;
4815
4816             telem = ast_type_copy(ast_ctx(var), array->expression.next);
4817             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4818             tfield->expression.next = telem;
4819             snprintf(name, sizeof(name), "%s##GETFP", var->name);
4820             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4821                 ast_delete(tfield);
4822                 goto cleanup;
4823             }
4824             ast_delete(tfield);
4825         }
4826
4827 skipvar:
4828         if (parser->tok == ';') {
4829             ast_delete(basetype);
4830             if (!parser_next(parser)) {
4831                 parseerror(parser, "error after variable declaration");
4832                 return false;
4833             }
4834             return true;
4835         }
4836
4837         if (parser->tok == ',')
4838             goto another;
4839
4840         /*
4841         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4842         */
4843         if (!var) {
4844             parseerror(parser, "missing comma or semicolon while parsing variables");
4845             break;
4846         }
4847
4848         if (localblock && opts.standard == COMPILER_QCC) {
4849             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4850                              "initializing expression turns variable `%s` into a constant in this standard",
4851                              var->name) )
4852             {
4853                 break;
4854             }
4855         }
4856
4857         if (parser->tok != '{') {
4858             if (parser->tok != '=') {
4859                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4860                 break;
4861             }
4862
4863             if (!parser_next(parser)) {
4864                 parseerror(parser, "error parsing initializer");
4865                 break;
4866             }
4867         }
4868         else if (opts.standard == COMPILER_QCC) {
4869             parseerror(parser, "expected '=' before function body in this standard");
4870         }
4871
4872         if (parser->tok == '#') {
4873             ast_function *func = NULL;
4874
4875             if (localblock) {
4876                 parseerror(parser, "cannot declare builtins within functions");
4877                 break;
4878             }
4879             if (var->expression.vtype != TYPE_FUNCTION) {
4880                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4881                 break;
4882             }
4883             if (!parser_next(parser)) {
4884                 parseerror(parser, "expected builtin number");
4885                 break;
4886             }
4887             if (parser->tok != TOKEN_INTCONST) {
4888                 parseerror(parser, "builtin number must be an integer constant");
4889                 break;
4890             }
4891             if (parser_token(parser)->constval.i < 0) {
4892                 parseerror(parser, "builtin number must be an integer greater than zero");
4893                 break;
4894             }
4895
4896             if (var->hasvalue) {
4897                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4898                                     "builtin `%s` has already been defined\n"
4899                                     " -> previous declaration here: %s:%i",
4900                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4901             }
4902             else
4903             {
4904                 func = ast_function_new(ast_ctx(var), var->name, var);
4905                 if (!func) {
4906                     parseerror(parser, "failed to allocate function for `%s`", var->name);
4907                     break;
4908                 }
4909                 vec_push(parser->functions, func);
4910
4911                 func->builtin = -parser_token(parser)->constval.i-1;
4912             }
4913
4914             if (!parser_next(parser)) {
4915                 parseerror(parser, "expected comma or semicolon");
4916                 if (func)
4917                     ast_function_delete(func);
4918                 var->constval.vfunc = NULL;
4919                 break;
4920             }
4921         }
4922         else if (parser->tok == '{' || parser->tok == '[')
4923         {
4924             if (localblock) {
4925                 parseerror(parser, "cannot declare functions within functions");
4926                 break;
4927             }
4928
4929             if (proto)
4930                 ast_ctx(proto) = parser_ctx(parser);
4931
4932             if (!parse_function_body(parser, var))
4933                 break;
4934             ast_delete(basetype);
4935             for (i = 0; i < vec_size(parser->gotos); ++i)
4936                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4937             vec_free(parser->gotos);
4938             vec_free(parser->labels);
4939             return true;
4940         } else {
4941             ast_expression *cexp;
4942             ast_value      *cval;
4943
4944             cexp = parse_expression_leave(parser, true, false);
4945             if (!cexp)
4946                 break;
4947
4948             if (!localblock) {
4949                 cval = (ast_value*)cexp;
4950                 if (cval != parser->nil &&
4951                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4952                    )
4953                 {
4954                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4955                 }
4956                 else
4957                 {
4958                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4959                         qualifier != CV_VAR)
4960                     {
4961                         var->cvq = CV_CONST;
4962                     }
4963                     if (cval == parser->nil)
4964                         var->expression.flags |= AST_FLAG_INITIALIZED;
4965                     else
4966                     {
4967                         var->hasvalue = true;
4968                         if (cval->expression.vtype == TYPE_STRING)
4969                             var->constval.vstring = parser_strdup(cval->constval.vstring);
4970                         else if (cval->expression.vtype == TYPE_FIELD)
4971                             var->constval.vfield = cval;
4972                         else
4973                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4974                         ast_unref(cval);
4975                     }
4976                 }
4977             } else {
4978                 int cvq;
4979                 shunt sy = { NULL, NULL };
4980                 cvq = var->cvq;
4981                 var->cvq = CV_NONE;
4982                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4983                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4984                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4985                 if (!parser_sy_apply_operator(parser, &sy))
4986                     ast_unref(cexp);
4987                 else {
4988                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4989                         parseerror(parser, "internal error: leaked operands");
4990                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4991                         break;
4992                 }
4993                 vec_free(sy.out);
4994                 vec_free(sy.ops);
4995                 var->cvq = cvq;
4996             }
4997         }
4998
4999 another:
5000         if (parser->tok == ',') {
5001             if (!parser_next(parser)) {
5002                 parseerror(parser, "expected another variable");
5003                 break;
5004             }
5005
5006             if (parser->tok != TOKEN_IDENT) {
5007                 parseerror(parser, "expected another variable");
5008                 break;
5009             }
5010             var = ast_value_copy(basetype);
5011             cleanvar = true;
5012             ast_value_set_name(var, parser_tokval(parser));
5013             if (!parser_next(parser)) {
5014                 parseerror(parser, "error parsing variable declaration");
5015                 break;
5016             }
5017             continue;
5018         }
5019
5020         if (parser->tok != ';') {
5021             parseerror(parser, "missing semicolon after variables");
5022             break;
5023         }
5024
5025         if (!parser_next(parser)) {
5026             parseerror(parser, "parse error after variable declaration");
5027             break;
5028         }
5029
5030         ast_delete(basetype);
5031         return true;
5032     }
5033
5034     if (cleanvar && var)
5035         ast_delete(var);
5036     ast_delete(basetype);
5037     return false;
5038
5039 cleanup:
5040     ast_delete(basetype);
5041     if (cleanvar && var)
5042         ast_delete(var);
5043     if (me[0]) ast_member_delete(me[0]);
5044     if (me[1]) ast_member_delete(me[1]);
5045     if (me[2]) ast_member_delete(me[2]);
5046     return retval;
5047 }
5048
5049 static bool parser_global_statement(parser_t *parser)
5050 {
5051     int        cvq       = CV_WRONG;
5052     bool       noref     = false;
5053     bool       is_static = false;
5054     uint32_t   qflags    = 0;
5055     ast_value *istype    = NULL;
5056     char      *vstring   = NULL;
5057
5058     if (parser->tok == TOKEN_IDENT)
5059         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5060
5061     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5062     {
5063         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5064     }
5065     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5066     {
5067         if (cvq == CV_WRONG)
5068             return false;
5069         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5070     }
5071     else if (parser->tok == TOKEN_KEYWORD)
5072     {
5073         if (!strcmp(parser_tokval(parser), "typedef")) {
5074             if (!parser_next(parser)) {
5075                 parseerror(parser, "expected type definition after 'typedef'");
5076                 return false;
5077             }
5078             return parse_typedef(parser);
5079         }
5080         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5081         return false;
5082     }
5083     else if (parser->tok == '#')
5084     {
5085         return parse_pragma(parser);
5086     }
5087     else if (parser->tok == '$')
5088     {
5089         if (!parser_next(parser)) {
5090             parseerror(parser, "parse error");
5091             return false;
5092         }
5093     }
5094     else
5095     {
5096         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5097         return false;
5098     }
5099     return true;
5100 }
5101
5102 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5103 {
5104     return util_crc16(old, str, strlen(str));
5105 }
5106
5107 static void progdefs_crc_file(const char *str)
5108 {
5109     /* write to progdefs.h here */
5110     (void)str;
5111 }
5112
5113 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5114 {
5115     old = progdefs_crc_sum(old, str);
5116     progdefs_crc_file(str);
5117     return old;
5118 }
5119
5120 static void generate_checksum(parser_t *parser)
5121 {
5122     uint16_t   crc = 0xFFFF;
5123     size_t     i;
5124     ast_value *value;
5125
5126     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5127     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5128     /*
5129     progdefs_crc_file("\tint\tpad;\n");
5130     progdefs_crc_file("\tint\tofs_return[3];\n");
5131     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5132     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5133     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5134     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5135     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5136     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5137     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5138     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5139     */
5140     for (i = 0; i < parser->crc_globals; ++i) {
5141         if (!ast_istype(parser->globals[i], ast_value))
5142             continue;
5143         value = (ast_value*)(parser->globals[i]);
5144         switch (value->expression.vtype) {
5145             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5146             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5147             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5148             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5149             default:
5150                 crc = progdefs_crc_both(crc, "\tint\t");
5151                 break;
5152         }
5153         crc = progdefs_crc_both(crc, value->name);
5154         crc = progdefs_crc_both(crc, ";\n");
5155     }
5156     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5157     for (i = 0; i < parser->crc_fields; ++i) {
5158         if (!ast_istype(parser->fields[i], ast_value))
5159             continue;
5160         value = (ast_value*)(parser->fields[i]);
5161         switch (value->expression.next->expression.vtype) {
5162             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5163             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5164             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5165             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5166             default:
5167                 crc = progdefs_crc_both(crc, "\tint\t");
5168                 break;
5169         }
5170         crc = progdefs_crc_both(crc, value->name);
5171         crc = progdefs_crc_both(crc, ";\n");
5172     }
5173     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5174
5175     code_crc = crc;
5176 }
5177
5178 static parser_t *parser;
5179
5180 bool parser_init()
5181 {
5182     lex_ctx empty_ctx;
5183     size_t i;
5184
5185     parser = (parser_t*)mem_a(sizeof(parser_t));
5186     if (!parser)
5187         return false;
5188
5189     memset(parser, 0, sizeof(*parser));
5190
5191     for (i = 0; i < operator_count; ++i) {
5192         if (operators[i].id == opid1('=')) {
5193             parser->assign_op = operators+i;
5194             break;
5195         }
5196     }
5197     if (!parser->assign_op) {
5198         printf("internal error: initializing parser: failed to find assign operator\n");
5199         mem_d(parser);
5200         return false;
5201     }
5202
5203     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5204     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5205     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5206     vec_push(parser->_blocktypedefs, 0);
5207
5208     empty_ctx.file = "<internal>";
5209     empty_ctx.line = 0;
5210     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5211     parser->nil->cvq = CV_CONST;
5212     if (OPTS_FLAG(UNTYPED_NIL))
5213         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5214     return true;
5215 }
5216
5217 bool parser_compile()
5218 {
5219     /* initial lexer/parser state */
5220     parser->lex->flags.noops = true;
5221
5222     if (parser_next(parser))
5223     {
5224         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5225         {
5226             if (!parser_global_statement(parser)) {
5227                 if (parser->tok == TOKEN_EOF)
5228                     parseerror(parser, "unexpected eof");
5229                 else if (compile_errors)
5230                     parseerror(parser, "there have been errors, bailing out");
5231                 lex_close(parser->lex);
5232                 parser->lex = NULL;
5233                 return false;
5234             }
5235         }
5236     } else {
5237         parseerror(parser, "parse error");
5238         lex_close(parser->lex);
5239         parser->lex = NULL;
5240         return false;
5241     }
5242
5243     lex_close(parser->lex);
5244     parser->lex = NULL;
5245
5246     return !compile_errors;
5247 }
5248
5249 bool parser_compile_file(const char *filename)
5250 {
5251     parser->lex = lex_open(filename);
5252     if (!parser->lex) {
5253         con_err("failed to open file \"%s\"\n", filename);
5254         return false;
5255     }
5256     return parser_compile();
5257 }
5258
5259 bool parser_compile_string(const char *name, const char *str, size_t len)
5260 {
5261     parser->lex = lex_open_string(str, len, name);
5262     if (!parser->lex) {
5263         con_err("failed to create lexer for string \"%s\"\n", name);
5264         return false;
5265     }
5266     return parser_compile();
5267 }
5268
5269 void parser_cleanup()
5270 {
5271     size_t i;
5272     for (i = 0; i < vec_size(parser->accessors); ++i) {
5273         ast_delete(parser->accessors[i]->constval.vfunc);
5274         parser->accessors[i]->constval.vfunc = NULL;
5275         ast_delete(parser->accessors[i]);
5276     }
5277     for (i = 0; i < vec_size(parser->functions); ++i) {
5278         ast_delete(parser->functions[i]);
5279     }
5280     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5281         ast_delete(parser->imm_vector[i]);
5282     }
5283     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5284         ast_delete(parser->imm_string[i]);
5285     }
5286     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5287         ast_delete(parser->imm_float[i]);
5288     }
5289     for (i = 0; i < vec_size(parser->fields); ++i) {
5290         ast_delete(parser->fields[i]);
5291     }
5292     for (i = 0; i < vec_size(parser->globals); ++i) {
5293         ast_delete(parser->globals[i]);
5294     }
5295     vec_free(parser->accessors);
5296     vec_free(parser->functions);
5297     vec_free(parser->imm_vector);
5298     vec_free(parser->imm_string);
5299     vec_free(parser->imm_float);
5300     vec_free(parser->globals);
5301     vec_free(parser->fields);
5302
5303     for (i = 0; i < vec_size(parser->variables); ++i)
5304         util_htdel(parser->variables[i]);
5305     vec_free(parser->variables);
5306     vec_free(parser->_blocklocals);
5307     vec_free(parser->_locals);
5308
5309     for (i = 0; i < vec_size(parser->_typedefs); ++i)
5310         ast_delete(parser->_typedefs[i]);
5311     vec_free(parser->_typedefs);
5312     for (i = 0; i < vec_size(parser->typedefs); ++i)
5313         util_htdel(parser->typedefs[i]);
5314     vec_free(parser->typedefs);
5315     vec_free(parser->_blocktypedefs);
5316
5317     vec_free(parser->_block_ctx);
5318
5319     vec_free(parser->labels);
5320     vec_free(parser->gotos);
5321     vec_free(parser->breaks);
5322     vec_free(parser->continues);
5323
5324     ast_value_delete(parser->nil);
5325
5326     mem_d(parser);
5327 }
5328
5329 bool parser_finish(const char *output)
5330 {
5331     size_t i;
5332     ir_builder *ir;
5333     bool retval = true;
5334
5335     if (compile_errors) {
5336         con_out("*** there were compile errors\n");
5337         return false;
5338     }
5339
5340     ir = ir_builder_new("gmqcc_out");
5341     if (!ir) {
5342         con_out("failed to allocate builder\n");
5343         return false;
5344     }
5345
5346     for (i = 0; i < vec_size(parser->fields); ++i) {
5347         ast_value *field;
5348         bool hasvalue;
5349         if (!ast_istype(parser->fields[i], ast_value))
5350             continue;
5351         field = (ast_value*)parser->fields[i];
5352         hasvalue = field->hasvalue;
5353         field->hasvalue = false;
5354         if (!ast_global_codegen((ast_value*)field, ir, true)) {
5355             con_out("failed to generate field %s\n", field->name);
5356             ir_builder_delete(ir);
5357             return false;
5358         }
5359         if (hasvalue) {
5360             ir_value *ifld;
5361             ast_expression *subtype;
5362             field->hasvalue = true;
5363             subtype = field->expression.next;
5364             ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5365             if (subtype->expression.vtype == TYPE_FIELD)
5366                 ifld->fieldtype = subtype->expression.next->expression.vtype;
5367             else if (subtype->expression.vtype == TYPE_FUNCTION)
5368                 ifld->outtype = subtype->expression.next->expression.vtype;
5369             (void)!ir_value_set_field(field->ir_v, ifld);
5370         }
5371     }
5372     for (i = 0; i < vec_size(parser->globals); ++i) {
5373         ast_value *asvalue;
5374         if (!ast_istype(parser->globals[i], ast_value))
5375             continue;
5376         asvalue = (ast_value*)(parser->globals[i]);
5377         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5378             retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5379                                            "unused global: `%s`", asvalue->name);
5380         }
5381         if (!ast_global_codegen(asvalue, ir, false)) {
5382             con_out("failed to generate global %s\n", asvalue->name);
5383             ir_builder_delete(ir);
5384             return false;
5385         }
5386     }
5387     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5388         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5389             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5390             ir_builder_delete(ir);
5391             return false;
5392         }
5393     }
5394     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5395         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5396             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5397             ir_builder_delete(ir);
5398             return false;
5399         }
5400     }
5401     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5402         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5403             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5404             ir_builder_delete(ir);
5405             return false;
5406         }
5407     }
5408     for (i = 0; i < vec_size(parser->globals); ++i) {
5409         ast_value *asvalue;
5410         if (!ast_istype(parser->globals[i], ast_value))
5411             continue;
5412         asvalue = (ast_value*)(parser->globals[i]);
5413         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5414         {
5415             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5416                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5417                                        "uninitialized constant: `%s`",
5418                                        asvalue->name);
5419             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5420                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5421                                        "uninitialized global: `%s`",
5422                                        asvalue->name);
5423         }
5424         if (!ast_generate_accessors(asvalue, ir)) {
5425             ir_builder_delete(ir);
5426             return false;
5427         }
5428     }
5429     for (i = 0; i < vec_size(parser->fields); ++i) {
5430         ast_value *asvalue;
5431         asvalue = (ast_value*)(parser->fields[i]->expression.next);
5432
5433         if (!ast_istype((ast_expression*)asvalue, ast_value))
5434             continue;
5435         if (asvalue->expression.vtype != TYPE_ARRAY)
5436             continue;
5437         if (!ast_generate_accessors(asvalue, ir)) {
5438             ir_builder_delete(ir);
5439             return false;
5440         }
5441     }
5442     for (i = 0; i < vec_size(parser->functions); ++i) {
5443         if (!ast_function_codegen(parser->functions[i], ir)) {
5444             con_out("failed to generate function %s\n", parser->functions[i]->name);
5445             ir_builder_delete(ir);
5446             return false;
5447         }
5448     }
5449     if (opts.dump)
5450         ir_builder_dump(ir, con_out);
5451     for (i = 0; i < vec_size(parser->functions); ++i) {
5452         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5453             con_out("failed to finalize function %s\n", parser->functions[i]->name);
5454             ir_builder_delete(ir);
5455             return false;
5456         }
5457     }
5458
5459     if (compile_Werrors) {
5460         con_out("*** there were warnings treated as errors\n");
5461         compile_show_werrors();
5462         retval = false;
5463     }
5464
5465     if (retval) {
5466         if (opts.dumpfin)
5467             ir_builder_dump(ir, con_out);
5468
5469         generate_checksum(parser);
5470
5471         if (!ir_builder_generate(ir, output)) {
5472             con_out("*** failed to generate output file\n");
5473             ir_builder_delete(ir);
5474             return false;
5475         }
5476     }
5477
5478     ir_builder_delete(ir);
5479     return retval;
5480 }