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