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