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