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