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