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