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