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