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