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