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