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