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