]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Constant fold intrinsics if their arguments are constant. TODO: reference count intri...
[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 *fold   = NULL;
1192
1193         for (i = 0; i < paramcount; i++)
1194             vec_push(exprs, sy->out[fid+1 + i].out);
1195
1196         if (!(fold = 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(fold->node.context, fold);
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, "`noref` attribute has no parameters, expected `]]`");
2742                     *cvq = CV_WRONG;
2743                     return false;
2744                 }
2745             }
2746             else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2747                 flags   |= AST_FLAG_ALIAS;
2748                 *message = NULL;
2749
2750                 if (!parser_next(parser)) {
2751                     parseerror(parser, "parse error in attribute");
2752                     goto argerr;
2753                 }
2754
2755                 if (parser->tok == '(') {
2756                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2757                         parseerror(parser, "`alias` attribute missing parameter");
2758                         goto argerr;
2759                     }
2760
2761                     *message = util_strdup(parser_tokval(parser));
2762
2763                     if (!parser_next(parser)) {
2764                         parseerror(parser, "parse error in attribute");
2765                         goto argerr;
2766                     }
2767
2768                     if (parser->tok != ')') {
2769                         parseerror(parser, "`alias` attribute expected `)` after parameter");
2770                         goto argerr;
2771                     }
2772
2773                     if (!parser_next(parser)) {
2774                         parseerror(parser, "parse error in attribute");
2775                         goto argerr;
2776                     }
2777                 }
2778
2779                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2780                     parseerror(parser, "`alias` attribute expected `]]`");
2781                     goto argerr;
2782                 }
2783             }
2784             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2785                 flags   |= AST_FLAG_DEPRECATED;
2786                 *message = NULL;
2787
2788                 if (!parser_next(parser)) {
2789                     parseerror(parser, "parse error in attribute");
2790                     goto argerr;
2791                 }
2792
2793                 if (parser->tok == '(') {
2794                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2795                         parseerror(parser, "`deprecated` attribute missing parameter");
2796                         goto argerr;
2797                     }
2798
2799                     *message = util_strdup(parser_tokval(parser));
2800
2801                     if (!parser_next(parser)) {
2802                         parseerror(parser, "parse error in attribute");
2803                         goto argerr;
2804                     }
2805
2806                     if(parser->tok != ')') {
2807                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2808                         goto argerr;
2809                     }
2810
2811                     if (!parser_next(parser)) {
2812                         parseerror(parser, "parse error in attribute");
2813                         goto argerr;
2814                     }
2815                 }
2816                 /* no message */
2817                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2818                     parseerror(parser, "`deprecated` attribute expected `]]`");
2819
2820                     argerr: /* ugly */
2821                     if (*message) mem_d(*message);
2822                     *message = NULL;
2823                     *cvq     = CV_WRONG;
2824                     return false;
2825                 }
2826             }
2827             else
2828             {
2829                 /* Skip tokens until we hit a ]] */
2830                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2831                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2832                     if (!parser_next(parser)) {
2833                         parseerror(parser, "error inside attribute");
2834                         *cvq = CV_WRONG;
2835                         return false;
2836                     }
2837                 }
2838             }
2839         }
2840         else if (with_local && !strcmp(parser_tokval(parser), "static"))
2841             had_static = true;
2842         else if (!strcmp(parser_tokval(parser), "const"))
2843             had_const = true;
2844         else if (!strcmp(parser_tokval(parser), "var"))
2845             had_var = true;
2846         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2847             had_var = true;
2848         else if (!strcmp(parser_tokval(parser), "noref"))
2849             had_noref = true;
2850         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2851             return false;
2852         }
2853         else
2854             break;
2855         if (!parser_next(parser))
2856             goto onerr;
2857     }
2858     if (had_const)
2859         *cvq = CV_CONST;
2860     else if (had_var)
2861         *cvq = CV_VAR;
2862     else
2863         *cvq = CV_NONE;
2864     *noref     = had_noref;
2865     *is_static = had_static;
2866     *_flags    = flags;
2867     return true;
2868 onerr:
2869     parseerror(parser, "parse error after variable qualifier");
2870     *cvq = CV_WRONG;
2871     return true;
2872 }
2873
2874 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2875 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2876 {
2877     bool rv;
2878     char *label = NULL;
2879
2880     /* skip the 'while' and get the body */
2881     if (!parser_next(parser)) {
2882         if (OPTS_FLAG(LOOP_LABELS))
2883             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2884         else
2885             parseerror(parser, "expected 'switch' operand in parenthesis");
2886         return false;
2887     }
2888
2889     if (parser->tok == ':') {
2890         if (!OPTS_FLAG(LOOP_LABELS))
2891             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2892         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2893             parseerror(parser, "expected loop label");
2894             return false;
2895         }
2896         label = util_strdup(parser_tokval(parser));
2897         if (!parser_next(parser)) {
2898             mem_d(label);
2899             parseerror(parser, "expected 'switch' operand in parenthesis");
2900             return false;
2901         }
2902     }
2903
2904     if (parser->tok != '(') {
2905         parseerror(parser, "expected 'switch' operand in parenthesis");
2906         return false;
2907     }
2908
2909     vec_push(parser->breaks, label);
2910
2911     rv = parse_switch_go(parser, block, out);
2912     if (label)
2913         mem_d(label);
2914     if (vec_last(parser->breaks) != label) {
2915         parseerror(parser, "internal error: label stack corrupted");
2916         rv = false;
2917         ast_delete(*out);
2918         *out = NULL;
2919     }
2920     else {
2921         vec_pop(parser->breaks);
2922     }
2923     return rv;
2924 }
2925
2926 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2927 {
2928     ast_expression *operand;
2929     ast_value      *opval;
2930     ast_value      *typevar;
2931     ast_switch     *switchnode;
2932     ast_switch_case swcase;
2933
2934     int  cvq;
2935     bool noref, is_static;
2936     uint32_t qflags = 0;
2937
2938     lex_ctx_t ctx = parser_ctx(parser);
2939
2940     (void)block; /* not touching */
2941     (void)opval;
2942
2943     /* parse into the expression */
2944     if (!parser_next(parser)) {
2945         parseerror(parser, "expected switch operand");
2946         return false;
2947     }
2948     /* parse the operand */
2949     operand = parse_expression_leave(parser, false, false, false);
2950     if (!operand)
2951         return false;
2952
2953     switchnode = ast_switch_new(ctx, operand);
2954
2955     /* closing paren */
2956     if (parser->tok != ')') {
2957         ast_delete(switchnode);
2958         parseerror(parser, "expected closing paren after 'switch' operand");
2959         return false;
2960     }
2961
2962     /* parse over the opening paren */
2963     if (!parser_next(parser) || parser->tok != '{') {
2964         ast_delete(switchnode);
2965         parseerror(parser, "expected list of cases");
2966         return false;
2967     }
2968
2969     if (!parser_next(parser)) {
2970         ast_delete(switchnode);
2971         parseerror(parser, "expected 'case' or 'default'");
2972         return false;
2973     }
2974
2975     /* new block; allow some variables to be declared here */
2976     parser_enterblock(parser);
2977     while (true) {
2978         typevar = NULL;
2979         if (parser->tok == TOKEN_IDENT)
2980             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2981         if (typevar || parser->tok == TOKEN_TYPENAME) {
2982             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2983                 ast_delete(switchnode);
2984                 return false;
2985             }
2986             continue;
2987         }
2988         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2989         {
2990             if (cvq == CV_WRONG) {
2991                 ast_delete(switchnode);
2992                 return false;
2993             }
2994             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2995                 ast_delete(switchnode);
2996                 return false;
2997             }
2998             continue;
2999         }
3000         break;
3001     }
3002
3003     /* case list! */
3004     while (parser->tok != '}') {
3005         ast_block *caseblock;
3006
3007         if (!strcmp(parser_tokval(parser), "case")) {
3008             if (!parser_next(parser)) {
3009                 ast_delete(switchnode);
3010                 parseerror(parser, "expected expression for case");
3011                 return false;
3012             }
3013             swcase.value = parse_expression_leave(parser, false, false, false);
3014             if (!swcase.value) {
3015                 ast_delete(switchnode);
3016                 parseerror(parser, "expected expression for case");
3017                 return false;
3018             }
3019             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3020                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3021                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3022                     ast_unref(operand);
3023                     return false;
3024                 }
3025             }
3026         }
3027         else if (!strcmp(parser_tokval(parser), "default")) {
3028             swcase.value = NULL;
3029             if (!parser_next(parser)) {
3030                 ast_delete(switchnode);
3031                 parseerror(parser, "expected colon");
3032                 return false;
3033             }
3034         }
3035         else {
3036             ast_delete(switchnode);
3037             parseerror(parser, "expected 'case' or 'default'");
3038             return false;
3039         }
3040
3041         /* Now the colon and body */
3042         if (parser->tok != ':') {
3043             if (swcase.value) ast_unref(swcase.value);
3044             ast_delete(switchnode);
3045             parseerror(parser, "expected colon");
3046             return false;
3047         }
3048
3049         if (!parser_next(parser)) {
3050             if (swcase.value) ast_unref(swcase.value);
3051             ast_delete(switchnode);
3052             parseerror(parser, "expected statements or case");
3053             return false;
3054         }
3055         caseblock = ast_block_new(parser_ctx(parser));
3056         if (!caseblock) {
3057             if (swcase.value) ast_unref(swcase.value);
3058             ast_delete(switchnode);
3059             return false;
3060         }
3061         swcase.code = (ast_expression*)caseblock;
3062         vec_push(switchnode->cases, swcase);
3063         while (true) {
3064             ast_expression *expr;
3065             if (parser->tok == '}')
3066                 break;
3067             if (parser->tok == TOKEN_KEYWORD) {
3068                 if (!strcmp(parser_tokval(parser), "case") ||
3069                     !strcmp(parser_tokval(parser), "default"))
3070                 {
3071                     break;
3072                 }
3073             }
3074             if (!parse_statement(parser, caseblock, &expr, true)) {
3075                 ast_delete(switchnode);
3076                 return false;
3077             }
3078             if (!expr)
3079                 continue;
3080             if (!ast_block_add_expr(caseblock, expr)) {
3081                 ast_delete(switchnode);
3082                 return false;
3083             }
3084         }
3085     }
3086
3087     parser_leaveblock(parser);
3088
3089     /* closing paren */
3090     if (parser->tok != '}') {
3091         ast_delete(switchnode);
3092         parseerror(parser, "expected closing paren of case list");
3093         return false;
3094     }
3095     if (!parser_next(parser)) {
3096         ast_delete(switchnode);
3097         parseerror(parser, "parse error after switch");
3098         return false;
3099     }
3100     *out = (ast_expression*)switchnode;
3101     return true;
3102 }
3103
3104 /* parse computed goto sides */
3105 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3106     ast_expression *on_true;
3107     ast_expression *on_false;
3108     ast_expression *cond;
3109
3110     if (!*side)
3111         return NULL;
3112
3113     if (ast_istype(*side, ast_ternary)) {
3114         ast_ternary *tern = (ast_ternary*)*side;
3115         on_true  = parse_goto_computed(parser, &tern->on_true);
3116         on_false = parse_goto_computed(parser, &tern->on_false);
3117
3118         if (!on_true || !on_false) {
3119             parseerror(parser, "expected label or expression in ternary");
3120             if (on_true) ast_unref(on_true);
3121             if (on_false) ast_unref(on_false);
3122             return NULL;
3123         }
3124
3125         cond = tern->cond;
3126         tern->cond = NULL;
3127         ast_delete(tern);
3128         *side = NULL;
3129         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3130     } else if (ast_istype(*side, ast_label)) {
3131         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3132         ast_goto_set_label(gt, ((ast_label*)*side));
3133         *side = NULL;
3134         return (ast_expression*)gt;
3135     }
3136     return NULL;
3137 }
3138
3139 static bool parse_goto(parser_t *parser, ast_expression **out)
3140 {
3141     ast_goto       *gt = NULL;
3142     ast_expression *lbl;
3143
3144     if (!parser_next(parser))
3145         return false;
3146
3147     if (parser->tok != TOKEN_IDENT) {
3148         ast_expression *expression;
3149
3150         /* could be an expression i.e computed goto :-) */
3151         if (parser->tok != '(') {
3152             parseerror(parser, "expected label name after `goto`");
3153             return false;
3154         }
3155
3156         /* failed to parse expression for goto */
3157         if (!(expression = parse_expression(parser, false, true)) ||
3158             !(*out = parse_goto_computed(parser, &expression))) {
3159             parseerror(parser, "invalid goto expression");
3160             if(expression)
3161                 ast_unref(expression);
3162             return false;
3163         }
3164
3165         return true;
3166     }
3167
3168     /* not computed goto */
3169     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3170     lbl = parser_find_label(parser, gt->name);
3171     if (lbl) {
3172         if (!ast_istype(lbl, ast_label)) {
3173             parseerror(parser, "internal error: label is not an ast_label");
3174             ast_delete(gt);
3175             return false;
3176         }
3177         ast_goto_set_label(gt, (ast_label*)lbl);
3178     }
3179     else
3180         vec_push(parser->gotos, gt);
3181
3182     if (!parser_next(parser) || parser->tok != ';') {
3183         parseerror(parser, "semicolon expected after goto label");
3184         return false;
3185     }
3186     if (!parser_next(parser)) {
3187         parseerror(parser, "parse error after goto");
3188         return false;
3189     }
3190
3191     *out = (ast_expression*)gt;
3192     return true;
3193 }
3194
3195 static bool parse_skipwhite(parser_t *parser)
3196 {
3197     do {
3198         if (!parser_next(parser))
3199             return false;
3200     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3201     return parser->tok < TOKEN_ERROR;
3202 }
3203
3204 static bool parse_eol(parser_t *parser)
3205 {
3206     if (!parse_skipwhite(parser))
3207         return false;
3208     return parser->tok == TOKEN_EOL;
3209 }
3210
3211 static bool parse_pragma_do(parser_t *parser)
3212 {
3213     if (!parser_next(parser) ||
3214         parser->tok != TOKEN_IDENT ||
3215         strcmp(parser_tokval(parser), "pragma"))
3216     {
3217         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3218         return false;
3219     }
3220     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3221         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3222         return false;
3223     }
3224
3225     if (!strcmp(parser_tokval(parser), "noref")) {
3226         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3227             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3228             return false;
3229         }
3230         parser->noref = !!parser_token(parser)->constval.i;
3231         if (!parse_eol(parser)) {
3232             parseerror(parser, "parse error after `noref` pragma");
3233             return false;
3234         }
3235     }
3236     else
3237     {
3238         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3239         return false;
3240     }
3241
3242     return true;
3243 }
3244
3245 static bool parse_pragma(parser_t *parser)
3246 {
3247     bool rv;
3248     parser->lex->flags.preprocessing = true;
3249     parser->lex->flags.mergelines = true;
3250     rv = parse_pragma_do(parser);
3251     if (parser->tok != TOKEN_EOL) {
3252         parseerror(parser, "junk after pragma");
3253         rv = false;
3254     }
3255     parser->lex->flags.preprocessing = false;
3256     parser->lex->flags.mergelines = false;
3257     if (!parser_next(parser)) {
3258         parseerror(parser, "parse error after pragma");
3259         rv = false;
3260     }
3261     return rv;
3262 }
3263
3264 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3265 {
3266     bool       noref, is_static;
3267     int        cvq     = CV_NONE;
3268     uint32_t   qflags  = 0;
3269     ast_value *typevar = NULL;
3270     char      *vstring = NULL;
3271
3272     *out = NULL;
3273
3274     if (parser->tok == TOKEN_IDENT)
3275         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3276
3277     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3278     {
3279         /* local variable */
3280         if (!block) {
3281             parseerror(parser, "cannot declare a variable from here");
3282             return false;
3283         }
3284         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3285             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3286                 return false;
3287         }
3288         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3289             return false;
3290         return true;
3291     }
3292     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3293     {
3294         if (cvq == CV_WRONG)
3295             return false;
3296         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3297     }
3298     else if (parser->tok == TOKEN_KEYWORD)
3299     {
3300         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3301         {
3302             char ty[1024];
3303             ast_value *tdef;
3304
3305             if (!parser_next(parser)) {
3306                 parseerror(parser, "parse error after __builtin_debug_printtype");
3307                 return false;
3308             }
3309
3310             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3311             {
3312                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3313                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3314                 if (!parser_next(parser)) {
3315                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3316                     return false;
3317                 }
3318             }
3319             else
3320             {
3321                 if (!parse_statement(parser, block, out, allow_cases))
3322                     return false;
3323                 if (!*out)
3324                     con_out("__builtin_debug_printtype: got no output node\n");
3325                 else
3326                 {
3327                     ast_type_to_string(*out, ty, sizeof(ty));
3328                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3329                 }
3330             }
3331             return true;
3332         }
3333         else if (!strcmp(parser_tokval(parser), "return"))
3334         {
3335             return parse_return(parser, block, out);
3336         }
3337         else if (!strcmp(parser_tokval(parser), "if"))
3338         {
3339             return parse_if(parser, block, out);
3340         }
3341         else if (!strcmp(parser_tokval(parser), "while"))
3342         {
3343             return parse_while(parser, block, out);
3344         }
3345         else if (!strcmp(parser_tokval(parser), "do"))
3346         {
3347             return parse_dowhile(parser, block, out);
3348         }
3349         else if (!strcmp(parser_tokval(parser), "for"))
3350         {
3351             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3352                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3353                     return false;
3354             }
3355             return parse_for(parser, block, out);
3356         }
3357         else if (!strcmp(parser_tokval(parser), "break"))
3358         {
3359             return parse_break_continue(parser, block, out, false);
3360         }
3361         else if (!strcmp(parser_tokval(parser), "continue"))
3362         {
3363             return parse_break_continue(parser, block, out, true);
3364         }
3365         else if (!strcmp(parser_tokval(parser), "switch"))
3366         {
3367             return parse_switch(parser, block, out);
3368         }
3369         else if (!strcmp(parser_tokval(parser), "case") ||
3370                  !strcmp(parser_tokval(parser), "default"))
3371         {
3372             if (!allow_cases) {
3373                 parseerror(parser, "unexpected 'case' label");
3374                 return false;
3375             }
3376             return true;
3377         }
3378         else if (!strcmp(parser_tokval(parser), "goto"))
3379         {
3380             return parse_goto(parser, out);
3381         }
3382         else if (!strcmp(parser_tokval(parser), "typedef"))
3383         {
3384             if (!parser_next(parser)) {
3385                 parseerror(parser, "expected type definition after 'typedef'");
3386                 return false;
3387             }
3388             return parse_typedef(parser);
3389         }
3390         parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3391         return false;
3392     }
3393     else if (parser->tok == '{')
3394     {
3395         ast_block *inner;
3396         inner = parse_block(parser);
3397         if (!inner)
3398             return false;
3399         *out = (ast_expression*)inner;
3400         return true;
3401     }
3402     else if (parser->tok == ':')
3403     {
3404         size_t i;
3405         ast_label *label;
3406         if (!parser_next(parser)) {
3407             parseerror(parser, "expected label name");
3408             return false;
3409         }
3410         if (parser->tok != TOKEN_IDENT) {
3411             parseerror(parser, "label must be an identifier");
3412             return false;
3413         }
3414         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3415         if (label) {
3416             if (!label->undefined) {
3417                 parseerror(parser, "label `%s` already defined", label->name);
3418                 return false;
3419             }
3420             label->undefined = false;
3421         }
3422         else {
3423             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3424             vec_push(parser->labels, label);
3425         }
3426         *out = (ast_expression*)label;
3427         if (!parser_next(parser)) {
3428             parseerror(parser, "parse error after label");
3429             return false;
3430         }
3431         for (i = 0; i < vec_size(parser->gotos); ++i) {
3432             if (!strcmp(parser->gotos[i]->name, label->name)) {
3433                 ast_goto_set_label(parser->gotos[i], label);
3434                 vec_remove(parser->gotos, i, 1);
3435                 --i;
3436             }
3437         }
3438         return true;
3439     }
3440     else if (parser->tok == ';')
3441     {
3442         if (!parser_next(parser)) {
3443             parseerror(parser, "parse error after empty statement");
3444             return false;
3445         }
3446         return true;
3447     }
3448     else
3449     {
3450         lex_ctx_t ctx = parser_ctx(parser);
3451         ast_expression *exp = parse_expression(parser, false, false);
3452         if (!exp)
3453             return false;
3454         *out = exp;
3455         if (!ast_side_effects(exp)) {
3456             if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3457                 return false;
3458         }
3459         return true;
3460     }
3461 }
3462
3463 static bool parse_enum(parser_t *parser)
3464 {
3465     bool        flag = false;
3466     bool        reverse = false;
3467     qcfloat_t     num = 0;
3468     ast_value **values = NULL;
3469     ast_value  *var = NULL;
3470     ast_value  *asvalue;
3471
3472     ast_expression *old;
3473
3474     if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3475         parseerror(parser, "expected `{` or `:` after `enum` keyword");
3476         return false;
3477     }
3478
3479     /* enumeration attributes (can add more later) */
3480     if (parser->tok == ':') {
3481         if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3482             parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3483             return false;
3484         }
3485
3486         /* attributes? */
3487         if (!strcmp(parser_tokval(parser), "flag")) {
3488             num  = 1;
3489             flag = true;
3490         }
3491         else if (!strcmp(parser_tokval(parser), "reverse")) {
3492             reverse = true;
3493         }
3494         else {
3495             parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3496             return false;
3497         }
3498
3499         if (!parser_next(parser) || parser->tok != '{') {
3500             parseerror(parser, "expected `{` after enum attribute ");
3501             return false;
3502         }
3503     }
3504
3505     while (true) {
3506         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3507             if (parser->tok == '}') {
3508                 /* allow an empty enum */
3509                 break;
3510             }
3511             parseerror(parser, "expected identifier or `}`");
3512             goto onerror;
3513         }
3514
3515         old = parser_find_field(parser, parser_tokval(parser));
3516         if (!old)
3517             old = parser_find_global(parser, parser_tokval(parser));
3518         if (old) {
3519             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3520                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3521             goto onerror;
3522         }
3523
3524         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3525         vec_push(values, var);
3526         var->cvq             = CV_CONST;
3527         var->hasvalue        = true;
3528
3529         /* for flagged enumerations increment in POTs of TWO */
3530         var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3531         parser_addglobal(parser, var->name, (ast_expression*)var);
3532
3533         if (!parser_next(parser)) {
3534             parseerror(parser, "expected `=`, `}` or comma after identifier");
3535             goto onerror;
3536         }
3537
3538         if (parser->tok == ',')
3539             continue;
3540         if (parser->tok == '}')
3541             break;
3542         if (parser->tok != '=') {
3543             parseerror(parser, "expected `=`, `}` or comma after identifier");
3544             goto onerror;
3545         }
3546
3547         if (!parser_next(parser)) {
3548             parseerror(parser, "expected expression after `=`");
3549             goto onerror;
3550         }
3551
3552         /* We got a value! */
3553         old = parse_expression_leave(parser, true, false, false);
3554         asvalue = (ast_value*)old;
3555         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3556             compile_error(ast_ctx(var), "constant value or expression expected");
3557             goto onerror;
3558         }
3559         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3560
3561         if (parser->tok == '}')
3562             break;
3563         if (parser->tok != ',') {
3564             parseerror(parser, "expected `}` or comma after expression");
3565             goto onerror;
3566         }
3567     }
3568
3569     /* patch them all (for reversed attribute) */
3570     if (reverse) {
3571         size_t i;
3572         for (i = 0; i < vec_size(values); i++)
3573             values[i]->constval.vfloat = vec_size(values) - i - 1;
3574     }
3575
3576     if (parser->tok != '}') {
3577         parseerror(parser, "internal error: breaking without `}`");
3578         goto onerror;
3579     }
3580
3581     if (!parser_next(parser) || parser->tok != ';') {
3582         parseerror(parser, "expected semicolon after enumeration");
3583         goto onerror;
3584     }
3585
3586     if (!parser_next(parser)) {
3587         parseerror(parser, "parse error after enumeration");
3588         goto onerror;
3589     }
3590
3591     vec_free(values);
3592     return true;
3593
3594 onerror:
3595     vec_free(values);
3596     return false;
3597 }
3598
3599 static bool parse_block_into(parser_t *parser, ast_block *block)
3600 {
3601     bool   retval = true;
3602
3603     parser_enterblock(parser);
3604
3605     if (!parser_next(parser)) { /* skip the '{' */
3606         parseerror(parser, "expected function body");
3607         goto cleanup;
3608     }
3609
3610     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3611     {
3612         ast_expression *expr = NULL;
3613         if (parser->tok == '}')
3614             break;
3615
3616         if (!parse_statement(parser, block, &expr, false)) {
3617             /* parseerror(parser, "parse error"); */
3618             block = NULL;
3619             goto cleanup;
3620         }
3621         if (!expr)
3622             continue;
3623         if (!ast_block_add_expr(block, expr)) {
3624             ast_delete(block);
3625             block = NULL;
3626             goto cleanup;
3627         }
3628     }
3629
3630     if (parser->tok != '}') {
3631         block = NULL;
3632     } else {
3633         (void)parser_next(parser);
3634     }
3635
3636 cleanup:
3637     if (!parser_leaveblock(parser))
3638         retval = false;
3639     return retval && !!block;
3640 }
3641
3642 static ast_block* parse_block(parser_t *parser)
3643 {
3644     ast_block *block;
3645     block = ast_block_new(parser_ctx(parser));
3646     if (!block)
3647         return NULL;
3648     if (!parse_block_into(parser, block)) {
3649         ast_block_delete(block);
3650         return NULL;
3651     }
3652     return block;
3653 }
3654
3655 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3656 {
3657     if (parser->tok == '{') {
3658         *out = (ast_expression*)parse_block(parser);
3659         return !!*out;
3660     }
3661     return parse_statement(parser, NULL, out, false);
3662 }
3663
3664 static bool create_vector_members(ast_value *var, ast_member **me)
3665 {
3666     size_t i;
3667     size_t len = strlen(var->name);
3668
3669     for (i = 0; i < 3; ++i) {
3670         char *name = (char*)mem_a(len+3);
3671         memcpy(name, var->name, len);
3672         name[len+0] = '_';
3673         name[len+1] = 'x'+i;
3674         name[len+2] = 0;
3675         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3676         mem_d(name);
3677         if (!me[i])
3678             break;
3679     }
3680     if (i == 3)
3681         return true;
3682
3683     /* unroll */
3684     do { ast_member_delete(me[--i]); } while(i);
3685     return false;
3686 }
3687
3688 static bool parse_function_body(parser_t *parser, ast_value *var)
3689 {
3690     ast_block      *block = NULL;
3691     ast_function   *func;
3692     ast_function   *old;
3693     size_t          parami;
3694
3695     ast_expression *framenum  = NULL;
3696     ast_expression *nextthink = NULL;
3697     /* None of the following have to be deleted */
3698     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3699     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3700     bool            has_frame_think;
3701
3702     bool retval = true;
3703
3704     has_frame_think = false;
3705     old = parser->function;
3706
3707     if (var->expression.flags & AST_FLAG_ALIAS) {
3708         parseerror(parser, "function aliases cannot have bodies");
3709         return false;
3710     }
3711
3712     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3713         parseerror(parser, "gotos/labels leaking");
3714         return false;
3715     }
3716
3717     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3718         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3719                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3720         {
3721             return false;
3722         }
3723     }
3724
3725     if (parser->tok == '[') {
3726         /* got a frame definition: [ framenum, nextthink ]
3727          * this translates to:
3728          * self.frame = framenum;
3729          * self.nextthink = time + 0.1;
3730          * self.think = nextthink;
3731          */
3732         nextthink = NULL;
3733
3734         fld_think     = parser_find_field(parser, "think");
3735         fld_nextthink = parser_find_field(parser, "nextthink");
3736         fld_frame     = parser_find_field(parser, "frame");
3737         if (!fld_think || !fld_nextthink || !fld_frame) {
3738             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3739             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3740             return false;
3741         }
3742         gbl_time      = parser_find_global(parser, "time");
3743         gbl_self      = parser_find_global(parser, "self");
3744         if (!gbl_time || !gbl_self) {
3745             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3746             parseerror(parser, "please declare the following globals: `time`, `self`");
3747             return false;
3748         }
3749
3750         if (!parser_next(parser))
3751             return false;
3752
3753         framenum = parse_expression_leave(parser, true, false, false);
3754         if (!framenum) {
3755             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3756             return false;
3757         }
3758         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3759             ast_unref(framenum);
3760             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3761             return false;
3762         }
3763
3764         if (parser->tok != ',') {
3765             ast_unref(framenum);
3766             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3767             parseerror(parser, "Got a %i\n", parser->tok);
3768             return false;
3769         }
3770
3771         if (!parser_next(parser)) {
3772             ast_unref(framenum);
3773             return false;
3774         }
3775
3776         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3777         {
3778             /* qc allows the use of not-yet-declared functions here
3779              * - this automatically creates a prototype */
3780             ast_value      *thinkfunc;
3781             ast_expression *functype = fld_think->next;
3782
3783             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3784             if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3785                 ast_unref(framenum);
3786                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3787                 return false;
3788             }
3789             ast_type_adopt(thinkfunc, functype);
3790
3791             if (!parser_next(parser)) {
3792                 ast_unref(framenum);
3793                 ast_delete(thinkfunc);
3794                 return false;
3795             }
3796
3797             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3798
3799             nextthink = (ast_expression*)thinkfunc;
3800
3801         } else {
3802             nextthink = parse_expression_leave(parser, true, false, false);
3803             if (!nextthink) {
3804                 ast_unref(framenum);
3805                 parseerror(parser, "expected a think-function in [frame,think] notation");
3806                 return false;
3807             }
3808         }
3809
3810         if (!ast_istype(nextthink, ast_value)) {
3811             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3812             retval = false;
3813         }
3814
3815         if (retval && parser->tok != ']') {
3816             parseerror(parser, "expected closing `]` for [frame,think] notation");
3817             retval = false;
3818         }
3819
3820         if (retval && !parser_next(parser)) {
3821             retval = false;
3822         }
3823
3824         if (retval && parser->tok != '{') {
3825             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3826             retval = false;
3827         }
3828
3829         if (!retval) {
3830             ast_unref(nextthink);
3831             ast_unref(framenum);
3832             return false;
3833         }
3834
3835         has_frame_think = true;
3836     }
3837
3838     block = ast_block_new(parser_ctx(parser));
3839     if (!block) {
3840         parseerror(parser, "failed to allocate block");
3841         if (has_frame_think) {
3842             ast_unref(nextthink);
3843             ast_unref(framenum);
3844         }
3845         return false;
3846     }
3847
3848     if (has_frame_think) {
3849         lex_ctx_t ctx;
3850         ast_expression *self_frame;
3851         ast_expression *self_nextthink;
3852         ast_expression *self_think;
3853         ast_expression *time_plus_1;
3854         ast_store *store_frame;
3855         ast_store *store_nextthink;
3856         ast_store *store_think;
3857
3858         ctx = parser_ctx(parser);
3859         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3860         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3861         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3862
3863         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3864                          gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3865
3866         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3867             if (self_frame)     ast_delete(self_frame);
3868             if (self_nextthink) ast_delete(self_nextthink);
3869             if (self_think)     ast_delete(self_think);
3870             if (time_plus_1)    ast_delete(time_plus_1);
3871             retval = false;
3872         }
3873
3874         if (retval)
3875         {
3876             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3877             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3878             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3879
3880             if (!store_frame) {
3881                 ast_delete(self_frame);
3882                 retval = false;
3883             }
3884             if (!store_nextthink) {
3885                 ast_delete(self_nextthink);
3886                 retval = false;
3887             }
3888             if (!store_think) {
3889                 ast_delete(self_think);
3890                 retval = false;
3891             }
3892             if (!retval) {
3893                 if (store_frame)     ast_delete(store_frame);
3894                 if (store_nextthink) ast_delete(store_nextthink);
3895                 if (store_think)     ast_delete(store_think);
3896                 retval = false;
3897             }
3898             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3899                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3900                 !ast_block_add_expr(block, (ast_expression*)store_think))
3901             {
3902                 retval = false;
3903             }
3904         }
3905
3906         if (!retval) {
3907             parseerror(parser, "failed to generate code for [frame,think]");
3908             ast_unref(nextthink);
3909             ast_unref(framenum);
3910             ast_delete(block);
3911             return false;
3912         }
3913     }
3914
3915     if (var->hasvalue) {
3916         parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3917         ast_block_delete(block);
3918         goto enderr;
3919     }
3920
3921     func = ast_function_new(ast_ctx(var), var->name, var);
3922     if (!func) {
3923         parseerror(parser, "failed to allocate function for `%s`", var->name);
3924         ast_block_delete(block);
3925         goto enderr;
3926     }
3927     vec_push(parser->functions, func);
3928
3929     parser_enterblock(parser);
3930
3931     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3932         size_t     e;
3933         ast_value *param = var->expression.params[parami];
3934         ast_member *me[3];
3935
3936         if (param->expression.vtype != TYPE_VECTOR &&
3937             (param->expression.vtype != TYPE_FIELD ||
3938              param->expression.next->vtype != TYPE_VECTOR))
3939         {
3940             continue;
3941         }
3942
3943         if (!create_vector_members(param, me)) {
3944             ast_block_delete(block);
3945             goto enderrfn;
3946         }
3947
3948         for (e = 0; e < 3; ++e) {
3949             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3950             ast_block_collect(block, (ast_expression*)me[e]);
3951         }
3952     }
3953
3954     if (var->argcounter) {
3955         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
3956         parser_addlocal(parser, argc->name, (ast_expression*)argc);
3957         func->argc = argc;
3958     }
3959
3960     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3961         char name[1024];
3962         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
3963         varargs->expression.flags |= AST_FLAG_IS_VARARG;
3964         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
3965         varargs->expression.count = 0;
3966         util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
3967         if (!parser_create_array_setter_proto(parser, varargs, name)) {
3968             ast_delete(varargs);
3969             ast_block_delete(block);
3970             goto enderrfn;
3971         }
3972         util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
3973         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
3974             ast_delete(varargs);
3975             ast_block_delete(block);
3976             goto enderrfn;
3977         }
3978         func->varargs     = varargs;
3979         func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
3980     }
3981
3982     parser->function = func;
3983     if (!parse_block_into(parser, block)) {
3984         ast_block_delete(block);
3985         goto enderrfn;
3986     }
3987
3988     vec_push(func->blocks, block);
3989
3990
3991     parser->function = old;
3992     if (!parser_leaveblock(parser))
3993         retval = false;
3994     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3995         parseerror(parser, "internal error: local scopes left");
3996         retval = false;
3997     }
3998
3999     if (parser->tok == ';')
4000         return parser_next(parser);
4001     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4002         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4003     return retval;
4004
4005 enderrfn:
4006     (void)!parser_leaveblock(parser);
4007     vec_pop(parser->functions);
4008     ast_function_delete(func);
4009     var->constval.vfunc = NULL;
4010
4011 enderr:
4012     parser->function = old;
4013     return false;
4014 }
4015
4016 static ast_expression *array_accessor_split(
4017     parser_t  *parser,
4018     ast_value *array,
4019     ast_value *index,
4020     size_t     middle,
4021     ast_expression *left,
4022     ast_expression *right
4023     )
4024 {
4025     ast_ifthen *ifthen;
4026     ast_binary *cmp;
4027
4028     lex_ctx_t ctx = ast_ctx(array);
4029
4030     if (!left || !right) {
4031         if (left)  ast_delete(left);
4032         if (right) ast_delete(right);
4033         return NULL;
4034     }
4035
4036     cmp = ast_binary_new(ctx, INSTR_LT,
4037                          (ast_expression*)index,
4038                          (ast_expression*)fold_constgen_float(parser->fold, middle));
4039     if (!cmp) {
4040         ast_delete(left);
4041         ast_delete(right);
4042         parseerror(parser, "internal error: failed to create comparison for array setter");
4043         return NULL;
4044     }
4045
4046     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4047     if (!ifthen) {
4048         ast_delete(cmp); /* will delete left and right */
4049         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4050         return NULL;
4051     }
4052
4053     return (ast_expression*)ifthen;
4054 }
4055
4056 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4057 {
4058     lex_ctx_t ctx = ast_ctx(array);
4059
4060     if (from+1 == afterend) {
4061         /* set this value */
4062         ast_block       *block;
4063         ast_return      *ret;
4064         ast_array_index *subscript;
4065         ast_store       *st;
4066         int assignop = type_store_instr[value->expression.vtype];
4067
4068         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4069             assignop = INSTR_STORE_V;
4070
4071         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4072         if (!subscript)
4073             return NULL;
4074
4075         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4076         if (!st) {
4077             ast_delete(subscript);
4078             return NULL;
4079         }
4080
4081         block = ast_block_new(ctx);
4082         if (!block) {
4083             ast_delete(st);
4084             return NULL;
4085         }
4086
4087         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4088             ast_delete(block);
4089             return NULL;
4090         }
4091
4092         ret = ast_return_new(ctx, NULL);
4093         if (!ret) {
4094             ast_delete(block);
4095             return NULL;
4096         }
4097
4098         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4099             ast_delete(block);
4100             return NULL;
4101         }
4102
4103         return (ast_expression*)block;
4104     } else {
4105         ast_expression *left, *right;
4106         size_t diff = afterend - from;
4107         size_t middle = from + diff/2;
4108         left  = array_setter_node(parser, array, index, value, from, middle);
4109         right = array_setter_node(parser, array, index, value, middle, afterend);
4110         return array_accessor_split(parser, array, index, middle, left, right);
4111     }
4112 }
4113
4114 static ast_expression *array_field_setter_node(
4115     parser_t  *parser,
4116     ast_value *array,
4117     ast_value *entity,
4118     ast_value *index,
4119     ast_value *value,
4120     size_t     from,
4121     size_t     afterend)
4122 {
4123     lex_ctx_t ctx = ast_ctx(array);
4124
4125     if (from+1 == afterend) {
4126         /* set this value */
4127         ast_block       *block;
4128         ast_return      *ret;
4129         ast_entfield    *entfield;
4130         ast_array_index *subscript;
4131         ast_store       *st;
4132         int assignop = type_storep_instr[value->expression.vtype];
4133
4134         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4135             assignop = INSTR_STOREP_V;
4136
4137         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4138         if (!subscript)
4139             return NULL;
4140
4141         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4142         subscript->expression.vtype = TYPE_FIELD;
4143
4144         entfield = ast_entfield_new_force(ctx,
4145                                           (ast_expression*)entity,
4146                                           (ast_expression*)subscript,
4147                                           (ast_expression*)subscript);
4148         if (!entfield) {
4149             ast_delete(subscript);
4150             return NULL;
4151         }
4152
4153         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4154         if (!st) {
4155             ast_delete(entfield);
4156             return NULL;
4157         }
4158
4159         block = ast_block_new(ctx);
4160         if (!block) {
4161             ast_delete(st);
4162             return NULL;
4163         }
4164
4165         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4166             ast_delete(block);
4167             return NULL;
4168         }
4169
4170         ret = ast_return_new(ctx, NULL);
4171         if (!ret) {
4172             ast_delete(block);
4173             return NULL;
4174         }
4175
4176         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4177             ast_delete(block);
4178             return NULL;
4179         }
4180
4181         return (ast_expression*)block;
4182     } else {
4183         ast_expression *left, *right;
4184         size_t diff = afterend - from;
4185         size_t middle = from + diff/2;
4186         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4187         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4188         return array_accessor_split(parser, array, index, middle, left, right);
4189     }
4190 }
4191
4192 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4193 {
4194     lex_ctx_t ctx = ast_ctx(array);
4195
4196     if (from+1 == afterend) {
4197         ast_return      *ret;
4198         ast_array_index *subscript;
4199
4200         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4201         if (!subscript)
4202             return NULL;
4203
4204         ret = ast_return_new(ctx, (ast_expression*)subscript);
4205         if (!ret) {
4206             ast_delete(subscript);
4207             return NULL;
4208         }
4209
4210         return (ast_expression*)ret;
4211     } else {
4212         ast_expression *left, *right;
4213         size_t diff = afterend - from;
4214         size_t middle = from + diff/2;
4215         left  = array_getter_node(parser, array, index, from, middle);
4216         right = array_getter_node(parser, array, index, middle, afterend);
4217         return array_accessor_split(parser, array, index, middle, left, right);
4218     }
4219 }
4220
4221 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4222 {
4223     ast_function   *func = NULL;
4224     ast_value      *fval = NULL;
4225     ast_block      *body = NULL;
4226
4227     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4228     if (!fval) {
4229         parseerror(parser, "failed to create accessor function value");
4230         return false;
4231     }
4232
4233     func = ast_function_new(ast_ctx(array), funcname, fval);
4234     if (!func) {
4235         ast_delete(fval);
4236         parseerror(parser, "failed to create accessor function node");
4237         return false;
4238     }
4239
4240     body = ast_block_new(ast_ctx(array));
4241     if (!body) {
4242         parseerror(parser, "failed to create block for array accessor");
4243         ast_delete(fval);
4244         ast_delete(func);
4245         return false;
4246     }
4247
4248     vec_push(func->blocks, body);
4249     *out = fval;
4250
4251     vec_push(parser->accessors, fval);
4252
4253     return true;
4254 }
4255
4256 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4257 {
4258     ast_value      *index = NULL;
4259     ast_value      *value = NULL;
4260     ast_function   *func;
4261     ast_value      *fval;
4262
4263     if (!ast_istype(array->expression.next, ast_value)) {
4264         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4265         return NULL;
4266     }
4267
4268     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4269         return NULL;
4270     func = fval->constval.vfunc;
4271     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4272
4273     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4274     value = ast_value_copy((ast_value*)array->expression.next);
4275
4276     if (!index || !value) {
4277         parseerror(parser, "failed to create locals for array accessor");
4278         goto cleanup;
4279     }
4280     (void)!ast_value_set_name(value, "value"); /* not important */
4281     vec_push(fval->expression.params, index);
4282     vec_push(fval->expression.params, value);
4283
4284     array->setter = fval;
4285     return fval;
4286 cleanup:
4287     if (index) ast_delete(index);
4288     if (value) ast_delete(value);
4289     ast_delete(func);
4290     ast_delete(fval);
4291     return NULL;
4292 }
4293
4294 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4295 {
4296     ast_expression *root = NULL;
4297     root = array_setter_node(parser, array,
4298                              array->setter->expression.params[0],
4299                              array->setter->expression.params[1],
4300                              0, array->expression.count);
4301     if (!root) {
4302         parseerror(parser, "failed to build accessor search tree");
4303         return false;
4304     }
4305     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4306         ast_delete(root);
4307         return false;
4308     }
4309     return true;
4310 }
4311
4312 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4313 {
4314     if (!parser_create_array_setter_proto(parser, array, funcname))
4315         return false;
4316     return parser_create_array_setter_impl(parser, array);
4317 }
4318
4319 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4320 {
4321     ast_expression *root = NULL;
4322     ast_value      *entity = NULL;
4323     ast_value      *index = NULL;
4324     ast_value      *value = NULL;
4325     ast_function   *func;
4326     ast_value      *fval;
4327
4328     if (!ast_istype(array->expression.next, ast_value)) {
4329         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4330         return false;
4331     }
4332
4333     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4334         return false;
4335     func = fval->constval.vfunc;
4336     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4337
4338     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4339     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4340     value  = ast_value_copy((ast_value*)array->expression.next);
4341     if (!entity || !index || !value) {
4342         parseerror(parser, "failed to create locals for array accessor");
4343         goto cleanup;
4344     }
4345     (void)!ast_value_set_name(value, "value"); /* not important */
4346     vec_push(fval->expression.params, entity);
4347     vec_push(fval->expression.params, index);
4348     vec_push(fval->expression.params, value);
4349
4350     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4351     if (!root) {
4352         parseerror(parser, "failed to build accessor search tree");
4353         goto cleanup;
4354     }
4355
4356     array->setter = fval;
4357     return ast_block_add_expr(func->blocks[0], root);
4358 cleanup:
4359     if (entity) ast_delete(entity);
4360     if (index)  ast_delete(index);
4361     if (value)  ast_delete(value);
4362     if (root)   ast_delete(root);
4363     ast_delete(func);
4364     ast_delete(fval);
4365     return false;
4366 }
4367
4368 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4369 {
4370     ast_value      *index = NULL;
4371     ast_value      *fval;
4372     ast_function   *func;
4373
4374     /* NOTE: checking array->expression.next rather than elemtype since
4375      * for fields elemtype is a temporary fieldtype.
4376      */
4377     if (!ast_istype(array->expression.next, ast_value)) {
4378         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4379         return NULL;
4380     }
4381
4382     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4383         return NULL;
4384     func = fval->constval.vfunc;
4385     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4386
4387     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4388
4389     if (!index) {
4390         parseerror(parser, "failed to create locals for array accessor");
4391         goto cleanup;
4392     }
4393     vec_push(fval->expression.params, index);
4394
4395     array->getter = fval;
4396     return fval;
4397 cleanup:
4398     if (index) ast_delete(index);
4399     ast_delete(func);
4400     ast_delete(fval);
4401     return NULL;
4402 }
4403
4404 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4405 {
4406     ast_expression *root = NULL;
4407
4408     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4409     if (!root) {
4410         parseerror(parser, "failed to build accessor search tree");
4411         return false;
4412     }
4413     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4414         ast_delete(root);
4415         return false;
4416     }
4417     return true;
4418 }
4419
4420 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4421 {
4422     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4423         return false;
4424     return parser_create_array_getter_impl(parser, array);
4425 }
4426
4427 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4428 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4429 {
4430     lex_ctx_t     ctx;
4431     size_t      i;
4432     ast_value **params;
4433     ast_value  *param;
4434     ast_value  *fval;
4435     bool        first = true;
4436     bool        variadic = false;
4437     ast_value  *varparam = NULL;
4438     char       *argcounter = NULL;
4439
4440     ctx = parser_ctx(parser);
4441
4442     /* for the sake of less code we parse-in in this function */
4443     if (!parser_next(parser)) {
4444         ast_delete(var);
4445         parseerror(parser, "expected parameter list");
4446         return NULL;
4447     }
4448
4449     params = NULL;
4450
4451     /* parse variables until we hit a closing paren */
4452     while (parser->tok != ')') {
4453         if (!first) {
4454             /* there must be commas between them */
4455             if (parser->tok != ',') {
4456                 parseerror(parser, "expected comma or end of parameter list");
4457                 goto on_error;
4458             }
4459             if (!parser_next(parser)) {
4460                 parseerror(parser, "expected parameter");
4461                 goto on_error;
4462             }
4463         }
4464         first = false;
4465
4466         if (parser->tok == TOKEN_DOTS) {
4467             /* '...' indicates a varargs function */
4468             variadic = true;
4469             if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4470                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4471                 goto on_error;
4472             }
4473             if (parser->tok == TOKEN_IDENT) {
4474                 argcounter = util_strdup(parser_tokval(parser));
4475                 if (!parser_next(parser) || parser->tok != ')') {
4476                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4477                     goto on_error;
4478                 }
4479             }
4480         }
4481         else
4482         {
4483             /* for anything else just parse a typename */
4484             param = parse_typename(parser, NULL, NULL);
4485             if (!param)
4486                 goto on_error;
4487             vec_push(params, param);
4488             if (param->expression.vtype >= TYPE_VARIANT) {
4489                 char tname[1024]; /* typename is reserved in C++ */
4490                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4491                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4492                 goto on_error;
4493             }
4494             /* type-restricted varargs */
4495             if (parser->tok == TOKEN_DOTS) {
4496                 variadic = true;
4497                 varparam = vec_last(params);
4498                 vec_pop(params);
4499                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4500                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4501                     goto on_error;
4502                 }
4503                 if (parser->tok == TOKEN_IDENT) {
4504                     argcounter = util_strdup(parser_tokval(parser));
4505                     if (!parser_next(parser) || parser->tok != ')') {
4506                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4507                         goto on_error;
4508                     }
4509                 }
4510             }
4511         }
4512     }
4513
4514     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4515         vec_free(params);
4516
4517     /* sanity check */
4518     if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4519         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4520
4521     /* parse-out */
4522     if (!parser_next(parser)) {
4523         parseerror(parser, "parse error after typename");
4524         goto on_error;
4525     }
4526
4527     /* now turn 'var' into a function type */
4528     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4529     fval->expression.next     = (ast_expression*)var;
4530     if (variadic)
4531         fval->expression.flags |= AST_FLAG_VARIADIC;
4532     var = fval;
4533
4534     var->expression.params   = params;
4535     var->expression.varparam = (ast_expression*)varparam;
4536     var->argcounter          = argcounter;
4537     params = NULL;
4538
4539     return var;
4540
4541 on_error:
4542     if (argcounter)
4543         mem_d(argcounter);
4544     if (varparam)
4545         ast_delete(varparam);
4546     ast_delete(var);
4547     for (i = 0; i < vec_size(params); ++i)
4548         ast_delete(params[i]);
4549     vec_free(params);
4550     return NULL;
4551 }
4552
4553 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4554 {
4555     ast_expression *cexp;
4556     ast_value      *cval, *tmp;
4557     lex_ctx_t ctx;
4558
4559     ctx = parser_ctx(parser);
4560
4561     if (!parser_next(parser)) {
4562         ast_delete(var);
4563         parseerror(parser, "expected array-size");
4564         return NULL;
4565     }
4566
4567     if (parser->tok != ']') {
4568         cexp = parse_expression_leave(parser, true, false, false);
4569
4570         if (!cexp || !ast_istype(cexp, ast_value)) {
4571             if (cexp)
4572                 ast_unref(cexp);
4573             ast_delete(var);
4574             parseerror(parser, "expected array-size as constant positive integer");
4575             return NULL;
4576         }
4577         cval = (ast_value*)cexp;
4578     }
4579     else {
4580         cexp = NULL;
4581         cval = NULL;
4582     }
4583
4584     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4585     tmp->expression.next = (ast_expression*)var;
4586     var = tmp;
4587
4588     if (cval) {
4589         if (cval->expression.vtype == TYPE_INTEGER)
4590             tmp->expression.count = cval->constval.vint;
4591         else if (cval->expression.vtype == TYPE_FLOAT)
4592             tmp->expression.count = cval->constval.vfloat;
4593         else {
4594             ast_unref(cexp);
4595             ast_delete(var);
4596             parseerror(parser, "array-size must be a positive integer constant");
4597             return NULL;
4598         }
4599
4600         ast_unref(cexp);
4601     } else {
4602         var->expression.count = -1;
4603         var->expression.flags |= AST_FLAG_ARRAY_INIT;
4604     }
4605
4606     if (parser->tok != ']') {
4607         ast_delete(var);
4608         parseerror(parser, "expected ']' after array-size");
4609         return NULL;
4610     }
4611     if (!parser_next(parser)) {
4612         ast_delete(var);
4613         parseerror(parser, "error after parsing array size");
4614         return NULL;
4615     }
4616     return var;
4617 }
4618
4619 /* Parse a complete typename.
4620  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4621  * but when parsing variables separated by comma
4622  * 'storebase' should point to where the base-type should be kept.
4623  * The base type makes up every bit of type information which comes *before* the
4624  * variable name.
4625  *
4626  * The following will be parsed in its entirety:
4627  *     void() foo()
4628  * The 'basetype' in this case is 'void()'
4629  * and if there's a comma after it, say:
4630  *     void() foo(), bar
4631  * then the type-information 'void()' can be stored in 'storebase'
4632  */
4633 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4634 {
4635     ast_value *var, *tmp;
4636     lex_ctx_t    ctx;
4637
4638     const char *name = NULL;
4639     bool        isfield  = false;
4640     bool        wasarray = false;
4641     size_t      morefields = 0;
4642
4643     ctx = parser_ctx(parser);
4644
4645     /* types may start with a dot */
4646     if (parser->tok == '.') {
4647         isfield = true;
4648         /* if we parsed a dot we need a typename now */
4649         if (!parser_next(parser)) {
4650             parseerror(parser, "expected typename for field definition");
4651             return NULL;
4652         }
4653
4654         /* Further dots are handled seperately because they won't be part of the
4655          * basetype
4656          */
4657         while (parser->tok == '.') {
4658             ++morefields;
4659             if (!parser_next(parser)) {
4660                 parseerror(parser, "expected typename for field definition");
4661                 return NULL;
4662             }
4663         }
4664     }
4665     if (parser->tok == TOKEN_IDENT)
4666         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4667     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4668         parseerror(parser, "expected typename");
4669         return NULL;
4670     }
4671
4672     /* generate the basic type value */
4673     if (cached_typedef) {
4674         var = ast_value_copy(cached_typedef);
4675         ast_value_set_name(var, "<type(from_def)>");
4676     } else
4677         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4678
4679     for (; morefields; --morefields) {
4680         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4681         tmp->expression.next = (ast_expression*)var;
4682         var = tmp;
4683     }
4684
4685     /* do not yet turn into a field - remember:
4686      * .void() foo; is a field too
4687      * .void()() foo; is a function
4688      */
4689
4690     /* parse on */
4691     if (!parser_next(parser)) {
4692         ast_delete(var);
4693         parseerror(parser, "parse error after typename");
4694         return NULL;
4695     }
4696
4697     /* an opening paren now starts the parameter-list of a function
4698      * this is where original-QC has parameter lists.
4699      * We allow a single parameter list here.
4700      * Much like fteqcc we don't allow `float()() x`
4701      */
4702     if (parser->tok == '(') {
4703         var = parse_parameter_list(parser, var);
4704         if (!var)
4705             return NULL;
4706     }
4707
4708     /* store the base if requested */
4709     if (storebase) {
4710         *storebase = ast_value_copy(var);
4711         if (isfield) {
4712             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4713             tmp->expression.next = (ast_expression*)*storebase;
4714             *storebase = tmp;
4715         }
4716     }
4717
4718     /* there may be a name now */
4719     if (parser->tok == TOKEN_IDENT) {
4720         name = util_strdup(parser_tokval(parser));
4721         /* parse on */
4722         if (!parser_next(parser)) {
4723             ast_delete(var);
4724             mem_d(name);
4725             parseerror(parser, "error after variable or field declaration");
4726             return NULL;
4727         }
4728     }
4729
4730     /* now this may be an array */
4731     if (parser->tok == '[') {
4732         wasarray = true;
4733         var = parse_arraysize(parser, var);
4734         if (!var) {
4735             if (name) mem_d(name);
4736             return NULL;
4737         }
4738     }
4739
4740     /* This is the point where we can turn it into a field */
4741     if (isfield) {
4742         /* turn it into a field if desired */
4743         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4744         tmp->expression.next = (ast_expression*)var;
4745         var = tmp;
4746     }
4747
4748     /* now there may be function parens again */
4749     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4750         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4751     if (parser->tok == '(' && wasarray)
4752         parseerror(parser, "arrays as part of a return type is not supported");
4753     while (parser->tok == '(') {
4754         var = parse_parameter_list(parser, var);
4755         if (!var) {
4756             if (name) mem_d(name);
4757             return NULL;
4758         }
4759     }
4760
4761     /* finally name it */
4762     if (name) {
4763         if (!ast_value_set_name(var, name)) {
4764             ast_delete(var);
4765             mem_d(name);
4766             parseerror(parser, "internal error: failed to set name");
4767             return NULL;
4768         }
4769         /* free the name, ast_value_set_name duplicates */
4770         mem_d(name);
4771     }
4772
4773     return var;
4774 }
4775
4776 static bool parse_typedef(parser_t *parser)
4777 {
4778     ast_value      *typevar, *oldtype;
4779     ast_expression *old;
4780
4781     typevar = parse_typename(parser, NULL, NULL);
4782
4783     if (!typevar)
4784         return false;
4785
4786     if ( (old = parser_find_var(parser, typevar->name)) ) {
4787         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4788                    " -> `%s` has been declared here: %s:%i",
4789                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4790         ast_delete(typevar);
4791         return false;
4792     }
4793
4794     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4795         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4796                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4797         ast_delete(typevar);
4798         return false;
4799     }
4800
4801     vec_push(parser->_typedefs, typevar);
4802     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4803
4804     if (parser->tok != ';') {
4805         parseerror(parser, "expected semicolon after typedef");
4806         return false;
4807     }
4808     if (!parser_next(parser)) {
4809         parseerror(parser, "parse error after typedef");
4810         return false;
4811     }
4812
4813     return true;
4814 }
4815
4816 static const char *cvq_to_str(int cvq) {
4817     switch (cvq) {
4818         case CV_NONE:  return "none";
4819         case CV_VAR:   return "`var`";
4820         case CV_CONST: return "`const`";
4821         default:       return "<INVALID>";
4822     }
4823 }
4824
4825 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4826 {
4827     bool av, ao;
4828     if (proto->cvq != var->cvq) {
4829         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4830               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4831               parser->tok == '='))
4832         {
4833             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4834                                  "`%s` declared with different qualifiers: %s\n"
4835                                  " -> previous declaration here: %s:%i uses %s",
4836                                  var->name, cvq_to_str(var->cvq),
4837                                  ast_ctx(proto).file, ast_ctx(proto).line,
4838                                  cvq_to_str(proto->cvq));
4839         }
4840     }
4841     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4842     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4843     if (!av != !ao) {
4844         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4845                              "`%s` declared with different attributes%s\n"
4846                              " -> previous declaration here: %s:%i",
4847                              var->name, (av ? ": noreturn" : ""),
4848                              ast_ctx(proto).file, ast_ctx(proto).line,
4849                              (ao ? ": noreturn" : ""));
4850     }
4851     return true;
4852 }
4853
4854 static bool create_array_accessors(parser_t *parser, ast_value *var)
4855 {
4856     char name[1024];
4857     util_snprintf(name, sizeof(name), "%s##SET", var->name);
4858     if (!parser_create_array_setter(parser, var, name))
4859         return false;
4860     util_snprintf(name, sizeof(name), "%s##GET", var->name);
4861     if (!parser_create_array_getter(parser, var, var->expression.next, name))
4862         return false;
4863     return true;
4864 }
4865
4866 static bool parse_array(parser_t *parser, ast_value *array)
4867 {
4868     size_t i;
4869     if (array->initlist) {
4870         parseerror(parser, "array already initialized elsewhere");
4871         return false;
4872     }
4873     if (!parser_next(parser)) {
4874         parseerror(parser, "parse error in array initializer");
4875         return false;
4876     }
4877     i = 0;
4878     while (parser->tok != '}') {
4879         ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4880         if (!v)
4881             return false;
4882         if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4883             ast_unref(v);
4884             parseerror(parser, "initializing element must be a compile time constant");
4885             return false;
4886         }
4887         vec_push(array->initlist, v->constval);
4888         if (v->expression.vtype == TYPE_STRING) {
4889             array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4890             ++i;
4891         }
4892         ast_unref(v);
4893         if (parser->tok == '}')
4894             break;
4895         if (parser->tok != ',' || !parser_next(parser)) {
4896             parseerror(parser, "expected comma or '}' in element list");
4897             return false;
4898         }
4899     }
4900     if (!parser_next(parser) || parser->tok != ';') {
4901         parseerror(parser, "expected semicolon after initializer, got %s");
4902         return false;
4903     }
4904     /*
4905     if (!parser_next(parser)) {
4906         parseerror(parser, "parse error after initializer");
4907         return false;
4908     }
4909     */
4910
4911     if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4912         if (array->expression.count != (size_t)-1) {
4913             parseerror(parser, "array `%s' has already been initialized with %u elements",
4914                        array->name, (unsigned)array->expression.count);
4915         }
4916         array->expression.count = vec_size(array->initlist);
4917         if (!create_array_accessors(parser, array))
4918             return false;
4919     }
4920     return true;
4921 }
4922
4923 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)
4924 {
4925     ast_value *var;
4926     ast_value *proto;
4927     ast_expression *old;
4928     bool       was_end;
4929     size_t     i;
4930
4931     ast_value *basetype = NULL;
4932     bool      retval    = true;
4933     bool      isparam   = false;
4934     bool      isvector  = false;
4935     bool      cleanvar  = true;
4936     bool      wasarray  = false;
4937
4938     ast_member *me[3] = { NULL, NULL, NULL };
4939
4940     if (!localblock && is_static)
4941         parseerror(parser, "`static` qualifier is not supported in global scope");
4942
4943     /* get the first complete variable */
4944     var = parse_typename(parser, &basetype, cached_typedef);
4945     if (!var) {
4946         if (basetype)
4947             ast_delete(basetype);
4948         return false;
4949     }
4950
4951     while (true) {
4952         proto = NULL;
4953         wasarray = false;
4954
4955         /* Part 0: finish the type */
4956         if (parser->tok == '(') {
4957             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4958                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4959             var = parse_parameter_list(parser, var);
4960             if (!var) {
4961                 retval = false;
4962                 goto cleanup;
4963             }
4964         }
4965         /* we only allow 1-dimensional arrays */
4966         if (parser->tok == '[') {
4967             wasarray = true;
4968             var = parse_arraysize(parser, var);
4969             if (!var) {
4970                 retval = false;
4971                 goto cleanup;
4972             }
4973         }
4974         if (parser->tok == '(' && wasarray) {
4975             parseerror(parser, "arrays as part of a return type is not supported");
4976             /* we'll still parse the type completely for now */
4977         }
4978         /* for functions returning functions */
4979         while (parser->tok == '(') {
4980             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4981                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4982             var = parse_parameter_list(parser, var);
4983             if (!var) {
4984                 retval = false;
4985                 goto cleanup;
4986             }
4987         }
4988
4989         var->cvq = qualifier;
4990         var->expression.flags |= qflags;
4991
4992         /*
4993          * store the vstring back to var for alias and
4994          * deprecation messages.
4995          */
4996         if (var->expression.flags & AST_FLAG_DEPRECATED ||
4997             var->expression.flags & AST_FLAG_ALIAS)
4998             var->desc = vstring;
4999
5000         /* Part 1:
5001          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5002          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5003          * is then filled with the previous definition and the parameter-names replaced.
5004          */
5005         if (!strcmp(var->name, "nil")) {
5006             if (OPTS_FLAG(UNTYPED_NIL)) {
5007                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5008                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5009             } else
5010                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5011         }
5012         if (!localblock) {
5013             /* Deal with end_sys_ vars */
5014             was_end = false;
5015             if (!strcmp(var->name, "end_sys_globals")) {
5016                 var->uses++;
5017                 parser->crc_globals = vec_size(parser->globals);
5018                 was_end = true;
5019             }
5020             else if (!strcmp(var->name, "end_sys_fields")) {
5021                 var->uses++;
5022                 parser->crc_fields = vec_size(parser->fields);
5023                 was_end = true;
5024             }
5025             if (was_end && var->expression.vtype == TYPE_FIELD) {
5026                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5027                                  "global '%s' hint should not be a field",
5028                                  parser_tokval(parser)))
5029                 {
5030                     retval = false;
5031                     goto cleanup;
5032                 }
5033             }
5034
5035             if (!nofields && var->expression.vtype == TYPE_FIELD)
5036             {
5037                 /* deal with field declarations */
5038                 old = parser_find_field(parser, var->name);
5039                 if (old) {
5040                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5041                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5042                     {
5043                         retval = false;
5044                         goto cleanup;
5045                     }
5046                     ast_delete(var);
5047                     var = NULL;
5048                     goto skipvar;
5049                     /*
5050                     parseerror(parser, "field `%s` already declared here: %s:%i",
5051                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5052                     retval = false;
5053                     goto cleanup;
5054                     */
5055                 }
5056                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5057                     (old = parser_find_global(parser, var->name)))
5058                 {
5059                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5060                     parseerror(parser, "field `%s` already declared here: %s:%i",
5061                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5062                     retval = false;
5063                     goto cleanup;
5064                 }
5065             }
5066             else
5067             {
5068                 /* deal with other globals */
5069                 old = parser_find_global(parser, var->name);
5070                 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5071                 {
5072                     /* This is a function which had a prototype */
5073                     if (!ast_istype(old, ast_value)) {
5074                         parseerror(parser, "internal error: prototype is not an ast_value");
5075                         retval = false;
5076                         goto cleanup;
5077                     }
5078                     proto = (ast_value*)old;
5079                     proto->desc = var->desc;
5080                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5081                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5082                                    proto->name,
5083                                    ast_ctx(proto).file, ast_ctx(proto).line);
5084                         retval = false;
5085                         goto cleanup;
5086                     }
5087                     /* we need the new parameter-names */
5088                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5089                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5090                     if (!parser_check_qualifiers(parser, var, proto)) {
5091                         retval = false;
5092                         if (proto->desc)
5093                             mem_d(proto->desc);
5094                         proto = NULL;
5095                         goto cleanup;
5096                     }
5097                     proto->expression.flags |= var->expression.flags;
5098                     ast_delete(var);
5099                     var = proto;
5100                 }
5101                 else
5102                 {
5103                     /* other globals */
5104                     if (old) {
5105                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5106                                          "global `%s` already declared here: %s:%i",
5107                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5108                         {
5109                             retval = false;
5110                             goto cleanup;
5111                         }
5112                         proto = (ast_value*)old;
5113                         if (!ast_istype(old, ast_value)) {
5114                             parseerror(parser, "internal error: not an ast_value");
5115                             retval = false;
5116                             proto = NULL;
5117                             goto cleanup;
5118                         }
5119                         if (!parser_check_qualifiers(parser, var, proto)) {
5120                             retval = false;
5121                             proto = NULL;
5122                             goto cleanup;
5123                         }
5124                         proto->expression.flags |= var->expression.flags;
5125                         ast_delete(var);
5126                         var = proto;
5127                     }
5128                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5129                         (old = parser_find_field(parser, var->name)))
5130                     {
5131                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5132                         parseerror(parser, "global `%s` already declared here: %s:%i",
5133                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5134                         retval = false;
5135                         goto cleanup;
5136                     }
5137                 }
5138             }
5139         }
5140         else /* it's not a global */
5141         {
5142             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5143             if (old && !isparam) {
5144                 parseerror(parser, "local `%s` already declared here: %s:%i",
5145                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5146                 retval = false;
5147                 goto cleanup;
5148             }
5149             old = parser_find_local(parser, var->name, 0, &isparam);
5150             if (old && isparam) {
5151                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5152                                  "local `%s` is shadowing a parameter", var->name))
5153                 {
5154                     parseerror(parser, "local `%s` already declared here: %s:%i",
5155                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5156                     retval = false;
5157                     goto cleanup;
5158                 }
5159                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5160                     ast_delete(var);
5161                     if (ast_istype(old, ast_value))
5162                         var = (ast_value*)old;
5163                     else {
5164                         var = NULL;
5165                         goto skipvar;
5166                     }
5167                 }
5168             }
5169         }
5170
5171         /* in a noref section we simply bump the usecount */
5172         if (noref || parser->noref)
5173             var->uses++;
5174
5175         /* Part 2:
5176          * Create the global/local, and deal with vector types.
5177          */
5178         if (!proto) {
5179             if (var->expression.vtype == TYPE_VECTOR)
5180                 isvector = true;
5181             else if (var->expression.vtype == TYPE_FIELD &&
5182                      var->expression.next->vtype == TYPE_VECTOR)
5183                 isvector = true;
5184
5185             if (isvector) {
5186                 if (!create_vector_members(var, me)) {
5187                     retval = false;
5188                     goto cleanup;
5189                 }
5190             }
5191
5192             if (!localblock) {
5193                 /* deal with global variables, fields, functions */
5194                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5195                     var->isfield = true;
5196                     vec_push(parser->fields, (ast_expression*)var);
5197                     util_htset(parser->htfields, var->name, var);
5198                     if (isvector) {
5199                         for (i = 0; i < 3; ++i) {
5200                             vec_push(parser->fields, (ast_expression*)me[i]);
5201                             util_htset(parser->htfields, me[i]->name, me[i]);
5202                         }
5203                     }
5204                 }
5205                 else {
5206                     if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5207                         parser_addglobal(parser, var->name, (ast_expression*)var);
5208                         if (isvector) {
5209                             for (i = 0; i < 3; ++i) {
5210                                 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5211                             }
5212                         }
5213                     } else {
5214                         ast_expression *find  = parser_find_global(parser, var->desc);
5215
5216                         if (!find) {
5217                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5218                             return false;
5219                         }
5220
5221                         if (var->expression.vtype != find->vtype) {
5222                             char ty1[1024];
5223                             char ty2[1024];
5224
5225                             ast_type_to_string(find,                  ty1, sizeof(ty1));
5226                             ast_type_to_string((ast_expression*)var,  ty2, sizeof(ty2));
5227
5228                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5229                                 ty1, ty2, var->name
5230                             );
5231                             return false;
5232                         }
5233
5234                         /*
5235                          * add alias to aliases table and to corrector
5236                          * so corrections can apply for aliases as well.
5237                          */
5238                         util_htset(parser->aliases, var->name, find);
5239
5240                         /*
5241                          * add to corrector so corrections can work
5242                          * even for aliases too.
5243                          */
5244                         correct_add (
5245                              vec_last(parser->correct_variables),
5246                             &vec_last(parser->correct_variables_score),
5247                             var->name
5248                         );
5249
5250                         /* generate aliases for vector components */
5251                         if (isvector) {
5252                             char *buffer[3];
5253
5254                             util_asprintf(&buffer[0], "%s_x", var->desc);
5255                             util_asprintf(&buffer[1], "%s_y", var->desc);
5256                             util_asprintf(&buffer[2], "%s_z", var->desc);
5257
5258                             util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5259                             util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5260                             util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5261
5262                             mem_d(buffer[0]);
5263                             mem_d(buffer[1]);
5264                             mem_d(buffer[2]);
5265
5266                             /*
5267                              * add to corrector so corrections can work
5268                              * even for aliases too.
5269                              */
5270                             correct_add (
5271                                  vec_last(parser->correct_variables),
5272                                 &vec_last(parser->correct_variables_score),
5273                                 me[0]->name
5274                             );
5275                             correct_add (
5276                                  vec_last(parser->correct_variables),
5277                                 &vec_last(parser->correct_variables_score),
5278                                 me[1]->name
5279                             );
5280                             correct_add (
5281                                  vec_last(parser->correct_variables),
5282                                 &vec_last(parser->correct_variables_score),
5283                                 me[2]->name
5284                             );
5285                         }
5286                     }
5287                 }
5288             } else {
5289                 if (is_static) {
5290                     /* a static adds itself to be generated like any other global
5291                      * but is added to the local namespace instead
5292                      */
5293                     char   *defname = NULL;
5294                     size_t  prefix_len, ln;
5295
5296                     ln = strlen(parser->function->name);
5297                     vec_append(defname, ln, parser->function->name);
5298
5299                     vec_append(defname, 2, "::");
5300                     /* remember the length up to here */
5301                     prefix_len = vec_size(defname);
5302
5303                     /* Add it to the local scope */
5304                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5305
5306                     /* corrector */
5307                     correct_add (
5308                          vec_last(parser->correct_variables),
5309                         &vec_last(parser->correct_variables_score),
5310                         var->name
5311                     );
5312
5313                     /* now rename the global */
5314                     ln = strlen(var->name);
5315                     vec_append(defname, ln, var->name);
5316                     ast_value_set_name(var, defname);
5317
5318                     /* push it to the to-be-generated globals */
5319                     vec_push(parser->globals, (ast_expression*)var);
5320
5321                     /* same game for the vector members */
5322                     if (isvector) {
5323                         for (i = 0; i < 3; ++i) {
5324                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5325
5326                             /* corrector */
5327                             correct_add(
5328                                  vec_last(parser->correct_variables),
5329                                 &vec_last(parser->correct_variables_score),
5330                                 me[i]->name
5331                             );
5332
5333                             vec_shrinkto(defname, prefix_len);
5334                             ln = strlen(me[i]->name);
5335                             vec_append(defname, ln, me[i]->name);
5336                             ast_member_set_name(me[i], defname);
5337
5338                             vec_push(parser->globals, (ast_expression*)me[i]);
5339                         }
5340                     }
5341                     vec_free(defname);
5342                 } else {
5343                     vec_push(localblock->locals, var);
5344                     parser_addlocal(parser, var->name, (ast_expression*)var);
5345                     if (isvector) {
5346                         for (i = 0; i < 3; ++i) {
5347                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5348                             ast_block_collect(localblock, (ast_expression*)me[i]);
5349                         }
5350                     }
5351                 }
5352             }
5353         }
5354         me[0] = me[1] = me[2] = NULL;
5355         cleanvar = false;
5356         /* Part 2.2
5357          * deal with arrays
5358          */
5359         if (var->expression.vtype == TYPE_ARRAY) {
5360             if (var->expression.count != (size_t)-1) {
5361                 if (!create_array_accessors(parser, var))
5362                     goto cleanup;
5363             }
5364         }
5365         else if (!localblock && !nofields &&
5366                  var->expression.vtype == TYPE_FIELD &&
5367                  var->expression.next->vtype == TYPE_ARRAY)
5368         {
5369             char name[1024];
5370             ast_expression *telem;
5371             ast_value      *tfield;
5372             ast_value      *array = (ast_value*)var->expression.next;
5373
5374             if (!ast_istype(var->expression.next, ast_value)) {
5375                 parseerror(parser, "internal error: field element type must be an ast_value");
5376                 goto cleanup;
5377             }
5378
5379             util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5380             if (!parser_create_array_field_setter(parser, array, name))
5381                 goto cleanup;
5382
5383             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5384             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5385             tfield->expression.next = telem;
5386             util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5387             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5388                 ast_delete(tfield);
5389                 goto cleanup;
5390             }
5391             ast_delete(tfield);
5392         }
5393
5394 skipvar:
5395         if (parser->tok == ';') {
5396             ast_delete(basetype);
5397             if (!parser_next(parser)) {
5398                 parseerror(parser, "error after variable declaration");
5399                 return false;
5400             }
5401             return true;
5402         }
5403
5404         if (parser->tok == ',')
5405             goto another;
5406
5407         /*
5408         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5409         */
5410         if (!var) {
5411             parseerror(parser, "missing comma or semicolon while parsing variables");
5412             break;
5413         }
5414
5415         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5416             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5417                              "initializing expression turns variable `%s` into a constant in this standard",
5418                              var->name) )
5419             {
5420                 break;
5421             }
5422         }
5423
5424         if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5425             if (parser->tok != '=') {
5426                 if (!strcmp(parser_tokval(parser), "break")) {
5427                     if (!parser_next(parser)) {
5428                         parseerror(parser, "error parsing break definition");
5429                         break;
5430                     }
5431                     (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5432                 } else {
5433                     parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5434                     break;
5435                 }
5436             }
5437
5438             if (!parser_next(parser)) {
5439                 parseerror(parser, "error parsing initializer");
5440                 break;
5441             }
5442         }
5443         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5444             parseerror(parser, "expected '=' before function body in this standard");
5445         }
5446
5447         if (parser->tok == '#') {
5448             ast_function *func   = NULL;
5449             ast_value    *number = NULL;
5450             float         fractional;
5451             float         integral;
5452             int           builtin_num;
5453
5454             if (localblock) {
5455                 parseerror(parser, "cannot declare builtins within functions");
5456                 break;
5457             }
5458             if (var->expression.vtype != TYPE_FUNCTION) {
5459                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5460                 break;
5461             }
5462             if (!parser_next(parser)) {
5463                 parseerror(parser, "expected builtin number");
5464                 break;
5465             }
5466
5467             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5468                 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5469                 if (!number) {
5470                     parseerror(parser, "builtin number expected");
5471                     break;
5472                 }
5473                 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5474                 {
5475                     ast_unref(number);
5476                     parseerror(parser, "builtin number must be a compile time constant");
5477                     break;
5478                 }
5479                 if (number->expression.vtype == TYPE_INTEGER)
5480                     builtin_num = number->constval.vint;
5481                 else if (number->expression.vtype == TYPE_FLOAT)
5482                     builtin_num = number->constval.vfloat;
5483                 else {
5484                     ast_unref(number);
5485                     parseerror(parser, "builtin number must be an integer constant");
5486                     break;
5487                 }
5488                 ast_unref(number);
5489
5490                 fractional = modff(builtin_num, &integral);
5491                 if (builtin_num < 0 || fractional != 0) {
5492                     parseerror(parser, "builtin number must be an integer greater than zero");
5493                     break;
5494                 }
5495
5496                 /* we only want the integral part anyways */
5497                 builtin_num = integral;
5498             } else if (parser->tok == TOKEN_INTCONST) {
5499                 builtin_num = parser_token(parser)->constval.i;
5500             } else {
5501                 parseerror(parser, "builtin number must be a compile time constant");
5502                 break;
5503             }
5504
5505             if (var->hasvalue) {
5506                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5507                                     "builtin `%s` has already been defined\n"
5508                                     " -> previous declaration here: %s:%i",
5509                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5510             }
5511             else
5512             {
5513                 func = ast_function_new(ast_ctx(var), var->name, var);
5514                 if (!func) {
5515                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5516                     break;
5517                 }
5518                 vec_push(parser->functions, func);
5519
5520                 func->builtin = -builtin_num-1;
5521             }
5522
5523             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5524                     ? (parser->tok != ',' && parser->tok != ';')
5525                     : (!parser_next(parser)))
5526             {
5527                 parseerror(parser, "expected comma or semicolon");
5528                 if (func)
5529                     ast_function_delete(func);
5530                 var->constval.vfunc = NULL;
5531                 break;
5532             }
5533         }
5534         else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5535         {
5536             if (localblock) {
5537                 /* Note that fteqcc and most others don't even *have*
5538                  * local arrays, so this is not a high priority.
5539                  */
5540                 parseerror(parser, "TODO: initializers for local arrays");
5541                 break;
5542             }
5543
5544             var->hasvalue = true;
5545             if (!parse_array(parser, var))
5546                 break;
5547         }
5548         else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5549         {
5550             if (localblock) {
5551                 parseerror(parser, "cannot declare functions within functions");
5552                 break;
5553             }
5554
5555             if (proto)
5556                 ast_ctx(proto) = parser_ctx(parser);
5557
5558             if (!parse_function_body(parser, var))
5559                 break;
5560             ast_delete(basetype);
5561             for (i = 0; i < vec_size(parser->gotos); ++i)
5562                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5563             vec_free(parser->gotos);
5564             vec_free(parser->labels);
5565             return true;
5566         } else {
5567             ast_expression *cexp;
5568             ast_value      *cval;
5569
5570             cexp = parse_expression_leave(parser, true, false, false);
5571             if (!cexp)
5572                 break;
5573
5574             if (!localblock) {
5575                 cval = (ast_value*)cexp;
5576                 if (cval != parser->nil &&
5577                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5578                    )
5579                 {
5580                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5581                 }
5582                 else
5583                 {
5584                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5585                         qualifier != CV_VAR)
5586                     {
5587                         var->cvq = CV_CONST;
5588                     }
5589                     if (cval == parser->nil)
5590                         var->expression.flags |= AST_FLAG_INITIALIZED;
5591                     else
5592                     {
5593                         var->hasvalue = true;
5594                         if (cval->expression.vtype == TYPE_STRING)
5595                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5596                         else if (cval->expression.vtype == TYPE_FIELD)
5597                             var->constval.vfield = cval;
5598                         else
5599                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5600                         ast_unref(cval);
5601                     }
5602                 }
5603             } else {
5604                 int cvq;
5605                 shunt sy = { NULL, NULL, NULL, NULL };
5606                 cvq = var->cvq;
5607                 var->cvq = CV_NONE;
5608                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5609                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5610                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5611                 if (!parser_sy_apply_operator(parser, &sy))
5612                     ast_unref(cexp);
5613                 else {
5614                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5615                         parseerror(parser, "internal error: leaked operands");
5616                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5617                         break;
5618                 }
5619                 vec_free(sy.out);
5620                 vec_free(sy.ops);
5621                 vec_free(sy.argc);
5622                 var->cvq = cvq;
5623             }
5624         }
5625
5626 another:
5627         if (parser->tok == ',') {
5628             if (!parser_next(parser)) {
5629                 parseerror(parser, "expected another variable");
5630                 break;
5631             }
5632
5633             if (parser->tok != TOKEN_IDENT) {
5634                 parseerror(parser, "expected another variable");
5635                 break;
5636             }
5637             var = ast_value_copy(basetype);
5638             cleanvar = true;
5639             ast_value_set_name(var, parser_tokval(parser));
5640             if (!parser_next(parser)) {
5641                 parseerror(parser, "error parsing variable declaration");
5642                 break;
5643             }
5644             continue;
5645         }
5646
5647         if (parser->tok != ';') {
5648             parseerror(parser, "missing semicolon after variables");
5649             break;
5650         }
5651
5652         if (!parser_next(parser)) {
5653             parseerror(parser, "parse error after variable declaration");
5654             break;
5655         }
5656
5657         ast_delete(basetype);
5658         return true;
5659     }
5660
5661     if (cleanvar && var)
5662         ast_delete(var);
5663     ast_delete(basetype);
5664     return false;
5665
5666 cleanup:
5667     ast_delete(basetype);
5668     if (cleanvar && var)
5669         ast_delete(var);
5670     if (me[0]) ast_member_delete(me[0]);
5671     if (me[1]) ast_member_delete(me[1]);
5672     if (me[2]) ast_member_delete(me[2]);
5673     return retval;
5674 }
5675
5676 static bool parser_global_statement(parser_t *parser)
5677 {
5678     int        cvq       = CV_WRONG;
5679     bool       noref     = false;
5680     bool       is_static = false;
5681     uint32_t   qflags    = 0;
5682     ast_value *istype    = NULL;
5683     char      *vstring   = NULL;
5684
5685     if (parser->tok == TOKEN_IDENT)
5686         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5687
5688     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5689     {
5690         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5691     }
5692     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5693     {
5694         if (cvq == CV_WRONG)
5695             return false;
5696         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5697     }
5698     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5699     {
5700         return parse_enum(parser);
5701     }
5702     else if (parser->tok == TOKEN_KEYWORD)
5703     {
5704         if (!strcmp(parser_tokval(parser), "typedef")) {
5705             if (!parser_next(parser)) {
5706                 parseerror(parser, "expected type definition after 'typedef'");
5707                 return false;
5708             }
5709             return parse_typedef(parser);
5710         }
5711         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5712         return false;
5713     }
5714     else if (parser->tok == '#')
5715     {
5716         return parse_pragma(parser);
5717     }
5718     else if (parser->tok == '$')
5719     {
5720         if (!parser_next(parser)) {
5721             parseerror(parser, "parse error");
5722             return false;
5723         }
5724     }
5725     else
5726     {
5727         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5728         return false;
5729     }
5730     return true;
5731 }
5732
5733 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5734 {
5735     return util_crc16(old, str, strlen(str));
5736 }
5737
5738 static void progdefs_crc_file(const char *str)
5739 {
5740     /* write to progdefs.h here */
5741     (void)str;
5742 }
5743
5744 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5745 {
5746     old = progdefs_crc_sum(old, str);
5747     progdefs_crc_file(str);
5748     return old;
5749 }
5750
5751 static void generate_checksum(parser_t *parser, ir_builder *ir)
5752 {
5753     uint16_t   crc = 0xFFFF;
5754     size_t     i;
5755     ast_value *value;
5756
5757     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5758     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5759     /*
5760     progdefs_crc_file("\tint\tpad;\n");
5761     progdefs_crc_file("\tint\tofs_return[3];\n");
5762     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5763     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5764     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5765     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5766     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5767     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5768     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5769     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5770     */
5771     for (i = 0; i < parser->crc_globals; ++i) {
5772         if (!ast_istype(parser->globals[i], ast_value))
5773             continue;
5774         value = (ast_value*)(parser->globals[i]);
5775         switch (value->expression.vtype) {
5776             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5777             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5778             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5779             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5780             default:
5781                 crc = progdefs_crc_both(crc, "\tint\t");
5782                 break;
5783         }
5784         crc = progdefs_crc_both(crc, value->name);
5785         crc = progdefs_crc_both(crc, ";\n");
5786     }
5787     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5788     for (i = 0; i < parser->crc_fields; ++i) {
5789         if (!ast_istype(parser->fields[i], ast_value))
5790             continue;
5791         value = (ast_value*)(parser->fields[i]);
5792         switch (value->expression.next->vtype) {
5793             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5794             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5795             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5796             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5797             default:
5798                 crc = progdefs_crc_both(crc, "\tint\t");
5799                 break;
5800         }
5801         crc = progdefs_crc_both(crc, value->name);
5802         crc = progdefs_crc_both(crc, ";\n");
5803     }
5804     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5805     ir->code->crc = crc;
5806 }
5807
5808 parser_t *parser_create()
5809 {
5810     parser_t *parser;
5811     lex_ctx_t empty_ctx;
5812     size_t i;
5813
5814     parser = (parser_t*)mem_a(sizeof(parser_t));
5815     if (!parser)
5816         return NULL;
5817
5818     memset(parser, 0, sizeof(*parser));
5819
5820     for (i = 0; i < operator_count; ++i) {
5821         if (operators[i].id == opid1('=')) {
5822             parser->assign_op = operators+i;
5823             break;
5824         }
5825     }
5826     if (!parser->assign_op) {
5827         printf("internal error: initializing parser: failed to find assign operator\n");
5828         mem_d(parser);
5829         return NULL;
5830     }
5831
5832     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5833     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5834     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5835     vec_push(parser->_blocktypedefs, 0);
5836
5837     parser->aliases = util_htnew(PARSER_HT_SIZE);
5838
5839     /* corrector */
5840     vec_push(parser->correct_variables, correct_trie_new());
5841     vec_push(parser->correct_variables_score, NULL);
5842
5843     empty_ctx.file   = "<internal>";
5844     empty_ctx.line   = 0;
5845     empty_ctx.column = 0;
5846     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5847     parser->nil->cvq = CV_CONST;
5848     if (OPTS_FLAG(UNTYPED_NIL))
5849         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5850
5851     parser->max_param_count = 1;
5852
5853     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5854     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5855     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5856
5857     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5858         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5859         parser->reserved_version->cvq = CV_CONST;
5860         parser->reserved_version->hasvalue = true;
5861         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5862         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5863     } else {
5864         parser->reserved_version = NULL;
5865     }
5866
5867     parser->fold   = fold_init  (parser);
5868     parser->intrin = intrin_init(parser);
5869     return parser;
5870 }
5871
5872 static bool parser_compile(parser_t *parser)
5873 {
5874     /* initial lexer/parser state */
5875     parser->lex->flags.noops = true;
5876
5877     if (parser_next(parser))
5878     {
5879         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5880         {
5881             if (!parser_global_statement(parser)) {
5882                 if (parser->tok == TOKEN_EOF)
5883                     parseerror(parser, "unexpected end of file");
5884                 else if (compile_errors)
5885                     parseerror(parser, "there have been errors, bailing out");
5886                 lex_close(parser->lex);
5887                 parser->lex = NULL;
5888                 return false;
5889             }
5890         }
5891     } else {
5892         parseerror(parser, "parse error");
5893         lex_close(parser->lex);
5894         parser->lex = NULL;
5895         return false;
5896     }
5897
5898     lex_close(parser->lex);
5899     parser->lex = NULL;
5900
5901     return !compile_errors;
5902 }
5903
5904 bool parser_compile_file(parser_t *parser, const char *filename)
5905 {
5906     parser->lex = lex_open(filename);
5907     if (!parser->lex) {
5908         con_err("failed to open file \"%s\"\n", filename);
5909         return false;
5910     }
5911     return parser_compile(parser);
5912 }
5913
5914 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5915 {
5916     parser->lex = lex_open_string(str, len, name);
5917     if (!parser->lex) {
5918         con_err("failed to create lexer for string \"%s\"\n", name);
5919         return false;
5920     }
5921     return parser_compile(parser);
5922 }
5923
5924 static void parser_remove_ast(parser_t *parser)
5925 {
5926     size_t i;
5927     if (parser->ast_cleaned)
5928         return;
5929     parser->ast_cleaned = true;
5930     for (i = 0; i < vec_size(parser->accessors); ++i) {
5931         ast_delete(parser->accessors[i]->constval.vfunc);
5932         parser->accessors[i]->constval.vfunc = NULL;
5933         ast_delete(parser->accessors[i]);
5934     }
5935     for (i = 0; i < vec_size(parser->functions); ++i) {
5936         ast_delete(parser->functions[i]);
5937     }
5938     for (i = 0; i < vec_size(parser->fields); ++i) {
5939         ast_delete(parser->fields[i]);
5940     }
5941     for (i = 0; i < vec_size(parser->globals); ++i) {
5942         ast_delete(parser->globals[i]);
5943     }
5944     vec_free(parser->accessors);
5945     vec_free(parser->functions);
5946     vec_free(parser->globals);
5947     vec_free(parser->fields);
5948
5949     for (i = 0; i < vec_size(parser->variables); ++i)
5950         util_htdel(parser->variables[i]);
5951     vec_free(parser->variables);
5952     vec_free(parser->_blocklocals);
5953     vec_free(parser->_locals);
5954
5955     /* corrector */
5956     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5957         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5958     }
5959     vec_free(parser->correct_variables);
5960     vec_free(parser->correct_variables_score);
5961
5962     for (i = 0; i < vec_size(parser->_typedefs); ++i)
5963         ast_delete(parser->_typedefs[i]);
5964     vec_free(parser->_typedefs);
5965     for (i = 0; i < vec_size(parser->typedefs); ++i)
5966         util_htdel(parser->typedefs[i]);
5967     vec_free(parser->typedefs);
5968     vec_free(parser->_blocktypedefs);
5969
5970     vec_free(parser->_block_ctx);
5971
5972     vec_free(parser->labels);
5973     vec_free(parser->gotos);
5974     vec_free(parser->breaks);
5975     vec_free(parser->continues);
5976
5977     ast_value_delete(parser->nil);
5978
5979     ast_value_delete(parser->const_vec[0]);
5980     ast_value_delete(parser->const_vec[1]);
5981     ast_value_delete(parser->const_vec[2]);
5982
5983     if (parser->reserved_version)
5984         ast_value_delete(parser->reserved_version);
5985
5986     util_htdel(parser->aliases);
5987     fold_cleanup(parser->fold);
5988     intrin_cleanup(parser->intrin);
5989 }
5990
5991 void parser_cleanup(parser_t *parser)
5992 {
5993     parser_remove_ast(parser);
5994     mem_d(parser);
5995 }
5996
5997 bool parser_finish(parser_t *parser, const char *output)
5998 {
5999     size_t i;
6000     ir_builder *ir;
6001     bool retval = true;
6002
6003     if (compile_errors) {
6004         con_out("*** there were compile errors\n");
6005         return false;
6006     }
6007
6008     ir = ir_builder_new("gmqcc_out");
6009     if (!ir) {
6010         con_out("failed to allocate builder\n");
6011         return false;
6012     }
6013
6014     for (i = 0; i < vec_size(parser->fields); ++i) {
6015         ast_value *field;
6016         bool hasvalue;
6017         if (!ast_istype(parser->fields[i], ast_value))
6018             continue;
6019         field = (ast_value*)parser->fields[i];
6020         hasvalue = field->hasvalue;
6021         field->hasvalue = false;
6022         if (!ast_global_codegen((ast_value*)field, ir, true)) {
6023             con_out("failed to generate field %s\n", field->name);
6024             ir_builder_delete(ir);
6025             return false;
6026         }
6027         if (hasvalue) {
6028             ir_value *ifld;
6029             ast_expression *subtype;
6030             field->hasvalue = true;
6031             subtype = field->expression.next;
6032             ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6033             if (subtype->vtype == TYPE_FIELD)
6034                 ifld->fieldtype = subtype->next->vtype;
6035             else if (subtype->vtype == TYPE_FUNCTION)
6036                 ifld->outtype = subtype->next->vtype;
6037             (void)!ir_value_set_field(field->ir_v, ifld);
6038         }
6039     }
6040     for (i = 0; i < vec_size(parser->globals); ++i) {
6041         ast_value *asvalue;
6042         if (!ast_istype(parser->globals[i], ast_value))
6043             continue;
6044         asvalue = (ast_value*)(parser->globals[i]);
6045         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6046             retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6047                                                 "unused global: `%s`", asvalue->name);
6048         }
6049         if (!ast_global_codegen(asvalue, ir, false)) {
6050             con_out("failed to generate global %s\n", asvalue->name);
6051             ir_builder_delete(ir);
6052             return false;
6053         }
6054     }
6055     /* Build function vararg accessor ast tree now before generating
6056      * immediates, because the accessors may add new immediates
6057      */
6058     for (i = 0; i < vec_size(parser->functions); ++i) {
6059         ast_function *f = parser->functions[i];
6060         if (f->varargs) {
6061             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6062                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6063                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6064                     con_out("failed to generate vararg setter for %s\n", f->name);
6065                     ir_builder_delete(ir);
6066                     return false;
6067                 }
6068                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6069                     con_out("failed to generate vararg getter for %s\n", f->name);
6070                     ir_builder_delete(ir);
6071                     return false;
6072                 }
6073             } else {
6074                 ast_delete(f->varargs);
6075                 f->varargs = NULL;
6076             }
6077         }
6078     }
6079     /* Now we can generate immediates */
6080     if (!fold_generate(parser->fold, ir))
6081         return false;
6082
6083     for (i = 0; i < vec_size(parser->globals); ++i) {
6084         ast_value *asvalue;
6085         if (!ast_istype(parser->globals[i], ast_value))
6086             continue;
6087         asvalue = (ast_value*)(parser->globals[i]);
6088         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6089         {
6090             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6091                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6092                                        "uninitialized constant: `%s`",
6093                                        asvalue->name);
6094             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6095                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6096                                        "uninitialized global: `%s`",
6097                                        asvalue->name);
6098         }
6099         if (!ast_generate_accessors(asvalue, ir)) {
6100             ir_builder_delete(ir);
6101             return false;
6102         }
6103     }
6104     for (i = 0; i < vec_size(parser->fields); ++i) {
6105         ast_value *asvalue;
6106         asvalue = (ast_value*)(parser->fields[i]->next);
6107
6108         if (!ast_istype((ast_expression*)asvalue, ast_value))
6109             continue;
6110         if (asvalue->expression.vtype != TYPE_ARRAY)
6111             continue;
6112         if (!ast_generate_accessors(asvalue, ir)) {
6113             ir_builder_delete(ir);
6114             return false;
6115         }
6116     }
6117     if (parser->reserved_version &&
6118         !ast_global_codegen(parser->reserved_version, ir, false))
6119     {
6120         con_out("failed to generate reserved::version");
6121         ir_builder_delete(ir);
6122         return false;
6123     }
6124     for (i = 0; i < vec_size(parser->functions); ++i) {
6125         ast_function *f = parser->functions[i];
6126         if (!ast_function_codegen(f, ir)) {
6127             con_out("failed to generate function %s\n", f->name);
6128             ir_builder_delete(ir);
6129             return false;
6130         }
6131     }
6132
6133     generate_checksum(parser, ir);
6134
6135     if (OPTS_OPTION_BOOL(OPTION_DUMP))
6136         ir_builder_dump(ir, con_out);
6137     for (i = 0; i < vec_size(parser->functions); ++i) {
6138         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6139             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6140             ir_builder_delete(ir);
6141             return false;
6142         }
6143     }
6144     parser_remove_ast(parser);
6145
6146     if (compile_Werrors) {
6147         con_out("*** there were warnings treated as errors\n");
6148         compile_show_werrors();
6149         retval = false;
6150     }
6151
6152     if (retval) {
6153         if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6154             ir_builder_dump(ir, con_out);
6155
6156         if (!ir_builder_generate(ir, output)) {
6157             con_out("*** failed to generate output file\n");
6158             ir_builder_delete(ir);
6159             return false;
6160         }
6161     }
6162     ir_builder_delete(ir);
6163     return retval;
6164 }