]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Resolve undefined functions to compiler builtins if they exist.
[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             char *tryintrinsic = NULL;
1579
1580             /*
1581              * now we try for the real intrinsic hashtable. If the string
1582              * begins with __builtin, we simply skip past it, otherwise we
1583              * use the identifier as is.
1584              */
1585             if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1586                 var = intrin_func(parser->intrin, parser_tokval(parser));
1587             }
1588
1589             /*
1590              * Try it as an instruction by appending __builtin_ to the token
1591              * and emit a warning if an intrinsic function matching that
1592              * name exists.
1593              */
1594             if (!var) {
1595                 util_asprintf(&tryintrinsic, "__builtin_%s", parser_tokval(parser));
1596                 if ((var = intrin_func(parser->intrin, tryintrinsic))) {
1597                     (void)!!compile_warning(
1598                         parser_ctx(parser),
1599                         WARN_BUILTINS,
1600                         "using implicitly defined builtin `%s' for `%s'",
1601                         tryintrinsic,
1602                         parser_tokval(parser)
1603                     );
1604                 }
1605                 mem_d(tryintrinsic);
1606             }
1607
1608
1609             if (!var) {
1610                 char *correct = NULL;
1611                 size_t i;
1612
1613                 /*
1614                  * sometimes people use preprocessing predefs without enabling them
1615                  * i've done this thousands of times already myself.  Lets check for
1616                  * it in the predef table.  And diagnose it better :)
1617                  */
1618                 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1619                     parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1620                     return false;
1621                 }
1622
1623                 /*
1624                  * TODO: determine the best score for the identifier: be it
1625                  * a variable, a field.
1626                  *
1627                  * We should also consider adding correction tables for
1628                  * other things as well.
1629                  */
1630                 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1631                     correction_t corr;
1632                     correct_init(&corr);
1633
1634                     for (i = 0; i < vec_size(parser->correct_variables); i++) {
1635                         correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1636                         if (strcmp(correct, parser_tokval(parser))) {
1637                             break;
1638                         } else  {
1639                             mem_d(correct);
1640                             correct = NULL;
1641                         }
1642                     }
1643                     correct_free(&corr);
1644
1645                     if (correct) {
1646                         parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1647                         mem_d(correct);
1648                         return false;
1649                     }
1650                 }
1651                 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1652                 return false;
1653             }
1654         }
1655         else
1656         {
1657             if (ast_istype(var, ast_value)) {
1658                 ((ast_value*)var)->uses++;
1659             }
1660             else if (ast_istype(var, ast_member)) {
1661                 ast_member *mem = (ast_member*)var;
1662                 if (ast_istype(mem->owner, ast_value))
1663                     ((ast_value*)(mem->owner))->uses++;
1664             }
1665         }
1666         vec_push(sy->out, syexp(parser_ctx(parser), var));
1667         return true;
1668     }
1669     parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1670     return false;
1671 }
1672
1673 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1674 {
1675     ast_expression *expr = NULL;
1676     shunt sy;
1677     size_t i;
1678     bool wantop = false;
1679     /* only warn once about an assignment in a truth value because the current code
1680      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1681      */
1682     bool warn_parenthesis = true;
1683
1684     /* count the parens because an if starts with one, so the
1685      * end of a condition is an unmatched closing paren
1686      */
1687     int ternaries = 0;
1688
1689     memset(&sy, 0, sizeof(sy));
1690
1691     parser->lex->flags.noops = false;
1692
1693     parser_reclassify_token(parser);
1694
1695     while (true)
1696     {
1697         if (parser->tok == TOKEN_TYPENAME) {
1698             parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1699             goto onerr;
1700         }
1701
1702         if (parser->tok == TOKEN_OPERATOR)
1703         {
1704             /* classify the operator */
1705             const oper_info *op;
1706             const oper_info *olast = NULL;
1707             size_t o;
1708             for (o = 0; o < operator_count; ++o) {
1709                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1710                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1711                     !strcmp(parser_tokval(parser), operators[o].op))
1712                 {
1713                     break;
1714                 }
1715             }
1716             if (o == operator_count) {
1717                 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1718                 goto onerr;
1719             }
1720             /* found an operator */
1721             op = &operators[o];
1722
1723             /* when declaring variables, a comma starts a new variable */
1724             if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1725                 /* fixup the token */
1726                 parser->tok = ',';
1727                 break;
1728             }
1729
1730             /* a colon without a pervious question mark cannot be a ternary */
1731             if (!ternaries && op->id == opid2(':','?')) {
1732                 parser->tok = ':';
1733                 break;
1734             }
1735
1736             if (op->id == opid1(',')) {
1737                 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1738                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1739                 }
1740             }
1741
1742             if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1743                 olast = &operators[vec_last(sy.ops).etype-1];
1744
1745             /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1746             while (olast && op->prec < olast->prec)
1747             {
1748                 if (!parser_sy_apply_operator(parser, &sy))
1749                     goto onerr;
1750                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1751                     olast = &operators[vec_last(sy.ops).etype-1];
1752                 else
1753                     olast = NULL;
1754             }
1755
1756 #define IsAssignOp(x) (\
1757                 (x) == opid1('=') || \
1758                 (x) == opid2('+','=') || \
1759                 (x) == opid2('-','=') || \
1760                 (x) == opid2('*','=') || \
1761                 (x) == opid2('/','=') || \
1762                 (x) == opid2('%','=') || \
1763                 (x) == opid2('&','=') || \
1764                 (x) == opid2('|','=') || \
1765                 (x) == opid3('&','~','=') \
1766                 )
1767             if (warn_parenthesis) {
1768                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1769                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1770                      (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1771                    )
1772                 {
1773                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1774                     warn_parenthesis = false;
1775                 }
1776
1777                 if (olast && olast->id != op->id) {
1778                     if ((op->id    == opid1('&') || op->id    == opid1('|') || op->id    == opid1('^')) &&
1779                         (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1780                     {
1781                         (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1782                         warn_parenthesis = false;
1783                     }
1784                     else if ((op->id    == opid2('&','&') || op->id    == opid2('|','|')) &&
1785                              (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1786                     {
1787                         (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1788                         warn_parenthesis = false;
1789                     }
1790                 }
1791             }
1792
1793             while (olast && (
1794                     (op->prec < olast->prec) ||
1795                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1796             {
1797                 if (!parser_sy_apply_operator(parser, &sy))
1798                     goto onerr;
1799                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1800                     olast = &operators[vec_last(sy.ops).etype-1];
1801                 else
1802                     olast = NULL;
1803             }
1804
1805             if (op->id == opid1('(')) {
1806                 if (wantop) {
1807                     size_t sycount = vec_size(sy.out);
1808                     /* we expected an operator, this is the function-call operator */
1809                     vec_push(sy.paren, PAREN_FUNC);
1810                     vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1811                     vec_push(sy.argc, 0);
1812                 } else {
1813                     vec_push(sy.paren, PAREN_EXPR);
1814                     vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1815                 }
1816                 wantop = false;
1817             } else if (op->id == opid1('[')) {
1818                 if (!wantop) {
1819                     parseerror(parser, "unexpected array subscript");
1820                     goto onerr;
1821                 }
1822                 vec_push(sy.paren, PAREN_INDEX);
1823                 /* push both the operator and the paren, this makes life easier */
1824                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1825                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1826                 wantop = false;
1827             } else if (op->id == opid2('?',':')) {
1828                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1829                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1830                 wantop = false;
1831                 ++ternaries;
1832                 vec_push(sy.paren, PAREN_TERNARY1);
1833             } else if (op->id == opid2(':','?')) {
1834                 if (!vec_size(sy.paren)) {
1835                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1836                     goto onerr;
1837                 }
1838                 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1839                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1840                     goto onerr;
1841                 }
1842                 if (!parser_close_paren(parser, &sy))
1843                     goto onerr;
1844                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1845                 wantop = false;
1846                 --ternaries;
1847             } else {
1848                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1849                 wantop = !!(op->flags & OP_SUFFIX);
1850             }
1851         }
1852         else if (parser->tok == ')') {
1853             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1854                 if (!parser_sy_apply_operator(parser, &sy))
1855                     goto onerr;
1856             }
1857             if (!vec_size(sy.paren))
1858                 break;
1859             if (wantop) {
1860                 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1861                     parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1862                     goto onerr;
1863                 }
1864                 if (!parser_close_paren(parser, &sy))
1865                     goto onerr;
1866             } else {
1867                 /* must be a function call without parameters */
1868                 if (vec_last(sy.paren) != PAREN_FUNC) {
1869                     parseerror(parser, "closing paren in invalid position");
1870                     goto onerr;
1871                 }
1872                 if (!parser_close_paren(parser, &sy))
1873                     goto onerr;
1874             }
1875             wantop = true;
1876         }
1877         else if (parser->tok == '(') {
1878             parseerror(parser, "internal error: '(' should be classified as operator");
1879             goto onerr;
1880         }
1881         else if (parser->tok == '[') {
1882             parseerror(parser, "internal error: '[' should be classified as operator");
1883             goto onerr;
1884         }
1885         else if (parser->tok == ']') {
1886             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1887                 if (!parser_sy_apply_operator(parser, &sy))
1888                     goto onerr;
1889             }
1890             if (!vec_size(sy.paren))
1891                 break;
1892             if (vec_last(sy.paren) != PAREN_INDEX) {
1893                 parseerror(parser, "mismatched parentheses, unexpected ']'");
1894                 goto onerr;
1895             }
1896             if (!parser_close_paren(parser, &sy))
1897                 goto onerr;
1898             wantop = true;
1899         }
1900         else if (!wantop) {
1901             if (!parse_sya_operand(parser, &sy, with_labels))
1902                 goto onerr;
1903 #if 0
1904             if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1905                 vec_last(sy.argc)++;
1906 #endif
1907             wantop = true;
1908         }
1909         else {
1910             /* in this case we might want to allow constant string concatenation */
1911             bool concatenated = false;
1912             if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1913                 ast_expression *lexpr = vec_last(sy.out).out;
1914                 if (ast_istype(lexpr, ast_value)) {
1915                     ast_value *last = (ast_value*)lexpr;
1916                     if (last->isimm == true && last->cvq == CV_CONST &&
1917                         last->hasvalue && last->expression.vtype == TYPE_STRING)
1918                     {
1919                         char *newstr = NULL;
1920                         util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1921                         vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1922                         mem_d(newstr);
1923                         concatenated = true;
1924                     }
1925                 }
1926             }
1927             if (!concatenated) {
1928                 parseerror(parser, "expected operator or end of statement");
1929                 goto onerr;
1930             }
1931         }
1932
1933         if (!parser_next(parser)) {
1934             goto onerr;
1935         }
1936         if (parser->tok == ';' ||
1937             ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1938             (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1939         {
1940             break;
1941         }
1942     }
1943
1944     while (vec_size(sy.ops)) {
1945         if (!parser_sy_apply_operator(parser, &sy))
1946             goto onerr;
1947     }
1948
1949     parser->lex->flags.noops = true;
1950     if (vec_size(sy.out) != 1) {
1951         parseerror(parser, "expression expected");
1952         expr = NULL;
1953     } else
1954         expr = sy.out[0].out;
1955     vec_free(sy.out);
1956     vec_free(sy.ops);
1957     if (vec_size(sy.paren)) {
1958         parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1959         return NULL;
1960     }
1961     vec_free(sy.paren);
1962     vec_free(sy.argc);
1963     return expr;
1964
1965 onerr:
1966     parser->lex->flags.noops = true;
1967     for (i = 0; i < vec_size(sy.out); ++i) {
1968         if (sy.out[i].out)
1969             ast_unref(sy.out[i].out);
1970     }
1971     vec_free(sy.out);
1972     vec_free(sy.ops);
1973     vec_free(sy.paren);
1974     vec_free(sy.argc);
1975     return NULL;
1976 }
1977
1978 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1979 {
1980     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1981     if (!e)
1982         return NULL;
1983     if (parser->tok != ';') {
1984         parseerror(parser, "semicolon expected after expression");
1985         ast_unref(e);
1986         return NULL;
1987     }
1988     if (!parser_next(parser)) {
1989         ast_unref(e);
1990         return NULL;
1991     }
1992     return e;
1993 }
1994
1995 static void parser_enterblock(parser_t *parser)
1996 {
1997     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1998     vec_push(parser->_blocklocals, vec_size(parser->_locals));
1999     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2000     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2001     vec_push(parser->_block_ctx, parser_ctx(parser));
2002
2003     /* corrector */
2004     vec_push(parser->correct_variables, correct_trie_new());
2005     vec_push(parser->correct_variables_score, NULL);
2006 }
2007
2008 static bool parser_leaveblock(parser_t *parser)
2009 {
2010     bool   rv = true;
2011     size_t locals, typedefs;
2012
2013     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2014         parseerror(parser, "internal error: parser_leaveblock with no block");
2015         return false;
2016     }
2017
2018     util_htdel(vec_last(parser->variables));
2019     correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2020
2021     vec_pop(parser->variables);
2022     vec_pop(parser->correct_variables);
2023     vec_pop(parser->correct_variables_score);
2024     if (!vec_size(parser->_blocklocals)) {
2025         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2026         return false;
2027     }
2028
2029     locals = vec_last(parser->_blocklocals);
2030     vec_pop(parser->_blocklocals);
2031     while (vec_size(parser->_locals) != locals) {
2032         ast_expression *e = vec_last(parser->_locals);
2033         ast_value      *v = (ast_value*)e;
2034         vec_pop(parser->_locals);
2035         if (ast_istype(e, ast_value) && !v->uses) {
2036             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2037                 rv = false;
2038         }
2039     }
2040
2041     typedefs = vec_last(parser->_blocktypedefs);
2042     while (vec_size(parser->_typedefs) != typedefs) {
2043         ast_delete(vec_last(parser->_typedefs));
2044         vec_pop(parser->_typedefs);
2045     }
2046     util_htdel(vec_last(parser->typedefs));
2047     vec_pop(parser->typedefs);
2048
2049     vec_pop(parser->_block_ctx);
2050
2051     return rv;
2052 }
2053
2054 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2055 {
2056     vec_push(parser->_locals, e);
2057     util_htset(vec_last(parser->variables), name, (void*)e);
2058
2059     /* corrector */
2060     correct_add (
2061          vec_last(parser->correct_variables),
2062         &vec_last(parser->correct_variables_score),
2063         name
2064     );
2065 }
2066
2067 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2068 {
2069     vec_push(parser->globals, e);
2070     util_htset(parser->htglobals, name, e);
2071
2072     /* corrector */
2073     correct_add (
2074          parser->correct_variables[0],
2075         &parser->correct_variables_score[0],
2076         name
2077     );
2078 }
2079
2080 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2081 {
2082     bool       ifnot = false;
2083     ast_unary *unary;
2084     ast_expression *prev;
2085
2086     if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2087         char ty[1024];
2088         ast_type_to_string(cond, ty, sizeof(ty));
2089         compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2090     }
2091
2092     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2093     {
2094         prev = cond;
2095         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2096         if (!cond) {
2097             ast_unref(prev);
2098             parseerror(parser, "internal error: failed to process condition");
2099             return NULL;
2100         }
2101         ifnot = !ifnot;
2102     }
2103     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2104     {
2105         /* vector types need to be cast to true booleans */
2106         ast_binary *bin = (ast_binary*)cond;
2107         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2108         {
2109             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2110             prev = cond;
2111             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2112             if (!cond) {
2113                 ast_unref(prev);
2114                 parseerror(parser, "internal error: failed to process condition");
2115                 return NULL;
2116             }
2117             ifnot = !ifnot;
2118         }
2119     }
2120
2121     unary = (ast_unary*)cond;
2122     /* ast_istype dereferences cond, should test here for safety */
2123     while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2124     {
2125         cond = unary->operand;
2126         unary->operand = NULL;
2127         ast_delete(unary);
2128         ifnot = !ifnot;
2129         unary = (ast_unary*)cond;
2130     }
2131
2132     if (!cond)
2133         parseerror(parser, "internal error: failed to process condition");
2134
2135     if (ifnot) *_ifnot = !*_ifnot;
2136     return cond;
2137 }
2138
2139 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2140 {
2141     ast_ifthen *ifthen;
2142     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2143     bool ifnot = false;
2144
2145     lex_ctx_t ctx = parser_ctx(parser);
2146
2147     (void)block; /* not touching */
2148
2149     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2150     if (!parser_next(parser)) {
2151         parseerror(parser, "expected condition or 'not'");
2152         return false;
2153     }
2154     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2155         ifnot = true;
2156         if (!parser_next(parser)) {
2157             parseerror(parser, "expected condition in parenthesis");
2158             return false;
2159         }
2160     }
2161     if (parser->tok != '(') {
2162         parseerror(parser, "expected 'if' condition in parenthesis");
2163         return false;
2164     }
2165     /* parse into the expression */
2166     if (!parser_next(parser)) {
2167         parseerror(parser, "expected 'if' condition after opening paren");
2168         return false;
2169     }
2170     /* parse the condition */
2171     cond = parse_expression_leave(parser, false, true, false);
2172     if (!cond)
2173         return false;
2174     /* closing paren */
2175     if (parser->tok != ')') {
2176         parseerror(parser, "expected closing paren after 'if' condition");
2177         ast_unref(cond);
2178         return false;
2179     }
2180     /* parse into the 'then' branch */
2181     if (!parser_next(parser)) {
2182         parseerror(parser, "expected statement for on-true branch of 'if'");
2183         ast_unref(cond);
2184         return false;
2185     }
2186     if (!parse_statement_or_block(parser, &ontrue)) {
2187         ast_unref(cond);
2188         return false;
2189     }
2190     if (!ontrue)
2191         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2192     /* check for an else */
2193     if (!strcmp(parser_tokval(parser), "else")) {
2194         /* parse into the 'else' branch */
2195         if (!parser_next(parser)) {
2196             parseerror(parser, "expected on-false branch after 'else'");
2197             ast_delete(ontrue);
2198             ast_unref(cond);
2199             return false;
2200         }
2201         if (!parse_statement_or_block(parser, &onfalse)) {
2202             ast_delete(ontrue);
2203             ast_unref(cond);
2204             return false;
2205         }
2206     }
2207
2208     cond = process_condition(parser, cond, &ifnot);
2209     if (!cond) {
2210         if (ontrue)  ast_delete(ontrue);
2211         if (onfalse) ast_delete(onfalse);
2212         return false;
2213     }
2214
2215     if (ifnot)
2216         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2217     else
2218         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2219     *out = (ast_expression*)ifthen;
2220     return true;
2221 }
2222
2223 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2224 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2225 {
2226     bool rv;
2227     char *label = NULL;
2228
2229     /* skip the 'while' and get the body */
2230     if (!parser_next(parser)) {
2231         if (OPTS_FLAG(LOOP_LABELS))
2232             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2233         else
2234             parseerror(parser, "expected 'while' condition in parenthesis");
2235         return false;
2236     }
2237
2238     if (parser->tok == ':') {
2239         if (!OPTS_FLAG(LOOP_LABELS))
2240             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2241         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2242             parseerror(parser, "expected loop label");
2243             return false;
2244         }
2245         label = util_strdup(parser_tokval(parser));
2246         if (!parser_next(parser)) {
2247             mem_d(label);
2248             parseerror(parser, "expected 'while' condition in parenthesis");
2249             return false;
2250         }
2251     }
2252
2253     if (parser->tok != '(') {
2254         parseerror(parser, "expected 'while' condition in parenthesis");
2255         return false;
2256     }
2257
2258     vec_push(parser->breaks, label);
2259     vec_push(parser->continues, label);
2260
2261     rv = parse_while_go(parser, block, out);
2262     if (label)
2263         mem_d(label);
2264     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2265         parseerror(parser, "internal error: label stack corrupted");
2266         rv = false;
2267         ast_delete(*out);
2268         *out = NULL;
2269     }
2270     else {
2271         vec_pop(parser->breaks);
2272         vec_pop(parser->continues);
2273     }
2274     return rv;
2275 }
2276
2277 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2278 {
2279     ast_loop *aloop;
2280     ast_expression *cond, *ontrue;
2281
2282     bool ifnot = false;
2283
2284     lex_ctx_t ctx = parser_ctx(parser);
2285
2286     (void)block; /* not touching */
2287
2288     /* parse into the expression */
2289     if (!parser_next(parser)) {
2290         parseerror(parser, "expected 'while' condition after opening paren");
2291         return false;
2292     }
2293     /* parse the condition */
2294     cond = parse_expression_leave(parser, false, true, false);
2295     if (!cond)
2296         return false;
2297     /* closing paren */
2298     if (parser->tok != ')') {
2299         parseerror(parser, "expected closing paren after 'while' condition");
2300         ast_unref(cond);
2301         return false;
2302     }
2303     /* parse into the 'then' branch */
2304     if (!parser_next(parser)) {
2305         parseerror(parser, "expected while-loop body");
2306         ast_unref(cond);
2307         return false;
2308     }
2309     if (!parse_statement_or_block(parser, &ontrue)) {
2310         ast_unref(cond);
2311         return false;
2312     }
2313
2314     cond = process_condition(parser, cond, &ifnot);
2315     if (!cond) {
2316         ast_unref(ontrue);
2317         return false;
2318     }
2319     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2320     *out = (ast_expression*)aloop;
2321     return true;
2322 }
2323
2324 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2325 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2326 {
2327     bool rv;
2328     char *label = NULL;
2329
2330     /* skip the 'do' and get the body */
2331     if (!parser_next(parser)) {
2332         if (OPTS_FLAG(LOOP_LABELS))
2333             parseerror(parser, "expected loop label or body");
2334         else
2335             parseerror(parser, "expected loop body");
2336         return false;
2337     }
2338
2339     if (parser->tok == ':') {
2340         if (!OPTS_FLAG(LOOP_LABELS))
2341             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2342         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2343             parseerror(parser, "expected loop label");
2344             return false;
2345         }
2346         label = util_strdup(parser_tokval(parser));
2347         if (!parser_next(parser)) {
2348             mem_d(label);
2349             parseerror(parser, "expected loop body");
2350             return false;
2351         }
2352     }
2353
2354     vec_push(parser->breaks, label);
2355     vec_push(parser->continues, label);
2356
2357     rv = parse_dowhile_go(parser, block, out);
2358     if (label)
2359         mem_d(label);
2360     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2361         parseerror(parser, "internal error: label stack corrupted");
2362         rv = false;
2363         /*
2364          * Test for NULL otherwise ast_delete dereferences null pointer
2365          * and boom.
2366          */
2367         if (*out)
2368             ast_delete(*out);
2369         *out = NULL;
2370     }
2371     else {
2372         vec_pop(parser->breaks);
2373         vec_pop(parser->continues);
2374     }
2375     return rv;
2376 }
2377
2378 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2379 {
2380     ast_loop *aloop;
2381     ast_expression *cond, *ontrue;
2382
2383     bool ifnot = false;
2384
2385     lex_ctx_t ctx = parser_ctx(parser);
2386
2387     (void)block; /* not touching */
2388
2389     if (!parse_statement_or_block(parser, &ontrue))
2390         return false;
2391
2392     /* expect the "while" */
2393     if (parser->tok != TOKEN_KEYWORD ||
2394         strcmp(parser_tokval(parser), "while"))
2395     {
2396         parseerror(parser, "expected 'while' and condition");
2397         ast_delete(ontrue);
2398         return false;
2399     }
2400
2401     /* skip the 'while' and check for opening paren */
2402     if (!parser_next(parser) || parser->tok != '(') {
2403         parseerror(parser, "expected 'while' condition in parenthesis");
2404         ast_delete(ontrue);
2405         return false;
2406     }
2407     /* parse into the expression */
2408     if (!parser_next(parser)) {
2409         parseerror(parser, "expected 'while' condition after opening paren");
2410         ast_delete(ontrue);
2411         return false;
2412     }
2413     /* parse the condition */
2414     cond = parse_expression_leave(parser, false, true, false);
2415     if (!cond)
2416         return false;
2417     /* closing paren */
2418     if (parser->tok != ')') {
2419         parseerror(parser, "expected closing paren after 'while' condition");
2420         ast_delete(ontrue);
2421         ast_unref(cond);
2422         return false;
2423     }
2424     /* parse on */
2425     if (!parser_next(parser) || parser->tok != ';') {
2426         parseerror(parser, "expected semicolon after condition");
2427         ast_delete(ontrue);
2428         ast_unref(cond);
2429         return false;
2430     }
2431
2432     if (!parser_next(parser)) {
2433         parseerror(parser, "parse error");
2434         ast_delete(ontrue);
2435         ast_unref(cond);
2436         return false;
2437     }
2438
2439     cond = process_condition(parser, cond, &ifnot);
2440     if (!cond) {
2441         ast_delete(ontrue);
2442         return false;
2443     }
2444     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2445     *out = (ast_expression*)aloop;
2446     return true;
2447 }
2448
2449 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2450 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2451 {
2452     bool rv;
2453     char *label = NULL;
2454
2455     /* skip the 'for' and check for opening paren */
2456     if (!parser_next(parser)) {
2457         if (OPTS_FLAG(LOOP_LABELS))
2458             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2459         else
2460             parseerror(parser, "expected 'for' expressions in parenthesis");
2461         return false;
2462     }
2463
2464     if (parser->tok == ':') {
2465         if (!OPTS_FLAG(LOOP_LABELS))
2466             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2467         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2468             parseerror(parser, "expected loop label");
2469             return false;
2470         }
2471         label = util_strdup(parser_tokval(parser));
2472         if (!parser_next(parser)) {
2473             mem_d(label);
2474             parseerror(parser, "expected 'for' expressions in parenthesis");
2475             return false;
2476         }
2477     }
2478
2479     if (parser->tok != '(') {
2480         parseerror(parser, "expected 'for' expressions in parenthesis");
2481         return false;
2482     }
2483
2484     vec_push(parser->breaks, label);
2485     vec_push(parser->continues, label);
2486
2487     rv = parse_for_go(parser, block, out);
2488     if (label)
2489         mem_d(label);
2490     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2491         parseerror(parser, "internal error: label stack corrupted");
2492         rv = false;
2493         ast_delete(*out);
2494         *out = NULL;
2495     }
2496     else {
2497         vec_pop(parser->breaks);
2498         vec_pop(parser->continues);
2499     }
2500     return rv;
2501 }
2502 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2503 {
2504     ast_loop       *aloop;
2505     ast_expression *initexpr, *cond, *increment, *ontrue;
2506     ast_value      *typevar;
2507
2508     bool ifnot  = false;
2509
2510     lex_ctx_t ctx = parser_ctx(parser);
2511
2512     parser_enterblock(parser);
2513
2514     initexpr  = NULL;
2515     cond      = NULL;
2516     increment = NULL;
2517     ontrue    = NULL;
2518
2519     /* parse into the expression */
2520     if (!parser_next(parser)) {
2521         parseerror(parser, "expected 'for' initializer after opening paren");
2522         goto onerr;
2523     }
2524
2525     typevar = NULL;
2526     if (parser->tok == TOKEN_IDENT)
2527         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2528
2529     if (typevar || parser->tok == TOKEN_TYPENAME) {
2530 #if 0
2531         if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2532             if (parsewarning(parser, WARN_EXTENSIONS,
2533                              "current standard does not allow variable declarations in for-loop initializers"))
2534                 goto onerr;
2535         }
2536 #endif
2537         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2538             goto onerr;
2539     }
2540     else if (parser->tok != ';')
2541     {
2542         initexpr = parse_expression_leave(parser, false, false, false);
2543         if (!initexpr)
2544             goto onerr;
2545     }
2546
2547     /* move on to condition */
2548     if (parser->tok != ';') {
2549         parseerror(parser, "expected semicolon after for-loop initializer");
2550         goto onerr;
2551     }
2552     if (!parser_next(parser)) {
2553         parseerror(parser, "expected for-loop condition");
2554         goto onerr;
2555     }
2556
2557     /* parse the condition */
2558     if (parser->tok != ';') {
2559         cond = parse_expression_leave(parser, false, true, false);
2560         if (!cond)
2561             goto onerr;
2562     }
2563
2564     /* move on to incrementor */
2565     if (parser->tok != ';') {
2566         parseerror(parser, "expected semicolon after for-loop initializer");
2567         goto onerr;
2568     }
2569     if (!parser_next(parser)) {
2570         parseerror(parser, "expected for-loop condition");
2571         goto onerr;
2572     }
2573
2574     /* parse the incrementor */
2575     if (parser->tok != ')') {
2576         lex_ctx_t condctx = parser_ctx(parser);
2577         increment = parse_expression_leave(parser, false, false, false);
2578         if (!increment)
2579             goto onerr;
2580         if (!ast_side_effects(increment)) {
2581             if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2582                 goto onerr;
2583         }
2584     }
2585
2586     /* closing paren */
2587     if (parser->tok != ')') {
2588         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2589         goto onerr;
2590     }
2591     /* parse into the 'then' branch */
2592     if (!parser_next(parser)) {
2593         parseerror(parser, "expected for-loop body");
2594         goto onerr;
2595     }
2596     if (!parse_statement_or_block(parser, &ontrue))
2597         goto onerr;
2598
2599     if (cond) {
2600         cond = process_condition(parser, cond, &ifnot);
2601         if (!cond)
2602             goto onerr;
2603     }
2604     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2605     *out = (ast_expression*)aloop;
2606
2607     if (!parser_leaveblock(parser)) {
2608         ast_delete(aloop);
2609         return false;
2610     }
2611     return true;
2612 onerr:
2613     if (initexpr)  ast_unref(initexpr);
2614     if (cond)      ast_unref(cond);
2615     if (increment) ast_unref(increment);
2616     (void)!parser_leaveblock(parser);
2617     return false;
2618 }
2619
2620 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2621 {
2622     ast_expression *exp      = NULL;
2623     ast_expression *var      = NULL;
2624     ast_return     *ret      = NULL;
2625     ast_value      *retval   = parser->function->return_value;
2626     ast_value      *expected = parser->function->vtype;
2627
2628     lex_ctx_t ctx = parser_ctx(parser);
2629
2630     (void)block; /* not touching */
2631
2632     if (!parser_next(parser)) {
2633         parseerror(parser, "expected return expression");
2634         return false;
2635     }
2636
2637     /* return assignments */
2638     if (parser->tok == '=') {
2639         if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2640             parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2641             return false;
2642         }
2643
2644         if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2645             char ty1[1024];
2646             ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2647             parseerror(parser, "invalid return type: `%s'", ty1);
2648             return false;
2649         }
2650
2651         if (!parser_next(parser)) {
2652             parseerror(parser, "expected return assignment expression");
2653             return false;
2654         }
2655
2656         if (!(exp = parse_expression_leave(parser, false, false, false)))
2657             return false;
2658
2659         /* prepare the return value */
2660         if (!retval) {
2661             retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2662             ast_type_adopt(retval, expected->expression.next);
2663             parser->function->return_value = retval;
2664         }
2665
2666         if (!ast_compare_type(exp, (ast_expression*)retval)) {
2667             char ty1[1024], ty2[1024];
2668             ast_type_to_string(exp, ty1, sizeof(ty1));
2669             ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2670             parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2671         }
2672
2673         /* store to 'return' local variable */
2674         var = (ast_expression*)ast_store_new(
2675             ctx,
2676             type_store_instr[expected->expression.next->vtype],
2677             (ast_expression*)retval, exp);
2678
2679         if (!var) {
2680             ast_unref(exp);
2681             return false;
2682         }
2683
2684         if (parser->tok != ';')
2685             parseerror(parser, "missing semicolon after return assignment");
2686         else if (!parser_next(parser))
2687             parseerror(parser, "parse error after return assignment");
2688
2689         *out = var;
2690         return true;
2691     }
2692
2693     if (parser->tok != ';') {
2694         exp = parse_expression(parser, false, false);
2695         if (!exp)
2696             return false;
2697
2698         if (exp->vtype != TYPE_NIL &&
2699             exp->vtype != ((ast_expression*)expected)->next->vtype)
2700         {
2701             parseerror(parser, "return with invalid expression");
2702         }
2703
2704         ret = ast_return_new(ctx, exp);
2705         if (!ret) {
2706             ast_unref(exp);
2707             return false;
2708         }
2709     } else {
2710         if (!parser_next(parser))
2711             parseerror(parser, "parse error");
2712
2713         if (!retval && expected->expression.next->vtype != TYPE_VOID)
2714         {
2715             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2716         }
2717         ret = ast_return_new(ctx, (ast_expression*)retval);
2718     }
2719     *out = (ast_expression*)ret;
2720     return true;
2721 }
2722
2723 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2724 {
2725     size_t       i;
2726     unsigned int levels = 0;
2727     lex_ctx_t      ctx = parser_ctx(parser);
2728     const char **loops = (is_continue ? parser->continues : parser->breaks);
2729
2730     (void)block; /* not touching */
2731     if (!parser_next(parser)) {
2732         parseerror(parser, "expected semicolon or loop label");
2733         return false;
2734     }
2735
2736     if (!vec_size(loops)) {
2737         if (is_continue)
2738             parseerror(parser, "`continue` can only be used inside loops");
2739         else
2740             parseerror(parser, "`break` can only be used inside loops or switches");
2741     }
2742
2743     if (parser->tok == TOKEN_IDENT) {
2744         if (!OPTS_FLAG(LOOP_LABELS))
2745             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2746         i = vec_size(loops);
2747         while (i--) {
2748             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2749                 break;
2750             if (!i) {
2751                 parseerror(parser, "no such loop to %s: `%s`",
2752                            (is_continue ? "continue" : "break out of"),
2753                            parser_tokval(parser));
2754                 return false;
2755             }
2756             ++levels;
2757         }
2758         if (!parser_next(parser)) {
2759             parseerror(parser, "expected semicolon");
2760             return false;
2761         }
2762     }
2763
2764     if (parser->tok != ';') {
2765         parseerror(parser, "expected semicolon");
2766         return false;
2767     }
2768
2769     if (!parser_next(parser))
2770         parseerror(parser, "parse error");
2771
2772     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2773     return true;
2774 }
2775
2776 /* returns true when it was a variable qualifier, false otherwise!
2777  * on error, cvq is set to CV_WRONG
2778  */
2779 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2780 {
2781     bool had_const    = false;
2782     bool had_var      = false;
2783     bool had_noref    = false;
2784     bool had_attrib   = false;
2785     bool had_static   = false;
2786     uint32_t flags    = 0;
2787
2788     *cvq = CV_NONE;
2789     for (;;) {
2790         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2791             had_attrib = true;
2792             /* parse an attribute */
2793             if (!parser_next(parser)) {
2794                 parseerror(parser, "expected attribute after `[[`");
2795                 *cvq = CV_WRONG;
2796                 return false;
2797             }
2798             if (!strcmp(parser_tokval(parser), "noreturn")) {
2799                 flags |= AST_FLAG_NORETURN;
2800                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2801                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2802                     *cvq = CV_WRONG;
2803                     return false;
2804                 }
2805             }
2806             else if (!strcmp(parser_tokval(parser), "noref")) {
2807                 had_noref = true;
2808                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2809                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2810                     *cvq = CV_WRONG;
2811                     return false;
2812                 }
2813             }
2814             else if (!strcmp(parser_tokval(parser), "inline")) {
2815                 flags |= AST_FLAG_INLINE;
2816                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2817                     parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2818                     *cvq = CV_WRONG;
2819                     return false;
2820                 }
2821             }
2822             else if (!strcmp(parser_tokval(parser), "eraseable")) {
2823                 flags |= AST_FLAG_ERASEABLE;
2824                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2825                     parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2826                     *cvq = CV_WRONG;
2827                     return false;
2828                 }
2829             }
2830             else if (!strcmp(parser_tokval(parser), "accumulate")) {
2831                 flags |= AST_FLAG_ACCUMULATE;
2832                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2833                     parseerror(parser, "`accumulate` attribute has no parameters, expected `]]`");
2834                     *cvq = CV_WRONG;
2835                     return false;
2836                 }
2837             }
2838             else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2839                 flags   |= AST_FLAG_ALIAS;
2840                 *message = NULL;
2841
2842                 if (!parser_next(parser)) {
2843                     parseerror(parser, "parse error in attribute");
2844                     goto argerr;
2845                 }
2846
2847                 if (parser->tok == '(') {
2848                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2849                         parseerror(parser, "`alias` attribute missing parameter");
2850                         goto argerr;
2851                     }
2852
2853                     *message = util_strdup(parser_tokval(parser));
2854
2855                     if (!parser_next(parser)) {
2856                         parseerror(parser, "parse error in attribute");
2857                         goto argerr;
2858                     }
2859
2860                     if (parser->tok != ')') {
2861                         parseerror(parser, "`alias` attribute expected `)` after parameter");
2862                         goto argerr;
2863                     }
2864
2865                     if (!parser_next(parser)) {
2866                         parseerror(parser, "parse error in attribute");
2867                         goto argerr;
2868                     }
2869                 }
2870
2871                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2872                     parseerror(parser, "`alias` attribute expected `]]`");
2873                     goto argerr;
2874                 }
2875             }
2876             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2877                 flags   |= AST_FLAG_DEPRECATED;
2878                 *message = NULL;
2879
2880                 if (!parser_next(parser)) {
2881                     parseerror(parser, "parse error in attribute");
2882                     goto argerr;
2883                 }
2884
2885                 if (parser->tok == '(') {
2886                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2887                         parseerror(parser, "`deprecated` attribute missing parameter");
2888                         goto argerr;
2889                     }
2890
2891                     *message = util_strdup(parser_tokval(parser));
2892
2893                     if (!parser_next(parser)) {
2894                         parseerror(parser, "parse error in attribute");
2895                         goto argerr;
2896                     }
2897
2898                     if(parser->tok != ')') {
2899                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2900                         goto argerr;
2901                     }
2902
2903                     if (!parser_next(parser)) {
2904                         parseerror(parser, "parse error in attribute");
2905                         goto argerr;
2906                     }
2907                 }
2908                 /* no message */
2909                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2910                     parseerror(parser, "`deprecated` attribute expected `]]`");
2911
2912                     argerr: /* ugly */
2913                     if (*message) mem_d(*message);
2914                     *message = NULL;
2915                     *cvq     = CV_WRONG;
2916                     return false;
2917                 }
2918             }
2919             else
2920             {
2921                 /* Skip tokens until we hit a ]] */
2922                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2923                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2924                     if (!parser_next(parser)) {
2925                         parseerror(parser, "error inside attribute");
2926                         *cvq = CV_WRONG;
2927                         return false;
2928                     }
2929                 }
2930             }
2931         }
2932         else if (with_local && !strcmp(parser_tokval(parser), "static"))
2933             had_static = true;
2934         else if (!strcmp(parser_tokval(parser), "const"))
2935             had_const = true;
2936         else if (!strcmp(parser_tokval(parser), "var"))
2937             had_var = true;
2938         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2939             had_var = true;
2940         else if (!strcmp(parser_tokval(parser), "noref"))
2941             had_noref = true;
2942         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2943             return false;
2944         }
2945         else
2946             break;
2947         if (!parser_next(parser))
2948             goto onerr;
2949     }
2950     if (had_const)
2951         *cvq = CV_CONST;
2952     else if (had_var)
2953         *cvq = CV_VAR;
2954     else
2955         *cvq = CV_NONE;
2956     *noref     = had_noref;
2957     *is_static = had_static;
2958     *_flags    = flags;
2959     return true;
2960 onerr:
2961     parseerror(parser, "parse error after variable qualifier");
2962     *cvq = CV_WRONG;
2963     return true;
2964 }
2965
2966 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2967 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2968 {
2969     bool rv;
2970     char *label = NULL;
2971
2972     /* skip the 'while' and get the body */
2973     if (!parser_next(parser)) {
2974         if (OPTS_FLAG(LOOP_LABELS))
2975             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2976         else
2977             parseerror(parser, "expected 'switch' operand in parenthesis");
2978         return false;
2979     }
2980
2981     if (parser->tok == ':') {
2982         if (!OPTS_FLAG(LOOP_LABELS))
2983             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2984         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2985             parseerror(parser, "expected loop label");
2986             return false;
2987         }
2988         label = util_strdup(parser_tokval(parser));
2989         if (!parser_next(parser)) {
2990             mem_d(label);
2991             parseerror(parser, "expected 'switch' operand in parenthesis");
2992             return false;
2993         }
2994     }
2995
2996     if (parser->tok != '(') {
2997         parseerror(parser, "expected 'switch' operand in parenthesis");
2998         return false;
2999     }
3000
3001     vec_push(parser->breaks, label);
3002
3003     rv = parse_switch_go(parser, block, out);
3004     if (label)
3005         mem_d(label);
3006     if (vec_last(parser->breaks) != label) {
3007         parseerror(parser, "internal error: label stack corrupted");
3008         rv = false;
3009         ast_delete(*out);
3010         *out = NULL;
3011     }
3012     else {
3013         vec_pop(parser->breaks);
3014     }
3015     return rv;
3016 }
3017
3018 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3019 {
3020     ast_expression *operand;
3021     ast_value      *opval;
3022     ast_value      *typevar;
3023     ast_switch     *switchnode;
3024     ast_switch_case swcase;
3025
3026     int  cvq;
3027     bool noref, is_static;
3028     uint32_t qflags = 0;
3029
3030     lex_ctx_t ctx = parser_ctx(parser);
3031
3032     (void)block; /* not touching */
3033     (void)opval;
3034
3035     /* parse into the expression */
3036     if (!parser_next(parser)) {
3037         parseerror(parser, "expected switch operand");
3038         return false;
3039     }
3040     /* parse the operand */
3041     operand = parse_expression_leave(parser, false, false, false);
3042     if (!operand)
3043         return false;
3044
3045     switchnode = ast_switch_new(ctx, operand);
3046
3047     /* closing paren */
3048     if (parser->tok != ')') {
3049         ast_delete(switchnode);
3050         parseerror(parser, "expected closing paren after 'switch' operand");
3051         return false;
3052     }
3053
3054     /* parse over the opening paren */
3055     if (!parser_next(parser) || parser->tok != '{') {
3056         ast_delete(switchnode);
3057         parseerror(parser, "expected list of cases");
3058         return false;
3059     }
3060
3061     if (!parser_next(parser)) {
3062         ast_delete(switchnode);
3063         parseerror(parser, "expected 'case' or 'default'");
3064         return false;
3065     }
3066
3067     /* new block; allow some variables to be declared here */
3068     parser_enterblock(parser);
3069     while (true) {
3070         typevar = NULL;
3071         if (parser->tok == TOKEN_IDENT)
3072             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3073         if (typevar || parser->tok == TOKEN_TYPENAME) {
3074             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3075                 ast_delete(switchnode);
3076                 return false;
3077             }
3078             continue;
3079         }
3080         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3081         {
3082             if (cvq == CV_WRONG) {
3083                 ast_delete(switchnode);
3084                 return false;
3085             }
3086             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3087                 ast_delete(switchnode);
3088                 return false;
3089             }
3090             continue;
3091         }
3092         break;
3093     }
3094
3095     /* case list! */
3096     while (parser->tok != '}') {
3097         ast_block *caseblock;
3098
3099         if (!strcmp(parser_tokval(parser), "case")) {
3100             if (!parser_next(parser)) {
3101                 ast_delete(switchnode);
3102                 parseerror(parser, "expected expression for case");
3103                 return false;
3104             }
3105             swcase.value = parse_expression_leave(parser, false, false, false);
3106             if (!swcase.value) {
3107                 ast_delete(switchnode);
3108                 parseerror(parser, "expected expression for case");
3109                 return false;
3110             }
3111             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3112                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3113                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3114                     ast_unref(operand);
3115                     return false;
3116                 }
3117             }
3118         }
3119         else if (!strcmp(parser_tokval(parser), "default")) {
3120             swcase.value = NULL;
3121             if (!parser_next(parser)) {
3122                 ast_delete(switchnode);
3123                 parseerror(parser, "expected colon");
3124                 return false;
3125             }
3126         }
3127         else {
3128             ast_delete(switchnode);
3129             parseerror(parser, "expected 'case' or 'default'");
3130             return false;
3131         }
3132
3133         /* Now the colon and body */
3134         if (parser->tok != ':') {
3135             if (swcase.value) ast_unref(swcase.value);
3136             ast_delete(switchnode);
3137             parseerror(parser, "expected colon");
3138             return false;
3139         }
3140
3141         if (!parser_next(parser)) {
3142             if (swcase.value) ast_unref(swcase.value);
3143             ast_delete(switchnode);
3144             parseerror(parser, "expected statements or case");
3145             return false;
3146         }
3147         caseblock = ast_block_new(parser_ctx(parser));
3148         if (!caseblock) {
3149             if (swcase.value) ast_unref(swcase.value);
3150             ast_delete(switchnode);
3151             return false;
3152         }
3153         swcase.code = (ast_expression*)caseblock;
3154         vec_push(switchnode->cases, swcase);
3155         while (true) {
3156             ast_expression *expr;
3157             if (parser->tok == '}')
3158                 break;
3159             if (parser->tok == TOKEN_KEYWORD) {
3160                 if (!strcmp(parser_tokval(parser), "case") ||
3161                     !strcmp(parser_tokval(parser), "default"))
3162                 {
3163                     break;
3164                 }
3165             }
3166             if (!parse_statement(parser, caseblock, &expr, true)) {
3167                 ast_delete(switchnode);
3168                 return false;
3169             }
3170             if (!expr)
3171                 continue;
3172             if (!ast_block_add_expr(caseblock, expr)) {
3173                 ast_delete(switchnode);
3174                 return false;
3175             }
3176         }
3177     }
3178
3179     parser_leaveblock(parser);
3180
3181     /* closing paren */
3182     if (parser->tok != '}') {
3183         ast_delete(switchnode);
3184         parseerror(parser, "expected closing paren of case list");
3185         return false;
3186     }
3187     if (!parser_next(parser)) {
3188         ast_delete(switchnode);
3189         parseerror(parser, "parse error after switch");
3190         return false;
3191     }
3192     *out = (ast_expression*)switchnode;
3193     return true;
3194 }
3195
3196 /* parse computed goto sides */
3197 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3198     ast_expression *on_true;
3199     ast_expression *on_false;
3200     ast_expression *cond;
3201
3202     if (!*side)
3203         return NULL;
3204
3205     if (ast_istype(*side, ast_ternary)) {
3206         ast_ternary *tern = (ast_ternary*)*side;
3207         on_true  = parse_goto_computed(parser, &tern->on_true);
3208         on_false = parse_goto_computed(parser, &tern->on_false);
3209
3210         if (!on_true || !on_false) {
3211             parseerror(parser, "expected label or expression in ternary");
3212             if (on_true) ast_unref(on_true);
3213             if (on_false) ast_unref(on_false);
3214             return NULL;
3215         }
3216
3217         cond = tern->cond;
3218         tern->cond = NULL;
3219         ast_delete(tern);
3220         *side = NULL;
3221         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3222     } else if (ast_istype(*side, ast_label)) {
3223         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3224         ast_goto_set_label(gt, ((ast_label*)*side));
3225         *side = NULL;
3226         return (ast_expression*)gt;
3227     }
3228     return NULL;
3229 }
3230
3231 static bool parse_goto(parser_t *parser, ast_expression **out)
3232 {
3233     ast_goto       *gt = NULL;
3234     ast_expression *lbl;
3235
3236     if (!parser_next(parser))
3237         return false;
3238
3239     if (parser->tok != TOKEN_IDENT) {
3240         ast_expression *expression;
3241
3242         /* could be an expression i.e computed goto :-) */
3243         if (parser->tok != '(') {
3244             parseerror(parser, "expected label name after `goto`");
3245             return false;
3246         }
3247
3248         /* failed to parse expression for goto */
3249         if (!(expression = parse_expression(parser, false, true)) ||
3250             !(*out = parse_goto_computed(parser, &expression))) {
3251             parseerror(parser, "invalid goto expression");
3252             if(expression)
3253                 ast_unref(expression);
3254             return false;
3255         }
3256
3257         return true;
3258     }
3259
3260     /* not computed goto */
3261     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3262     lbl = parser_find_label(parser, gt->name);
3263     if (lbl) {
3264         if (!ast_istype(lbl, ast_label)) {
3265             parseerror(parser, "internal error: label is not an ast_label");
3266             ast_delete(gt);
3267             return false;
3268         }
3269         ast_goto_set_label(gt, (ast_label*)lbl);
3270     }
3271     else
3272         vec_push(parser->gotos, gt);
3273
3274     if (!parser_next(parser) || parser->tok != ';') {
3275         parseerror(parser, "semicolon expected after goto label");
3276         return false;
3277     }
3278     if (!parser_next(parser)) {
3279         parseerror(parser, "parse error after goto");
3280         return false;
3281     }
3282
3283     *out = (ast_expression*)gt;
3284     return true;
3285 }
3286
3287 static bool parse_skipwhite(parser_t *parser)
3288 {
3289     do {
3290         if (!parser_next(parser))
3291             return false;
3292     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3293     return parser->tok < TOKEN_ERROR;
3294 }
3295
3296 static bool parse_eol(parser_t *parser)
3297 {
3298     if (!parse_skipwhite(parser))
3299         return false;
3300     return parser->tok == TOKEN_EOL;
3301 }
3302
3303 static bool parse_pragma_do(parser_t *parser)
3304 {
3305     if (!parser_next(parser) ||
3306         parser->tok != TOKEN_IDENT ||
3307         strcmp(parser_tokval(parser), "pragma"))
3308     {
3309         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3310         return false;
3311     }
3312     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3313         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3314         return false;
3315     }
3316
3317     if (!strcmp(parser_tokval(parser), "noref")) {
3318         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3319             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3320             return false;
3321         }
3322         parser->noref = !!parser_token(parser)->constval.i;
3323         if (!parse_eol(parser)) {
3324             parseerror(parser, "parse error after `noref` pragma");
3325             return false;
3326         }
3327     }
3328     else
3329     {
3330         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3331
3332         /* skip to eol */
3333         while (!parse_eol(parser)) {
3334             parser_next(parser);
3335         }
3336
3337         return true;
3338     }
3339
3340     return true;
3341 }
3342
3343 static bool parse_pragma(parser_t *parser)
3344 {
3345     bool rv;
3346     parser->lex->flags.preprocessing = true;
3347     parser->lex->flags.mergelines = true;
3348     rv = parse_pragma_do(parser);
3349     if (parser->tok != TOKEN_EOL) {
3350         parseerror(parser, "junk after pragma");
3351         rv = false;
3352     }
3353     parser->lex->flags.preprocessing = false;
3354     parser->lex->flags.mergelines = false;
3355     if (!parser_next(parser)) {
3356         parseerror(parser, "parse error after pragma");
3357         rv = false;
3358     }
3359     return rv;
3360 }
3361
3362 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3363 {
3364     bool       noref, is_static;
3365     int        cvq     = CV_NONE;
3366     uint32_t   qflags  = 0;
3367     ast_value *typevar = NULL;
3368     char      *vstring = NULL;
3369
3370     *out = NULL;
3371
3372     if (parser->tok == TOKEN_IDENT)
3373         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3374
3375     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3376     {
3377         /* local variable */
3378         if (!block) {
3379             parseerror(parser, "cannot declare a variable from here");
3380             return false;
3381         }
3382         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3383             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3384                 return false;
3385         }
3386         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3387             return false;
3388         return true;
3389     }
3390     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3391     {
3392         if (cvq == CV_WRONG)
3393             return false;
3394         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3395     }
3396     else if (parser->tok == TOKEN_KEYWORD)
3397     {
3398         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3399         {
3400             char ty[1024];
3401             ast_value *tdef;
3402
3403             if (!parser_next(parser)) {
3404                 parseerror(parser, "parse error after __builtin_debug_printtype");
3405                 return false;
3406             }
3407
3408             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3409             {
3410                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3411                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3412                 if (!parser_next(parser)) {
3413                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3414                     return false;
3415                 }
3416             }
3417             else
3418             {
3419                 if (!parse_statement(parser, block, out, allow_cases))
3420                     return false;
3421                 if (!*out)
3422                     con_out("__builtin_debug_printtype: got no output node\n");
3423                 else
3424                 {
3425                     ast_type_to_string(*out, ty, sizeof(ty));
3426                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3427                 }
3428             }
3429             return true;
3430         }
3431         else if (!strcmp(parser_tokval(parser), "return"))
3432         {
3433             return parse_return(parser, block, out);
3434         }
3435         else if (!strcmp(parser_tokval(parser), "if"))
3436         {
3437             return parse_if(parser, block, out);
3438         }
3439         else if (!strcmp(parser_tokval(parser), "while"))
3440         {
3441             return parse_while(parser, block, out);
3442         }
3443         else if (!strcmp(parser_tokval(parser), "do"))
3444         {
3445             return parse_dowhile(parser, block, out);
3446         }
3447         else if (!strcmp(parser_tokval(parser), "for"))
3448         {
3449             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3450                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3451                     return false;
3452             }
3453             return parse_for(parser, block, out);
3454         }
3455         else if (!strcmp(parser_tokval(parser), "break"))
3456         {
3457             return parse_break_continue(parser, block, out, false);
3458         }
3459         else if (!strcmp(parser_tokval(parser), "continue"))
3460         {
3461             return parse_break_continue(parser, block, out, true);
3462         }
3463         else if (!strcmp(parser_tokval(parser), "switch"))
3464         {
3465             return parse_switch(parser, block, out);
3466         }
3467         else if (!strcmp(parser_tokval(parser), "case") ||
3468                  !strcmp(parser_tokval(parser), "default"))
3469         {
3470             if (!allow_cases) {
3471                 parseerror(parser, "unexpected 'case' label");
3472                 return false;
3473             }
3474             return true;
3475         }
3476         else if (!strcmp(parser_tokval(parser), "goto"))
3477         {
3478             return parse_goto(parser, out);
3479         }
3480         else if (!strcmp(parser_tokval(parser), "typedef"))
3481         {
3482             if (!parser_next(parser)) {
3483                 parseerror(parser, "expected type definition after 'typedef'");
3484                 return false;
3485             }
3486             return parse_typedef(parser);
3487         }
3488         parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3489         return false;
3490     }
3491     else if (parser->tok == '{')
3492     {
3493         ast_block *inner;
3494         inner = parse_block(parser);
3495         if (!inner)
3496             return false;
3497         *out = (ast_expression*)inner;
3498         return true;
3499     }
3500     else if (parser->tok == ':')
3501     {
3502         size_t i;
3503         ast_label *label;
3504         if (!parser_next(parser)) {
3505             parseerror(parser, "expected label name");
3506             return false;
3507         }
3508         if (parser->tok != TOKEN_IDENT) {
3509             parseerror(parser, "label must be an identifier");
3510             return false;
3511         }
3512         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3513         if (label) {
3514             if (!label->undefined) {
3515                 parseerror(parser, "label `%s` already defined", label->name);
3516                 return false;
3517             }
3518             label->undefined = false;
3519         }
3520         else {
3521             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3522             vec_push(parser->labels, label);
3523         }
3524         *out = (ast_expression*)label;
3525         if (!parser_next(parser)) {
3526             parseerror(parser, "parse error after label");
3527             return false;
3528         }
3529         for (i = 0; i < vec_size(parser->gotos); ++i) {
3530             if (!strcmp(parser->gotos[i]->name, label->name)) {
3531                 ast_goto_set_label(parser->gotos[i], label);
3532                 vec_remove(parser->gotos, i, 1);
3533                 --i;
3534             }
3535         }
3536         return true;
3537     }
3538     else if (parser->tok == ';')
3539     {
3540         if (!parser_next(parser)) {
3541             parseerror(parser, "parse error after empty statement");
3542             return false;
3543         }
3544         return true;
3545     }
3546     else
3547     {
3548         lex_ctx_t ctx = parser_ctx(parser);
3549         ast_expression *exp = parse_expression(parser, false, false);
3550         if (!exp)
3551             return false;
3552         *out = exp;
3553         if (!ast_side_effects(exp)) {
3554             if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3555                 return false;
3556         }
3557         return true;
3558     }
3559 }
3560
3561 static bool parse_enum(parser_t *parser)
3562 {
3563     bool        flag = false;
3564     bool        reverse = false;
3565     qcfloat_t     num = 0;
3566     ast_value **values = NULL;
3567     ast_value  *var = NULL;
3568     ast_value  *asvalue;
3569
3570     ast_expression *old;
3571
3572     if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3573         parseerror(parser, "expected `{` or `:` after `enum` keyword");
3574         return false;
3575     }
3576
3577     /* enumeration attributes (can add more later) */
3578     if (parser->tok == ':') {
3579         if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3580             parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3581             return false;
3582         }
3583
3584         /* attributes? */
3585         if (!strcmp(parser_tokval(parser), "flag")) {
3586             num  = 1;
3587             flag = true;
3588         }
3589         else if (!strcmp(parser_tokval(parser), "reverse")) {
3590             reverse = true;
3591         }
3592         else {
3593             parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3594             return false;
3595         }
3596
3597         if (!parser_next(parser) || parser->tok != '{') {
3598             parseerror(parser, "expected `{` after enum attribute ");
3599             return false;
3600         }
3601     }
3602
3603     while (true) {
3604         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3605             if (parser->tok == '}') {
3606                 /* allow an empty enum */
3607                 break;
3608             }
3609             parseerror(parser, "expected identifier or `}`");
3610             goto onerror;
3611         }
3612
3613         old = parser_find_field(parser, parser_tokval(parser));
3614         if (!old)
3615             old = parser_find_global(parser, parser_tokval(parser));
3616         if (old) {
3617             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3618                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3619             goto onerror;
3620         }
3621
3622         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3623         vec_push(values, var);
3624         var->cvq             = CV_CONST;
3625         var->hasvalue        = true;
3626
3627         /* for flagged enumerations increment in POTs of TWO */
3628         var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3629         parser_addglobal(parser, var->name, (ast_expression*)var);
3630
3631         if (!parser_next(parser)) {
3632             parseerror(parser, "expected `=`, `}` or comma after identifier");
3633             goto onerror;
3634         }
3635
3636         if (parser->tok == ',')
3637             continue;
3638         if (parser->tok == '}')
3639             break;
3640         if (parser->tok != '=') {
3641             parseerror(parser, "expected `=`, `}` or comma after identifier");
3642             goto onerror;
3643         }
3644
3645         if (!parser_next(parser)) {
3646             parseerror(parser, "expected expression after `=`");
3647             goto onerror;
3648         }
3649
3650         /* We got a value! */
3651         old = parse_expression_leave(parser, true, false, false);
3652         asvalue = (ast_value*)old;
3653         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3654             compile_error(ast_ctx(var), "constant value or expression expected");
3655             goto onerror;
3656         }
3657         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3658
3659         if (parser->tok == '}')
3660             break;
3661         if (parser->tok != ',') {
3662             parseerror(parser, "expected `}` or comma after expression");
3663             goto onerror;
3664         }
3665     }
3666
3667     /* patch them all (for reversed attribute) */
3668     if (reverse) {
3669         size_t i;
3670         for (i = 0; i < vec_size(values); i++)
3671             values[i]->constval.vfloat = vec_size(values) - i - 1;
3672     }
3673
3674     if (parser->tok != '}') {
3675         parseerror(parser, "internal error: breaking without `}`");
3676         goto onerror;
3677     }
3678
3679     if (!parser_next(parser) || parser->tok != ';') {
3680         parseerror(parser, "expected semicolon after enumeration");
3681         goto onerror;
3682     }
3683
3684     if (!parser_next(parser)) {
3685         parseerror(parser, "parse error after enumeration");
3686         goto onerror;
3687     }
3688
3689     vec_free(values);
3690     return true;
3691
3692 onerror:
3693     vec_free(values);
3694     return false;
3695 }
3696
3697 static bool parse_block_into(parser_t *parser, ast_block *block)
3698 {
3699     bool   retval = true;
3700
3701     parser_enterblock(parser);
3702
3703     if (!parser_next(parser)) { /* skip the '{' */
3704         parseerror(parser, "expected function body");
3705         goto cleanup;
3706     }
3707
3708     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3709     {
3710         ast_expression *expr = NULL;
3711         if (parser->tok == '}')
3712             break;
3713
3714         if (!parse_statement(parser, block, &expr, false)) {
3715             /* parseerror(parser, "parse error"); */
3716             block = NULL;
3717             goto cleanup;
3718         }
3719         if (!expr)
3720             continue;
3721         if (!ast_block_add_expr(block, expr)) {
3722             ast_delete(block);
3723             block = NULL;
3724             goto cleanup;
3725         }
3726     }
3727
3728     if (parser->tok != '}') {
3729         block = NULL;
3730     } else {
3731         (void)parser_next(parser);
3732     }
3733
3734 cleanup:
3735     if (!parser_leaveblock(parser))
3736         retval = false;
3737     return retval && !!block;
3738 }
3739
3740 static ast_block* parse_block(parser_t *parser)
3741 {
3742     ast_block *block;
3743     block = ast_block_new(parser_ctx(parser));
3744     if (!block)
3745         return NULL;
3746     if (!parse_block_into(parser, block)) {
3747         ast_block_delete(block);
3748         return NULL;
3749     }
3750     return block;
3751 }
3752
3753 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3754 {
3755     if (parser->tok == '{') {
3756         *out = (ast_expression*)parse_block(parser);
3757         return !!*out;
3758     }
3759     return parse_statement(parser, NULL, out, false);
3760 }
3761
3762 static bool create_vector_members(ast_value *var, ast_member **me)
3763 {
3764     size_t i;
3765     size_t len = strlen(var->name);
3766
3767     for (i = 0; i < 3; ++i) {
3768         char *name = (char*)mem_a(len+3);
3769         memcpy(name, var->name, len);
3770         name[len+0] = '_';
3771         name[len+1] = 'x'+i;
3772         name[len+2] = 0;
3773         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3774         mem_d(name);
3775         if (!me[i])
3776             break;
3777     }
3778     if (i == 3)
3779         return true;
3780
3781     /* unroll */
3782     do { ast_member_delete(me[--i]); } while(i);
3783     return false;
3784 }
3785
3786 static bool parse_function_body(parser_t *parser, ast_value *var)
3787 {
3788     ast_block      *block = NULL;
3789     ast_function   *func;
3790     ast_function   *old;
3791     size_t          parami;
3792
3793     ast_expression *framenum  = NULL;
3794     ast_expression *nextthink = NULL;
3795     /* None of the following have to be deleted */
3796     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3797     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3798     bool            has_frame_think;
3799
3800     bool retval = true;
3801
3802     has_frame_think = false;
3803     old = parser->function;
3804
3805     if (var->expression.flags & AST_FLAG_ALIAS) {
3806         parseerror(parser, "function aliases cannot have bodies");
3807         return false;
3808     }
3809
3810     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3811         parseerror(parser, "gotos/labels leaking");
3812         return false;
3813     }
3814
3815     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3816         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3817                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3818         {
3819             return false;
3820         }
3821     }
3822
3823     if (parser->tok == '[') {
3824         /* got a frame definition: [ framenum, nextthink ]
3825          * this translates to:
3826          * self.frame = framenum;
3827          * self.nextthink = time + 0.1;
3828          * self.think = nextthink;
3829          */
3830         nextthink = NULL;
3831
3832         fld_think     = parser_find_field(parser, "think");
3833         fld_nextthink = parser_find_field(parser, "nextthink");
3834         fld_frame     = parser_find_field(parser, "frame");
3835         if (!fld_think || !fld_nextthink || !fld_frame) {
3836             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3837             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3838             return false;
3839         }
3840         gbl_time      = parser_find_global(parser, "time");
3841         gbl_self      = parser_find_global(parser, "self");
3842         if (!gbl_time || !gbl_self) {
3843             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3844             parseerror(parser, "please declare the following globals: `time`, `self`");
3845             return false;
3846         }
3847
3848         if (!parser_next(parser))
3849             return false;
3850
3851         framenum = parse_expression_leave(parser, true, false, false);
3852         if (!framenum) {
3853             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3854             return false;
3855         }
3856         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3857             ast_unref(framenum);
3858             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3859             return false;
3860         }
3861
3862         if (parser->tok != ',') {
3863             ast_unref(framenum);
3864             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3865             parseerror(parser, "Got a %i\n", parser->tok);
3866             return false;
3867         }
3868
3869         if (!parser_next(parser)) {
3870             ast_unref(framenum);
3871             return false;
3872         }
3873
3874         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3875         {
3876             /* qc allows the use of not-yet-declared functions here
3877              * - this automatically creates a prototype */
3878             ast_value      *thinkfunc;
3879             ast_expression *functype = fld_think->next;
3880
3881             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3882             if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3883                 ast_unref(framenum);
3884                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3885                 return false;
3886             }
3887             ast_type_adopt(thinkfunc, functype);
3888
3889             if (!parser_next(parser)) {
3890                 ast_unref(framenum);
3891                 ast_delete(thinkfunc);
3892                 return false;
3893             }
3894
3895             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3896
3897             nextthink = (ast_expression*)thinkfunc;
3898
3899         } else {
3900             nextthink = parse_expression_leave(parser, true, false, false);
3901             if (!nextthink) {
3902                 ast_unref(framenum);
3903                 parseerror(parser, "expected a think-function in [frame,think] notation");
3904                 return false;
3905             }
3906         }
3907
3908         if (!ast_istype(nextthink, ast_value)) {
3909             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3910             retval = false;
3911         }
3912
3913         if (retval && parser->tok != ']') {
3914             parseerror(parser, "expected closing `]` for [frame,think] notation");
3915             retval = false;
3916         }
3917
3918         if (retval && !parser_next(parser)) {
3919             retval = false;
3920         }
3921
3922         if (retval && parser->tok != '{') {
3923             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3924             retval = false;
3925         }
3926
3927         if (!retval) {
3928             ast_unref(nextthink);
3929             ast_unref(framenum);
3930             return false;
3931         }
3932
3933         has_frame_think = true;
3934     }
3935
3936     block = ast_block_new(parser_ctx(parser));
3937     if (!block) {
3938         parseerror(parser, "failed to allocate block");
3939         if (has_frame_think) {
3940             ast_unref(nextthink);
3941             ast_unref(framenum);
3942         }
3943         return false;
3944     }
3945
3946     if (has_frame_think) {
3947         lex_ctx_t ctx;
3948         ast_expression *self_frame;
3949         ast_expression *self_nextthink;
3950         ast_expression *self_think;
3951         ast_expression *time_plus_1;
3952         ast_store *store_frame;
3953         ast_store *store_nextthink;
3954         ast_store *store_think;
3955
3956         ctx = parser_ctx(parser);
3957         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3958         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3959         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3960
3961         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3962                          gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3963
3964         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3965             if (self_frame)     ast_delete(self_frame);
3966             if (self_nextthink) ast_delete(self_nextthink);
3967             if (self_think)     ast_delete(self_think);
3968             if (time_plus_1)    ast_delete(time_plus_1);
3969             retval = false;
3970         }
3971
3972         if (retval)
3973         {
3974             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3975             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3976             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3977
3978             if (!store_frame) {
3979                 ast_delete(self_frame);
3980                 retval = false;
3981             }
3982             if (!store_nextthink) {
3983                 ast_delete(self_nextthink);
3984                 retval = false;
3985             }
3986             if (!store_think) {
3987                 ast_delete(self_think);
3988                 retval = false;
3989             }
3990             if (!retval) {
3991                 if (store_frame)     ast_delete(store_frame);
3992                 if (store_nextthink) ast_delete(store_nextthink);
3993                 if (store_think)     ast_delete(store_think);
3994                 retval = false;
3995             }
3996             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3997                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3998                 !ast_block_add_expr(block, (ast_expression*)store_think))
3999             {
4000                 retval = false;
4001             }
4002         }
4003
4004         if (!retval) {
4005             parseerror(parser, "failed to generate code for [frame,think]");
4006             ast_unref(nextthink);
4007             ast_unref(framenum);
4008             ast_delete(block);
4009             return false;
4010         }
4011     }
4012
4013     if (var->hasvalue) {
4014         if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
4015             parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4016             ast_block_delete(block);
4017             goto enderr;
4018         }
4019         func = var->constval.vfunc;
4020
4021         if (!func) {
4022             parseerror(parser, "internal error: NULL function: `%s`", var->name);
4023             ast_block_delete(block);
4024             goto enderr;
4025         }
4026     } else {
4027         func = ast_function_new(ast_ctx(var), var->name, var);
4028
4029         if (!func) {
4030             parseerror(parser, "failed to allocate function for `%s`", var->name);
4031             ast_block_delete(block);
4032             goto enderr;
4033         }
4034         vec_push(parser->functions, func);
4035     }
4036
4037     parser_enterblock(parser);
4038
4039     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4040         size_t     e;
4041         ast_value *param = var->expression.params[parami];
4042         ast_member *me[3];
4043
4044         if (param->expression.vtype != TYPE_VECTOR &&
4045             (param->expression.vtype != TYPE_FIELD ||
4046              param->expression.next->vtype != TYPE_VECTOR))
4047         {
4048             continue;
4049         }
4050
4051         if (!create_vector_members(param, me)) {
4052             ast_block_delete(block);
4053             goto enderrfn;
4054         }
4055
4056         for (e = 0; e < 3; ++e) {
4057             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4058             ast_block_collect(block, (ast_expression*)me[e]);
4059         }
4060     }
4061
4062     if (var->argcounter && !func->argc) {
4063         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4064         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4065         func->argc = argc;
4066     }
4067
4068     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4069         char name[1024];
4070         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4071         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4072         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4073         varargs->expression.count = 0;
4074         util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4075         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4076             ast_delete(varargs);
4077             ast_block_delete(block);
4078             goto enderrfn;
4079         }
4080         util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4081         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4082             ast_delete(varargs);
4083             ast_block_delete(block);
4084             goto enderrfn;
4085         }
4086         func->varargs     = varargs;
4087         func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4088     }
4089
4090     parser->function = func;
4091     if (!parse_block_into(parser, block)) {
4092         ast_block_delete(block);
4093         goto enderrfn;
4094     }
4095
4096     vec_push(func->blocks, block);
4097
4098     parser->function = old;
4099     if (!parser_leaveblock(parser))
4100         retval = false;
4101     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4102         parseerror(parser, "internal error: local scopes left");
4103         retval = false;
4104     }
4105
4106     if (parser->tok == ';')
4107         return parser_next(parser);
4108     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4109         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4110     return retval;
4111
4112 enderrfn:
4113     (void)!parser_leaveblock(parser);
4114     vec_pop(parser->functions);
4115     ast_function_delete(func);
4116     var->constval.vfunc = NULL;
4117
4118 enderr:
4119     parser->function = old;
4120     return false;
4121 }
4122
4123 static ast_expression *array_accessor_split(
4124     parser_t  *parser,
4125     ast_value *array,
4126     ast_value *index,
4127     size_t     middle,
4128     ast_expression *left,
4129     ast_expression *right
4130     )
4131 {
4132     ast_ifthen *ifthen;
4133     ast_binary *cmp;
4134
4135     lex_ctx_t ctx = ast_ctx(array);
4136
4137     if (!left || !right) {
4138         if (left)  ast_delete(left);
4139         if (right) ast_delete(right);
4140         return NULL;
4141     }
4142
4143     cmp = ast_binary_new(ctx, INSTR_LT,
4144                          (ast_expression*)index,
4145                          (ast_expression*)fold_constgen_float(parser->fold, middle));
4146     if (!cmp) {
4147         ast_delete(left);
4148         ast_delete(right);
4149         parseerror(parser, "internal error: failed to create comparison for array setter");
4150         return NULL;
4151     }
4152
4153     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4154     if (!ifthen) {
4155         ast_delete(cmp); /* will delete left and right */
4156         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4157         return NULL;
4158     }
4159
4160     return (ast_expression*)ifthen;
4161 }
4162
4163 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4164 {
4165     lex_ctx_t ctx = ast_ctx(array);
4166
4167     if (from+1 == afterend) {
4168         /* set this value */
4169         ast_block       *block;
4170         ast_return      *ret;
4171         ast_array_index *subscript;
4172         ast_store       *st;
4173         int assignop = type_store_instr[value->expression.vtype];
4174
4175         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4176             assignop = INSTR_STORE_V;
4177
4178         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4179         if (!subscript)
4180             return NULL;
4181
4182         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4183         if (!st) {
4184             ast_delete(subscript);
4185             return NULL;
4186         }
4187
4188         block = ast_block_new(ctx);
4189         if (!block) {
4190             ast_delete(st);
4191             return NULL;
4192         }
4193
4194         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4195             ast_delete(block);
4196             return NULL;
4197         }
4198
4199         ret = ast_return_new(ctx, NULL);
4200         if (!ret) {
4201             ast_delete(block);
4202             return NULL;
4203         }
4204
4205         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4206             ast_delete(block);
4207             return NULL;
4208         }
4209
4210         return (ast_expression*)block;
4211     } else {
4212         ast_expression *left, *right;
4213         size_t diff = afterend - from;
4214         size_t middle = from + diff/2;
4215         left  = array_setter_node(parser, array, index, value, from, middle);
4216         right = array_setter_node(parser, array, index, value, middle, afterend);
4217         return array_accessor_split(parser, array, index, middle, left, right);
4218     }
4219 }
4220
4221 static ast_expression *array_field_setter_node(
4222     parser_t  *parser,
4223     ast_value *array,
4224     ast_value *entity,
4225     ast_value *index,
4226     ast_value *value,
4227     size_t     from,
4228     size_t     afterend)
4229 {
4230     lex_ctx_t ctx = ast_ctx(array);
4231
4232     if (from+1 == afterend) {
4233         /* set this value */
4234         ast_block       *block;
4235         ast_return      *ret;
4236         ast_entfield    *entfield;
4237         ast_array_index *subscript;
4238         ast_store       *st;
4239         int assignop = type_storep_instr[value->expression.vtype];
4240
4241         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4242             assignop = INSTR_STOREP_V;
4243
4244         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4245         if (!subscript)
4246             return NULL;
4247
4248         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4249         subscript->expression.vtype = TYPE_FIELD;
4250
4251         entfield = ast_entfield_new_force(ctx,
4252                                           (ast_expression*)entity,
4253                                           (ast_expression*)subscript,
4254                                           (ast_expression*)subscript);
4255         if (!entfield) {
4256             ast_delete(subscript);
4257             return NULL;
4258         }
4259
4260         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4261         if (!st) {
4262             ast_delete(entfield);
4263             return NULL;
4264         }
4265
4266         block = ast_block_new(ctx);
4267         if (!block) {
4268             ast_delete(st);
4269             return NULL;
4270         }
4271
4272         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4273             ast_delete(block);
4274             return NULL;
4275         }
4276
4277         ret = ast_return_new(ctx, NULL);
4278         if (!ret) {
4279             ast_delete(block);
4280             return NULL;
4281         }
4282
4283         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4284             ast_delete(block);
4285             return NULL;
4286         }
4287
4288         return (ast_expression*)block;
4289     } else {
4290         ast_expression *left, *right;
4291         size_t diff = afterend - from;
4292         size_t middle = from + diff/2;
4293         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4294         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4295         return array_accessor_split(parser, array, index, middle, left, right);
4296     }
4297 }
4298
4299 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4300 {
4301     lex_ctx_t ctx = ast_ctx(array);
4302
4303     if (from+1 == afterend) {
4304         ast_return      *ret;
4305         ast_array_index *subscript;
4306
4307         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4308         if (!subscript)
4309             return NULL;
4310
4311         ret = ast_return_new(ctx, (ast_expression*)subscript);
4312         if (!ret) {
4313             ast_delete(subscript);
4314             return NULL;
4315         }
4316
4317         return (ast_expression*)ret;
4318     } else {
4319         ast_expression *left, *right;
4320         size_t diff = afterend - from;
4321         size_t middle = from + diff/2;
4322         left  = array_getter_node(parser, array, index, from, middle);
4323         right = array_getter_node(parser, array, index, middle, afterend);
4324         return array_accessor_split(parser, array, index, middle, left, right);
4325     }
4326 }
4327
4328 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4329 {
4330     ast_function   *func = NULL;
4331     ast_value      *fval = NULL;
4332     ast_block      *body = NULL;
4333
4334     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4335     if (!fval) {
4336         parseerror(parser, "failed to create accessor function value");
4337         return false;
4338     }
4339
4340     func = ast_function_new(ast_ctx(array), funcname, fval);
4341     if (!func) {
4342         ast_delete(fval);
4343         parseerror(parser, "failed to create accessor function node");
4344         return false;
4345     }
4346
4347     body = ast_block_new(ast_ctx(array));
4348     if (!body) {
4349         parseerror(parser, "failed to create block for array accessor");
4350         ast_delete(fval);
4351         ast_delete(func);
4352         return false;
4353     }
4354
4355     vec_push(func->blocks, body);
4356     *out = fval;
4357
4358     vec_push(parser->accessors, fval);
4359
4360     return true;
4361 }
4362
4363 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4364 {
4365     ast_value      *index = NULL;
4366     ast_value      *value = NULL;
4367     ast_function   *func;
4368     ast_value      *fval;
4369
4370     if (!ast_istype(array->expression.next, ast_value)) {
4371         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4372         return NULL;
4373     }
4374
4375     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4376         return NULL;
4377     func = fval->constval.vfunc;
4378     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4379
4380     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4381     value = ast_value_copy((ast_value*)array->expression.next);
4382
4383     if (!index || !value) {
4384         parseerror(parser, "failed to create locals for array accessor");
4385         goto cleanup;
4386     }
4387     (void)!ast_value_set_name(value, "value"); /* not important */
4388     vec_push(fval->expression.params, index);
4389     vec_push(fval->expression.params, value);
4390
4391     array->setter = fval;
4392     return fval;
4393 cleanup:
4394     if (index) ast_delete(index);
4395     if (value) ast_delete(value);
4396     ast_delete(func);
4397     ast_delete(fval);
4398     return NULL;
4399 }
4400
4401 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4402 {
4403     ast_expression *root = NULL;
4404     root = array_setter_node(parser, array,
4405                              array->setter->expression.params[0],
4406                              array->setter->expression.params[1],
4407                              0, array->expression.count);
4408     if (!root) {
4409         parseerror(parser, "failed to build accessor search tree");
4410         return false;
4411     }
4412     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4413         ast_delete(root);
4414         return false;
4415     }
4416     return true;
4417 }
4418
4419 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4420 {
4421     if (!parser_create_array_setter_proto(parser, array, funcname))
4422         return false;
4423     return parser_create_array_setter_impl(parser, array);
4424 }
4425
4426 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4427 {
4428     ast_expression *root = NULL;
4429     ast_value      *entity = NULL;
4430     ast_value      *index = NULL;
4431     ast_value      *value = NULL;
4432     ast_function   *func;
4433     ast_value      *fval;
4434
4435     if (!ast_istype(array->expression.next, ast_value)) {
4436         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4437         return false;
4438     }
4439
4440     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4441         return false;
4442     func = fval->constval.vfunc;
4443     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4444
4445     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4446     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4447     value  = ast_value_copy((ast_value*)array->expression.next);
4448     if (!entity || !index || !value) {
4449         parseerror(parser, "failed to create locals for array accessor");
4450         goto cleanup;
4451     }
4452     (void)!ast_value_set_name(value, "value"); /* not important */
4453     vec_push(fval->expression.params, entity);
4454     vec_push(fval->expression.params, index);
4455     vec_push(fval->expression.params, value);
4456
4457     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4458     if (!root) {
4459         parseerror(parser, "failed to build accessor search tree");
4460         goto cleanup;
4461     }
4462
4463     array->setter = fval;
4464     return ast_block_add_expr(func->blocks[0], root);
4465 cleanup:
4466     if (entity) ast_delete(entity);
4467     if (index)  ast_delete(index);
4468     if (value)  ast_delete(value);
4469     if (root)   ast_delete(root);
4470     ast_delete(func);
4471     ast_delete(fval);
4472     return false;
4473 }
4474
4475 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4476 {
4477     ast_value      *index = NULL;
4478     ast_value      *fval;
4479     ast_function   *func;
4480
4481     /* NOTE: checking array->expression.next rather than elemtype since
4482      * for fields elemtype is a temporary fieldtype.
4483      */
4484     if (!ast_istype(array->expression.next, ast_value)) {
4485         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4486         return NULL;
4487     }
4488
4489     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4490         return NULL;
4491     func = fval->constval.vfunc;
4492     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4493
4494     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4495
4496     if (!index) {
4497         parseerror(parser, "failed to create locals for array accessor");
4498         goto cleanup;
4499     }
4500     vec_push(fval->expression.params, index);
4501
4502     array->getter = fval;
4503     return fval;
4504 cleanup:
4505     if (index) ast_delete(index);
4506     ast_delete(func);
4507     ast_delete(fval);
4508     return NULL;
4509 }
4510
4511 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4512 {
4513     ast_expression *root = NULL;
4514
4515     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4516     if (!root) {
4517         parseerror(parser, "failed to build accessor search tree");
4518         return false;
4519     }
4520     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4521         ast_delete(root);
4522         return false;
4523     }
4524     return true;
4525 }
4526
4527 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4528 {
4529     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4530         return false;
4531     return parser_create_array_getter_impl(parser, array);
4532 }
4533
4534 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4535 {
4536     lex_ctx_t     ctx;
4537     size_t      i;
4538     ast_value **params;
4539     ast_value  *param;
4540     ast_value  *fval;
4541     bool        first = true;
4542     bool        variadic = false;
4543     ast_value  *varparam = NULL;
4544     char       *argcounter = NULL;
4545
4546     ctx = parser_ctx(parser);
4547
4548     /* for the sake of less code we parse-in in this function */
4549     if (!parser_next(parser)) {
4550         ast_delete(var);
4551         parseerror(parser, "expected parameter list");
4552         return NULL;
4553     }
4554
4555     params = NULL;
4556
4557     /* parse variables until we hit a closing paren */
4558     while (parser->tok != ')') {
4559         bool is_varargs = false;
4560
4561         if (!first) {
4562             /* there must be commas between them */
4563             if (parser->tok != ',') {
4564                 parseerror(parser, "expected comma or end of parameter list");
4565                 goto on_error;
4566             }
4567             if (!parser_next(parser)) {
4568                 parseerror(parser, "expected parameter");
4569                 goto on_error;
4570             }
4571         }
4572         first = false;
4573
4574         param = parse_typename(parser, NULL, NULL, &is_varargs);
4575         if (!param && !is_varargs)
4576             goto on_error;
4577         if (is_varargs) {
4578             /* '...' indicates a varargs function */
4579             variadic = true;
4580             if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4581                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4582                 goto on_error;
4583             }
4584             if (parser->tok == TOKEN_IDENT) {
4585                 argcounter = util_strdup(parser_tokval(parser));
4586                 if (!parser_next(parser) || parser->tok != ')') {
4587                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4588                     goto on_error;
4589                 }
4590             }
4591         } else {
4592             vec_push(params, param);
4593             if (param->expression.vtype >= TYPE_VARIANT) {
4594                 char tname[1024]; /* typename is reserved in C++ */
4595                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4596                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4597                 goto on_error;
4598             }
4599             /* type-restricted varargs */
4600             if (parser->tok == TOKEN_DOTS) {
4601                 variadic = true;
4602                 varparam = vec_last(params);
4603                 vec_pop(params);
4604                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4605                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4606                     goto on_error;
4607                 }
4608                 if (parser->tok == TOKEN_IDENT) {
4609                     argcounter = util_strdup(parser_tokval(parser));
4610                     if (!parser_next(parser) || parser->tok != ')') {
4611                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4612                         goto on_error;
4613                     }
4614                 }
4615             }
4616         }
4617     }
4618
4619     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4620         vec_free(params);
4621
4622     /* sanity check */
4623     if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4624         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4625
4626     /* parse-out */
4627     if (!parser_next(parser)) {
4628         parseerror(parser, "parse error after typename");
4629         goto on_error;
4630     }
4631
4632     /* now turn 'var' into a function type */
4633     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4634     fval->expression.next     = (ast_expression*)var;
4635     if (variadic)
4636         fval->expression.flags |= AST_FLAG_VARIADIC;
4637     var = fval;
4638
4639     var->expression.params   = params;
4640     var->expression.varparam = (ast_expression*)varparam;
4641     var->argcounter          = argcounter;
4642     params = NULL;
4643
4644     return var;
4645
4646 on_error:
4647     if (argcounter)
4648         mem_d(argcounter);
4649     if (varparam)
4650         ast_delete(varparam);
4651     ast_delete(var);
4652     for (i = 0; i < vec_size(params); ++i)
4653         ast_delete(params[i]);
4654     vec_free(params);
4655     return NULL;
4656 }
4657
4658 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4659 {
4660     ast_expression *cexp;
4661     ast_value      *cval, *tmp;
4662     lex_ctx_t ctx;
4663
4664     ctx = parser_ctx(parser);
4665
4666     if (!parser_next(parser)) {
4667         ast_delete(var);
4668         parseerror(parser, "expected array-size");
4669         return NULL;
4670     }
4671
4672     if (parser->tok != ']') {
4673         cexp = parse_expression_leave(parser, true, false, false);
4674
4675         if (!cexp || !ast_istype(cexp, ast_value)) {
4676             if (cexp)
4677                 ast_unref(cexp);
4678             ast_delete(var);
4679             parseerror(parser, "expected array-size as constant positive integer");
4680             return NULL;
4681         }
4682         cval = (ast_value*)cexp;
4683     }
4684     else {
4685         cexp = NULL;
4686         cval = NULL;
4687     }
4688
4689     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4690     tmp->expression.next = (ast_expression*)var;
4691     var = tmp;
4692
4693     if (cval) {
4694         if (cval->expression.vtype == TYPE_INTEGER)
4695             tmp->expression.count = cval->constval.vint;
4696         else if (cval->expression.vtype == TYPE_FLOAT)
4697             tmp->expression.count = cval->constval.vfloat;
4698         else {
4699             ast_unref(cexp);
4700             ast_delete(var);
4701             parseerror(parser, "array-size must be a positive integer constant");
4702             return NULL;
4703         }
4704
4705         ast_unref(cexp);
4706     } else {
4707         var->expression.count = -1;
4708         var->expression.flags |= AST_FLAG_ARRAY_INIT;
4709     }
4710
4711     if (parser->tok != ']') {
4712         ast_delete(var);
4713         parseerror(parser, "expected ']' after array-size");
4714         return NULL;
4715     }
4716     if (!parser_next(parser)) {
4717         ast_delete(var);
4718         parseerror(parser, "error after parsing array size");
4719         return NULL;
4720     }
4721     return var;
4722 }
4723
4724 /* Parse a complete typename.
4725  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4726  * but when parsing variables separated by comma
4727  * 'storebase' should point to where the base-type should be kept.
4728  * The base type makes up every bit of type information which comes *before* the
4729  * variable name.
4730  *
4731  * NOTE: The value must either be named, have a NULL name, or a name starting
4732  *       with '<'. In the first case, this will be the actual variable or type
4733  *       name, in the other cases it is assumed that the name will appear
4734  *       later, and an error is generated otherwise.
4735  *
4736  * The following will be parsed in its entirety:
4737  *     void() foo()
4738  * The 'basetype' in this case is 'void()'
4739  * and if there's a comma after it, say:
4740  *     void() foo(), bar
4741  * then the type-information 'void()' can be stored in 'storebase'
4742  */
4743 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4744 {
4745     ast_value *var, *tmp;
4746     lex_ctx_t    ctx;
4747
4748     const char *name = NULL;
4749     bool        isfield  = false;
4750     bool        wasarray = false;
4751     size_t      morefields = 0;
4752
4753     bool        vararg = (parser->tok == TOKEN_DOTS);
4754
4755     ctx = parser_ctx(parser);
4756
4757     /* types may start with a dot */
4758     if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4759         isfield = true;
4760         if (parser->tok == TOKEN_DOTS)
4761             morefields += 2;
4762         /* if we parsed a dot we need a typename now */
4763         if (!parser_next(parser)) {
4764             parseerror(parser, "expected typename for field definition");
4765             return NULL;
4766         }
4767
4768         /* Further dots are handled seperately because they won't be part of the
4769          * basetype
4770          */
4771         while (true) {
4772             if (parser->tok == '.')
4773                 ++morefields;
4774             else if (parser->tok == TOKEN_DOTS)
4775                 morefields += 3;
4776             else
4777                 break;
4778             vararg = false;
4779             if (!parser_next(parser)) {
4780                 parseerror(parser, "expected typename for field definition");
4781                 return NULL;
4782             }
4783         }
4784     }
4785     if (parser->tok == TOKEN_IDENT)
4786         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4787     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4788         if (vararg && is_vararg) {
4789             *is_vararg = true;
4790             return NULL;
4791         }
4792         parseerror(parser, "expected typename");
4793         return NULL;
4794     }
4795
4796     /* generate the basic type value */
4797     if (cached_typedef) {
4798         var = ast_value_copy(cached_typedef);
4799         ast_value_set_name(var, "<type(from_def)>");
4800     } else
4801         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4802
4803     for (; morefields; --morefields) {
4804         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4805         tmp->expression.next = (ast_expression*)var;
4806         var = tmp;
4807     }
4808
4809     /* do not yet turn into a field - remember:
4810      * .void() foo; is a field too
4811      * .void()() foo; is a function
4812      */
4813
4814     /* parse on */
4815     if (!parser_next(parser)) {
4816         ast_delete(var);
4817         parseerror(parser, "parse error after typename");
4818         return NULL;
4819     }
4820
4821     /* an opening paren now starts the parameter-list of a function
4822      * this is where original-QC has parameter lists.
4823      * We allow a single parameter list here.
4824      * Much like fteqcc we don't allow `float()() x`
4825      */
4826     if (parser->tok == '(') {
4827         var = parse_parameter_list(parser, var);
4828         if (!var)
4829             return NULL;
4830     }
4831
4832     /* store the base if requested */
4833     if (storebase) {
4834         *storebase = ast_value_copy(var);
4835         if (isfield) {
4836             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4837             tmp->expression.next = (ast_expression*)*storebase;
4838             *storebase = tmp;
4839         }
4840     }
4841
4842     /* there may be a name now */
4843     if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4844         if (!strcmp(parser_tokval(parser), "break"))
4845             (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4846         else if (parser->tok == TOKEN_KEYWORD)
4847             goto leave;
4848
4849         name = util_strdup(parser_tokval(parser));
4850
4851         /* parse on */
4852         if (!parser_next(parser)) {
4853             ast_delete(var);
4854             mem_d(name);
4855             parseerror(parser, "error after variable or field declaration");
4856             return NULL;
4857         }
4858     }
4859
4860     leave:
4861     /* now this may be an array */
4862     if (parser->tok == '[') {
4863         wasarray = true;
4864         var = parse_arraysize(parser, var);
4865         if (!var) {
4866             if (name) mem_d(name);
4867             return NULL;
4868         }
4869     }
4870
4871     /* This is the point where we can turn it into a field */
4872     if (isfield) {
4873         /* turn it into a field if desired */
4874         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4875         tmp->expression.next = (ast_expression*)var;
4876         var = tmp;
4877     }
4878
4879     /* now there may be function parens again */
4880     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4881         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4882     if (parser->tok == '(' && wasarray)
4883         parseerror(parser, "arrays as part of a return type is not supported");
4884     while (parser->tok == '(') {
4885         var = parse_parameter_list(parser, var);
4886         if (!var) {
4887             if (name) mem_d(name);
4888             return NULL;
4889         }
4890     }
4891
4892     /* finally name it */
4893     if (name) {
4894         if (!ast_value_set_name(var, name)) {
4895             ast_delete(var);
4896             mem_d(name);
4897             parseerror(parser, "internal error: failed to set name");
4898             return NULL;
4899         }
4900         /* free the name, ast_value_set_name duplicates */
4901         mem_d(name);
4902     }
4903
4904     return var;
4905 }
4906
4907 static bool parse_typedef(parser_t *parser)
4908 {
4909     ast_value      *typevar, *oldtype;
4910     ast_expression *old;
4911
4912     typevar = parse_typename(parser, NULL, NULL, NULL);
4913
4914     if (!typevar)
4915         return false;
4916
4917     /* while parsing types, the ast_value's get named '<something>' */
4918     if (!typevar->name || typevar->name[0] == '<') {
4919         parseerror(parser, "missing name in typedef");
4920         ast_delete(typevar);
4921         return false;
4922     }
4923
4924     if ( (old = parser_find_var(parser, typevar->name)) ) {
4925         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4926                    " -> `%s` has been declared here: %s:%i",
4927                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4928         ast_delete(typevar);
4929         return false;
4930     }
4931
4932     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4933         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4934                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4935         ast_delete(typevar);
4936         return false;
4937     }
4938
4939     vec_push(parser->_typedefs, typevar);
4940     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4941
4942     if (parser->tok != ';') {
4943         parseerror(parser, "expected semicolon after typedef");
4944         return false;
4945     }
4946     if (!parser_next(parser)) {
4947         parseerror(parser, "parse error after typedef");
4948         return false;
4949     }
4950
4951     return true;
4952 }
4953
4954 static const char *cvq_to_str(int cvq) {
4955     switch (cvq) {
4956         case CV_NONE:  return "none";
4957         case CV_VAR:   return "`var`";
4958         case CV_CONST: return "`const`";
4959         default:       return "<INVALID>";
4960     }
4961 }
4962
4963 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4964 {
4965     bool av, ao;
4966     if (proto->cvq != var->cvq) {
4967         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4968               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4969               parser->tok == '='))
4970         {
4971             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4972                                  "`%s` declared with different qualifiers: %s\n"
4973                                  " -> previous declaration here: %s:%i uses %s",
4974                                  var->name, cvq_to_str(var->cvq),
4975                                  ast_ctx(proto).file, ast_ctx(proto).line,
4976                                  cvq_to_str(proto->cvq));
4977         }
4978     }
4979     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4980     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4981     if (!av != !ao) {
4982         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4983                              "`%s` declared with different attributes%s\n"
4984                              " -> previous declaration here: %s:%i",
4985                              var->name, (av ? ": noreturn" : ""),
4986                              ast_ctx(proto).file, ast_ctx(proto).line,
4987                              (ao ? ": noreturn" : ""));
4988     }
4989     return true;
4990 }
4991
4992 static bool create_array_accessors(parser_t *parser, ast_value *var)
4993 {
4994     char name[1024];
4995     util_snprintf(name, sizeof(name), "%s##SET", var->name);
4996     if (!parser_create_array_setter(parser, var, name))
4997         return false;
4998     util_snprintf(name, sizeof(name), "%s##GET", var->name);
4999     if (!parser_create_array_getter(parser, var, var->expression.next, name))
5000         return false;
5001     return true;
5002 }
5003
5004 static bool parse_array(parser_t *parser, ast_value *array)
5005 {
5006     size_t i;
5007     if (array->initlist) {
5008         parseerror(parser, "array already initialized elsewhere");
5009         return false;
5010     }
5011     if (!parser_next(parser)) {
5012         parseerror(parser, "parse error in array initializer");
5013         return false;
5014     }
5015     i = 0;
5016     while (parser->tok != '}') {
5017         ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5018         if (!v)
5019             return false;
5020         if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5021             ast_unref(v);
5022             parseerror(parser, "initializing element must be a compile time constant");
5023             return false;
5024         }
5025         vec_push(array->initlist, v->constval);
5026         if (v->expression.vtype == TYPE_STRING) {
5027             array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5028             ++i;
5029         }
5030         ast_unref(v);
5031         if (parser->tok == '}')
5032             break;
5033         if (parser->tok != ',' || !parser_next(parser)) {
5034             parseerror(parser, "expected comma or '}' in element list");
5035             return false;
5036         }
5037     }
5038     if (!parser_next(parser) || parser->tok != ';') {
5039         parseerror(parser, "expected semicolon after initializer, got %s");
5040         return false;
5041     }
5042     /*
5043     if (!parser_next(parser)) {
5044         parseerror(parser, "parse error after initializer");
5045         return false;
5046     }
5047     */
5048
5049     if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5050         if (array->expression.count != (size_t)-1) {
5051             parseerror(parser, "array `%s' has already been initialized with %u elements",
5052                        array->name, (unsigned)array->expression.count);
5053         }
5054         array->expression.count = vec_size(array->initlist);
5055         if (!create_array_accessors(parser, array))
5056             return false;
5057     }
5058     return true;
5059 }
5060
5061 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)
5062 {
5063     ast_value *var;
5064     ast_value *proto;
5065     ast_expression *old;
5066     bool       was_end;
5067     size_t     i;
5068
5069     ast_value *basetype = NULL;
5070     bool      retval    = true;
5071     bool      isparam   = false;
5072     bool      isvector  = false;
5073     bool      cleanvar  = true;
5074     bool      wasarray  = false;
5075
5076     ast_member *me[3] = { NULL, NULL, NULL };
5077
5078     if (!localblock && is_static)
5079         parseerror(parser, "`static` qualifier is not supported in global scope");
5080
5081     /* get the first complete variable */
5082     var = parse_typename(parser, &basetype, cached_typedef, NULL);
5083     if (!var) {
5084         if (basetype)
5085             ast_delete(basetype);
5086         return false;
5087     }
5088
5089     /* while parsing types, the ast_value's get named '<something>' */
5090     if (!var->name || var->name[0] == '<') {
5091         parseerror(parser, "declaration does not declare anything");
5092         if (basetype)
5093             ast_delete(basetype);
5094         return false;
5095     }
5096
5097     while (true) {
5098         proto = NULL;
5099         wasarray = false;
5100
5101         /* Part 0: finish the type */
5102         if (parser->tok == '(') {
5103             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5104                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5105             var = parse_parameter_list(parser, var);
5106             if (!var) {
5107                 retval = false;
5108                 goto cleanup;
5109             }
5110         }
5111         /* we only allow 1-dimensional arrays */
5112         if (parser->tok == '[') {
5113             wasarray = true;
5114             var = parse_arraysize(parser, var);
5115             if (!var) {
5116                 retval = false;
5117                 goto cleanup;
5118             }
5119         }
5120         if (parser->tok == '(' && wasarray) {
5121             parseerror(parser, "arrays as part of a return type is not supported");
5122             /* we'll still parse the type completely for now */
5123         }
5124         /* for functions returning functions */
5125         while (parser->tok == '(') {
5126             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5127                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5128             var = parse_parameter_list(parser, var);
5129             if (!var) {
5130                 retval = false;
5131                 goto cleanup;
5132             }
5133         }
5134
5135         var->cvq = qualifier;
5136         var->expression.flags |= qflags;
5137
5138         /*
5139          * store the vstring back to var for alias and
5140          * deprecation messages.
5141          */
5142         if (var->expression.flags & AST_FLAG_DEPRECATED ||
5143             var->expression.flags & AST_FLAG_ALIAS)
5144             var->desc = vstring;
5145
5146         if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5147             parseerror(parser, "function aliases cannot be forward declared");
5148             retval = false;
5149             goto cleanup;
5150         }
5151
5152
5153         /* Part 1:
5154          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5155          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5156          * is then filled with the previous definition and the parameter-names replaced.
5157          */
5158         if (!strcmp(var->name, "nil")) {
5159             if (OPTS_FLAG(UNTYPED_NIL)) {
5160                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5161                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5162             } else
5163                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5164         }
5165         if (!localblock) {
5166             /* Deal with end_sys_ vars */
5167             was_end = false;
5168             if (!strcmp(var->name, "end_sys_globals")) {
5169                 var->uses++;
5170                 parser->crc_globals = vec_size(parser->globals);
5171                 was_end = true;
5172             }
5173             else if (!strcmp(var->name, "end_sys_fields")) {
5174                 var->uses++;
5175                 parser->crc_fields = vec_size(parser->fields);
5176                 was_end = true;
5177             }
5178             if (was_end && var->expression.vtype == TYPE_FIELD) {
5179                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5180                                  "global '%s' hint should not be a field",
5181                                  parser_tokval(parser)))
5182                 {
5183                     retval = false;
5184                     goto cleanup;
5185                 }
5186             }
5187
5188             if (!nofields && var->expression.vtype == TYPE_FIELD)
5189             {
5190                 /* deal with field declarations */
5191                 old = parser_find_field(parser, var->name);
5192                 if (old) {
5193                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5194                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5195                     {
5196                         retval = false;
5197                         goto cleanup;
5198                     }
5199                     ast_delete(var);
5200                     var = NULL;
5201                     goto skipvar;
5202                     /*
5203                     parseerror(parser, "field `%s` already declared here: %s:%i",
5204                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5205                     retval = false;
5206                     goto cleanup;
5207                     */
5208                 }
5209                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5210                     (old = parser_find_global(parser, var->name)))
5211                 {
5212                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5213                     parseerror(parser, "field `%s` already declared here: %s:%i",
5214                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5215                     retval = false;
5216                     goto cleanup;
5217                 }
5218             }
5219             else
5220             {
5221                 /* deal with other globals */
5222                 old = parser_find_global(parser, var->name);
5223                 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5224                 {
5225                     /* This is a function which had a prototype */
5226                     if (!ast_istype(old, ast_value)) {
5227                         parseerror(parser, "internal error: prototype is not an ast_value");
5228                         retval = false;
5229                         goto cleanup;
5230                     }
5231                     proto = (ast_value*)old;
5232                     proto->desc = var->desc;
5233                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5234                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5235                                    proto->name,
5236                                    ast_ctx(proto).file, ast_ctx(proto).line);
5237                         retval = false;
5238                         goto cleanup;
5239                     }
5240                     /* we need the new parameter-names */
5241                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5242                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5243                     if (!parser_check_qualifiers(parser, var, proto)) {
5244                         retval = false;
5245                         if (proto->desc)
5246                             mem_d(proto->desc);
5247                         proto = NULL;
5248                         goto cleanup;
5249                     }
5250                     proto->expression.flags |= var->expression.flags;
5251                     ast_delete(var);
5252                     var = proto;
5253                 }
5254                 else
5255                 {
5256                     /* other globals */
5257                     if (old) {
5258                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5259                                          "global `%s` already declared here: %s:%i",
5260                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5261                         {
5262                             retval = false;
5263                             goto cleanup;
5264                         }
5265                         proto = (ast_value*)old;
5266                         if (!ast_istype(old, ast_value)) {
5267                             parseerror(parser, "internal error: not an ast_value");
5268                             retval = false;
5269                             proto = NULL;
5270                             goto cleanup;
5271                         }
5272                         if (!parser_check_qualifiers(parser, var, proto)) {
5273                             retval = false;
5274                             proto = NULL;
5275                             goto cleanup;
5276                         }
5277                         proto->expression.flags |= var->expression.flags;
5278                         ast_delete(var);
5279                         var = proto;
5280                     }
5281                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5282                         (old = parser_find_field(parser, var->name)))
5283                     {
5284                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5285                         parseerror(parser, "global `%s` already declared here: %s:%i",
5286                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5287                         retval = false;
5288                         goto cleanup;
5289                     }
5290                 }
5291             }
5292         }
5293         else /* it's not a global */
5294         {
5295             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5296             if (old && !isparam) {
5297                 parseerror(parser, "local `%s` already declared here: %s:%i",
5298                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5299                 retval = false;
5300                 goto cleanup;
5301             }
5302             /* doing this here as the above is just for a single scope */
5303             old = parser_find_local(parser, var->name, 0, &isparam);
5304             if (old && isparam) {
5305                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5306                                  "local `%s` is shadowing a parameter", var->name))
5307                 {
5308                     parseerror(parser, "local `%s` already declared here: %s:%i",
5309                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5310                     retval = false;
5311                     goto cleanup;
5312                 }
5313                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5314                     ast_delete(var);
5315                     if (ast_istype(old, ast_value))
5316                         var = proto = (ast_value*)old;
5317                     else {
5318                         var = NULL;
5319                         goto skipvar;
5320                     }
5321                 }
5322             }
5323         }
5324
5325         /* in a noref section we simply bump the usecount */
5326         if (noref || parser->noref)
5327             var->uses++;
5328
5329         /* Part 2:
5330          * Create the global/local, and deal with vector types.
5331          */
5332         if (!proto) {
5333             if (var->expression.vtype == TYPE_VECTOR)
5334                 isvector = true;
5335             else if (var->expression.vtype == TYPE_FIELD &&
5336                      var->expression.next->vtype == TYPE_VECTOR)
5337                 isvector = true;
5338
5339             if (isvector) {
5340                 if (!create_vector_members(var, me)) {
5341                     retval = false;
5342                     goto cleanup;
5343                 }
5344             }
5345
5346             if (!localblock) {
5347                 /* deal with global variables, fields, functions */
5348                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5349                     var->isfield = true;
5350                     vec_push(parser->fields, (ast_expression*)var);
5351                     util_htset(parser->htfields, var->name, var);
5352                     if (isvector) {
5353                         for (i = 0; i < 3; ++i) {
5354                             vec_push(parser->fields, (ast_expression*)me[i]);
5355                             util_htset(parser->htfields, me[i]->name, me[i]);
5356                         }
5357                     }
5358                 }
5359                 else {
5360                     if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5361                         parser_addglobal(parser, var->name, (ast_expression*)var);
5362                         if (isvector) {
5363                             for (i = 0; i < 3; ++i) {
5364                                 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5365                             }
5366                         }
5367                     } else {
5368                         ast_expression *find  = parser_find_global(parser, var->desc);
5369
5370                         if (!find) {
5371                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5372                             return false;
5373                         }
5374
5375                         if (!ast_compare_type((ast_expression*)var, find)) {
5376                             char ty1[1024];
5377                             char ty2[1024];
5378
5379                             ast_type_to_string(find,                  ty1, sizeof(ty1));
5380                             ast_type_to_string((ast_expression*)var,  ty2, sizeof(ty2));
5381
5382                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5383                                 ty1, ty2, var->name
5384                             );
5385                             return false;
5386                         }
5387
5388                         /*
5389                          * add alias to aliases table and to corrector
5390                          * so corrections can apply for aliases as well.
5391                          */
5392                         util_htset(parser->aliases, var->name, find);
5393
5394                         /*
5395                          * add to corrector so corrections can work
5396                          * even for aliases too.
5397                          */
5398                         correct_add (
5399                              vec_last(parser->correct_variables),
5400                             &vec_last(parser->correct_variables_score),
5401                             var->name
5402                         );
5403
5404                         /* generate aliases for vector components */
5405                         if (isvector) {
5406                             char *buffer[3];
5407
5408                             util_asprintf(&buffer[0], "%s_x", var->desc);
5409                             util_asprintf(&buffer[1], "%s_y", var->desc);
5410                             util_asprintf(&buffer[2], "%s_z", var->desc);
5411
5412                             util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5413                             util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5414                             util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5415
5416                             mem_d(buffer[0]);
5417                             mem_d(buffer[1]);
5418                             mem_d(buffer[2]);
5419
5420                             /*
5421                              * add to corrector so corrections can work
5422                              * even for aliases too.
5423                              */
5424                             correct_add (
5425                                  vec_last(parser->correct_variables),
5426                                 &vec_last(parser->correct_variables_score),
5427                                 me[0]->name
5428                             );
5429                             correct_add (
5430                                  vec_last(parser->correct_variables),
5431                                 &vec_last(parser->correct_variables_score),
5432                                 me[1]->name
5433                             );
5434                             correct_add (
5435                                  vec_last(parser->correct_variables),
5436                                 &vec_last(parser->correct_variables_score),
5437                                 me[2]->name
5438                             );
5439                         }
5440                     }
5441                 }
5442             } else {
5443                 if (is_static) {
5444                     /* a static adds itself to be generated like any other global
5445                      * but is added to the local namespace instead
5446                      */
5447                     char   *defname = NULL;
5448                     size_t  prefix_len, ln;
5449
5450                     ln = strlen(parser->function->name);
5451                     vec_append(defname, ln, parser->function->name);
5452
5453                     vec_append(defname, 2, "::");
5454                     /* remember the length up to here */
5455                     prefix_len = vec_size(defname);
5456
5457                     /* Add it to the local scope */
5458                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5459
5460                     /* corrector */
5461                     correct_add (
5462                          vec_last(parser->correct_variables),
5463                         &vec_last(parser->correct_variables_score),
5464                         var->name
5465                     );
5466
5467                     /* now rename the global */
5468                     ln = strlen(var->name);
5469                     vec_append(defname, ln, var->name);
5470                     ast_value_set_name(var, defname);
5471
5472                     /* push it to the to-be-generated globals */
5473                     vec_push(parser->globals, (ast_expression*)var);
5474
5475                     /* same game for the vector members */
5476                     if (isvector) {
5477                         for (i = 0; i < 3; ++i) {
5478                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5479
5480                             /* corrector */
5481                             correct_add(
5482                                  vec_last(parser->correct_variables),
5483                                 &vec_last(parser->correct_variables_score),
5484                                 me[i]->name
5485                             );
5486
5487                             vec_shrinkto(defname, prefix_len);
5488                             ln = strlen(me[i]->name);
5489                             vec_append(defname, ln, me[i]->name);
5490                             ast_member_set_name(me[i], defname);
5491
5492                             vec_push(parser->globals, (ast_expression*)me[i]);
5493                         }
5494                     }
5495                     vec_free(defname);
5496                 } else {
5497                     vec_push(localblock->locals, var);
5498                     parser_addlocal(parser, var->name, (ast_expression*)var);
5499                     if (isvector) {
5500                         for (i = 0; i < 3; ++i) {
5501                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5502                             ast_block_collect(localblock, (ast_expression*)me[i]);
5503                         }
5504                     }
5505                 }
5506             }
5507         }
5508         me[0] = me[1] = me[2] = NULL;
5509         cleanvar = false;
5510         /* Part 2.2
5511          * deal with arrays
5512          */
5513         if (var->expression.vtype == TYPE_ARRAY) {
5514             if (var->expression.count != (size_t)-1) {
5515                 if (!create_array_accessors(parser, var))
5516                     goto cleanup;
5517             }
5518         }
5519         else if (!localblock && !nofields &&
5520                  var->expression.vtype == TYPE_FIELD &&
5521                  var->expression.next->vtype == TYPE_ARRAY)
5522         {
5523             char name[1024];
5524             ast_expression *telem;
5525             ast_value      *tfield;
5526             ast_value      *array = (ast_value*)var->expression.next;
5527
5528             if (!ast_istype(var->expression.next, ast_value)) {
5529                 parseerror(parser, "internal error: field element type must be an ast_value");
5530                 goto cleanup;
5531             }
5532
5533             util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5534             if (!parser_create_array_field_setter(parser, array, name))
5535                 goto cleanup;
5536
5537             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5538             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5539             tfield->expression.next = telem;
5540             util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5541             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5542                 ast_delete(tfield);
5543                 goto cleanup;
5544             }
5545             ast_delete(tfield);
5546         }
5547
5548 skipvar:
5549         if (parser->tok == ';') {
5550             ast_delete(basetype);
5551             if (!parser_next(parser)) {
5552                 parseerror(parser, "error after variable declaration");
5553                 return false;
5554             }
5555             return true;
5556         }
5557
5558         if (parser->tok == ',')
5559             goto another;
5560
5561         /*
5562         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5563         */
5564         if (!var) {
5565             parseerror(parser, "missing comma or semicolon while parsing variables");
5566             break;
5567         }
5568
5569         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5570             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5571                              "initializing expression turns variable `%s` into a constant in this standard",
5572                              var->name) )
5573             {
5574                 break;
5575             }
5576         }
5577
5578         if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5579             if (parser->tok != '=') {
5580                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5581                 break;
5582             }
5583
5584             if (!parser_next(parser)) {
5585                 parseerror(parser, "error parsing initializer");
5586                 break;
5587             }
5588         }
5589         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5590             parseerror(parser, "expected '=' before function body in this standard");
5591         }
5592
5593         if (parser->tok == '#') {
5594             ast_function *func   = NULL;
5595             ast_value    *number = NULL;
5596             float         fractional;
5597             float         integral;
5598             int           builtin_num;
5599
5600             if (localblock) {
5601                 parseerror(parser, "cannot declare builtins within functions");
5602                 break;
5603             }
5604             if (var->expression.vtype != TYPE_FUNCTION) {
5605                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5606                 break;
5607             }
5608             if (!parser_next(parser)) {
5609                 parseerror(parser, "expected builtin number");
5610                 break;
5611             }
5612
5613             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5614                 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5615                 if (!number) {
5616                     parseerror(parser, "builtin number expected");
5617                     break;
5618                 }
5619                 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5620                 {
5621                     ast_unref(number);
5622                     parseerror(parser, "builtin number must be a compile time constant");
5623                     break;
5624                 }
5625                 if (number->expression.vtype == TYPE_INTEGER)
5626                     builtin_num = number->constval.vint;
5627                 else if (number->expression.vtype == TYPE_FLOAT)
5628                     builtin_num = number->constval.vfloat;
5629                 else {
5630                     ast_unref(number);
5631                     parseerror(parser, "builtin number must be an integer constant");
5632                     break;
5633                 }
5634                 ast_unref(number);
5635
5636                 fractional = modff(builtin_num, &integral);
5637                 if (builtin_num < 0 || fractional != 0) {
5638                     parseerror(parser, "builtin number must be an integer greater than zero");
5639                     break;
5640                 }
5641
5642                 /* we only want the integral part anyways */
5643                 builtin_num = integral;
5644             } else if (parser->tok == TOKEN_INTCONST) {
5645                 builtin_num = parser_token(parser)->constval.i;
5646             } else {
5647                 parseerror(parser, "builtin number must be a compile time constant");
5648                 break;
5649             }
5650
5651             if (var->hasvalue) {
5652                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5653                                     "builtin `%s` has already been defined\n"
5654                                     " -> previous declaration here: %s:%i",
5655                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5656             }
5657             else
5658             {
5659                 func = ast_function_new(ast_ctx(var), var->name, var);
5660                 if (!func) {
5661                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5662                     break;
5663                 }
5664                 vec_push(parser->functions, func);
5665
5666                 func->builtin = -builtin_num-1;
5667             }
5668
5669             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5670                     ? (parser->tok != ',' && parser->tok != ';')
5671                     : (!parser_next(parser)))
5672             {
5673                 parseerror(parser, "expected comma or semicolon");
5674                 if (func)
5675                     ast_function_delete(func);
5676                 var->constval.vfunc = NULL;
5677                 break;
5678             }
5679         }
5680         else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5681         {
5682             if (localblock) {
5683                 /* Note that fteqcc and most others don't even *have*
5684                  * local arrays, so this is not a high priority.
5685                  */
5686                 parseerror(parser, "TODO: initializers for local arrays");
5687                 break;
5688             }
5689
5690             var->hasvalue = true;
5691             if (!parse_array(parser, var))
5692                 break;
5693         }
5694         else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5695         {
5696             if (localblock) {
5697                 parseerror(parser, "cannot declare functions within functions");
5698                 break;
5699             }
5700
5701             if (proto)
5702                 ast_ctx(proto) = parser_ctx(parser);
5703
5704             if (!parse_function_body(parser, var))
5705                 break;
5706             ast_delete(basetype);
5707             for (i = 0; i < vec_size(parser->gotos); ++i)
5708                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5709             vec_free(parser->gotos);
5710             vec_free(parser->labels);
5711             return true;
5712         } else {
5713             ast_expression *cexp;
5714             ast_value      *cval;
5715
5716             cexp = parse_expression_leave(parser, true, false, false);
5717             if (!cexp)
5718                 break;
5719
5720             if (!localblock) {
5721                 cval = (ast_value*)cexp;
5722                 if (cval != parser->nil &&
5723                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5724                    )
5725                 {
5726                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5727                 }
5728                 else
5729                 {
5730                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5731                         qualifier != CV_VAR)
5732                     {
5733                         var->cvq = CV_CONST;
5734                     }
5735                     if (cval == parser->nil)
5736                         var->expression.flags |= AST_FLAG_INITIALIZED;
5737                     else
5738                     {
5739                         var->hasvalue = true;
5740                         if (cval->expression.vtype == TYPE_STRING)
5741                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5742                         else if (cval->expression.vtype == TYPE_FIELD)
5743                             var->constval.vfield = cval;
5744                         else
5745                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5746                         ast_unref(cval);
5747                     }
5748                 }
5749             } else {
5750                 int cvq;
5751                 shunt sy = { NULL, NULL, NULL, NULL };
5752                 cvq = var->cvq;
5753                 var->cvq = CV_NONE;
5754                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5755                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5756                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5757                 if (!parser_sy_apply_operator(parser, &sy))
5758                     ast_unref(cexp);
5759                 else {
5760                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5761                         parseerror(parser, "internal error: leaked operands");
5762                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5763                         break;
5764                 }
5765                 vec_free(sy.out);
5766                 vec_free(sy.ops);
5767                 vec_free(sy.argc);
5768                 var->cvq = cvq;
5769             }
5770         }
5771
5772 another:
5773         if (parser->tok == ',') {
5774             if (!parser_next(parser)) {
5775                 parseerror(parser, "expected another variable");
5776                 break;
5777             }
5778
5779             if (parser->tok != TOKEN_IDENT) {
5780                 parseerror(parser, "expected another variable");
5781                 break;
5782             }
5783             var = ast_value_copy(basetype);
5784             cleanvar = true;
5785             ast_value_set_name(var, parser_tokval(parser));
5786             if (!parser_next(parser)) {
5787                 parseerror(parser, "error parsing variable declaration");
5788                 break;
5789             }
5790             continue;
5791         }
5792
5793         if (parser->tok != ';') {
5794             parseerror(parser, "missing semicolon after variables");
5795             break;
5796         }
5797
5798         if (!parser_next(parser)) {
5799             parseerror(parser, "parse error after variable declaration");
5800             break;
5801         }
5802
5803         ast_delete(basetype);
5804         return true;
5805     }
5806
5807     if (cleanvar && var)
5808         ast_delete(var);
5809     ast_delete(basetype);
5810     return false;
5811
5812 cleanup:
5813     ast_delete(basetype);
5814     if (cleanvar && var)
5815         ast_delete(var);
5816     if (me[0]) ast_member_delete(me[0]);
5817     if (me[1]) ast_member_delete(me[1]);
5818     if (me[2]) ast_member_delete(me[2]);
5819     return retval;
5820 }
5821
5822 static bool parser_global_statement(parser_t *parser)
5823 {
5824     int        cvq       = CV_WRONG;
5825     bool       noref     = false;
5826     bool       is_static = false;
5827     uint32_t   qflags    = 0;
5828     ast_value *istype    = NULL;
5829     char      *vstring   = NULL;
5830
5831     if (parser->tok == TOKEN_IDENT)
5832         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5833
5834     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5835     {
5836         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5837     }
5838     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5839     {
5840         if (cvq == CV_WRONG)
5841             return false;
5842         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5843     }
5844     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5845     {
5846         return parse_enum(parser);
5847     }
5848     else if (parser->tok == TOKEN_KEYWORD)
5849     {
5850         if (!strcmp(parser_tokval(parser), "typedef")) {
5851             if (!parser_next(parser)) {
5852                 parseerror(parser, "expected type definition after 'typedef'");
5853                 return false;
5854             }
5855             return parse_typedef(parser);
5856         }
5857         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5858         return false;
5859     }
5860     else if (parser->tok == '#')
5861     {
5862         return parse_pragma(parser);
5863     }
5864     else if (parser->tok == '$')
5865     {
5866         if (!parser_next(parser)) {
5867             parseerror(parser, "parse error");
5868             return false;
5869         }
5870     }
5871     else
5872     {
5873         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5874         return false;
5875     }
5876     return true;
5877 }
5878
5879 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5880 {
5881     return util_crc16(old, str, strlen(str));
5882 }
5883
5884 static void progdefs_crc_file(const char *str)
5885 {
5886     /* write to progdefs.h here */
5887     (void)str;
5888 }
5889
5890 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5891 {
5892     old = progdefs_crc_sum(old, str);
5893     progdefs_crc_file(str);
5894     return old;
5895 }
5896
5897 static void generate_checksum(parser_t *parser, ir_builder *ir)
5898 {
5899     uint16_t   crc = 0xFFFF;
5900     size_t     i;
5901     ast_value *value;
5902
5903     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5904     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5905     /*
5906     progdefs_crc_file("\tint\tpad;\n");
5907     progdefs_crc_file("\tint\tofs_return[3];\n");
5908     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5909     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5910     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5911     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5912     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5913     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5914     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5915     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5916     */
5917     for (i = 0; i < parser->crc_globals; ++i) {
5918         if (!ast_istype(parser->globals[i], ast_value))
5919             continue;
5920         value = (ast_value*)(parser->globals[i]);
5921         switch (value->expression.vtype) {
5922             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5923             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5924             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5925             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5926             default:
5927                 crc = progdefs_crc_both(crc, "\tint\t");
5928                 break;
5929         }
5930         crc = progdefs_crc_both(crc, value->name);
5931         crc = progdefs_crc_both(crc, ";\n");
5932     }
5933     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5934     for (i = 0; i < parser->crc_fields; ++i) {
5935         if (!ast_istype(parser->fields[i], ast_value))
5936             continue;
5937         value = (ast_value*)(parser->fields[i]);
5938         switch (value->expression.next->vtype) {
5939             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5940             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5941             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5942             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5943             default:
5944                 crc = progdefs_crc_both(crc, "\tint\t");
5945                 break;
5946         }
5947         crc = progdefs_crc_both(crc, value->name);
5948         crc = progdefs_crc_both(crc, ";\n");
5949     }
5950     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5951     ir->code->crc = crc;
5952 }
5953
5954 parser_t *parser_create()
5955 {
5956     parser_t *parser;
5957     lex_ctx_t empty_ctx;
5958     size_t i;
5959
5960     parser = (parser_t*)mem_a(sizeof(parser_t));
5961     if (!parser)
5962         return NULL;
5963
5964     memset(parser, 0, sizeof(*parser));
5965
5966     for (i = 0; i < operator_count; ++i) {
5967         if (operators[i].id == opid1('=')) {
5968             parser->assign_op = operators+i;
5969             break;
5970         }
5971     }
5972     if (!parser->assign_op) {
5973         con_err("internal error: initializing parser: failed to find assign operator\n");
5974         mem_d(parser);
5975         return NULL;
5976     }
5977
5978     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5979     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5980     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5981     vec_push(parser->_blocktypedefs, 0);
5982
5983     parser->aliases = util_htnew(PARSER_HT_SIZE);
5984
5985     /* corrector */
5986     vec_push(parser->correct_variables, correct_trie_new());
5987     vec_push(parser->correct_variables_score, NULL);
5988
5989     empty_ctx.file   = "<internal>";
5990     empty_ctx.line   = 0;
5991     empty_ctx.column = 0;
5992     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5993     parser->nil->cvq = CV_CONST;
5994     if (OPTS_FLAG(UNTYPED_NIL))
5995         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5996
5997     parser->max_param_count = 1;
5998
5999     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6000     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6001     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6002
6003     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6004         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6005         parser->reserved_version->cvq = CV_CONST;
6006         parser->reserved_version->hasvalue = true;
6007         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6008         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6009     } else {
6010         parser->reserved_version = NULL;
6011     }
6012
6013     parser->fold   = fold_init  (parser);
6014     parser->intrin = intrin_init(parser);
6015     return parser;
6016 }
6017
6018 static bool parser_compile(parser_t *parser)
6019 {
6020     /* initial lexer/parser state */
6021     parser->lex->flags.noops = true;
6022
6023     if (parser_next(parser))
6024     {
6025         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6026         {
6027             if (!parser_global_statement(parser)) {
6028                 if (parser->tok == TOKEN_EOF)
6029                     parseerror(parser, "unexpected end of file");
6030                 else if (compile_errors)
6031                     parseerror(parser, "there have been errors, bailing out");
6032                 lex_close(parser->lex);
6033                 parser->lex = NULL;
6034                 return false;
6035             }
6036         }
6037     } else {
6038         parseerror(parser, "parse error");
6039         lex_close(parser->lex);
6040         parser->lex = NULL;
6041         return false;
6042     }
6043
6044     lex_close(parser->lex);
6045     parser->lex = NULL;
6046
6047     return !compile_errors;
6048 }
6049
6050 bool parser_compile_file(parser_t *parser, const char *filename)
6051 {
6052     parser->lex = lex_open(filename);
6053     if (!parser->lex) {
6054         con_err("failed to open file \"%s\"\n", filename);
6055         return false;
6056     }
6057     return parser_compile(parser);
6058 }
6059
6060 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6061 {
6062     parser->lex = lex_open_string(str, len, name);
6063     if (!parser->lex) {
6064         con_err("failed to create lexer for string \"%s\"\n", name);
6065         return false;
6066     }
6067     return parser_compile(parser);
6068 }
6069
6070 static void parser_remove_ast(parser_t *parser)
6071 {
6072     size_t i;
6073     if (parser->ast_cleaned)
6074         return;
6075     parser->ast_cleaned = true;
6076     for (i = 0; i < vec_size(parser->accessors); ++i) {
6077         ast_delete(parser->accessors[i]->constval.vfunc);
6078         parser->accessors[i]->constval.vfunc = NULL;
6079         ast_delete(parser->accessors[i]);
6080     }
6081     for (i = 0; i < vec_size(parser->functions); ++i) {
6082         ast_delete(parser->functions[i]);
6083     }
6084     for (i = 0; i < vec_size(parser->fields); ++i) {
6085         ast_delete(parser->fields[i]);
6086     }
6087     for (i = 0; i < vec_size(parser->globals); ++i) {
6088         ast_delete(parser->globals[i]);
6089     }
6090     vec_free(parser->accessors);
6091     vec_free(parser->functions);
6092     vec_free(parser->globals);
6093     vec_free(parser->fields);
6094
6095     for (i = 0; i < vec_size(parser->variables); ++i)
6096         util_htdel(parser->variables[i]);
6097     vec_free(parser->variables);
6098     vec_free(parser->_blocklocals);
6099     vec_free(parser->_locals);
6100
6101     /* corrector */
6102     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6103         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6104     }
6105     vec_free(parser->correct_variables);
6106     vec_free(parser->correct_variables_score);
6107
6108     for (i = 0; i < vec_size(parser->_typedefs); ++i)
6109         ast_delete(parser->_typedefs[i]);
6110     vec_free(parser->_typedefs);
6111     for (i = 0; i < vec_size(parser->typedefs); ++i)
6112         util_htdel(parser->typedefs[i]);
6113     vec_free(parser->typedefs);
6114     vec_free(parser->_blocktypedefs);
6115
6116     vec_free(parser->_block_ctx);
6117
6118     vec_free(parser->labels);
6119     vec_free(parser->gotos);
6120     vec_free(parser->breaks);
6121     vec_free(parser->continues);
6122
6123     ast_value_delete(parser->nil);
6124
6125     ast_value_delete(parser->const_vec[0]);
6126     ast_value_delete(parser->const_vec[1]);
6127     ast_value_delete(parser->const_vec[2]);
6128
6129     if (parser->reserved_version)
6130         ast_value_delete(parser->reserved_version);
6131
6132     util_htdel(parser->aliases);
6133     fold_cleanup(parser->fold);
6134     intrin_cleanup(parser->intrin);
6135 }
6136
6137 void parser_cleanup(parser_t *parser)
6138 {
6139     parser_remove_ast(parser);
6140     mem_d(parser);
6141 }
6142
6143 bool parser_finish(parser_t *parser, const char *output)
6144 {
6145     size_t i;
6146     ir_builder *ir;
6147     bool retval = true;
6148
6149     if (compile_errors) {
6150         con_out("*** there were compile errors\n");
6151         return false;
6152     }
6153
6154     ir = ir_builder_new("gmqcc_out");
6155     if (!ir) {
6156         con_out("failed to allocate builder\n");
6157         return false;
6158     }
6159
6160     for (i = 0; i < vec_size(parser->fields); ++i) {
6161         ast_value *field;
6162         bool hasvalue;
6163         if (!ast_istype(parser->fields[i], ast_value))
6164             continue;
6165         field = (ast_value*)parser->fields[i];
6166         hasvalue = field->hasvalue;
6167         field->hasvalue = false;
6168         if (!ast_global_codegen((ast_value*)field, ir, true)) {
6169             con_out("failed to generate field %s\n", field->name);
6170             ir_builder_delete(ir);
6171             return false;
6172         }
6173         if (hasvalue) {
6174             ir_value *ifld;
6175             ast_expression *subtype;
6176             field->hasvalue = true;
6177             subtype = field->expression.next;
6178             ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6179             if (subtype->vtype == TYPE_FIELD)
6180                 ifld->fieldtype = subtype->next->vtype;
6181             else if (subtype->vtype == TYPE_FUNCTION)
6182                 ifld->outtype = subtype->next->vtype;
6183             (void)!ir_value_set_field(field->ir_v, ifld);
6184         }
6185     }
6186     for (i = 0; i < vec_size(parser->globals); ++i) {
6187         ast_value *asvalue;
6188         if (!ast_istype(parser->globals[i], ast_value))
6189             continue;
6190         asvalue = (ast_value*)(parser->globals[i]);
6191         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6192             retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6193                                                 "unused global: `%s`", asvalue->name);
6194         }
6195         if (!ast_global_codegen(asvalue, ir, false)) {
6196             con_out("failed to generate global %s\n", asvalue->name);
6197             ir_builder_delete(ir);
6198             return false;
6199         }
6200     }
6201     /* Build function vararg accessor ast tree now before generating
6202      * immediates, because the accessors may add new immediates
6203      */
6204     for (i = 0; i < vec_size(parser->functions); ++i) {
6205         ast_function *f = parser->functions[i];
6206         if (f->varargs) {
6207             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6208                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6209                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6210                     con_out("failed to generate vararg setter for %s\n", f->name);
6211                     ir_builder_delete(ir);
6212                     return false;
6213                 }
6214                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6215                     con_out("failed to generate vararg getter for %s\n", f->name);
6216                     ir_builder_delete(ir);
6217                     return false;
6218                 }
6219             } else {
6220                 ast_delete(f->varargs);
6221                 f->varargs = NULL;
6222             }
6223         }
6224     }
6225     /* Now we can generate immediates */
6226     if (!fold_generate(parser->fold, ir))
6227         return false;
6228
6229     for (i = 0; i < vec_size(parser->globals); ++i) {
6230         ast_value *asvalue;
6231         if (!ast_istype(parser->globals[i], ast_value))
6232             continue;
6233         asvalue = (ast_value*)(parser->globals[i]);
6234         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6235         {
6236             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6237                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6238                                        "uninitialized constant: `%s`",
6239                                        asvalue->name);
6240             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6241                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6242                                        "uninitialized global: `%s`",
6243                                        asvalue->name);
6244         }
6245         if (!ast_generate_accessors(asvalue, ir)) {
6246             ir_builder_delete(ir);
6247             return false;
6248         }
6249     }
6250     for (i = 0; i < vec_size(parser->fields); ++i) {
6251         ast_value *asvalue;
6252         asvalue = (ast_value*)(parser->fields[i]->next);
6253
6254         if (!ast_istype((ast_expression*)asvalue, ast_value))
6255             continue;
6256         if (asvalue->expression.vtype != TYPE_ARRAY)
6257             continue;
6258         if (!ast_generate_accessors(asvalue, ir)) {
6259             ir_builder_delete(ir);
6260             return false;
6261         }
6262     }
6263     if (parser->reserved_version &&
6264         !ast_global_codegen(parser->reserved_version, ir, false))
6265     {
6266         con_out("failed to generate reserved::version");
6267         ir_builder_delete(ir);
6268         return false;
6269     }
6270     for (i = 0; i < vec_size(parser->functions); ++i) {
6271         ast_function *f = parser->functions[i];
6272         if (!ast_function_codegen(f, ir)) {
6273             con_out("failed to generate function %s\n", f->name);
6274             ir_builder_delete(ir);
6275             return false;
6276         }
6277     }
6278
6279     generate_checksum(parser, ir);
6280
6281     if (OPTS_OPTION_BOOL(OPTION_DUMP))
6282         ir_builder_dump(ir, con_out);
6283     for (i = 0; i < vec_size(parser->functions); ++i) {
6284         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6285             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6286             ir_builder_delete(ir);
6287             return false;
6288         }
6289     }
6290     parser_remove_ast(parser);
6291
6292     if (compile_Werrors) {
6293         con_out("*** there were warnings treated as errors\n");
6294         compile_show_werrors();
6295         retval = false;
6296     }
6297
6298     if (retval) {
6299         if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6300             ir_builder_dump(ir, con_out);
6301
6302         if (!ir_builder_generate(ir, output)) {
6303             con_out("*** failed to generate output file\n");
6304             ir_builder_delete(ir);
6305             return false;
6306         }
6307     }
6308     ir_builder_delete(ir);
6309     return retval;
6310 }