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