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