]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Merge branch 'cooking' of github.com:graphitemaster/gmqcc into cooking
[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         return false;
3303     }
3304
3305     return true;
3306 }
3307
3308 static bool parse_pragma(parser_t *parser)
3309 {
3310     bool rv;
3311     parser->lex->flags.preprocessing = true;
3312     parser->lex->flags.mergelines = true;
3313     rv = parse_pragma_do(parser);
3314     if (parser->tok != TOKEN_EOL) {
3315         parseerror(parser, "junk after pragma");
3316         rv = false;
3317     }
3318     parser->lex->flags.preprocessing = false;
3319     parser->lex->flags.mergelines = false;
3320     if (!parser_next(parser)) {
3321         parseerror(parser, "parse error after pragma");
3322         rv = false;
3323     }
3324     return rv;
3325 }
3326
3327 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3328 {
3329     bool       noref, is_static;
3330     int        cvq     = CV_NONE;
3331     uint32_t   qflags  = 0;
3332     ast_value *typevar = NULL;
3333     char      *vstring = NULL;
3334
3335     *out = NULL;
3336
3337     if (parser->tok == TOKEN_IDENT)
3338         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3339
3340     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3341     {
3342         /* local variable */
3343         if (!block) {
3344             parseerror(parser, "cannot declare a variable from here");
3345             return false;
3346         }
3347         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3348             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3349                 return false;
3350         }
3351         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3352             return false;
3353         return true;
3354     }
3355     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3356     {
3357         if (cvq == CV_WRONG)
3358             return false;
3359         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3360     }
3361     else if (parser->tok == TOKEN_KEYWORD)
3362     {
3363         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3364         {
3365             char ty[1024];
3366             ast_value *tdef;
3367
3368             if (!parser_next(parser)) {
3369                 parseerror(parser, "parse error after __builtin_debug_printtype");
3370                 return false;
3371             }
3372
3373             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3374             {
3375                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3376                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3377                 if (!parser_next(parser)) {
3378                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3379                     return false;
3380                 }
3381             }
3382             else
3383             {
3384                 if (!parse_statement(parser, block, out, allow_cases))
3385                     return false;
3386                 if (!*out)
3387                     con_out("__builtin_debug_printtype: got no output node\n");
3388                 else
3389                 {
3390                     ast_type_to_string(*out, ty, sizeof(ty));
3391                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3392                 }
3393             }
3394             return true;
3395         }
3396         else if (!strcmp(parser_tokval(parser), "return"))
3397         {
3398             return parse_return(parser, block, out);
3399         }
3400         else if (!strcmp(parser_tokval(parser), "if"))
3401         {
3402             return parse_if(parser, block, out);
3403         }
3404         else if (!strcmp(parser_tokval(parser), "while"))
3405         {
3406             return parse_while(parser, block, out);
3407         }
3408         else if (!strcmp(parser_tokval(parser), "do"))
3409         {
3410             return parse_dowhile(parser, block, out);
3411         }
3412         else if (!strcmp(parser_tokval(parser), "for"))
3413         {
3414             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3415                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3416                     return false;
3417             }
3418             return parse_for(parser, block, out);
3419         }
3420         else if (!strcmp(parser_tokval(parser), "break"))
3421         {
3422             return parse_break_continue(parser, block, out, false);
3423         }
3424         else if (!strcmp(parser_tokval(parser), "continue"))
3425         {
3426             return parse_break_continue(parser, block, out, true);
3427         }
3428         else if (!strcmp(parser_tokval(parser), "switch"))
3429         {
3430             return parse_switch(parser, block, out);
3431         }
3432         else if (!strcmp(parser_tokval(parser), "case") ||
3433                  !strcmp(parser_tokval(parser), "default"))
3434         {
3435             if (!allow_cases) {
3436                 parseerror(parser, "unexpected 'case' label");
3437                 return false;
3438             }
3439             return true;
3440         }
3441         else if (!strcmp(parser_tokval(parser), "goto"))
3442         {
3443             return parse_goto(parser, out);
3444         }
3445         else if (!strcmp(parser_tokval(parser), "typedef"))
3446         {
3447             if (!parser_next(parser)) {
3448                 parseerror(parser, "expected type definition after 'typedef'");
3449                 return false;
3450             }
3451             return parse_typedef(parser);
3452         }
3453         parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3454         return false;
3455     }
3456     else if (parser->tok == '{')
3457     {
3458         ast_block *inner;
3459         inner = parse_block(parser);
3460         if (!inner)
3461             return false;
3462         *out = (ast_expression*)inner;
3463         return true;
3464     }
3465     else if (parser->tok == ':')
3466     {
3467         size_t i;
3468         ast_label *label;
3469         if (!parser_next(parser)) {
3470             parseerror(parser, "expected label name");
3471             return false;
3472         }
3473         if (parser->tok != TOKEN_IDENT) {
3474             parseerror(parser, "label must be an identifier");
3475             return false;
3476         }
3477         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3478         if (label) {
3479             if (!label->undefined) {
3480                 parseerror(parser, "label `%s` already defined", label->name);
3481                 return false;
3482             }
3483             label->undefined = false;
3484         }
3485         else {
3486             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3487             vec_push(parser->labels, label);
3488         }
3489         *out = (ast_expression*)label;
3490         if (!parser_next(parser)) {
3491             parseerror(parser, "parse error after label");
3492             return false;
3493         }
3494         for (i = 0; i < vec_size(parser->gotos); ++i) {
3495             if (!strcmp(parser->gotos[i]->name, label->name)) {
3496                 ast_goto_set_label(parser->gotos[i], label);
3497                 vec_remove(parser->gotos, i, 1);
3498                 --i;
3499             }
3500         }
3501         return true;
3502     }
3503     else if (parser->tok == ';')
3504     {
3505         if (!parser_next(parser)) {
3506             parseerror(parser, "parse error after empty statement");
3507             return false;
3508         }
3509         return true;
3510     }
3511     else
3512     {
3513         lex_ctx_t ctx = parser_ctx(parser);
3514         ast_expression *exp = parse_expression(parser, false, false);
3515         if (!exp)
3516             return false;
3517         *out = exp;
3518         if (!ast_side_effects(exp)) {
3519             if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3520                 return false;
3521         }
3522         return true;
3523     }
3524 }
3525
3526 static bool parse_enum(parser_t *parser)
3527 {
3528     bool        flag = false;
3529     bool        reverse = false;
3530     qcfloat_t     num = 0;
3531     ast_value **values = NULL;
3532     ast_value  *var = NULL;
3533     ast_value  *asvalue;
3534
3535     ast_expression *old;
3536
3537     if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3538         parseerror(parser, "expected `{` or `:` after `enum` keyword");
3539         return false;
3540     }
3541
3542     /* enumeration attributes (can add more later) */
3543     if (parser->tok == ':') {
3544         if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3545             parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3546             return false;
3547         }
3548
3549         /* attributes? */
3550         if (!strcmp(parser_tokval(parser), "flag")) {
3551             num  = 1;
3552             flag = true;
3553         }
3554         else if (!strcmp(parser_tokval(parser), "reverse")) {
3555             reverse = true;
3556         }
3557         else {
3558             parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3559             return false;
3560         }
3561
3562         if (!parser_next(parser) || parser->tok != '{') {
3563             parseerror(parser, "expected `{` after enum attribute ");
3564             return false;
3565         }
3566     }
3567
3568     while (true) {
3569         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3570             if (parser->tok == '}') {
3571                 /* allow an empty enum */
3572                 break;
3573             }
3574             parseerror(parser, "expected identifier or `}`");
3575             goto onerror;
3576         }
3577
3578         old = parser_find_field(parser, parser_tokval(parser));
3579         if (!old)
3580             old = parser_find_global(parser, parser_tokval(parser));
3581         if (old) {
3582             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3583                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3584             goto onerror;
3585         }
3586
3587         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3588         vec_push(values, var);
3589         var->cvq             = CV_CONST;
3590         var->hasvalue        = true;
3591
3592         /* for flagged enumerations increment in POTs of TWO */
3593         var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3594         parser_addglobal(parser, var->name, (ast_expression*)var);
3595
3596         if (!parser_next(parser)) {
3597             parseerror(parser, "expected `=`, `}` or comma after identifier");
3598             goto onerror;
3599         }
3600
3601         if (parser->tok == ',')
3602             continue;
3603         if (parser->tok == '}')
3604             break;
3605         if (parser->tok != '=') {
3606             parseerror(parser, "expected `=`, `}` or comma after identifier");
3607             goto onerror;
3608         }
3609
3610         if (!parser_next(parser)) {
3611             parseerror(parser, "expected expression after `=`");
3612             goto onerror;
3613         }
3614
3615         /* We got a value! */
3616         old = parse_expression_leave(parser, true, false, false);
3617         asvalue = (ast_value*)old;
3618         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3619             compile_error(ast_ctx(var), "constant value or expression expected");
3620             goto onerror;
3621         }
3622         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3623
3624         if (parser->tok == '}')
3625             break;
3626         if (parser->tok != ',') {
3627             parseerror(parser, "expected `}` or comma after expression");
3628             goto onerror;
3629         }
3630     }
3631
3632     /* patch them all (for reversed attribute) */
3633     if (reverse) {
3634         size_t i;
3635         for (i = 0; i < vec_size(values); i++)
3636             values[i]->constval.vfloat = vec_size(values) - i - 1;
3637     }
3638
3639     if (parser->tok != '}') {
3640         parseerror(parser, "internal error: breaking without `}`");
3641         goto onerror;
3642     }
3643
3644     if (!parser_next(parser) || parser->tok != ';') {
3645         parseerror(parser, "expected semicolon after enumeration");
3646         goto onerror;
3647     }
3648
3649     if (!parser_next(parser)) {
3650         parseerror(parser, "parse error after enumeration");
3651         goto onerror;
3652     }
3653
3654     vec_free(values);
3655     return true;
3656
3657 onerror:
3658     vec_free(values);
3659     return false;
3660 }
3661
3662 static bool parse_block_into(parser_t *parser, ast_block *block)
3663 {
3664     bool   retval = true;
3665
3666     parser_enterblock(parser);
3667
3668     if (!parser_next(parser)) { /* skip the '{' */
3669         parseerror(parser, "expected function body");
3670         goto cleanup;
3671     }
3672
3673     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3674     {
3675         ast_expression *expr = NULL;
3676         if (parser->tok == '}')
3677             break;
3678
3679         if (!parse_statement(parser, block, &expr, false)) {
3680             /* parseerror(parser, "parse error"); */
3681             block = NULL;
3682             goto cleanup;
3683         }
3684         if (!expr)
3685             continue;
3686         if (!ast_block_add_expr(block, expr)) {
3687             ast_delete(block);
3688             block = NULL;
3689             goto cleanup;
3690         }
3691     }
3692
3693     if (parser->tok != '}') {
3694         block = NULL;
3695     } else {
3696         (void)parser_next(parser);
3697     }
3698
3699 cleanup:
3700     if (!parser_leaveblock(parser))
3701         retval = false;
3702     return retval && !!block;
3703 }
3704
3705 static ast_block* parse_block(parser_t *parser)
3706 {
3707     ast_block *block;
3708     block = ast_block_new(parser_ctx(parser));
3709     if (!block)
3710         return NULL;
3711     if (!parse_block_into(parser, block)) {
3712         ast_block_delete(block);
3713         return NULL;
3714     }
3715     return block;
3716 }
3717
3718 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3719 {
3720     if (parser->tok == '{') {
3721         *out = (ast_expression*)parse_block(parser);
3722         return !!*out;
3723     }
3724     return parse_statement(parser, NULL, out, false);
3725 }
3726
3727 static bool create_vector_members(ast_value *var, ast_member **me)
3728 {
3729     size_t i;
3730     size_t len = strlen(var->name);
3731
3732     for (i = 0; i < 3; ++i) {
3733         char *name = (char*)mem_a(len+3);
3734         memcpy(name, var->name, len);
3735         name[len+0] = '_';
3736         name[len+1] = 'x'+i;
3737         name[len+2] = 0;
3738         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3739         mem_d(name);
3740         if (!me[i])
3741             break;
3742     }
3743     if (i == 3)
3744         return true;
3745
3746     /* unroll */
3747     do { ast_member_delete(me[--i]); } while(i);
3748     return false;
3749 }
3750
3751 static bool parse_function_body(parser_t *parser, ast_value *var)
3752 {
3753     ast_block      *block = NULL;
3754     ast_function   *func;
3755     ast_function   *old;
3756     size_t          parami;
3757
3758     ast_expression *framenum  = NULL;
3759     ast_expression *nextthink = NULL;
3760     /* None of the following have to be deleted */
3761     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3762     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3763     bool            has_frame_think;
3764
3765     bool retval = true;
3766
3767     has_frame_think = false;
3768     old = parser->function;
3769
3770     if (var->expression.flags & AST_FLAG_ALIAS) {
3771         parseerror(parser, "function aliases cannot have bodies");
3772         return false;
3773     }
3774
3775     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3776         parseerror(parser, "gotos/labels leaking");
3777         return false;
3778     }
3779
3780     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3781         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3782                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3783         {
3784             return false;
3785         }
3786     }
3787
3788     if (parser->tok == '[') {
3789         /* got a frame definition: [ framenum, nextthink ]
3790          * this translates to:
3791          * self.frame = framenum;
3792          * self.nextthink = time + 0.1;
3793          * self.think = nextthink;
3794          */
3795         nextthink = NULL;
3796
3797         fld_think     = parser_find_field(parser, "think");
3798         fld_nextthink = parser_find_field(parser, "nextthink");
3799         fld_frame     = parser_find_field(parser, "frame");
3800         if (!fld_think || !fld_nextthink || !fld_frame) {
3801             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3802             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3803             return false;
3804         }
3805         gbl_time      = parser_find_global(parser, "time");
3806         gbl_self      = parser_find_global(parser, "self");
3807         if (!gbl_time || !gbl_self) {
3808             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3809             parseerror(parser, "please declare the following globals: `time`, `self`");
3810             return false;
3811         }
3812
3813         if (!parser_next(parser))
3814             return false;
3815
3816         framenum = parse_expression_leave(parser, true, false, false);
3817         if (!framenum) {
3818             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3819             return false;
3820         }
3821         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3822             ast_unref(framenum);
3823             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3824             return false;
3825         }
3826
3827         if (parser->tok != ',') {
3828             ast_unref(framenum);
3829             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3830             parseerror(parser, "Got a %i\n", parser->tok);
3831             return false;
3832         }
3833
3834         if (!parser_next(parser)) {
3835             ast_unref(framenum);
3836             return false;
3837         }
3838
3839         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3840         {
3841             /* qc allows the use of not-yet-declared functions here
3842              * - this automatically creates a prototype */
3843             ast_value      *thinkfunc;
3844             ast_expression *functype = fld_think->next;
3845
3846             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3847             if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3848                 ast_unref(framenum);
3849                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3850                 return false;
3851             }
3852             ast_type_adopt(thinkfunc, functype);
3853
3854             if (!parser_next(parser)) {
3855                 ast_unref(framenum);
3856                 ast_delete(thinkfunc);
3857                 return false;
3858             }
3859
3860             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3861
3862             nextthink = (ast_expression*)thinkfunc;
3863
3864         } else {
3865             nextthink = parse_expression_leave(parser, true, false, false);
3866             if (!nextthink) {
3867                 ast_unref(framenum);
3868                 parseerror(parser, "expected a think-function in [frame,think] notation");
3869                 return false;
3870             }
3871         }
3872
3873         if (!ast_istype(nextthink, ast_value)) {
3874             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3875             retval = false;
3876         }
3877
3878         if (retval && parser->tok != ']') {
3879             parseerror(parser, "expected closing `]` for [frame,think] notation");
3880             retval = false;
3881         }
3882
3883         if (retval && !parser_next(parser)) {
3884             retval = false;
3885         }
3886
3887         if (retval && parser->tok != '{') {
3888             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3889             retval = false;
3890         }
3891
3892         if (!retval) {
3893             ast_unref(nextthink);
3894             ast_unref(framenum);
3895             return false;
3896         }
3897
3898         has_frame_think = true;
3899     }
3900
3901     block = ast_block_new(parser_ctx(parser));
3902     if (!block) {
3903         parseerror(parser, "failed to allocate block");
3904         if (has_frame_think) {
3905             ast_unref(nextthink);
3906             ast_unref(framenum);
3907         }
3908         return false;
3909     }
3910
3911     if (has_frame_think) {
3912         lex_ctx_t ctx;
3913         ast_expression *self_frame;
3914         ast_expression *self_nextthink;
3915         ast_expression *self_think;
3916         ast_expression *time_plus_1;
3917         ast_store *store_frame;
3918         ast_store *store_nextthink;
3919         ast_store *store_think;
3920
3921         ctx = parser_ctx(parser);
3922         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3923         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3924         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3925
3926         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3927                          gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3928
3929         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3930             if (self_frame)     ast_delete(self_frame);
3931             if (self_nextthink) ast_delete(self_nextthink);
3932             if (self_think)     ast_delete(self_think);
3933             if (time_plus_1)    ast_delete(time_plus_1);
3934             retval = false;
3935         }
3936
3937         if (retval)
3938         {
3939             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3940             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3941             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3942
3943             if (!store_frame) {
3944                 ast_delete(self_frame);
3945                 retval = false;
3946             }
3947             if (!store_nextthink) {
3948                 ast_delete(self_nextthink);
3949                 retval = false;
3950             }
3951             if (!store_think) {
3952                 ast_delete(self_think);
3953                 retval = false;
3954             }
3955             if (!retval) {
3956                 if (store_frame)     ast_delete(store_frame);
3957                 if (store_nextthink) ast_delete(store_nextthink);
3958                 if (store_think)     ast_delete(store_think);
3959                 retval = false;
3960             }
3961             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3962                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3963                 !ast_block_add_expr(block, (ast_expression*)store_think))
3964             {
3965                 retval = false;
3966             }
3967         }
3968
3969         if (!retval) {
3970             parseerror(parser, "failed to generate code for [frame,think]");
3971             ast_unref(nextthink);
3972             ast_unref(framenum);
3973             ast_delete(block);
3974             return false;
3975         }
3976     }
3977
3978     if (var->hasvalue) {
3979         parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3980         ast_block_delete(block);
3981         goto enderr;
3982     }
3983
3984     func = ast_function_new(ast_ctx(var), var->name, var);
3985     if (!func) {
3986         parseerror(parser, "failed to allocate function for `%s`", var->name);
3987         ast_block_delete(block);
3988         goto enderr;
3989     }
3990     vec_push(parser->functions, func);
3991
3992     parser_enterblock(parser);
3993
3994     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3995         size_t     e;
3996         ast_value *param = var->expression.params[parami];
3997         ast_member *me[3];
3998
3999         if (param->expression.vtype != TYPE_VECTOR &&
4000             (param->expression.vtype != TYPE_FIELD ||
4001              param->expression.next->vtype != TYPE_VECTOR))
4002         {
4003             continue;
4004         }
4005
4006         if (!create_vector_members(param, me)) {
4007             ast_block_delete(block);
4008             goto enderrfn;
4009         }
4010
4011         for (e = 0; e < 3; ++e) {
4012             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4013             ast_block_collect(block, (ast_expression*)me[e]);
4014         }
4015     }
4016
4017     if (var->argcounter) {
4018         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4019         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4020         func->argc = argc;
4021     }
4022
4023     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4024         char name[1024];
4025         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4026         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4027         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4028         varargs->expression.count = 0;
4029         util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4030         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4031             ast_delete(varargs);
4032             ast_block_delete(block);
4033             goto enderrfn;
4034         }
4035         util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4036         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4037             ast_delete(varargs);
4038             ast_block_delete(block);
4039             goto enderrfn;
4040         }
4041         func->varargs     = varargs;
4042         func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4043     }
4044
4045     parser->function = func;
4046     if (!parse_block_into(parser, block)) {
4047         ast_block_delete(block);
4048         goto enderrfn;
4049     }
4050
4051     vec_push(func->blocks, block);
4052
4053
4054     parser->function = old;
4055     if (!parser_leaveblock(parser))
4056         retval = false;
4057     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4058         parseerror(parser, "internal error: local scopes left");
4059         retval = false;
4060     }
4061
4062     if (parser->tok == ';')
4063         return parser_next(parser);
4064     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4065         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4066     return retval;
4067
4068 enderrfn:
4069     (void)!parser_leaveblock(parser);
4070     vec_pop(parser->functions);
4071     ast_function_delete(func);
4072     var->constval.vfunc = NULL;
4073
4074 enderr:
4075     parser->function = old;
4076     return false;
4077 }
4078
4079 static ast_expression *array_accessor_split(
4080     parser_t  *parser,
4081     ast_value *array,
4082     ast_value *index,
4083     size_t     middle,
4084     ast_expression *left,
4085     ast_expression *right
4086     )
4087 {
4088     ast_ifthen *ifthen;
4089     ast_binary *cmp;
4090
4091     lex_ctx_t ctx = ast_ctx(array);
4092
4093     if (!left || !right) {
4094         if (left)  ast_delete(left);
4095         if (right) ast_delete(right);
4096         return NULL;
4097     }
4098
4099     cmp = ast_binary_new(ctx, INSTR_LT,
4100                          (ast_expression*)index,
4101                          (ast_expression*)fold_constgen_float(parser->fold, middle));
4102     if (!cmp) {
4103         ast_delete(left);
4104         ast_delete(right);
4105         parseerror(parser, "internal error: failed to create comparison for array setter");
4106         return NULL;
4107     }
4108
4109     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4110     if (!ifthen) {
4111         ast_delete(cmp); /* will delete left and right */
4112         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4113         return NULL;
4114     }
4115
4116     return (ast_expression*)ifthen;
4117 }
4118
4119 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4120 {
4121     lex_ctx_t ctx = ast_ctx(array);
4122
4123     if (from+1 == afterend) {
4124         /* set this value */
4125         ast_block       *block;
4126         ast_return      *ret;
4127         ast_array_index *subscript;
4128         ast_store       *st;
4129         int assignop = type_store_instr[value->expression.vtype];
4130
4131         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4132             assignop = INSTR_STORE_V;
4133
4134         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4135         if (!subscript)
4136             return NULL;
4137
4138         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4139         if (!st) {
4140             ast_delete(subscript);
4141             return NULL;
4142         }
4143
4144         block = ast_block_new(ctx);
4145         if (!block) {
4146             ast_delete(st);
4147             return NULL;
4148         }
4149
4150         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4151             ast_delete(block);
4152             return NULL;
4153         }
4154
4155         ret = ast_return_new(ctx, NULL);
4156         if (!ret) {
4157             ast_delete(block);
4158             return NULL;
4159         }
4160
4161         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4162             ast_delete(block);
4163             return NULL;
4164         }
4165
4166         return (ast_expression*)block;
4167     } else {
4168         ast_expression *left, *right;
4169         size_t diff = afterend - from;
4170         size_t middle = from + diff/2;
4171         left  = array_setter_node(parser, array, index, value, from, middle);
4172         right = array_setter_node(parser, array, index, value, middle, afterend);
4173         return array_accessor_split(parser, array, index, middle, left, right);
4174     }
4175 }
4176
4177 static ast_expression *array_field_setter_node(
4178     parser_t  *parser,
4179     ast_value *array,
4180     ast_value *entity,
4181     ast_value *index,
4182     ast_value *value,
4183     size_t     from,
4184     size_t     afterend)
4185 {
4186     lex_ctx_t ctx = ast_ctx(array);
4187
4188     if (from+1 == afterend) {
4189         /* set this value */
4190         ast_block       *block;
4191         ast_return      *ret;
4192         ast_entfield    *entfield;
4193         ast_array_index *subscript;
4194         ast_store       *st;
4195         int assignop = type_storep_instr[value->expression.vtype];
4196
4197         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4198             assignop = INSTR_STOREP_V;
4199
4200         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4201         if (!subscript)
4202             return NULL;
4203
4204         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4205         subscript->expression.vtype = TYPE_FIELD;
4206
4207         entfield = ast_entfield_new_force(ctx,
4208                                           (ast_expression*)entity,
4209                                           (ast_expression*)subscript,
4210                                           (ast_expression*)subscript);
4211         if (!entfield) {
4212             ast_delete(subscript);
4213             return NULL;
4214         }
4215
4216         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4217         if (!st) {
4218             ast_delete(entfield);
4219             return NULL;
4220         }
4221
4222         block = ast_block_new(ctx);
4223         if (!block) {
4224             ast_delete(st);
4225             return NULL;
4226         }
4227
4228         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4229             ast_delete(block);
4230             return NULL;
4231         }
4232
4233         ret = ast_return_new(ctx, NULL);
4234         if (!ret) {
4235             ast_delete(block);
4236             return NULL;
4237         }
4238
4239         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4240             ast_delete(block);
4241             return NULL;
4242         }
4243
4244         return (ast_expression*)block;
4245     } else {
4246         ast_expression *left, *right;
4247         size_t diff = afterend - from;
4248         size_t middle = from + diff/2;
4249         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4250         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4251         return array_accessor_split(parser, array, index, middle, left, right);
4252     }
4253 }
4254
4255 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4256 {
4257     lex_ctx_t ctx = ast_ctx(array);
4258
4259     if (from+1 == afterend) {
4260         ast_return      *ret;
4261         ast_array_index *subscript;
4262
4263         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4264         if (!subscript)
4265             return NULL;
4266
4267         ret = ast_return_new(ctx, (ast_expression*)subscript);
4268         if (!ret) {
4269             ast_delete(subscript);
4270             return NULL;
4271         }
4272
4273         return (ast_expression*)ret;
4274     } else {
4275         ast_expression *left, *right;
4276         size_t diff = afterend - from;
4277         size_t middle = from + diff/2;
4278         left  = array_getter_node(parser, array, index, from, middle);
4279         right = array_getter_node(parser, array, index, middle, afterend);
4280         return array_accessor_split(parser, array, index, middle, left, right);
4281     }
4282 }
4283
4284 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4285 {
4286     ast_function   *func = NULL;
4287     ast_value      *fval = NULL;
4288     ast_block      *body = NULL;
4289
4290     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4291     if (!fval) {
4292         parseerror(parser, "failed to create accessor function value");
4293         return false;
4294     }
4295
4296     func = ast_function_new(ast_ctx(array), funcname, fval);
4297     if (!func) {
4298         ast_delete(fval);
4299         parseerror(parser, "failed to create accessor function node");
4300         return false;
4301     }
4302
4303     body = ast_block_new(ast_ctx(array));
4304     if (!body) {
4305         parseerror(parser, "failed to create block for array accessor");
4306         ast_delete(fval);
4307         ast_delete(func);
4308         return false;
4309     }
4310
4311     vec_push(func->blocks, body);
4312     *out = fval;
4313
4314     vec_push(parser->accessors, fval);
4315
4316     return true;
4317 }
4318
4319 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4320 {
4321     ast_value      *index = NULL;
4322     ast_value      *value = NULL;
4323     ast_function   *func;
4324     ast_value      *fval;
4325
4326     if (!ast_istype(array->expression.next, ast_value)) {
4327         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4328         return NULL;
4329     }
4330
4331     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4332         return NULL;
4333     func = fval->constval.vfunc;
4334     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4335
4336     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4337     value = ast_value_copy((ast_value*)array->expression.next);
4338
4339     if (!index || !value) {
4340         parseerror(parser, "failed to create locals for array accessor");
4341         goto cleanup;
4342     }
4343     (void)!ast_value_set_name(value, "value"); /* not important */
4344     vec_push(fval->expression.params, index);
4345     vec_push(fval->expression.params, value);
4346
4347     array->setter = fval;
4348     return fval;
4349 cleanup:
4350     if (index) ast_delete(index);
4351     if (value) ast_delete(value);
4352     ast_delete(func);
4353     ast_delete(fval);
4354     return NULL;
4355 }
4356
4357 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4358 {
4359     ast_expression *root = NULL;
4360     root = array_setter_node(parser, array,
4361                              array->setter->expression.params[0],
4362                              array->setter->expression.params[1],
4363                              0, array->expression.count);
4364     if (!root) {
4365         parseerror(parser, "failed to build accessor search tree");
4366         return false;
4367     }
4368     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4369         ast_delete(root);
4370         return false;
4371     }
4372     return true;
4373 }
4374
4375 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4376 {
4377     if (!parser_create_array_setter_proto(parser, array, funcname))
4378         return false;
4379     return parser_create_array_setter_impl(parser, array);
4380 }
4381
4382 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4383 {
4384     ast_expression *root = NULL;
4385     ast_value      *entity = NULL;
4386     ast_value      *index = NULL;
4387     ast_value      *value = NULL;
4388     ast_function   *func;
4389     ast_value      *fval;
4390
4391     if (!ast_istype(array->expression.next, ast_value)) {
4392         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4393         return false;
4394     }
4395
4396     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4397         return false;
4398     func = fval->constval.vfunc;
4399     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4400
4401     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4402     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4403     value  = ast_value_copy((ast_value*)array->expression.next);
4404     if (!entity || !index || !value) {
4405         parseerror(parser, "failed to create locals for array accessor");
4406         goto cleanup;
4407     }
4408     (void)!ast_value_set_name(value, "value"); /* not important */
4409     vec_push(fval->expression.params, entity);
4410     vec_push(fval->expression.params, index);
4411     vec_push(fval->expression.params, value);
4412
4413     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4414     if (!root) {
4415         parseerror(parser, "failed to build accessor search tree");
4416         goto cleanup;
4417     }
4418
4419     array->setter = fval;
4420     return ast_block_add_expr(func->blocks[0], root);
4421 cleanup:
4422     if (entity) ast_delete(entity);
4423     if (index)  ast_delete(index);
4424     if (value)  ast_delete(value);
4425     if (root)   ast_delete(root);
4426     ast_delete(func);
4427     ast_delete(fval);
4428     return false;
4429 }
4430
4431 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4432 {
4433     ast_value      *index = NULL;
4434     ast_value      *fval;
4435     ast_function   *func;
4436
4437     /* NOTE: checking array->expression.next rather than elemtype since
4438      * for fields elemtype is a temporary fieldtype.
4439      */
4440     if (!ast_istype(array->expression.next, ast_value)) {
4441         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4442         return NULL;
4443     }
4444
4445     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4446         return NULL;
4447     func = fval->constval.vfunc;
4448     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4449
4450     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4451
4452     if (!index) {
4453         parseerror(parser, "failed to create locals for array accessor");
4454         goto cleanup;
4455     }
4456     vec_push(fval->expression.params, index);
4457
4458     array->getter = fval;
4459     return fval;
4460 cleanup:
4461     if (index) ast_delete(index);
4462     ast_delete(func);
4463     ast_delete(fval);
4464     return NULL;
4465 }
4466
4467 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4468 {
4469     ast_expression *root = NULL;
4470
4471     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4472     if (!root) {
4473         parseerror(parser, "failed to build accessor search tree");
4474         return false;
4475     }
4476     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4477         ast_delete(root);
4478         return false;
4479     }
4480     return true;
4481 }
4482
4483 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4484 {
4485     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4486         return false;
4487     return parser_create_array_getter_impl(parser, array);
4488 }
4489
4490 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4491 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4492 {
4493     lex_ctx_t     ctx;
4494     size_t      i;
4495     ast_value **params;
4496     ast_value  *param;
4497     ast_value  *fval;
4498     bool        first = true;
4499     bool        variadic = false;
4500     ast_value  *varparam = NULL;
4501     char       *argcounter = NULL;
4502
4503     ctx = parser_ctx(parser);
4504
4505     /* for the sake of less code we parse-in in this function */
4506     if (!parser_next(parser)) {
4507         ast_delete(var);
4508         parseerror(parser, "expected parameter list");
4509         return NULL;
4510     }
4511
4512     params = NULL;
4513
4514     /* parse variables until we hit a closing paren */
4515     while (parser->tok != ')') {
4516         if (!first) {
4517             /* there must be commas between them */
4518             if (parser->tok != ',') {
4519                 parseerror(parser, "expected comma or end of parameter list");
4520                 goto on_error;
4521             }
4522             if (!parser_next(parser)) {
4523                 parseerror(parser, "expected parameter");
4524                 goto on_error;
4525             }
4526         }
4527         first = false;
4528
4529         if (parser->tok == TOKEN_DOTS) {
4530             /* '...' indicates a varargs function */
4531             variadic = true;
4532             if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4533                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4534                 goto on_error;
4535             }
4536             if (parser->tok == TOKEN_IDENT) {
4537                 argcounter = util_strdup(parser_tokval(parser));
4538                 if (!parser_next(parser) || parser->tok != ')') {
4539                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4540                     goto on_error;
4541                 }
4542             }
4543         }
4544         else
4545         {
4546             /* for anything else just parse a typename */
4547             param = parse_typename(parser, NULL, NULL);
4548             if (!param)
4549                 goto on_error;
4550             vec_push(params, param);
4551             if (param->expression.vtype >= TYPE_VARIANT) {
4552                 char tname[1024]; /* typename is reserved in C++ */
4553                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4554                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4555                 goto on_error;
4556             }
4557             /* type-restricted varargs */
4558             if (parser->tok == TOKEN_DOTS) {
4559                 variadic = true;
4560                 varparam = vec_last(params);
4561                 vec_pop(params);
4562                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4563                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4564                     goto on_error;
4565                 }
4566                 if (parser->tok == TOKEN_IDENT) {
4567                     argcounter = util_strdup(parser_tokval(parser));
4568                     if (!parser_next(parser) || parser->tok != ')') {
4569                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4570                         goto on_error;
4571                     }
4572                 }
4573             }
4574         }
4575     }
4576
4577     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4578         vec_free(params);
4579
4580     /* sanity check */
4581     if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4582         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4583
4584     /* parse-out */
4585     if (!parser_next(parser)) {
4586         parseerror(parser, "parse error after typename");
4587         goto on_error;
4588     }
4589
4590     /* now turn 'var' into a function type */
4591     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4592     fval->expression.next     = (ast_expression*)var;
4593     if (variadic)
4594         fval->expression.flags |= AST_FLAG_VARIADIC;
4595     var = fval;
4596
4597     var->expression.params   = params;
4598     var->expression.varparam = (ast_expression*)varparam;
4599     var->argcounter          = argcounter;
4600     params = NULL;
4601
4602     return var;
4603
4604 on_error:
4605     if (argcounter)
4606         mem_d(argcounter);
4607     if (varparam)
4608         ast_delete(varparam);
4609     ast_delete(var);
4610     for (i = 0; i < vec_size(params); ++i)
4611         ast_delete(params[i]);
4612     vec_free(params);
4613     return NULL;
4614 }
4615
4616 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4617 {
4618     ast_expression *cexp;
4619     ast_value      *cval, *tmp;
4620     lex_ctx_t ctx;
4621
4622     ctx = parser_ctx(parser);
4623
4624     if (!parser_next(parser)) {
4625         ast_delete(var);
4626         parseerror(parser, "expected array-size");
4627         return NULL;
4628     }
4629
4630     if (parser->tok != ']') {
4631         cexp = parse_expression_leave(parser, true, false, false);
4632
4633         if (!cexp || !ast_istype(cexp, ast_value)) {
4634             if (cexp)
4635                 ast_unref(cexp);
4636             ast_delete(var);
4637             parseerror(parser, "expected array-size as constant positive integer");
4638             return NULL;
4639         }
4640         cval = (ast_value*)cexp;
4641     }
4642     else {
4643         cexp = NULL;
4644         cval = NULL;
4645     }
4646
4647     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4648     tmp->expression.next = (ast_expression*)var;
4649     var = tmp;
4650
4651     if (cval) {
4652         if (cval->expression.vtype == TYPE_INTEGER)
4653             tmp->expression.count = cval->constval.vint;
4654         else if (cval->expression.vtype == TYPE_FLOAT)
4655             tmp->expression.count = cval->constval.vfloat;
4656         else {
4657             ast_unref(cexp);
4658             ast_delete(var);
4659             parseerror(parser, "array-size must be a positive integer constant");
4660             return NULL;
4661         }
4662
4663         ast_unref(cexp);
4664     } else {
4665         var->expression.count = -1;
4666         var->expression.flags |= AST_FLAG_ARRAY_INIT;
4667     }
4668
4669     if (parser->tok != ']') {
4670         ast_delete(var);
4671         parseerror(parser, "expected ']' after array-size");
4672         return NULL;
4673     }
4674     if (!parser_next(parser)) {
4675         ast_delete(var);
4676         parseerror(parser, "error after parsing array size");
4677         return NULL;
4678     }
4679     return var;
4680 }
4681
4682 /* Parse a complete typename.
4683  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4684  * but when parsing variables separated by comma
4685  * 'storebase' should point to where the base-type should be kept.
4686  * The base type makes up every bit of type information which comes *before* the
4687  * variable name.
4688  *
4689  * NOTE: The value must either be named, have a NULL name, or a name starting
4690  *       with '<'. In the first case, this will be the actual variable or type
4691  *       name, in the other cases it is assumed that the name will appear
4692  *       later, and an error is generated otherwise.
4693  *
4694  * The following will be parsed in its entirety:
4695  *     void() foo()
4696  * The 'basetype' in this case is 'void()'
4697  * and if there's a comma after it, say:
4698  *     void() foo(), bar
4699  * then the type-information 'void()' can be stored in 'storebase'
4700  */
4701 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4702 {
4703     ast_value *var, *tmp;
4704     lex_ctx_t    ctx;
4705
4706     const char *name = NULL;
4707     bool        isfield  = false;
4708     bool        wasarray = false;
4709     size_t      morefields = 0;
4710
4711     ctx = parser_ctx(parser);
4712
4713     /* types may start with a dot */
4714     if (parser->tok == '.') {
4715         isfield = true;
4716         /* if we parsed a dot we need a typename now */
4717         if (!parser_next(parser)) {
4718             parseerror(parser, "expected typename for field definition");
4719             return NULL;
4720         }
4721
4722         /* Further dots are handled seperately because they won't be part of the
4723          * basetype
4724          */
4725         while (parser->tok == '.') {
4726             ++morefields;
4727             if (!parser_next(parser)) {
4728                 parseerror(parser, "expected typename for field definition");
4729                 return NULL;
4730             }
4731         }
4732     }
4733     if (parser->tok == TOKEN_IDENT)
4734         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4735     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4736         parseerror(parser, "expected typename");
4737         return NULL;
4738     }
4739
4740     /* generate the basic type value */
4741     if (cached_typedef) {
4742         var = ast_value_copy(cached_typedef);
4743         ast_value_set_name(var, "<type(from_def)>");
4744     } else
4745         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4746
4747     for (; morefields; --morefields) {
4748         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4749         tmp->expression.next = (ast_expression*)var;
4750         var = tmp;
4751     }
4752
4753     /* do not yet turn into a field - remember:
4754      * .void() foo; is a field too
4755      * .void()() foo; is a function
4756      */
4757
4758     /* parse on */
4759     if (!parser_next(parser)) {
4760         ast_delete(var);
4761         parseerror(parser, "parse error after typename");
4762         return NULL;
4763     }
4764
4765     /* an opening paren now starts the parameter-list of a function
4766      * this is where original-QC has parameter lists.
4767      * We allow a single parameter list here.
4768      * Much like fteqcc we don't allow `float()() x`
4769      */
4770     if (parser->tok == '(') {
4771         var = parse_parameter_list(parser, var);
4772         if (!var)
4773             return NULL;
4774     }
4775
4776     /* store the base if requested */
4777     if (storebase) {
4778         *storebase = ast_value_copy(var);
4779         if (isfield) {
4780             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4781             tmp->expression.next = (ast_expression*)*storebase;
4782             *storebase = tmp;
4783         }
4784     }
4785
4786     /* there may be a name now */
4787     if (parser->tok == TOKEN_IDENT) {
4788         name = util_strdup(parser_tokval(parser));
4789         /* parse on */
4790         if (!parser_next(parser)) {
4791             ast_delete(var);
4792             mem_d(name);
4793             parseerror(parser, "error after variable or field declaration");
4794             return NULL;
4795         }
4796     }
4797
4798     /* now this may be an array */
4799     if (parser->tok == '[') {
4800         wasarray = true;
4801         var = parse_arraysize(parser, var);
4802         if (!var) {
4803             if (name) mem_d(name);
4804             return NULL;
4805         }
4806     }
4807
4808     /* This is the point where we can turn it into a field */
4809     if (isfield) {
4810         /* turn it into a field if desired */
4811         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4812         tmp->expression.next = (ast_expression*)var;
4813         var = tmp;
4814     }
4815
4816     /* now there may be function parens again */
4817     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4818         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4819     if (parser->tok == '(' && wasarray)
4820         parseerror(parser, "arrays as part of a return type is not supported");
4821     while (parser->tok == '(') {
4822         var = parse_parameter_list(parser, var);
4823         if (!var) {
4824             if (name) mem_d(name);
4825             return NULL;
4826         }
4827     }
4828
4829     /* finally name it */
4830     if (name) {
4831         if (!ast_value_set_name(var, name)) {
4832             ast_delete(var);
4833             mem_d(name);
4834             parseerror(parser, "internal error: failed to set name");
4835             return NULL;
4836         }
4837         /* free the name, ast_value_set_name duplicates */
4838         mem_d(name);
4839     }
4840
4841     return var;
4842 }
4843
4844 static bool parse_typedef(parser_t *parser)
4845 {
4846     ast_value      *typevar, *oldtype;
4847     ast_expression *old;
4848
4849     typevar = parse_typename(parser, NULL, NULL);
4850
4851     if (!typevar)
4852         return false;
4853
4854     /* while parsing types, the ast_value's get named '<something>' */
4855     if (!typevar->name || typevar->name[0] == '<') {
4856         parseerror(parser, "missing name in typedef");
4857         ast_delete(typevar);
4858         return false;
4859     }
4860
4861     if ( (old = parser_find_var(parser, typevar->name)) ) {
4862         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4863                    " -> `%s` has been declared here: %s:%i",
4864                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4865         ast_delete(typevar);
4866         return false;
4867     }
4868
4869     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4870         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4871                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4872         ast_delete(typevar);
4873         return false;
4874     }
4875
4876     vec_push(parser->_typedefs, typevar);
4877     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4878
4879     if (parser->tok != ';') {
4880         parseerror(parser, "expected semicolon after typedef");
4881         return false;
4882     }
4883     if (!parser_next(parser)) {
4884         parseerror(parser, "parse error after typedef");
4885         return false;
4886     }
4887
4888     return true;
4889 }
4890
4891 static const char *cvq_to_str(int cvq) {
4892     switch (cvq) {
4893         case CV_NONE:  return "none";
4894         case CV_VAR:   return "`var`";
4895         case CV_CONST: return "`const`";
4896         default:       return "<INVALID>";
4897     }
4898 }
4899
4900 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4901 {
4902     bool av, ao;
4903     if (proto->cvq != var->cvq) {
4904         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4905               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4906               parser->tok == '='))
4907         {
4908             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4909                                  "`%s` declared with different qualifiers: %s\n"
4910                                  " -> previous declaration here: %s:%i uses %s",
4911                                  var->name, cvq_to_str(var->cvq),
4912                                  ast_ctx(proto).file, ast_ctx(proto).line,
4913                                  cvq_to_str(proto->cvq));
4914         }
4915     }
4916     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4917     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4918     if (!av != !ao) {
4919         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4920                              "`%s` declared with different attributes%s\n"
4921                              " -> previous declaration here: %s:%i",
4922                              var->name, (av ? ": noreturn" : ""),
4923                              ast_ctx(proto).file, ast_ctx(proto).line,
4924                              (ao ? ": noreturn" : ""));
4925     }
4926     return true;
4927 }
4928
4929 static bool create_array_accessors(parser_t *parser, ast_value *var)
4930 {
4931     char name[1024];
4932     util_snprintf(name, sizeof(name), "%s##SET", var->name);
4933     if (!parser_create_array_setter(parser, var, name))
4934         return false;
4935     util_snprintf(name, sizeof(name), "%s##GET", var->name);
4936     if (!parser_create_array_getter(parser, var, var->expression.next, name))
4937         return false;
4938     return true;
4939 }
4940
4941 static bool parse_array(parser_t *parser, ast_value *array)
4942 {
4943     size_t i;
4944     if (array->initlist) {
4945         parseerror(parser, "array already initialized elsewhere");
4946         return false;
4947     }
4948     if (!parser_next(parser)) {
4949         parseerror(parser, "parse error in array initializer");
4950         return false;
4951     }
4952     i = 0;
4953     while (parser->tok != '}') {
4954         ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4955         if (!v)
4956             return false;
4957         if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4958             ast_unref(v);
4959             parseerror(parser, "initializing element must be a compile time constant");
4960             return false;
4961         }
4962         vec_push(array->initlist, v->constval);
4963         if (v->expression.vtype == TYPE_STRING) {
4964             array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4965             ++i;
4966         }
4967         ast_unref(v);
4968         if (parser->tok == '}')
4969             break;
4970         if (parser->tok != ',' || !parser_next(parser)) {
4971             parseerror(parser, "expected comma or '}' in element list");
4972             return false;
4973         }
4974     }
4975     if (!parser_next(parser) || parser->tok != ';') {
4976         parseerror(parser, "expected semicolon after initializer, got %s");
4977         return false;
4978     }
4979     /*
4980     if (!parser_next(parser)) {
4981         parseerror(parser, "parse error after initializer");
4982         return false;
4983     }
4984     */
4985
4986     if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4987         if (array->expression.count != (size_t)-1) {
4988             parseerror(parser, "array `%s' has already been initialized with %u elements",
4989                        array->name, (unsigned)array->expression.count);
4990         }
4991         array->expression.count = vec_size(array->initlist);
4992         if (!create_array_accessors(parser, array))
4993             return false;
4994     }
4995     return true;
4996 }
4997
4998 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)
4999 {
5000     ast_value *var;
5001     ast_value *proto;
5002     ast_expression *old;
5003     bool       was_end;
5004     size_t     i;
5005
5006     ast_value *basetype = NULL;
5007     bool      retval    = true;
5008     bool      isparam   = false;
5009     bool      isvector  = false;
5010     bool      cleanvar  = true;
5011     bool      wasarray  = false;
5012
5013     ast_member *me[3] = { NULL, NULL, NULL };
5014
5015     if (!localblock && is_static)
5016         parseerror(parser, "`static` qualifier is not supported in global scope");
5017
5018     /* get the first complete variable */
5019     var = parse_typename(parser, &basetype, cached_typedef);
5020     if (!var) {
5021         if (basetype)
5022             ast_delete(basetype);
5023         return false;
5024     }
5025
5026     /* while parsing types, the ast_value's get named '<something>' */
5027     if (!var->name || var->name[0] == '<') {
5028         parseerror(parser, "declaration does not declare anything");
5029         if (basetype)
5030             ast_delete(basetype);
5031         return false;
5032     }
5033
5034     while (true) {
5035         proto = NULL;
5036         wasarray = false;
5037
5038         /* Part 0: finish the type */
5039         if (parser->tok == '(') {
5040             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5041                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5042             var = parse_parameter_list(parser, var);
5043             if (!var) {
5044                 retval = false;
5045                 goto cleanup;
5046             }
5047         }
5048         /* we only allow 1-dimensional arrays */
5049         if (parser->tok == '[') {
5050             wasarray = true;
5051             var = parse_arraysize(parser, var);
5052             if (!var) {
5053                 retval = false;
5054                 goto cleanup;
5055             }
5056         }
5057         if (parser->tok == '(' && wasarray) {
5058             parseerror(parser, "arrays as part of a return type is not supported");
5059             /* we'll still parse the type completely for now */
5060         }
5061         /* for functions returning functions */
5062         while (parser->tok == '(') {
5063             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5064                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5065             var = parse_parameter_list(parser, var);
5066             if (!var) {
5067                 retval = false;
5068                 goto cleanup;
5069             }
5070         }
5071
5072         var->cvq = qualifier;
5073         var->expression.flags |= qflags;
5074
5075         /*
5076          * store the vstring back to var for alias and
5077          * deprecation messages.
5078          */
5079         if (var->expression.flags & AST_FLAG_DEPRECATED ||
5080             var->expression.flags & AST_FLAG_ALIAS)
5081             var->desc = vstring;
5082
5083         /* Part 1:
5084          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5085          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5086          * is then filled with the previous definition and the parameter-names replaced.
5087          */
5088         if (!strcmp(var->name, "nil")) {
5089             if (OPTS_FLAG(UNTYPED_NIL)) {
5090                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5091                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5092             } else
5093                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5094         }
5095         if (!localblock) {
5096             /* Deal with end_sys_ vars */
5097             was_end = false;
5098             if (!strcmp(var->name, "end_sys_globals")) {
5099                 var->uses++;
5100                 parser->crc_globals = vec_size(parser->globals);
5101                 was_end = true;
5102             }
5103             else if (!strcmp(var->name, "end_sys_fields")) {
5104                 var->uses++;
5105                 parser->crc_fields = vec_size(parser->fields);
5106                 was_end = true;
5107             }
5108             if (was_end && var->expression.vtype == TYPE_FIELD) {
5109                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5110                                  "global '%s' hint should not be a field",
5111                                  parser_tokval(parser)))
5112                 {
5113                     retval = false;
5114                     goto cleanup;
5115                 }
5116             }
5117
5118             if (!nofields && var->expression.vtype == TYPE_FIELD)
5119             {
5120                 /* deal with field declarations */
5121                 old = parser_find_field(parser, var->name);
5122                 if (old) {
5123                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5124                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5125                     {
5126                         retval = false;
5127                         goto cleanup;
5128                     }
5129                     ast_delete(var);
5130                     var = NULL;
5131                     goto skipvar;
5132                     /*
5133                     parseerror(parser, "field `%s` already declared here: %s:%i",
5134                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5135                     retval = false;
5136                     goto cleanup;
5137                     */
5138                 }
5139                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5140                     (old = parser_find_global(parser, var->name)))
5141                 {
5142                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5143                     parseerror(parser, "field `%s` already declared here: %s:%i",
5144                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5145                     retval = false;
5146                     goto cleanup;
5147                 }
5148             }
5149             else
5150             {
5151                 /* deal with other globals */
5152                 old = parser_find_global(parser, var->name);
5153                 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5154                 {
5155                     /* This is a function which had a prototype */
5156                     if (!ast_istype(old, ast_value)) {
5157                         parseerror(parser, "internal error: prototype is not an ast_value");
5158                         retval = false;
5159                         goto cleanup;
5160                     }
5161                     proto = (ast_value*)old;
5162                     proto->desc = var->desc;
5163                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5164                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5165                                    proto->name,
5166                                    ast_ctx(proto).file, ast_ctx(proto).line);
5167                         retval = false;
5168                         goto cleanup;
5169                     }
5170                     /* we need the new parameter-names */
5171                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5172                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5173                     if (!parser_check_qualifiers(parser, var, proto)) {
5174                         retval = false;
5175                         if (proto->desc)
5176                             mem_d(proto->desc);
5177                         proto = NULL;
5178                         goto cleanup;
5179                     }
5180                     proto->expression.flags |= var->expression.flags;
5181                     ast_delete(var);
5182                     var = proto;
5183                 }
5184                 else
5185                 {
5186                     /* other globals */
5187                     if (old) {
5188                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5189                                          "global `%s` already declared here: %s:%i",
5190                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5191                         {
5192                             retval = false;
5193                             goto cleanup;
5194                         }
5195                         proto = (ast_value*)old;
5196                         if (!ast_istype(old, ast_value)) {
5197                             parseerror(parser, "internal error: not an ast_value");
5198                             retval = false;
5199                             proto = NULL;
5200                             goto cleanup;
5201                         }
5202                         if (!parser_check_qualifiers(parser, var, proto)) {
5203                             retval = false;
5204                             proto = NULL;
5205                             goto cleanup;
5206                         }
5207                         proto->expression.flags |= var->expression.flags;
5208                         ast_delete(var);
5209                         var = proto;
5210                     }
5211                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5212                         (old = parser_find_field(parser, var->name)))
5213                     {
5214                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5215                         parseerror(parser, "global `%s` already declared here: %s:%i",
5216                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5217                         retval = false;
5218                         goto cleanup;
5219                     }
5220                 }
5221             }
5222         }
5223         else /* it's not a global */
5224         {
5225             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5226             if (old && !isparam) {
5227                 parseerror(parser, "local `%s` already declared here: %s:%i",
5228                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5229                 retval = false;
5230                 goto cleanup;
5231             }
5232             /* doing this here as the above is just for a single scope */
5233             old = parser_find_local(parser, var->name, 0, &isparam);
5234             if (old && isparam) {
5235                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5236                                  "local `%s` is shadowing a parameter", var->name))
5237                 {
5238                     parseerror(parser, "local `%s` already declared here: %s:%i",
5239                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5240                     retval = false;
5241                     goto cleanup;
5242                 }
5243                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5244                     ast_delete(var);
5245                     if (ast_istype(old, ast_value))
5246                         var = proto = (ast_value*)old;
5247                     else {
5248                         var = NULL;
5249                         goto skipvar;
5250                     }
5251                 }
5252             }
5253         }
5254
5255         /* in a noref section we simply bump the usecount */
5256         if (noref || parser->noref)
5257             var->uses++;
5258
5259         /* Part 2:
5260          * Create the global/local, and deal with vector types.
5261          */
5262         if (!proto) {
5263             if (var->expression.vtype == TYPE_VECTOR)
5264                 isvector = true;
5265             else if (var->expression.vtype == TYPE_FIELD &&
5266                      var->expression.next->vtype == TYPE_VECTOR)
5267                 isvector = true;
5268
5269             if (isvector) {
5270                 if (!create_vector_members(var, me)) {
5271                     retval = false;
5272                     goto cleanup;
5273                 }
5274             }
5275
5276             if (!localblock) {
5277                 /* deal with global variables, fields, functions */
5278                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5279                     var->isfield = true;
5280                     vec_push(parser->fields, (ast_expression*)var);
5281                     util_htset(parser->htfields, var->name, var);
5282                     if (isvector) {
5283                         for (i = 0; i < 3; ++i) {
5284                             vec_push(parser->fields, (ast_expression*)me[i]);
5285                             util_htset(parser->htfields, me[i]->name, me[i]);
5286                         }
5287                     }
5288                 }
5289                 else {
5290                     if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5291                         parser_addglobal(parser, var->name, (ast_expression*)var);
5292                         if (isvector) {
5293                             for (i = 0; i < 3; ++i) {
5294                                 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5295                             }
5296                         }
5297                     } else {
5298                         ast_expression *find  = parser_find_global(parser, var->desc);
5299
5300                         if (!find) {
5301                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5302                             return false;
5303                         }
5304
5305                         if (var->expression.vtype != find->vtype) {
5306                             char ty1[1024];
5307                             char ty2[1024];
5308
5309                             ast_type_to_string(find,                  ty1, sizeof(ty1));
5310                             ast_type_to_string((ast_expression*)var,  ty2, sizeof(ty2));
5311
5312                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5313                                 ty1, ty2, var->name
5314                             );
5315                             return false;
5316                         }
5317
5318                         /*
5319                          * add alias to aliases table and to corrector
5320                          * so corrections can apply for aliases as well.
5321                          */
5322                         util_htset(parser->aliases, var->name, find);
5323
5324                         /*
5325                          * add to corrector so corrections can work
5326                          * even for aliases too.
5327                          */
5328                         correct_add (
5329                              vec_last(parser->correct_variables),
5330                             &vec_last(parser->correct_variables_score),
5331                             var->name
5332                         );
5333
5334                         /* generate aliases for vector components */
5335                         if (isvector) {
5336                             char *buffer[3];
5337
5338                             util_asprintf(&buffer[0], "%s_x", var->desc);
5339                             util_asprintf(&buffer[1], "%s_y", var->desc);
5340                             util_asprintf(&buffer[2], "%s_z", var->desc);
5341
5342                             util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5343                             util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5344                             util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5345
5346                             mem_d(buffer[0]);
5347                             mem_d(buffer[1]);
5348                             mem_d(buffer[2]);
5349
5350                             /*
5351                              * add to corrector so corrections can work
5352                              * even for aliases too.
5353                              */
5354                             correct_add (
5355                                  vec_last(parser->correct_variables),
5356                                 &vec_last(parser->correct_variables_score),
5357                                 me[0]->name
5358                             );
5359                             correct_add (
5360                                  vec_last(parser->correct_variables),
5361                                 &vec_last(parser->correct_variables_score),
5362                                 me[1]->name
5363                             );
5364                             correct_add (
5365                                  vec_last(parser->correct_variables),
5366                                 &vec_last(parser->correct_variables_score),
5367                                 me[2]->name
5368                             );
5369                         }
5370                     }
5371                 }
5372             } else {
5373                 if (is_static) {
5374                     /* a static adds itself to be generated like any other global
5375                      * but is added to the local namespace instead
5376                      */
5377                     char   *defname = NULL;
5378                     size_t  prefix_len, ln;
5379
5380                     ln = strlen(parser->function->name);
5381                     vec_append(defname, ln, parser->function->name);
5382
5383                     vec_append(defname, 2, "::");
5384                     /* remember the length up to here */
5385                     prefix_len = vec_size(defname);
5386
5387                     /* Add it to the local scope */
5388                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5389
5390                     /* corrector */
5391                     correct_add (
5392                          vec_last(parser->correct_variables),
5393                         &vec_last(parser->correct_variables_score),
5394                         var->name
5395                     );
5396
5397                     /* now rename the global */
5398                     ln = strlen(var->name);
5399                     vec_append(defname, ln, var->name);
5400                     ast_value_set_name(var, defname);
5401
5402                     /* push it to the to-be-generated globals */
5403                     vec_push(parser->globals, (ast_expression*)var);
5404
5405                     /* same game for the vector members */
5406                     if (isvector) {
5407                         for (i = 0; i < 3; ++i) {
5408                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5409
5410                             /* corrector */
5411                             correct_add(
5412                                  vec_last(parser->correct_variables),
5413                                 &vec_last(parser->correct_variables_score),
5414                                 me[i]->name
5415                             );
5416
5417                             vec_shrinkto(defname, prefix_len);
5418                             ln = strlen(me[i]->name);
5419                             vec_append(defname, ln, me[i]->name);
5420                             ast_member_set_name(me[i], defname);
5421
5422                             vec_push(parser->globals, (ast_expression*)me[i]);
5423                         }
5424                     }
5425                     vec_free(defname);
5426                 } else {
5427                     vec_push(localblock->locals, var);
5428                     parser_addlocal(parser, var->name, (ast_expression*)var);
5429                     if (isvector) {
5430                         for (i = 0; i < 3; ++i) {
5431                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5432                             ast_block_collect(localblock, (ast_expression*)me[i]);
5433                         }
5434                     }
5435                 }
5436             }
5437         }
5438         me[0] = me[1] = me[2] = NULL;
5439         cleanvar = false;
5440         /* Part 2.2
5441          * deal with arrays
5442          */
5443         if (var->expression.vtype == TYPE_ARRAY) {
5444             if (var->expression.count != (size_t)-1) {
5445                 if (!create_array_accessors(parser, var))
5446                     goto cleanup;
5447             }
5448         }
5449         else if (!localblock && !nofields &&
5450                  var->expression.vtype == TYPE_FIELD &&
5451                  var->expression.next->vtype == TYPE_ARRAY)
5452         {
5453             char name[1024];
5454             ast_expression *telem;
5455             ast_value      *tfield;
5456             ast_value      *array = (ast_value*)var->expression.next;
5457
5458             if (!ast_istype(var->expression.next, ast_value)) {
5459                 parseerror(parser, "internal error: field element type must be an ast_value");
5460                 goto cleanup;
5461             }
5462
5463             util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5464             if (!parser_create_array_field_setter(parser, array, name))
5465                 goto cleanup;
5466
5467             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5468             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5469             tfield->expression.next = telem;
5470             util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5471             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5472                 ast_delete(tfield);
5473                 goto cleanup;
5474             }
5475             ast_delete(tfield);
5476         }
5477
5478 skipvar:
5479         if (parser->tok == ';') {
5480             ast_delete(basetype);
5481             if (!parser_next(parser)) {
5482                 parseerror(parser, "error after variable declaration");
5483                 return false;
5484             }
5485             return true;
5486         }
5487
5488         if (parser->tok == ',')
5489             goto another;
5490
5491         /*
5492         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5493         */
5494         if (!var) {
5495             parseerror(parser, "missing comma or semicolon while parsing variables");
5496             break;
5497         }
5498
5499         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5500             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5501                              "initializing expression turns variable `%s` into a constant in this standard",
5502                              var->name) )
5503             {
5504                 break;
5505             }
5506         }
5507
5508         if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5509             if (parser->tok != '=') {
5510                 if (!strcmp(parser_tokval(parser), "break")) {
5511                     if (!parser_next(parser)) {
5512                         parseerror(parser, "error parsing break definition");
5513                         break;
5514                     }
5515                     (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5516                 } else {
5517                     parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5518                     break;
5519                 }
5520             }
5521
5522             if (!parser_next(parser)) {
5523                 parseerror(parser, "error parsing initializer");
5524                 break;
5525             }
5526         }
5527         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5528             parseerror(parser, "expected '=' before function body in this standard");
5529         }
5530
5531         if (parser->tok == '#') {
5532             ast_function *func   = NULL;
5533             ast_value    *number = NULL;
5534             float         fractional;
5535             float         integral;
5536             int           builtin_num;
5537
5538             if (localblock) {
5539                 parseerror(parser, "cannot declare builtins within functions");
5540                 break;
5541             }
5542             if (var->expression.vtype != TYPE_FUNCTION) {
5543                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5544                 break;
5545             }
5546             if (!parser_next(parser)) {
5547                 parseerror(parser, "expected builtin number");
5548                 break;
5549             }
5550
5551             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5552                 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5553                 if (!number) {
5554                     parseerror(parser, "builtin number expected");
5555                     break;
5556                 }
5557                 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5558                 {
5559                     ast_unref(number);
5560                     parseerror(parser, "builtin number must be a compile time constant");
5561                     break;
5562                 }
5563                 if (number->expression.vtype == TYPE_INTEGER)
5564                     builtin_num = number->constval.vint;
5565                 else if (number->expression.vtype == TYPE_FLOAT)
5566                     builtin_num = number->constval.vfloat;
5567                 else {
5568                     ast_unref(number);
5569                     parseerror(parser, "builtin number must be an integer constant");
5570                     break;
5571                 }
5572                 ast_unref(number);
5573
5574                 fractional = modff(builtin_num, &integral);
5575                 if (builtin_num < 0 || fractional != 0) {
5576                     parseerror(parser, "builtin number must be an integer greater than zero");
5577                     break;
5578                 }
5579
5580                 /* we only want the integral part anyways */
5581                 builtin_num = integral;
5582             } else if (parser->tok == TOKEN_INTCONST) {
5583                 builtin_num = parser_token(parser)->constval.i;
5584             } else {
5585                 parseerror(parser, "builtin number must be a compile time constant");
5586                 break;
5587             }
5588
5589             if (var->hasvalue) {
5590                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5591                                     "builtin `%s` has already been defined\n"
5592                                     " -> previous declaration here: %s:%i",
5593                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5594             }
5595             else
5596             {
5597                 func = ast_function_new(ast_ctx(var), var->name, var);
5598                 if (!func) {
5599                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5600                     break;
5601                 }
5602                 vec_push(parser->functions, func);
5603
5604                 func->builtin = -builtin_num-1;
5605             }
5606
5607             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5608                     ? (parser->tok != ',' && parser->tok != ';')
5609                     : (!parser_next(parser)))
5610             {
5611                 parseerror(parser, "expected comma or semicolon");
5612                 if (func)
5613                     ast_function_delete(func);
5614                 var->constval.vfunc = NULL;
5615                 break;
5616             }
5617         }
5618         else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5619         {
5620             if (localblock) {
5621                 /* Note that fteqcc and most others don't even *have*
5622                  * local arrays, so this is not a high priority.
5623                  */
5624                 parseerror(parser, "TODO: initializers for local arrays");
5625                 break;
5626             }
5627
5628             var->hasvalue = true;
5629             if (!parse_array(parser, var))
5630                 break;
5631         }
5632         else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5633         {
5634             if (localblock) {
5635                 parseerror(parser, "cannot declare functions within functions");
5636                 break;
5637             }
5638
5639             if (proto)
5640                 ast_ctx(proto) = parser_ctx(parser);
5641
5642             if (!parse_function_body(parser, var))
5643                 break;
5644             ast_delete(basetype);
5645             for (i = 0; i < vec_size(parser->gotos); ++i)
5646                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5647             vec_free(parser->gotos);
5648             vec_free(parser->labels);
5649             return true;
5650         } else {
5651             ast_expression *cexp;
5652             ast_value      *cval;
5653
5654             cexp = parse_expression_leave(parser, true, false, false);
5655             if (!cexp)
5656                 break;
5657
5658             if (!localblock) {
5659                 cval = (ast_value*)cexp;
5660                 if (cval != parser->nil &&
5661                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5662                    )
5663                 {
5664                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5665                 }
5666                 else
5667                 {
5668                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5669                         qualifier != CV_VAR)
5670                     {
5671                         var->cvq = CV_CONST;
5672                     }
5673                     if (cval == parser->nil)
5674                         var->expression.flags |= AST_FLAG_INITIALIZED;
5675                     else
5676                     {
5677                         var->hasvalue = true;
5678                         if (cval->expression.vtype == TYPE_STRING)
5679                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5680                         else if (cval->expression.vtype == TYPE_FIELD)
5681                             var->constval.vfield = cval;
5682                         else
5683                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5684                         ast_unref(cval);
5685                     }
5686                 }
5687             } else {
5688                 int cvq;
5689                 shunt sy = { NULL, NULL, NULL, NULL };
5690                 cvq = var->cvq;
5691                 var->cvq = CV_NONE;
5692                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5693                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5694                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5695                 if (!parser_sy_apply_operator(parser, &sy))
5696                     ast_unref(cexp);
5697                 else {
5698                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5699                         parseerror(parser, "internal error: leaked operands");
5700                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5701                         break;
5702                 }
5703                 vec_free(sy.out);
5704                 vec_free(sy.ops);
5705                 vec_free(sy.argc);
5706                 var->cvq = cvq;
5707             }
5708         }
5709
5710 another:
5711         if (parser->tok == ',') {
5712             if (!parser_next(parser)) {
5713                 parseerror(parser, "expected another variable");
5714                 break;
5715             }
5716
5717             if (parser->tok != TOKEN_IDENT) {
5718                 parseerror(parser, "expected another variable");
5719                 break;
5720             }
5721             var = ast_value_copy(basetype);
5722             cleanvar = true;
5723             ast_value_set_name(var, parser_tokval(parser));
5724             if (!parser_next(parser)) {
5725                 parseerror(parser, "error parsing variable declaration");
5726                 break;
5727             }
5728             continue;
5729         }
5730
5731         if (parser->tok != ';') {
5732             parseerror(parser, "missing semicolon after variables");
5733             break;
5734         }
5735
5736         if (!parser_next(parser)) {
5737             parseerror(parser, "parse error after variable declaration");
5738             break;
5739         }
5740
5741         ast_delete(basetype);
5742         return true;
5743     }
5744
5745     if (cleanvar && var)
5746         ast_delete(var);
5747     ast_delete(basetype);
5748     return false;
5749
5750 cleanup:
5751     ast_delete(basetype);
5752     if (cleanvar && var)
5753         ast_delete(var);
5754     if (me[0]) ast_member_delete(me[0]);
5755     if (me[1]) ast_member_delete(me[1]);
5756     if (me[2]) ast_member_delete(me[2]);
5757     return retval;
5758 }
5759
5760 static bool parser_global_statement(parser_t *parser)
5761 {
5762     int        cvq       = CV_WRONG;
5763     bool       noref     = false;
5764     bool       is_static = false;
5765     uint32_t   qflags    = 0;
5766     ast_value *istype    = NULL;
5767     char      *vstring   = NULL;
5768
5769     if (parser->tok == TOKEN_IDENT)
5770         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5771
5772     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5773     {
5774         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5775     }
5776     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5777     {
5778         if (cvq == CV_WRONG)
5779             return false;
5780         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5781     }
5782     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5783     {
5784         return parse_enum(parser);
5785     }
5786     else if (parser->tok == TOKEN_KEYWORD)
5787     {
5788         if (!strcmp(parser_tokval(parser), "typedef")) {
5789             if (!parser_next(parser)) {
5790                 parseerror(parser, "expected type definition after 'typedef'");
5791                 return false;
5792             }
5793             return parse_typedef(parser);
5794         }
5795         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5796         return false;
5797     }
5798     else if (parser->tok == '#')
5799     {
5800         return parse_pragma(parser);
5801     }
5802     else if (parser->tok == '$')
5803     {
5804         if (!parser_next(parser)) {
5805             parseerror(parser, "parse error");
5806             return false;
5807         }
5808     }
5809     else
5810     {
5811         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5812         return false;
5813     }
5814     return true;
5815 }
5816
5817 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5818 {
5819     return util_crc16(old, str, strlen(str));
5820 }
5821
5822 static void progdefs_crc_file(const char *str)
5823 {
5824     /* write to progdefs.h here */
5825     (void)str;
5826 }
5827
5828 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5829 {
5830     old = progdefs_crc_sum(old, str);
5831     progdefs_crc_file(str);
5832     return old;
5833 }
5834
5835 static void generate_checksum(parser_t *parser, ir_builder *ir)
5836 {
5837     uint16_t   crc = 0xFFFF;
5838     size_t     i;
5839     ast_value *value;
5840
5841     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5842     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5843     /*
5844     progdefs_crc_file("\tint\tpad;\n");
5845     progdefs_crc_file("\tint\tofs_return[3];\n");
5846     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5847     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5848     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5849     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5850     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5851     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5852     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5853     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5854     */
5855     for (i = 0; i < parser->crc_globals; ++i) {
5856         if (!ast_istype(parser->globals[i], ast_value))
5857             continue;
5858         value = (ast_value*)(parser->globals[i]);
5859         switch (value->expression.vtype) {
5860             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5861             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5862             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5863             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5864             default:
5865                 crc = progdefs_crc_both(crc, "\tint\t");
5866                 break;
5867         }
5868         crc = progdefs_crc_both(crc, value->name);
5869         crc = progdefs_crc_both(crc, ";\n");
5870     }
5871     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5872     for (i = 0; i < parser->crc_fields; ++i) {
5873         if (!ast_istype(parser->fields[i], ast_value))
5874             continue;
5875         value = (ast_value*)(parser->fields[i]);
5876         switch (value->expression.next->vtype) {
5877             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5878             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5879             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5880             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5881             default:
5882                 crc = progdefs_crc_both(crc, "\tint\t");
5883                 break;
5884         }
5885         crc = progdefs_crc_both(crc, value->name);
5886         crc = progdefs_crc_both(crc, ";\n");
5887     }
5888     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5889     ir->code->crc = crc;
5890 }
5891
5892 parser_t *parser_create()
5893 {
5894     parser_t *parser;
5895     lex_ctx_t empty_ctx;
5896     size_t i;
5897
5898     parser = (parser_t*)mem_a(sizeof(parser_t));
5899     if (!parser)
5900         return NULL;
5901
5902     memset(parser, 0, sizeof(*parser));
5903
5904     for (i = 0; i < operator_count; ++i) {
5905         if (operators[i].id == opid1('=')) {
5906             parser->assign_op = operators+i;
5907             break;
5908         }
5909     }
5910     if (!parser->assign_op) {
5911         printf("internal error: initializing parser: failed to find assign operator\n");
5912         mem_d(parser);
5913         return NULL;
5914     }
5915
5916     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5917     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5918     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5919     vec_push(parser->_blocktypedefs, 0);
5920
5921     parser->aliases = util_htnew(PARSER_HT_SIZE);
5922
5923     /* corrector */
5924     vec_push(parser->correct_variables, correct_trie_new());
5925     vec_push(parser->correct_variables_score, NULL);
5926
5927     empty_ctx.file   = "<internal>";
5928     empty_ctx.line   = 0;
5929     empty_ctx.column = 0;
5930     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5931     parser->nil->cvq = CV_CONST;
5932     if (OPTS_FLAG(UNTYPED_NIL))
5933         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5934
5935     parser->max_param_count = 1;
5936
5937     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5938     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5939     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5940
5941     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5942         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5943         parser->reserved_version->cvq = CV_CONST;
5944         parser->reserved_version->hasvalue = true;
5945         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5946         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5947     } else {
5948         parser->reserved_version = NULL;
5949     }
5950
5951     parser->fold   = fold_init  (parser);
5952     parser->intrin = intrin_init(parser);
5953     return parser;
5954 }
5955
5956 static bool parser_compile(parser_t *parser)
5957 {
5958     /* initial lexer/parser state */
5959     parser->lex->flags.noops = true;
5960
5961     if (parser_next(parser))
5962     {
5963         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5964         {
5965             if (!parser_global_statement(parser)) {
5966                 if (parser->tok == TOKEN_EOF)
5967                     parseerror(parser, "unexpected end of file");
5968                 else if (compile_errors)
5969                     parseerror(parser, "there have been errors, bailing out");
5970                 lex_close(parser->lex);
5971                 parser->lex = NULL;
5972                 return false;
5973             }
5974         }
5975     } else {
5976         parseerror(parser, "parse error");
5977         lex_close(parser->lex);
5978         parser->lex = NULL;
5979         return false;
5980     }
5981
5982     lex_close(parser->lex);
5983     parser->lex = NULL;
5984
5985     return !compile_errors;
5986 }
5987
5988 bool parser_compile_file(parser_t *parser, const char *filename)
5989 {
5990     parser->lex = lex_open(filename);
5991     if (!parser->lex) {
5992         con_err("failed to open file \"%s\"\n", filename);
5993         return false;
5994     }
5995     return parser_compile(parser);
5996 }
5997
5998 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5999 {
6000     parser->lex = lex_open_string(str, len, name);
6001     if (!parser->lex) {
6002         con_err("failed to create lexer for string \"%s\"\n", name);
6003         return false;
6004     }
6005     return parser_compile(parser);
6006 }
6007
6008 static void parser_remove_ast(parser_t *parser)
6009 {
6010     size_t i;
6011     if (parser->ast_cleaned)
6012         return;
6013     parser->ast_cleaned = true;
6014     for (i = 0; i < vec_size(parser->accessors); ++i) {
6015         ast_delete(parser->accessors[i]->constval.vfunc);
6016         parser->accessors[i]->constval.vfunc = NULL;
6017         ast_delete(parser->accessors[i]);
6018     }
6019     for (i = 0; i < vec_size(parser->functions); ++i) {
6020         ast_delete(parser->functions[i]);
6021     }
6022     for (i = 0; i < vec_size(parser->fields); ++i) {
6023         ast_delete(parser->fields[i]);
6024     }
6025     for (i = 0; i < vec_size(parser->globals); ++i) {
6026         ast_delete(parser->globals[i]);
6027     }
6028     vec_free(parser->accessors);
6029     vec_free(parser->functions);
6030     vec_free(parser->globals);
6031     vec_free(parser->fields);
6032
6033     for (i = 0; i < vec_size(parser->variables); ++i)
6034         util_htdel(parser->variables[i]);
6035     vec_free(parser->variables);
6036     vec_free(parser->_blocklocals);
6037     vec_free(parser->_locals);
6038
6039     /* corrector */
6040     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6041         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6042     }
6043     vec_free(parser->correct_variables);
6044     vec_free(parser->correct_variables_score);
6045
6046     for (i = 0; i < vec_size(parser->_typedefs); ++i)
6047         ast_delete(parser->_typedefs[i]);
6048     vec_free(parser->_typedefs);
6049     for (i = 0; i < vec_size(parser->typedefs); ++i)
6050         util_htdel(parser->typedefs[i]);
6051     vec_free(parser->typedefs);
6052     vec_free(parser->_blocktypedefs);
6053
6054     vec_free(parser->_block_ctx);
6055
6056     vec_free(parser->labels);
6057     vec_free(parser->gotos);
6058     vec_free(parser->breaks);
6059     vec_free(parser->continues);
6060
6061     ast_value_delete(parser->nil);
6062
6063     ast_value_delete(parser->const_vec[0]);
6064     ast_value_delete(parser->const_vec[1]);
6065     ast_value_delete(parser->const_vec[2]);
6066
6067     if (parser->reserved_version)
6068         ast_value_delete(parser->reserved_version);
6069
6070     util_htdel(parser->aliases);
6071     fold_cleanup(parser->fold);
6072     intrin_cleanup(parser->intrin);
6073 }
6074
6075 void parser_cleanup(parser_t *parser)
6076 {
6077     parser_remove_ast(parser);
6078     mem_d(parser);
6079 }
6080
6081 bool parser_finish(parser_t *parser, const char *output)
6082 {
6083     size_t i;
6084     ir_builder *ir;
6085     bool retval = true;
6086
6087     if (compile_errors) {
6088         con_out("*** there were compile errors\n");
6089         return false;
6090     }
6091
6092     ir = ir_builder_new("gmqcc_out");
6093     if (!ir) {
6094         con_out("failed to allocate builder\n");
6095         return false;
6096     }
6097
6098     for (i = 0; i < vec_size(parser->fields); ++i) {
6099         ast_value *field;
6100         bool hasvalue;
6101         if (!ast_istype(parser->fields[i], ast_value))
6102             continue;
6103         field = (ast_value*)parser->fields[i];
6104         hasvalue = field->hasvalue;
6105         field->hasvalue = false;
6106         if (!ast_global_codegen((ast_value*)field, ir, true)) {
6107             con_out("failed to generate field %s\n", field->name);
6108             ir_builder_delete(ir);
6109             return false;
6110         }
6111         if (hasvalue) {
6112             ir_value *ifld;
6113             ast_expression *subtype;
6114             field->hasvalue = true;
6115             subtype = field->expression.next;
6116             ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6117             if (subtype->vtype == TYPE_FIELD)
6118                 ifld->fieldtype = subtype->next->vtype;
6119             else if (subtype->vtype == TYPE_FUNCTION)
6120                 ifld->outtype = subtype->next->vtype;
6121             (void)!ir_value_set_field(field->ir_v, ifld);
6122         }
6123     }
6124     for (i = 0; i < vec_size(parser->globals); ++i) {
6125         ast_value *asvalue;
6126         if (!ast_istype(parser->globals[i], ast_value))
6127             continue;
6128         asvalue = (ast_value*)(parser->globals[i]);
6129         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6130             retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6131                                                 "unused global: `%s`", asvalue->name);
6132         }
6133         if (!ast_global_codegen(asvalue, ir, false)) {
6134             con_out("failed to generate global %s\n", asvalue->name);
6135             ir_builder_delete(ir);
6136             return false;
6137         }
6138     }
6139     /* Build function vararg accessor ast tree now before generating
6140      * immediates, because the accessors may add new immediates
6141      */
6142     for (i = 0; i < vec_size(parser->functions); ++i) {
6143         ast_function *f = parser->functions[i];
6144         if (f->varargs) {
6145             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6146                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6147                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6148                     con_out("failed to generate vararg setter for %s\n", f->name);
6149                     ir_builder_delete(ir);
6150                     return false;
6151                 }
6152                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6153                     con_out("failed to generate vararg getter for %s\n", f->name);
6154                     ir_builder_delete(ir);
6155                     return false;
6156                 }
6157             } else {
6158                 ast_delete(f->varargs);
6159                 f->varargs = NULL;
6160             }
6161         }
6162     }
6163     /* Now we can generate immediates */
6164     if (!fold_generate(parser->fold, ir))
6165         return false;
6166
6167     for (i = 0; i < vec_size(parser->globals); ++i) {
6168         ast_value *asvalue;
6169         if (!ast_istype(parser->globals[i], ast_value))
6170             continue;
6171         asvalue = (ast_value*)(parser->globals[i]);
6172         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6173         {
6174             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6175                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6176                                        "uninitialized constant: `%s`",
6177                                        asvalue->name);
6178             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6179                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6180                                        "uninitialized global: `%s`",
6181                                        asvalue->name);
6182         }
6183         if (!ast_generate_accessors(asvalue, ir)) {
6184             ir_builder_delete(ir);
6185             return false;
6186         }
6187     }
6188     for (i = 0; i < vec_size(parser->fields); ++i) {
6189         ast_value *asvalue;
6190         asvalue = (ast_value*)(parser->fields[i]->next);
6191
6192         if (!ast_istype((ast_expression*)asvalue, ast_value))
6193             continue;
6194         if (asvalue->expression.vtype != TYPE_ARRAY)
6195             continue;
6196         if (!ast_generate_accessors(asvalue, ir)) {
6197             ir_builder_delete(ir);
6198             return false;
6199         }
6200     }
6201     if (parser->reserved_version &&
6202         !ast_global_codegen(parser->reserved_version, ir, false))
6203     {
6204         con_out("failed to generate reserved::version");
6205         ir_builder_delete(ir);
6206         return false;
6207     }
6208     for (i = 0; i < vec_size(parser->functions); ++i) {
6209         ast_function *f = parser->functions[i];
6210         if (!ast_function_codegen(f, ir)) {
6211             con_out("failed to generate function %s\n", f->name);
6212             ir_builder_delete(ir);
6213             return false;
6214         }
6215     }
6216
6217     generate_checksum(parser, ir);
6218
6219     if (OPTS_OPTION_BOOL(OPTION_DUMP))
6220         ir_builder_dump(ir, con_out);
6221     for (i = 0; i < vec_size(parser->functions); ++i) {
6222         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6223             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6224             ir_builder_delete(ir);
6225             return false;
6226         }
6227     }
6228     parser_remove_ast(parser);
6229
6230     if (compile_Werrors) {
6231         con_out("*** there were warnings treated as errors\n");
6232         compile_show_werrors();
6233         retval = false;
6234     }
6235
6236     if (retval) {
6237         if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6238             ir_builder_dump(ir, con_out);
6239
6240         if (!ir_builder_generate(ir, output)) {
6241             con_out("*** failed to generate output file\n");
6242             ir_builder_delete(ir);
6243             return false;
6244         }
6245     }
6246     ir_builder_delete(ir);
6247     return retval;
6248 }