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