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