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