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