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