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