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