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