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