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