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