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