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