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