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