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