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