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