]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Merge pull request #138 from ignatenkobrain/fix_authors
[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
27 #include "parser.h"
28
29 #define PARSER_HT_LOCALS  2
30 #define PARSER_HT_SIZE    512
31 #define TYPEDEF_HT_SIZE   512
32
33 static void parser_enterblock(parser_t *parser);
34 static bool parser_leaveblock(parser_t *parser);
35 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
36 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
37 static bool parse_typedef(parser_t *parser);
38 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);
39 static ast_block* parse_block(parser_t *parser);
40 static bool parse_block_into(parser_t *parser, ast_block *block);
41 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
42 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
43 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
44 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
45 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
46 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
47 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
48
49 static void parseerror(parser_t *parser, const char *fmt, ...)
50 {
51     va_list ap;
52     va_start(ap, fmt);
53     vcompile_error(parser->lex->tok.ctx, fmt, ap);
54     va_end(ap);
55 }
56
57 /* returns true if it counts as an error */
58 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
59 {
60     bool    r;
61     va_list ap;
62     va_start(ap, fmt);
63     r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
64     va_end(ap);
65     return r;
66 }
67
68 /**********************************************************************
69  * parsing
70  */
71
72 static bool parser_next(parser_t *parser)
73 {
74     /* lex_do kills the previous token */
75     parser->tok = lex_do(parser->lex);
76     if (parser->tok == TOKEN_EOF)
77         return true;
78     if (parser->tok >= TOKEN_ERROR) {
79         parseerror(parser, "lex error");
80         return false;
81     }
82     return true;
83 }
84
85 #define parser_tokval(p) ((p)->lex->tok.value)
86 #define parser_token(p)  (&((p)->lex->tok))
87
88 char *parser_strdup(const char *str)
89 {
90     if (str && !*str) {
91         /* actually dup empty strings */
92         char *out = (char*)mem_a(1);
93         *out = 0;
94         return out;
95     }
96     return util_strdup(str);
97 }
98
99 static ast_expression* parser_find_field(parser_t *parser, const char *name)
100 {
101     return ( ast_expression*)util_htget(parser->htfields, name);
102 }
103
104 static ast_expression* parser_find_label(parser_t *parser, const char *name)
105 {
106     size_t i;
107     for(i = 0; i < vec_size(parser->labels); i++)
108         if (!strcmp(parser->labels[i]->name, name))
109             return (ast_expression*)parser->labels[i];
110     return NULL;
111 }
112
113 ast_expression* parser_find_global(parser_t *parser, const char *name)
114 {
115     ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
116     if (var)
117         return var;
118     return (ast_expression*)util_htget(parser->htglobals, name);
119 }
120
121 static ast_expression* parser_find_param(parser_t *parser, const char *name)
122 {
123     size_t i;
124     ast_value *fun;
125     if (!parser->function)
126         return NULL;
127     fun = parser->function->vtype;
128     for (i = 0; i < vec_size(fun->expression.params); ++i) {
129         if (!strcmp(fun->expression.params[i]->name, name))
130             return (ast_expression*)(fun->expression.params[i]);
131     }
132     return NULL;
133 }
134
135 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
136 {
137     size_t          i, hash;
138     ast_expression *e;
139
140     hash = util_hthash(parser->htglobals, name);
141
142     *isparam = false;
143     for (i = vec_size(parser->variables); i > upto;) {
144         --i;
145         if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
146             return e;
147     }
148     *isparam = true;
149     return parser_find_param(parser, name);
150 }
151
152 static ast_expression* parser_find_var(parser_t *parser, const char *name)
153 {
154     bool dummy;
155     ast_expression *v;
156     v         = parser_find_local(parser, name, 0, &dummy);
157     if (!v) v = parser_find_global(parser, name);
158     return v;
159 }
160
161 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
162 {
163     size_t     i, hash;
164     ast_value *e;
165     hash = util_hthash(parser->typedefs[0], name);
166
167     for (i = vec_size(parser->typedefs); i > upto;) {
168         --i;
169         if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
170             return e;
171     }
172     return NULL;
173 }
174
175 typedef struct
176 {
177     size_t etype; /* 0 = expression, others are operators */
178     bool            isparen;
179     size_t          off;
180     ast_expression *out;
181     ast_block      *block; /* for commas and function calls */
182     lex_ctx_t ctx;
183 } sy_elem;
184
185 enum {
186     PAREN_EXPR,
187     PAREN_FUNC,
188     PAREN_INDEX,
189     PAREN_TERNARY1,
190     PAREN_TERNARY2
191 };
192 typedef struct
193 {
194     sy_elem        *out;
195     sy_elem        *ops;
196     size_t         *argc;
197     unsigned int   *paren;
198 } shunt;
199
200 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
201     sy_elem e;
202     e.etype = 0;
203     e.off   = 0;
204     e.out   = v;
205     e.block = NULL;
206     e.ctx   = ctx;
207     e.isparen = false;
208     return e;
209 }
210
211 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
212     sy_elem e;
213     e.etype = 0;
214     e.off   = 0;
215     e.out   = (ast_expression*)v;
216     e.block = v;
217     e.ctx   = ctx;
218     e.isparen = false;
219     return e;
220 }
221
222 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
223     sy_elem e;
224     e.etype = 1 + (op - operators);
225     e.off   = 0;
226     e.out   = NULL;
227     e.block = NULL;
228     e.ctx   = ctx;
229     e.isparen = false;
230     return e;
231 }
232
233 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
234     sy_elem e;
235     e.etype = 0;
236     e.off   = off;
237     e.out   = NULL;
238     e.block = NULL;
239     e.ctx   = ctx;
240     e.isparen = true;
241     return e;
242 }
243
244 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
245  * so we need to rotate it to become ent.(foo[n]).
246  */
247 static bool rotate_entfield_array_index_nodes(ast_expression **out)
248 {
249     ast_array_index *index, *oldindex;
250     ast_entfield    *entfield;
251
252     ast_value       *field;
253     ast_expression  *sub;
254     ast_expression  *entity;
255
256     lex_ctx_t ctx = ast_ctx(*out);
257
258     if (!ast_istype(*out, ast_array_index))
259         return false;
260     index = (ast_array_index*)*out;
261
262     if (!ast_istype(index->array, ast_entfield))
263         return false;
264     entfield = (ast_entfield*)index->array;
265
266     if (!ast_istype(entfield->field, ast_value))
267         return false;
268     field = (ast_value*)entfield->field;
269
270     sub    = index->index;
271     entity = entfield->entity;
272
273     oldindex = index;
274
275     index = ast_array_index_new(ctx, (ast_expression*)field, sub);
276     entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
277     *out = (ast_expression*)entfield;
278
279     oldindex->array = NULL;
280     oldindex->index = NULL;
281     ast_delete(oldindex);
282
283     return true;
284 }
285
286 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
287 {
288     if (ast_istype(expr, ast_value)) {
289         ast_value *val = (ast_value*)expr;
290         if (val->cvq == CV_CONST) {
291             if (val->name[0] == '#') {
292                 compile_error(ctx, "invalid assignment to a literal constant");
293                 return false;
294             }
295             /*
296              * To work around quakeworld we must elide the error and make it
297              * a warning instead.
298              */
299             if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
300                 compile_error(ctx, "assignment to constant `%s`", val->name);
301             else
302                 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
303             return false;
304         }
305     }
306     return true;
307 }
308
309 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
310 {
311     const oper_info *op;
312     lex_ctx_t ctx;
313     ast_expression *out = NULL;
314     ast_expression *exprs[3];
315     ast_block      *blocks[3];
316     ast_binstore   *asbinstore;
317     size_t i, assignop, addop, subop;
318     qcint_t  generated_op = 0;
319
320     char ty1[1024];
321     char ty2[1024];
322
323     if (!vec_size(sy->ops)) {
324         parseerror(parser, "internal error: missing operator");
325         return false;
326     }
327
328     if (vec_last(sy->ops).isparen) {
329         parseerror(parser, "unmatched parenthesis");
330         return false;
331     }
332
333     op = &operators[vec_last(sy->ops).etype - 1];
334     ctx = vec_last(sy->ops).ctx;
335
336     if (vec_size(sy->out) < op->operands) {
337         if (op->flags & OP_PREFIX)
338             compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
339         else /* this should have errored previously already */
340             compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
341         return false;
342     }
343
344     vec_shrinkby(sy->ops, 1);
345
346     /* op(:?) has no input and no output */
347     if (!op->operands)
348         return true;
349
350     vec_shrinkby(sy->out, op->operands);
351     for (i = 0; i < op->operands; ++i) {
352         exprs[i]  = sy->out[vec_size(sy->out)+i].out;
353         blocks[i] = sy->out[vec_size(sy->out)+i].block;
354
355         if (exprs[i]->vtype == TYPE_NOEXPR &&
356             !(i != 0 && op->id == opid2('?',':')) &&
357             !(i == 1 && op->id == opid1('.')))
358         {
359             if (ast_istype(exprs[i], ast_label))
360                 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
361             else
362                 compile_error(ast_ctx(exprs[i]), "not an expression");
363             (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
364         }
365     }
366
367     if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
368         compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
369         return false;
370     }
371
372 #define NotSameType(T) \
373              (exprs[0]->vtype != exprs[1]->vtype || \
374               exprs[0]->vtype != T)
375
376     switch (op->id)
377     {
378         default:
379             compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
380             return false;
381
382         case opid1('.'):
383             if (exprs[0]->vtype == TYPE_VECTOR &&
384                 exprs[1]->vtype == TYPE_NOEXPR)
385             {
386                 if      (exprs[1] == (ast_expression*)parser->const_vec[0])
387                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
388                 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
389                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
390                 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
391                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
392                 else {
393                     compile_error(ctx, "access to invalid vector component");
394                     return false;
395                 }
396             }
397             else if (exprs[0]->vtype == TYPE_ENTITY) {
398                 if (exprs[1]->vtype != TYPE_FIELD) {
399                     compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
400                     return false;
401                 }
402                 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
403             }
404             else if (exprs[0]->vtype == TYPE_VECTOR) {
405                 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
406                 return false;
407             }
408             else {
409                 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
410                 return false;
411             }
412             break;
413
414         case opid1('['):
415             if (exprs[0]->vtype != TYPE_ARRAY &&
416                 !(exprs[0]->vtype == TYPE_FIELD &&
417                   exprs[0]->next->vtype == TYPE_ARRAY))
418             {
419                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
420                 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
421                 return false;
422             }
423             if (exprs[1]->vtype != TYPE_FLOAT) {
424                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
425                 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
426                 return false;
427             }
428             out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
429             if (rotate_entfield_array_index_nodes(&out))
430             {
431 #if 0
432                 /* This is not broken in fteqcc anymore */
433                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
434                     /* this error doesn't need to make us bail out */
435                     (void)!parsewarning(parser, WARN_EXTENSIONS,
436                                         "accessing array-field members of an entity without parenthesis\n"
437                                         " -> this is an extension from -std=gmqcc");
438                 }
439 #endif
440             }
441             break;
442
443         case opid1(','):
444             if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
445                 vec_push(sy->out, syexp(ctx, exprs[0]));
446                 vec_push(sy->out, syexp(ctx, exprs[1]));
447                 vec_last(sy->argc)++;
448                 return true;
449             }
450             if (blocks[0]) {
451                 if (!ast_block_add_expr(blocks[0], exprs[1]))
452                     return false;
453             } else {
454                 blocks[0] = ast_block_new(ctx);
455                 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
456                     !ast_block_add_expr(blocks[0], exprs[1]))
457                 {
458                     return false;
459                 }
460             }
461             ast_block_set_type(blocks[0], exprs[1]);
462
463             vec_push(sy->out, syblock(ctx, blocks[0]));
464             return true;
465
466         case opid2('+','P'):
467             out = exprs[0];
468             break;
469         case opid2('-','P'):
470             if ((out = fold_op(parser->fold, op, exprs)))
471                 break;
472
473             if (exprs[0]->vtype != TYPE_FLOAT &&
474                 exprs[0]->vtype != TYPE_VECTOR) {
475                     compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
476                                   type_name[exprs[0]->vtype]);
477                 return false;
478             }
479             out = (ast_expression*)ast_unary_new(ctx, (VINSTR_NEG_F-TYPE_FLOAT) + exprs[0]->vtype, exprs[0]);
480             break;
481
482         case opid2('!','P'):
483             if (!(out = fold_op(parser->fold, op, exprs))) {
484                 switch (exprs[0]->vtype) {
485                     case TYPE_FLOAT:
486                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
487                         break;
488                     case TYPE_VECTOR:
489                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
490                         break;
491                     case TYPE_STRING:
492                         if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
493                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
494                         else
495                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
496                         break;
497                     /* we don't constant-fold NOT for these types */
498                     case TYPE_ENTITY:
499                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
500                         break;
501                     case TYPE_FUNCTION:
502                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
503                         break;
504                     default:
505                     compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
506                                   type_name[exprs[0]->vtype]);
507                     return false;
508                 }
509             }
510             break;
511
512         case opid1('+'):
513             if (exprs[0]->vtype != exprs[1]->vtype ||
514                (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
515             {
516                 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
517                               type_name[exprs[0]->vtype],
518                               type_name[exprs[1]->vtype]);
519                 return false;
520             }
521             if (!(out = fold_op(parser->fold, op, exprs))) {
522                 switch (exprs[0]->vtype) {
523                     case TYPE_FLOAT:
524                         out = fold_binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
525                         break;
526                     case TYPE_VECTOR:
527                         out = fold_binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
528                         break;
529                     default:
530                         compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
531                                       type_name[exprs[0]->vtype],
532                                       type_name[exprs[1]->vtype]);
533                         return false;
534                 }
535             }
536             break;
537         case opid1('-'):
538             if  (exprs[0]->vtype != exprs[1]->vtype ||
539                 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
540             {
541                 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
542                               type_name[exprs[1]->vtype],
543                               type_name[exprs[0]->vtype]);
544                 return false;
545             }
546             if (!(out = fold_op(parser->fold, op, exprs))) {
547                 switch (exprs[0]->vtype) {
548                     case TYPE_FLOAT:
549                         out = fold_binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
550                         break;
551                     case TYPE_VECTOR:
552                         out = fold_binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
553                         break;
554                     default:
555                         compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
556                                       type_name[exprs[1]->vtype],
557                                       type_name[exprs[0]->vtype]);
558                         return false;
559                 }
560             }
561             break;
562         case opid1('*'):
563             if (exprs[0]->vtype != exprs[1]->vtype &&
564                 !(exprs[0]->vtype == TYPE_VECTOR &&
565                   exprs[1]->vtype == TYPE_FLOAT) &&
566                 !(exprs[1]->vtype == TYPE_VECTOR &&
567                   exprs[0]->vtype == TYPE_FLOAT)
568                 )
569             {
570                 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
571                               type_name[exprs[1]->vtype],
572                               type_name[exprs[0]->vtype]);
573                 return false;
574             }
575             if (!(out = fold_op(parser->fold, op, exprs))) {
576                 switch (exprs[0]->vtype) {
577                     case TYPE_FLOAT:
578                         if (exprs[1]->vtype == TYPE_VECTOR)
579                             out = fold_binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
580                         else
581                             out = fold_binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
582                         break;
583                     case TYPE_VECTOR:
584                         if (exprs[1]->vtype == TYPE_FLOAT)
585                             out = fold_binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
586                         else
587                             out = fold_binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
588                         break;
589                     default:
590                         compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
591                                       type_name[exprs[1]->vtype],
592                                       type_name[exprs[0]->vtype]);
593                         return false;
594                 }
595             }
596             break;
597
598         case opid1('/'):
599             if (exprs[1]->vtype != TYPE_FLOAT) {
600                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
601                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
602                 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
603                 return false;
604             }
605             if (!(out = fold_op(parser->fold, op, exprs))) {
606                 if (exprs[0]->vtype == TYPE_FLOAT)
607                     out = fold_binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
608                 else {
609                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
610                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
611                     compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
612                     return false;
613                 }
614             }
615             break;
616
617         case opid1('%'):
618             if (NotSameType(TYPE_FLOAT)) {
619                 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
620                     type_name[exprs[0]->vtype],
621                     type_name[exprs[1]->vtype]);
622                 return false;
623             } else if (!(out = fold_op(parser->fold, op, exprs))) {
624                 /* generate a call to __builtin_mod */
625                 ast_expression *mod  = intrin_func(parser->intrin, "mod");
626                 ast_call       *call = NULL;
627                 if (!mod) return false; /* can return null for missing floor */
628
629                 call = ast_call_new(parser_ctx(parser), mod);
630                 vec_push(call->params, exprs[0]);
631                 vec_push(call->params, exprs[1]);
632
633                 out = (ast_expression*)call;
634             }
635             break;
636
637         case opid2('%','='):
638             compile_error(ctx, "%= is unimplemented");
639             return false;
640
641         case opid1('|'):
642         case opid1('&'):
643         case opid1('^'):
644             if ( !(exprs[0]->vtype == TYPE_FLOAT  && exprs[1]->vtype == TYPE_FLOAT) &&
645                  !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
646                  !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
647             {
648                 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
649                               type_name[exprs[0]->vtype],
650                               type_name[exprs[1]->vtype]);
651                 return false;
652             }
653
654             if (!(out = fold_op(parser->fold, op, exprs))) {
655                 /*
656                  * IF the first expression is float, the following will be too
657                  * since scalar ^ vector is not allowed.
658                  */
659                 if (exprs[0]->vtype == TYPE_FLOAT) {
660                     out = fold_binary(ctx,
661                         (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
662                         exprs[0], exprs[1]);
663                 } else {
664                     /*
665                      * The first is a vector: vector is allowed to bitop with vector and
666                      * with scalar, branch here for the second operand.
667                      */
668                     if (exprs[1]->vtype == TYPE_VECTOR) {
669                         /*
670                          * Bitop all the values of the vector components against the
671                          * vectors components in question.
672                          */
673                         out = fold_binary(ctx,
674                             (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
675                             exprs[0], exprs[1]);
676                     } else {
677                         out = fold_binary(ctx,
678                             (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
679                             exprs[0], exprs[1]);
680                     }
681                 }
682             }
683             break;
684
685         case opid2('<','<'):
686         case opid2('>','>'):
687         case opid3('<','<','='):
688         case opid3('>','>','='):
689             if(!(out = fold_op(parser->fold, op, exprs))) {
690                 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
691                 return false;
692             }
693             break;
694
695         case opid2('|','|'):
696             generated_op += 1; /* INSTR_OR */
697         case opid2('&','&'):
698             generated_op += INSTR_AND;
699             if (!(out = fold_op(parser->fold, op, exprs))) {
700                 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
701                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
702                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
703                     compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
704                     return false;
705                 }
706                 for (i = 0; i < 2; ++i) {
707                     if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
708                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
709                         if (!out) break;
710                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
711                         if (!out) break;
712                         exprs[i] = out; out = NULL;
713                         if (OPTS_FLAG(PERL_LOGIC)) {
714                             /* here we want to keep the right expressions' type */
715                             break;
716                         }
717                     }
718                     else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
719                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
720                         if (!out) break;
721                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
722                         if (!out) break;
723                         exprs[i] = out; out = NULL;
724                         if (OPTS_FLAG(PERL_LOGIC)) {
725                             /* here we want to keep the right expressions' type */
726                             break;
727                         }
728                     }
729                 }
730                 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
731             }
732             break;
733
734         case opid2('?',':'):
735             if (vec_last(sy->paren) != PAREN_TERNARY2) {
736                 compile_error(ctx, "mismatched parenthesis/ternary");
737                 return false;
738             }
739             vec_pop(sy->paren);
740             if (!ast_compare_type(exprs[1], exprs[2])) {
741                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
742                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
743                 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
744                 return false;
745             }
746             if (!(out = fold_op(parser->fold, op, exprs)))
747                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
748             break;
749
750         case opid2('*', '*'):
751             if (NotSameType(TYPE_FLOAT)) {
752                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
753                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
754                 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
755                     ty1, ty2);
756                 return false;
757             }
758
759             if (!(out = fold_op(parser->fold, op, exprs))) {
760                 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
761                 vec_push(gencall->params, exprs[0]);
762                 vec_push(gencall->params, exprs[1]);
763                 out = (ast_expression*)gencall;
764             }
765             break;
766
767         case opid2('>', '<'):
768             if (NotSameType(TYPE_VECTOR)) {
769                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
770                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
771                 compile_error(ctx, "invalid types used in cross product: %s and %s",
772                     ty1, ty2);
773                 return false;
774             }
775
776             if (!(out = fold_op(parser->fold, op, exprs))) {
777                 out = fold_binary(
778                         parser_ctx(parser),
779                         VINSTR_CROSS,
780                         exprs[0],
781                         exprs[1]
782                 );
783             }
784
785             break;
786
787         case opid3('<','=','>'): /* -1, 0, or 1 */
788             if (NotSameType(TYPE_FLOAT)) {
789                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
790                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
791                 compile_error(ctx, "invalid types used in comparision: %s and %s",
792                     ty1, ty2);
793
794                 return false;
795             }
796
797             if (!(out = fold_op(parser->fold, op, exprs))) {
798                 /* This whole block is NOT fold_binary safe */
799                 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
800
801                 eq->refs = AST_REF_NONE;
802
803                     /* if (lt) { */
804                 out = (ast_expression*)ast_ternary_new(ctx,
805                         (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
806                         /* out = -1 */
807                         (ast_expression*)parser->fold->imm_float[2],
808                     /* } else { */
809                         /* if (eq) { */
810                         (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
811                             /* out = 0 */
812                             (ast_expression*)parser->fold->imm_float[0],
813                         /* } else { */
814                             /* out = 1 */
815                             (ast_expression*)parser->fold->imm_float[1]
816                         /* } */
817                         )
818                     /* } */
819                     );
820
821             }
822             break;
823
824         case opid1('>'):
825             generated_op += 1; /* INSTR_GT */
826         case opid1('<'):
827             generated_op += 1; /* INSTR_LT */
828         case opid2('>', '='):
829             generated_op += 1; /* INSTR_GE */
830         case opid2('<', '='):
831             generated_op += INSTR_LE;
832             if (NotSameType(TYPE_FLOAT)) {
833                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
834                               type_name[exprs[0]->vtype],
835                               type_name[exprs[1]->vtype]);
836                 return false;
837             }
838             if (!(out = fold_op(parser->fold, op, exprs)))
839                 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
840             break;
841         case opid2('!', '='):
842             if (exprs[0]->vtype != exprs[1]->vtype) {
843                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
844                               type_name[exprs[0]->vtype],
845                               type_name[exprs[1]->vtype]);
846                 return false;
847             }
848             if (!(out = fold_op(parser->fold, op, exprs)))
849                 out = fold_binary(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
850             break;
851         case opid2('=', '='):
852             if (exprs[0]->vtype != exprs[1]->vtype) {
853                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
854                               type_name[exprs[0]->vtype],
855                               type_name[exprs[1]->vtype]);
856                 return false;
857             }
858             if (!(out = fold_op(parser->fold, op, exprs)))
859                 out = fold_binary(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
860             break;
861
862         case opid1('='):
863             if (ast_istype(exprs[0], ast_entfield)) {
864                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
865                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
866                     exprs[0]->vtype == TYPE_FIELD &&
867                     exprs[0]->next->vtype == TYPE_VECTOR)
868                 {
869                     assignop = type_storep_instr[TYPE_VECTOR];
870                 }
871                 else
872                     assignop = type_storep_instr[exprs[0]->vtype];
873                 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
874                 {
875                     ast_type_to_string(field->next, ty1, sizeof(ty1));
876                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
877                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
878                         field->next->vtype == TYPE_FUNCTION &&
879                         exprs[1]->vtype == TYPE_FUNCTION)
880                     {
881                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
882                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
883                     }
884                     else
885                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
886                 }
887             }
888             else
889             {
890                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
891                     exprs[0]->vtype == TYPE_FIELD &&
892                     exprs[0]->next->vtype == TYPE_VECTOR)
893                 {
894                     assignop = type_store_instr[TYPE_VECTOR];
895                 }
896                 else {
897                     assignop = type_store_instr[exprs[0]->vtype];
898                 }
899
900                 if (assignop == VINSTR_END) {
901                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
902                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
903                     compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
904                 }
905                 else if (!ast_compare_type(exprs[0], exprs[1]))
906                 {
907                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
908                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
909                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
910                         exprs[0]->vtype == TYPE_FUNCTION &&
911                         exprs[1]->vtype == TYPE_FUNCTION)
912                     {
913                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
914                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
915                     }
916                     else
917                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
918                 }
919             }
920             (void)check_write_to(ctx, exprs[0]);
921             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
922             break;
923         case opid3('+','+','P'):
924         case opid3('-','-','P'):
925             /* prefix ++ */
926             if (exprs[0]->vtype != TYPE_FLOAT) {
927                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
928                 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
929                 return false;
930             }
931             if (op->id == opid3('+','+','P'))
932                 addop = INSTR_ADD_F;
933             else
934                 addop = INSTR_SUB_F;
935             (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
936             if (ast_istype(exprs[0], ast_entfield)) {
937                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
938                                                         exprs[0],
939                                                         (ast_expression*)parser->fold->imm_float[1]);
940             } else {
941                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
942                                                         exprs[0],
943                                                         (ast_expression*)parser->fold->imm_float[1]);
944             }
945             break;
946         case opid3('S','+','+'):
947         case opid3('S','-','-'):
948             /* prefix ++ */
949             if (exprs[0]->vtype != TYPE_FLOAT) {
950                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
951                 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
952                 return false;
953             }
954             if (op->id == opid3('S','+','+')) {
955                 addop = INSTR_ADD_F;
956                 subop = INSTR_SUB_F;
957             } else {
958                 addop = INSTR_SUB_F;
959                 subop = INSTR_ADD_F;
960             }
961             (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
962             if (ast_istype(exprs[0], ast_entfield)) {
963                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
964                                                         exprs[0],
965                                                         (ast_expression*)parser->fold->imm_float[1]);
966             } else {
967                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
968                                                         exprs[0],
969                                                         (ast_expression*)parser->fold->imm_float[1]);
970             }
971             if (!out)
972                 return false;
973             out = fold_binary(ctx, subop,
974                               out,
975                               (ast_expression*)parser->fold->imm_float[1]);
976
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 = fold_binary(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 = fold_binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1100             else
1101                 out = fold_binary(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 = fold_binary(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1122                 } else {
1123                     out = fold_binary(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, paramcount);
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, 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), "accumulate")) {
2806                 flags |= AST_FLAG_ACCUMULATE;
2807                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2808                     parseerror(parser, "`accumulate` attribute has no parameters, expected `]]`");
2809                     *cvq = CV_WRONG;
2810                     return false;
2811                 }
2812             }
2813             else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2814                 flags   |= AST_FLAG_ALIAS;
2815                 *message = NULL;
2816
2817                 if (!parser_next(parser)) {
2818                     parseerror(parser, "parse error in attribute");
2819                     goto argerr;
2820                 }
2821
2822                 if (parser->tok == '(') {
2823                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2824                         parseerror(parser, "`alias` attribute missing parameter");
2825                         goto argerr;
2826                     }
2827
2828                     *message = util_strdup(parser_tokval(parser));
2829
2830                     if (!parser_next(parser)) {
2831                         parseerror(parser, "parse error in attribute");
2832                         goto argerr;
2833                     }
2834
2835                     if (parser->tok != ')') {
2836                         parseerror(parser, "`alias` attribute expected `)` after parameter");
2837                         goto argerr;
2838                     }
2839
2840                     if (!parser_next(parser)) {
2841                         parseerror(parser, "parse error in attribute");
2842                         goto argerr;
2843                     }
2844                 }
2845
2846                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2847                     parseerror(parser, "`alias` attribute expected `]]`");
2848                     goto argerr;
2849                 }
2850             }
2851             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2852                 flags   |= AST_FLAG_DEPRECATED;
2853                 *message = NULL;
2854
2855                 if (!parser_next(parser)) {
2856                     parseerror(parser, "parse error in attribute");
2857                     goto argerr;
2858                 }
2859
2860                 if (parser->tok == '(') {
2861                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2862                         parseerror(parser, "`deprecated` attribute missing parameter");
2863                         goto argerr;
2864                     }
2865
2866                     *message = util_strdup(parser_tokval(parser));
2867
2868                     if (!parser_next(parser)) {
2869                         parseerror(parser, "parse error in attribute");
2870                         goto argerr;
2871                     }
2872
2873                     if(parser->tok != ')') {
2874                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2875                         goto argerr;
2876                     }
2877
2878                     if (!parser_next(parser)) {
2879                         parseerror(parser, "parse error in attribute");
2880                         goto argerr;
2881                     }
2882                 }
2883                 /* no message */
2884                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2885                     parseerror(parser, "`deprecated` attribute expected `]]`");
2886
2887                     argerr: /* ugly */
2888                     if (*message) mem_d(*message);
2889                     *message = NULL;
2890                     *cvq     = CV_WRONG;
2891                     return false;
2892                 }
2893             }
2894             else
2895             {
2896                 /* Skip tokens until we hit a ]] */
2897                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2898                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2899                     if (!parser_next(parser)) {
2900                         parseerror(parser, "error inside attribute");
2901                         *cvq = CV_WRONG;
2902                         return false;
2903                     }
2904                 }
2905             }
2906         }
2907         else if (with_local && !strcmp(parser_tokval(parser), "static"))
2908             had_static = true;
2909         else if (!strcmp(parser_tokval(parser), "const"))
2910             had_const = true;
2911         else if (!strcmp(parser_tokval(parser), "var"))
2912             had_var = true;
2913         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2914             had_var = true;
2915         else if (!strcmp(parser_tokval(parser), "noref"))
2916             had_noref = true;
2917         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2918             return false;
2919         }
2920         else
2921             break;
2922         if (!parser_next(parser))
2923             goto onerr;
2924     }
2925     if (had_const)
2926         *cvq = CV_CONST;
2927     else if (had_var)
2928         *cvq = CV_VAR;
2929     else
2930         *cvq = CV_NONE;
2931     *noref     = had_noref;
2932     *is_static = had_static;
2933     *_flags    = flags;
2934     return true;
2935 onerr:
2936     parseerror(parser, "parse error after variable qualifier");
2937     *cvq = CV_WRONG;
2938     return true;
2939 }
2940
2941 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2942 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2943 {
2944     bool rv;
2945     char *label = NULL;
2946
2947     /* skip the 'while' and get the body */
2948     if (!parser_next(parser)) {
2949         if (OPTS_FLAG(LOOP_LABELS))
2950             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2951         else
2952             parseerror(parser, "expected 'switch' operand in parenthesis");
2953         return false;
2954     }
2955
2956     if (parser->tok == ':') {
2957         if (!OPTS_FLAG(LOOP_LABELS))
2958             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2959         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2960             parseerror(parser, "expected loop label");
2961             return false;
2962         }
2963         label = util_strdup(parser_tokval(parser));
2964         if (!parser_next(parser)) {
2965             mem_d(label);
2966             parseerror(parser, "expected 'switch' operand in parenthesis");
2967             return false;
2968         }
2969     }
2970
2971     if (parser->tok != '(') {
2972         parseerror(parser, "expected 'switch' operand in parenthesis");
2973         return false;
2974     }
2975
2976     vec_push(parser->breaks, label);
2977
2978     rv = parse_switch_go(parser, block, out);
2979     if (label)
2980         mem_d(label);
2981     if (vec_last(parser->breaks) != label) {
2982         parseerror(parser, "internal error: label stack corrupted");
2983         rv = false;
2984         ast_delete(*out);
2985         *out = NULL;
2986     }
2987     else {
2988         vec_pop(parser->breaks);
2989     }
2990     return rv;
2991 }
2992
2993 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2994 {
2995     ast_expression *operand;
2996     ast_value      *opval;
2997     ast_value      *typevar;
2998     ast_switch     *switchnode;
2999     ast_switch_case swcase;
3000
3001     int  cvq;
3002     bool noref, is_static;
3003     uint32_t qflags = 0;
3004
3005     lex_ctx_t ctx = parser_ctx(parser);
3006
3007     (void)block; /* not touching */
3008     (void)opval;
3009
3010     /* parse into the expression */
3011     if (!parser_next(parser)) {
3012         parseerror(parser, "expected switch operand");
3013         return false;
3014     }
3015     /* parse the operand */
3016     operand = parse_expression_leave(parser, false, false, false);
3017     if (!operand)
3018         return false;
3019
3020     switchnode = ast_switch_new(ctx, operand);
3021
3022     /* closing paren */
3023     if (parser->tok != ')') {
3024         ast_delete(switchnode);
3025         parseerror(parser, "expected closing paren after 'switch' operand");
3026         return false;
3027     }
3028
3029     /* parse over the opening paren */
3030     if (!parser_next(parser) || parser->tok != '{') {
3031         ast_delete(switchnode);
3032         parseerror(parser, "expected list of cases");
3033         return false;
3034     }
3035
3036     if (!parser_next(parser)) {
3037         ast_delete(switchnode);
3038         parseerror(parser, "expected 'case' or 'default'");
3039         return false;
3040     }
3041
3042     /* new block; allow some variables to be declared here */
3043     parser_enterblock(parser);
3044     while (true) {
3045         typevar = NULL;
3046         if (parser->tok == TOKEN_IDENT)
3047             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3048         if (typevar || parser->tok == TOKEN_TYPENAME) {
3049             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3050                 ast_delete(switchnode);
3051                 return false;
3052             }
3053             continue;
3054         }
3055         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3056         {
3057             if (cvq == CV_WRONG) {
3058                 ast_delete(switchnode);
3059                 return false;
3060             }
3061             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3062                 ast_delete(switchnode);
3063                 return false;
3064             }
3065             continue;
3066         }
3067         break;
3068     }
3069
3070     /* case list! */
3071     while (parser->tok != '}') {
3072         ast_block *caseblock;
3073
3074         if (!strcmp(parser_tokval(parser), "case")) {
3075             if (!parser_next(parser)) {
3076                 ast_delete(switchnode);
3077                 parseerror(parser, "expected expression for case");
3078                 return false;
3079             }
3080             swcase.value = parse_expression_leave(parser, false, false, false);
3081             if (!swcase.value) {
3082                 ast_delete(switchnode);
3083                 parseerror(parser, "expected expression for case");
3084                 return false;
3085             }
3086             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3087                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3088                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3089                     ast_unref(operand);
3090                     return false;
3091                 }
3092             }
3093         }
3094         else if (!strcmp(parser_tokval(parser), "default")) {
3095             swcase.value = NULL;
3096             if (!parser_next(parser)) {
3097                 ast_delete(switchnode);
3098                 parseerror(parser, "expected colon");
3099                 return false;
3100             }
3101         }
3102         else {
3103             ast_delete(switchnode);
3104             parseerror(parser, "expected 'case' or 'default'");
3105             return false;
3106         }
3107
3108         /* Now the colon and body */
3109         if (parser->tok != ':') {
3110             if (swcase.value) ast_unref(swcase.value);
3111             ast_delete(switchnode);
3112             parseerror(parser, "expected colon");
3113             return false;
3114         }
3115
3116         if (!parser_next(parser)) {
3117             if (swcase.value) ast_unref(swcase.value);
3118             ast_delete(switchnode);
3119             parseerror(parser, "expected statements or case");
3120             return false;
3121         }
3122         caseblock = ast_block_new(parser_ctx(parser));
3123         if (!caseblock) {
3124             if (swcase.value) ast_unref(swcase.value);
3125             ast_delete(switchnode);
3126             return false;
3127         }
3128         swcase.code = (ast_expression*)caseblock;
3129         vec_push(switchnode->cases, swcase);
3130         while (true) {
3131             ast_expression *expr;
3132             if (parser->tok == '}')
3133                 break;
3134             if (parser->tok == TOKEN_KEYWORD) {
3135                 if (!strcmp(parser_tokval(parser), "case") ||
3136                     !strcmp(parser_tokval(parser), "default"))
3137                 {
3138                     break;
3139                 }
3140             }
3141             if (!parse_statement(parser, caseblock, &expr, true)) {
3142                 ast_delete(switchnode);
3143                 return false;
3144             }
3145             if (!expr)
3146                 continue;
3147             if (!ast_block_add_expr(caseblock, expr)) {
3148                 ast_delete(switchnode);
3149                 return false;
3150             }
3151         }
3152     }
3153
3154     parser_leaveblock(parser);
3155
3156     /* closing paren */
3157     if (parser->tok != '}') {
3158         ast_delete(switchnode);
3159         parseerror(parser, "expected closing paren of case list");
3160         return false;
3161     }
3162     if (!parser_next(parser)) {
3163         ast_delete(switchnode);
3164         parseerror(parser, "parse error after switch");
3165         return false;
3166     }
3167     *out = (ast_expression*)switchnode;
3168     return true;
3169 }
3170
3171 /* parse computed goto sides */
3172 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3173     ast_expression *on_true;
3174     ast_expression *on_false;
3175     ast_expression *cond;
3176
3177     if (!*side)
3178         return NULL;
3179
3180     if (ast_istype(*side, ast_ternary)) {
3181         ast_ternary *tern = (ast_ternary*)*side;
3182         on_true  = parse_goto_computed(parser, &tern->on_true);
3183         on_false = parse_goto_computed(parser, &tern->on_false);
3184
3185         if (!on_true || !on_false) {
3186             parseerror(parser, "expected label or expression in ternary");
3187             if (on_true) ast_unref(on_true);
3188             if (on_false) ast_unref(on_false);
3189             return NULL;
3190         }
3191
3192         cond = tern->cond;
3193         tern->cond = NULL;
3194         ast_delete(tern);
3195         *side = NULL;
3196         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3197     } else if (ast_istype(*side, ast_label)) {
3198         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3199         ast_goto_set_label(gt, ((ast_label*)*side));
3200         *side = NULL;
3201         return (ast_expression*)gt;
3202     }
3203     return NULL;
3204 }
3205
3206 static bool parse_goto(parser_t *parser, ast_expression **out)
3207 {
3208     ast_goto       *gt = NULL;
3209     ast_expression *lbl;
3210
3211     if (!parser_next(parser))
3212         return false;
3213
3214     if (parser->tok != TOKEN_IDENT) {
3215         ast_expression *expression;
3216
3217         /* could be an expression i.e computed goto :-) */
3218         if (parser->tok != '(') {
3219             parseerror(parser, "expected label name after `goto`");
3220             return false;
3221         }
3222
3223         /* failed to parse expression for goto */
3224         if (!(expression = parse_expression(parser, false, true)) ||
3225             !(*out = parse_goto_computed(parser, &expression))) {
3226             parseerror(parser, "invalid goto expression");
3227             if(expression)
3228                 ast_unref(expression);
3229             return false;
3230         }
3231
3232         return true;
3233     }
3234
3235     /* not computed goto */
3236     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3237     lbl = parser_find_label(parser, gt->name);
3238     if (lbl) {
3239         if (!ast_istype(lbl, ast_label)) {
3240             parseerror(parser, "internal error: label is not an ast_label");
3241             ast_delete(gt);
3242             return false;
3243         }
3244         ast_goto_set_label(gt, (ast_label*)lbl);
3245     }
3246     else
3247         vec_push(parser->gotos, gt);
3248
3249     if (!parser_next(parser) || parser->tok != ';') {
3250         parseerror(parser, "semicolon expected after goto label");
3251         return false;
3252     }
3253     if (!parser_next(parser)) {
3254         parseerror(parser, "parse error after goto");
3255         return false;
3256     }
3257
3258     *out = (ast_expression*)gt;
3259     return true;
3260 }
3261
3262 static bool parse_skipwhite(parser_t *parser)
3263 {
3264     do {
3265         if (!parser_next(parser))
3266             return false;
3267     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3268     return parser->tok < TOKEN_ERROR;
3269 }
3270
3271 static bool parse_eol(parser_t *parser)
3272 {
3273     if (!parse_skipwhite(parser))
3274         return false;
3275     return parser->tok == TOKEN_EOL;
3276 }
3277
3278 static bool parse_pragma_do(parser_t *parser)
3279 {
3280     if (!parser_next(parser) ||
3281         parser->tok != TOKEN_IDENT ||
3282         strcmp(parser_tokval(parser), "pragma"))
3283     {
3284         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3285         return false;
3286     }
3287     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3288         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3289         return false;
3290     }
3291
3292     if (!strcmp(parser_tokval(parser), "noref")) {
3293         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3294             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3295             return false;
3296         }
3297         parser->noref = !!parser_token(parser)->constval.i;
3298         if (!parse_eol(parser)) {
3299             parseerror(parser, "parse error after `noref` pragma");
3300             return false;
3301         }
3302     }
3303     else
3304     {
3305         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3306
3307         /* skip to eol */
3308         while (!parse_eol(parser)) {
3309             parser_next(parser);
3310         }
3311
3312         return true;
3313     }
3314
3315     return true;
3316 }
3317
3318 static bool parse_pragma(parser_t *parser)
3319 {
3320     bool rv;
3321     parser->lex->flags.preprocessing = true;
3322     parser->lex->flags.mergelines = true;
3323     rv = parse_pragma_do(parser);
3324     if (parser->tok != TOKEN_EOL) {
3325         parseerror(parser, "junk after pragma");
3326         rv = false;
3327     }
3328     parser->lex->flags.preprocessing = false;
3329     parser->lex->flags.mergelines = false;
3330     if (!parser_next(parser)) {
3331         parseerror(parser, "parse error after pragma");
3332         rv = false;
3333     }
3334     return rv;
3335 }
3336
3337 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3338 {
3339     bool       noref, is_static;
3340     int        cvq     = CV_NONE;
3341     uint32_t   qflags  = 0;
3342     ast_value *typevar = NULL;
3343     char      *vstring = NULL;
3344
3345     *out = NULL;
3346
3347     if (parser->tok == TOKEN_IDENT)
3348         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3349
3350     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3351     {
3352         /* local variable */
3353         if (!block) {
3354             parseerror(parser, "cannot declare a variable from here");
3355             return false;
3356         }
3357         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3358             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3359                 return false;
3360         }
3361         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3362             return false;
3363         return true;
3364     }
3365     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3366     {
3367         if (cvq == CV_WRONG)
3368             return false;
3369         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3370     }
3371     else if (parser->tok == TOKEN_KEYWORD)
3372     {
3373         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3374         {
3375             char ty[1024];
3376             ast_value *tdef;
3377
3378             if (!parser_next(parser)) {
3379                 parseerror(parser, "parse error after __builtin_debug_printtype");
3380                 return false;
3381             }
3382
3383             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3384             {
3385                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3386                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3387                 if (!parser_next(parser)) {
3388                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3389                     return false;
3390                 }
3391             }
3392             else
3393             {
3394                 if (!parse_statement(parser, block, out, allow_cases))
3395                     return false;
3396                 if (!*out)
3397                     con_out("__builtin_debug_printtype: got no output node\n");
3398                 else
3399                 {
3400                     ast_type_to_string(*out, ty, sizeof(ty));
3401                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3402                 }
3403             }
3404             return true;
3405         }
3406         else if (!strcmp(parser_tokval(parser), "return"))
3407         {
3408             return parse_return(parser, block, out);
3409         }
3410         else if (!strcmp(parser_tokval(parser), "if"))
3411         {
3412             return parse_if(parser, block, out);
3413         }
3414         else if (!strcmp(parser_tokval(parser), "while"))
3415         {
3416             return parse_while(parser, block, out);
3417         }
3418         else if (!strcmp(parser_tokval(parser), "do"))
3419         {
3420             return parse_dowhile(parser, block, out);
3421         }
3422         else if (!strcmp(parser_tokval(parser), "for"))
3423         {
3424             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3425                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3426                     return false;
3427             }
3428             return parse_for(parser, block, out);
3429         }
3430         else if (!strcmp(parser_tokval(parser), "break"))
3431         {
3432             return parse_break_continue(parser, block, out, false);
3433         }
3434         else if (!strcmp(parser_tokval(parser), "continue"))
3435         {
3436             return parse_break_continue(parser, block, out, true);
3437         }
3438         else if (!strcmp(parser_tokval(parser), "switch"))
3439         {
3440             return parse_switch(parser, block, out);
3441         }
3442         else if (!strcmp(parser_tokval(parser), "case") ||
3443                  !strcmp(parser_tokval(parser), "default"))
3444         {
3445             if (!allow_cases) {
3446                 parseerror(parser, "unexpected 'case' label");
3447                 return false;
3448             }
3449             return true;
3450         }
3451         else if (!strcmp(parser_tokval(parser), "goto"))
3452         {
3453             return parse_goto(parser, out);
3454         }
3455         else if (!strcmp(parser_tokval(parser), "typedef"))
3456         {
3457             if (!parser_next(parser)) {
3458                 parseerror(parser, "expected type definition after 'typedef'");
3459                 return false;
3460             }
3461             return parse_typedef(parser);
3462         }
3463         parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3464         return false;
3465     }
3466     else if (parser->tok == '{')
3467     {
3468         ast_block *inner;
3469         inner = parse_block(parser);
3470         if (!inner)
3471             return false;
3472         *out = (ast_expression*)inner;
3473         return true;
3474     }
3475     else if (parser->tok == ':')
3476     {
3477         size_t i;
3478         ast_label *label;
3479         if (!parser_next(parser)) {
3480             parseerror(parser, "expected label name");
3481             return false;
3482         }
3483         if (parser->tok != TOKEN_IDENT) {
3484             parseerror(parser, "label must be an identifier");
3485             return false;
3486         }
3487         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3488         if (label) {
3489             if (!label->undefined) {
3490                 parseerror(parser, "label `%s` already defined", label->name);
3491                 return false;
3492             }
3493             label->undefined = false;
3494         }
3495         else {
3496             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3497             vec_push(parser->labels, label);
3498         }
3499         *out = (ast_expression*)label;
3500         if (!parser_next(parser)) {
3501             parseerror(parser, "parse error after label");
3502             return false;
3503         }
3504         for (i = 0; i < vec_size(parser->gotos); ++i) {
3505             if (!strcmp(parser->gotos[i]->name, label->name)) {
3506                 ast_goto_set_label(parser->gotos[i], label);
3507                 vec_remove(parser->gotos, i, 1);
3508                 --i;
3509             }
3510         }
3511         return true;
3512     }
3513     else if (parser->tok == ';')
3514     {
3515         if (!parser_next(parser)) {
3516             parseerror(parser, "parse error after empty statement");
3517             return false;
3518         }
3519         return true;
3520     }
3521     else
3522     {
3523         lex_ctx_t ctx = parser_ctx(parser);
3524         ast_expression *exp = parse_expression(parser, false, false);
3525         if (!exp)
3526             return false;
3527         *out = exp;
3528         if (!ast_side_effects(exp)) {
3529             if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3530                 return false;
3531         }
3532         return true;
3533     }
3534 }
3535
3536 static bool parse_enum(parser_t *parser)
3537 {
3538     bool        flag = false;
3539     bool        reverse = false;
3540     qcfloat_t     num = 0;
3541     ast_value **values = NULL;
3542     ast_value  *var = NULL;
3543     ast_value  *asvalue;
3544
3545     ast_expression *old;
3546
3547     if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3548         parseerror(parser, "expected `{` or `:` after `enum` keyword");
3549         return false;
3550     }
3551
3552     /* enumeration attributes (can add more later) */
3553     if (parser->tok == ':') {
3554         if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3555             parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3556             return false;
3557         }
3558
3559         /* attributes? */
3560         if (!strcmp(parser_tokval(parser), "flag")) {
3561             num  = 1;
3562             flag = true;
3563         }
3564         else if (!strcmp(parser_tokval(parser), "reverse")) {
3565             reverse = true;
3566         }
3567         else {
3568             parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3569             return false;
3570         }
3571
3572         if (!parser_next(parser) || parser->tok != '{') {
3573             parseerror(parser, "expected `{` after enum attribute ");
3574             return false;
3575         }
3576     }
3577
3578     while (true) {
3579         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3580             if (parser->tok == '}') {
3581                 /* allow an empty enum */
3582                 break;
3583             }
3584             parseerror(parser, "expected identifier or `}`");
3585             goto onerror;
3586         }
3587
3588         old = parser_find_field(parser, parser_tokval(parser));
3589         if (!old)
3590             old = parser_find_global(parser, parser_tokval(parser));
3591         if (old) {
3592             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3593                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3594             goto onerror;
3595         }
3596
3597         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3598         vec_push(values, var);
3599         var->cvq             = CV_CONST;
3600         var->hasvalue        = true;
3601
3602         /* for flagged enumerations increment in POTs of TWO */
3603         var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3604         parser_addglobal(parser, var->name, (ast_expression*)var);
3605
3606         if (!parser_next(parser)) {
3607             parseerror(parser, "expected `=`, `}` or comma after identifier");
3608             goto onerror;
3609         }
3610
3611         if (parser->tok == ',')
3612             continue;
3613         if (parser->tok == '}')
3614             break;
3615         if (parser->tok != '=') {
3616             parseerror(parser, "expected `=`, `}` or comma after identifier");
3617             goto onerror;
3618         }
3619
3620         if (!parser_next(parser)) {
3621             parseerror(parser, "expected expression after `=`");
3622             goto onerror;
3623         }
3624
3625         /* We got a value! */
3626         old = parse_expression_leave(parser, true, false, false);
3627         asvalue = (ast_value*)old;
3628         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3629             compile_error(ast_ctx(var), "constant value or expression expected");
3630             goto onerror;
3631         }
3632         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3633
3634         if (parser->tok == '}')
3635             break;
3636         if (parser->tok != ',') {
3637             parseerror(parser, "expected `}` or comma after expression");
3638             goto onerror;
3639         }
3640     }
3641
3642     /* patch them all (for reversed attribute) */
3643     if (reverse) {
3644         size_t i;
3645         for (i = 0; i < vec_size(values); i++)
3646             values[i]->constval.vfloat = vec_size(values) - i - 1;
3647     }
3648
3649     if (parser->tok != '}') {
3650         parseerror(parser, "internal error: breaking without `}`");
3651         goto onerror;
3652     }
3653
3654     if (!parser_next(parser) || parser->tok != ';') {
3655         parseerror(parser, "expected semicolon after enumeration");
3656         goto onerror;
3657     }
3658
3659     if (!parser_next(parser)) {
3660         parseerror(parser, "parse error after enumeration");
3661         goto onerror;
3662     }
3663
3664     vec_free(values);
3665     return true;
3666
3667 onerror:
3668     vec_free(values);
3669     return false;
3670 }
3671
3672 static bool parse_block_into(parser_t *parser, ast_block *block)
3673 {
3674     bool   retval = true;
3675
3676     parser_enterblock(parser);
3677
3678     if (!parser_next(parser)) { /* skip the '{' */
3679         parseerror(parser, "expected function body");
3680         goto cleanup;
3681     }
3682
3683     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3684     {
3685         ast_expression *expr = NULL;
3686         if (parser->tok == '}')
3687             break;
3688
3689         if (!parse_statement(parser, block, &expr, false)) {
3690             /* parseerror(parser, "parse error"); */
3691             block = NULL;
3692             goto cleanup;
3693         }
3694         if (!expr)
3695             continue;
3696         if (!ast_block_add_expr(block, expr)) {
3697             ast_delete(block);
3698             block = NULL;
3699             goto cleanup;
3700         }
3701     }
3702
3703     if (parser->tok != '}') {
3704         block = NULL;
3705     } else {
3706         (void)parser_next(parser);
3707     }
3708
3709 cleanup:
3710     if (!parser_leaveblock(parser))
3711         retval = false;
3712     return retval && !!block;
3713 }
3714
3715 static ast_block* parse_block(parser_t *parser)
3716 {
3717     ast_block *block;
3718     block = ast_block_new(parser_ctx(parser));
3719     if (!block)
3720         return NULL;
3721     if (!parse_block_into(parser, block)) {
3722         ast_block_delete(block);
3723         return NULL;
3724     }
3725     return block;
3726 }
3727
3728 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3729 {
3730     if (parser->tok == '{') {
3731         *out = (ast_expression*)parse_block(parser);
3732         return !!*out;
3733     }
3734     return parse_statement(parser, NULL, out, false);
3735 }
3736
3737 static bool create_vector_members(ast_value *var, ast_member **me)
3738 {
3739     size_t i;
3740     size_t len = strlen(var->name);
3741
3742     for (i = 0; i < 3; ++i) {
3743         char *name = (char*)mem_a(len+3);
3744         memcpy(name, var->name, len);
3745         name[len+0] = '_';
3746         name[len+1] = 'x'+i;
3747         name[len+2] = 0;
3748         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3749         mem_d(name);
3750         if (!me[i])
3751             break;
3752     }
3753     if (i == 3)
3754         return true;
3755
3756     /* unroll */
3757     do { ast_member_delete(me[--i]); } while(i);
3758     return false;
3759 }
3760
3761 static bool parse_function_body(parser_t *parser, ast_value *var)
3762 {
3763     ast_block      *block = NULL;
3764     ast_function   *func;
3765     ast_function   *old;
3766     size_t          parami;
3767
3768     ast_expression *framenum  = NULL;
3769     ast_expression *nextthink = NULL;
3770     /* None of the following have to be deleted */
3771     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3772     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3773     bool            has_frame_think;
3774
3775     bool retval = true;
3776
3777     has_frame_think = false;
3778     old = parser->function;
3779
3780     if (var->expression.flags & AST_FLAG_ALIAS) {
3781         parseerror(parser, "function aliases cannot have bodies");
3782         return false;
3783     }
3784
3785     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3786         parseerror(parser, "gotos/labels leaking");
3787         return false;
3788     }
3789
3790     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3791         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3792                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3793         {
3794             return false;
3795         }
3796     }
3797
3798     if (parser->tok == '[') {
3799         /* got a frame definition: [ framenum, nextthink ]
3800          * this translates to:
3801          * self.frame = framenum;
3802          * self.nextthink = time + 0.1;
3803          * self.think = nextthink;
3804          */
3805         nextthink = NULL;
3806
3807         fld_think     = parser_find_field(parser, "think");
3808         fld_nextthink = parser_find_field(parser, "nextthink");
3809         fld_frame     = parser_find_field(parser, "frame");
3810         if (!fld_think || !fld_nextthink || !fld_frame) {
3811             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3812             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3813             return false;
3814         }
3815         gbl_time      = parser_find_global(parser, "time");
3816         gbl_self      = parser_find_global(parser, "self");
3817         if (!gbl_time || !gbl_self) {
3818             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3819             parseerror(parser, "please declare the following globals: `time`, `self`");
3820             return false;
3821         }
3822
3823         if (!parser_next(parser))
3824             return false;
3825
3826         framenum = parse_expression_leave(parser, true, false, false);
3827         if (!framenum) {
3828             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3829             return false;
3830         }
3831         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3832             ast_unref(framenum);
3833             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3834             return false;
3835         }
3836
3837         if (parser->tok != ',') {
3838             ast_unref(framenum);
3839             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3840             parseerror(parser, "Got a %i\n", parser->tok);
3841             return false;
3842         }
3843
3844         if (!parser_next(parser)) {
3845             ast_unref(framenum);
3846             return false;
3847         }
3848
3849         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3850         {
3851             /* qc allows the use of not-yet-declared functions here
3852              * - this automatically creates a prototype */
3853             ast_value      *thinkfunc;
3854             ast_expression *functype = fld_think->next;
3855
3856             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3857             if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3858                 ast_unref(framenum);
3859                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3860                 return false;
3861             }
3862             ast_type_adopt(thinkfunc, functype);
3863
3864             if (!parser_next(parser)) {
3865                 ast_unref(framenum);
3866                 ast_delete(thinkfunc);
3867                 return false;
3868             }
3869
3870             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3871
3872             nextthink = (ast_expression*)thinkfunc;
3873
3874         } else {
3875             nextthink = parse_expression_leave(parser, true, false, false);
3876             if (!nextthink) {
3877                 ast_unref(framenum);
3878                 parseerror(parser, "expected a think-function in [frame,think] notation");
3879                 return false;
3880             }
3881         }
3882
3883         if (!ast_istype(nextthink, ast_value)) {
3884             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3885             retval = false;
3886         }
3887
3888         if (retval && parser->tok != ']') {
3889             parseerror(parser, "expected closing `]` for [frame,think] notation");
3890             retval = false;
3891         }
3892
3893         if (retval && !parser_next(parser)) {
3894             retval = false;
3895         }
3896
3897         if (retval && parser->tok != '{') {
3898             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3899             retval = false;
3900         }
3901
3902         if (!retval) {
3903             ast_unref(nextthink);
3904             ast_unref(framenum);
3905             return false;
3906         }
3907
3908         has_frame_think = true;
3909     }
3910
3911     block = ast_block_new(parser_ctx(parser));
3912     if (!block) {
3913         parseerror(parser, "failed to allocate block");
3914         if (has_frame_think) {
3915             ast_unref(nextthink);
3916             ast_unref(framenum);
3917         }
3918         return false;
3919     }
3920
3921     if (has_frame_think) {
3922         lex_ctx_t ctx;
3923         ast_expression *self_frame;
3924         ast_expression *self_nextthink;
3925         ast_expression *self_think;
3926         ast_expression *time_plus_1;
3927         ast_store *store_frame;
3928         ast_store *store_nextthink;
3929         ast_store *store_think;
3930
3931         ctx = parser_ctx(parser);
3932         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3933         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3934         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3935
3936         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3937                          gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3938
3939         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3940             if (self_frame)     ast_delete(self_frame);
3941             if (self_nextthink) ast_delete(self_nextthink);
3942             if (self_think)     ast_delete(self_think);
3943             if (time_plus_1)    ast_delete(time_plus_1);
3944             retval = false;
3945         }
3946
3947         if (retval)
3948         {
3949             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3950             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3951             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3952
3953             if (!store_frame) {
3954                 ast_delete(self_frame);
3955                 retval = false;
3956             }
3957             if (!store_nextthink) {
3958                 ast_delete(self_nextthink);
3959                 retval = false;
3960             }
3961             if (!store_think) {
3962                 ast_delete(self_think);
3963                 retval = false;
3964             }
3965             if (!retval) {
3966                 if (store_frame)     ast_delete(store_frame);
3967                 if (store_nextthink) ast_delete(store_nextthink);
3968                 if (store_think)     ast_delete(store_think);
3969                 retval = false;
3970             }
3971             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3972                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3973                 !ast_block_add_expr(block, (ast_expression*)store_think))
3974             {
3975                 retval = false;
3976             }
3977         }
3978
3979         if (!retval) {
3980             parseerror(parser, "failed to generate code for [frame,think]");
3981             ast_unref(nextthink);
3982             ast_unref(framenum);
3983             ast_delete(block);
3984             return false;
3985         }
3986     }
3987
3988     if (var->hasvalue) {
3989         if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
3990             parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3991             ast_block_delete(block);
3992             goto enderr;
3993         }
3994         func = var->constval.vfunc;
3995
3996         if (!func) {
3997             parseerror(parser, "internal error: NULL function: `%s`", var->name);
3998             ast_block_delete(block);
3999             goto enderr;
4000         }
4001     } else {
4002         func = ast_function_new(ast_ctx(var), var->name, var);
4003
4004         if (!func) {
4005             parseerror(parser, "failed to allocate function for `%s`", var->name);
4006             ast_block_delete(block);
4007             goto enderr;
4008         }
4009         vec_push(parser->functions, func);
4010     }
4011
4012     parser_enterblock(parser);
4013
4014     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4015         size_t     e;
4016         ast_value *param = var->expression.params[parami];
4017         ast_member *me[3];
4018
4019         if (param->expression.vtype != TYPE_VECTOR &&
4020             (param->expression.vtype != TYPE_FIELD ||
4021              param->expression.next->vtype != TYPE_VECTOR))
4022         {
4023             continue;
4024         }
4025
4026         if (!create_vector_members(param, me)) {
4027             ast_block_delete(block);
4028             goto enderrfn;
4029         }
4030
4031         for (e = 0; e < 3; ++e) {
4032             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4033             ast_block_collect(block, (ast_expression*)me[e]);
4034         }
4035     }
4036
4037     if (var->argcounter && !func->argc) {
4038         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4039         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4040         func->argc = argc;
4041     }
4042
4043     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4044         char name[1024];
4045         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4046         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4047         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4048         varargs->expression.count = 0;
4049         util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4050         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4051             ast_delete(varargs);
4052             ast_block_delete(block);
4053             goto enderrfn;
4054         }
4055         util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4056         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4057             ast_delete(varargs);
4058             ast_block_delete(block);
4059             goto enderrfn;
4060         }
4061         func->varargs     = varargs;
4062         func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4063     }
4064
4065     parser->function = func;
4066     if (!parse_block_into(parser, block)) {
4067         ast_block_delete(block);
4068         goto enderrfn;
4069     }
4070
4071     vec_push(func->blocks, block);
4072
4073     parser->function = old;
4074     if (!parser_leaveblock(parser))
4075         retval = false;
4076     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4077         parseerror(parser, "internal error: local scopes left");
4078         retval = false;
4079     }
4080
4081     if (parser->tok == ';')
4082         return parser_next(parser);
4083     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4084         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4085     return retval;
4086
4087 enderrfn:
4088     (void)!parser_leaveblock(parser);
4089     vec_pop(parser->functions);
4090     ast_function_delete(func);
4091     var->constval.vfunc = NULL;
4092
4093 enderr:
4094     parser->function = old;
4095     return false;
4096 }
4097
4098 static ast_expression *array_accessor_split(
4099     parser_t  *parser,
4100     ast_value *array,
4101     ast_value *index,
4102     size_t     middle,
4103     ast_expression *left,
4104     ast_expression *right
4105     )
4106 {
4107     ast_ifthen *ifthen;
4108     ast_binary *cmp;
4109
4110     lex_ctx_t ctx = ast_ctx(array);
4111
4112     if (!left || !right) {
4113         if (left)  ast_delete(left);
4114         if (right) ast_delete(right);
4115         return NULL;
4116     }
4117
4118     cmp = ast_binary_new(ctx, INSTR_LT,
4119                          (ast_expression*)index,
4120                          (ast_expression*)fold_constgen_float(parser->fold, middle));
4121     if (!cmp) {
4122         ast_delete(left);
4123         ast_delete(right);
4124         parseerror(parser, "internal error: failed to create comparison for array setter");
4125         return NULL;
4126     }
4127
4128     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4129     if (!ifthen) {
4130         ast_delete(cmp); /* will delete left and right */
4131         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4132         return NULL;
4133     }
4134
4135     return (ast_expression*)ifthen;
4136 }
4137
4138 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4139 {
4140     lex_ctx_t ctx = ast_ctx(array);
4141
4142     if (from+1 == afterend) {
4143         /* set this value */
4144         ast_block       *block;
4145         ast_return      *ret;
4146         ast_array_index *subscript;
4147         ast_store       *st;
4148         int assignop = type_store_instr[value->expression.vtype];
4149
4150         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4151             assignop = INSTR_STORE_V;
4152
4153         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4154         if (!subscript)
4155             return NULL;
4156
4157         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4158         if (!st) {
4159             ast_delete(subscript);
4160             return NULL;
4161         }
4162
4163         block = ast_block_new(ctx);
4164         if (!block) {
4165             ast_delete(st);
4166             return NULL;
4167         }
4168
4169         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4170             ast_delete(block);
4171             return NULL;
4172         }
4173
4174         ret = ast_return_new(ctx, NULL);
4175         if (!ret) {
4176             ast_delete(block);
4177             return NULL;
4178         }
4179
4180         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4181             ast_delete(block);
4182             return NULL;
4183         }
4184
4185         return (ast_expression*)block;
4186     } else {
4187         ast_expression *left, *right;
4188         size_t diff = afterend - from;
4189         size_t middle = from + diff/2;
4190         left  = array_setter_node(parser, array, index, value, from, middle);
4191         right = array_setter_node(parser, array, index, value, middle, afterend);
4192         return array_accessor_split(parser, array, index, middle, left, right);
4193     }
4194 }
4195
4196 static ast_expression *array_field_setter_node(
4197     parser_t  *parser,
4198     ast_value *array,
4199     ast_value *entity,
4200     ast_value *index,
4201     ast_value *value,
4202     size_t     from,
4203     size_t     afterend)
4204 {
4205     lex_ctx_t ctx = ast_ctx(array);
4206
4207     if (from+1 == afterend) {
4208         /* set this value */
4209         ast_block       *block;
4210         ast_return      *ret;
4211         ast_entfield    *entfield;
4212         ast_array_index *subscript;
4213         ast_store       *st;
4214         int assignop = type_storep_instr[value->expression.vtype];
4215
4216         if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4217             assignop = INSTR_STOREP_V;
4218
4219         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4220         if (!subscript)
4221             return NULL;
4222
4223         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4224         subscript->expression.vtype = TYPE_FIELD;
4225
4226         entfield = ast_entfield_new_force(ctx,
4227                                           (ast_expression*)entity,
4228                                           (ast_expression*)subscript,
4229                                           (ast_expression*)subscript);
4230         if (!entfield) {
4231             ast_delete(subscript);
4232             return NULL;
4233         }
4234
4235         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4236         if (!st) {
4237             ast_delete(entfield);
4238             return NULL;
4239         }
4240
4241         block = ast_block_new(ctx);
4242         if (!block) {
4243             ast_delete(st);
4244             return NULL;
4245         }
4246
4247         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4248             ast_delete(block);
4249             return NULL;
4250         }
4251
4252         ret = ast_return_new(ctx, NULL);
4253         if (!ret) {
4254             ast_delete(block);
4255             return NULL;
4256         }
4257
4258         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4259             ast_delete(block);
4260             return NULL;
4261         }
4262
4263         return (ast_expression*)block;
4264     } else {
4265         ast_expression *left, *right;
4266         size_t diff = afterend - from;
4267         size_t middle = from + diff/2;
4268         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4269         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4270         return array_accessor_split(parser, array, index, middle, left, right);
4271     }
4272 }
4273
4274 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4275 {
4276     lex_ctx_t ctx = ast_ctx(array);
4277
4278     if (from+1 == afterend) {
4279         ast_return      *ret;
4280         ast_array_index *subscript;
4281
4282         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4283         if (!subscript)
4284             return NULL;
4285
4286         ret = ast_return_new(ctx, (ast_expression*)subscript);
4287         if (!ret) {
4288             ast_delete(subscript);
4289             return NULL;
4290         }
4291
4292         return (ast_expression*)ret;
4293     } else {
4294         ast_expression *left, *right;
4295         size_t diff = afterend - from;
4296         size_t middle = from + diff/2;
4297         left  = array_getter_node(parser, array, index, from, middle);
4298         right = array_getter_node(parser, array, index, middle, afterend);
4299         return array_accessor_split(parser, array, index, middle, left, right);
4300     }
4301 }
4302
4303 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4304 {
4305     ast_function   *func = NULL;
4306     ast_value      *fval = NULL;
4307     ast_block      *body = NULL;
4308
4309     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4310     if (!fval) {
4311         parseerror(parser, "failed to create accessor function value");
4312         return false;
4313     }
4314
4315     func = ast_function_new(ast_ctx(array), funcname, fval);
4316     if (!func) {
4317         ast_delete(fval);
4318         parseerror(parser, "failed to create accessor function node");
4319         return false;
4320     }
4321
4322     body = ast_block_new(ast_ctx(array));
4323     if (!body) {
4324         parseerror(parser, "failed to create block for array accessor");
4325         ast_delete(fval);
4326         ast_delete(func);
4327         return false;
4328     }
4329
4330     vec_push(func->blocks, body);
4331     *out = fval;
4332
4333     vec_push(parser->accessors, fval);
4334
4335     return true;
4336 }
4337
4338 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4339 {
4340     ast_value      *index = NULL;
4341     ast_value      *value = NULL;
4342     ast_function   *func;
4343     ast_value      *fval;
4344
4345     if (!ast_istype(array->expression.next, ast_value)) {
4346         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4347         return NULL;
4348     }
4349
4350     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4351         return NULL;
4352     func = fval->constval.vfunc;
4353     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4354
4355     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4356     value = ast_value_copy((ast_value*)array->expression.next);
4357
4358     if (!index || !value) {
4359         parseerror(parser, "failed to create locals for array accessor");
4360         goto cleanup;
4361     }
4362     (void)!ast_value_set_name(value, "value"); /* not important */
4363     vec_push(fval->expression.params, index);
4364     vec_push(fval->expression.params, value);
4365
4366     array->setter = fval;
4367     return fval;
4368 cleanup:
4369     if (index) ast_delete(index);
4370     if (value) ast_delete(value);
4371     ast_delete(func);
4372     ast_delete(fval);
4373     return NULL;
4374 }
4375
4376 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4377 {
4378     ast_expression *root = NULL;
4379     root = array_setter_node(parser, array,
4380                              array->setter->expression.params[0],
4381                              array->setter->expression.params[1],
4382                              0, array->expression.count);
4383     if (!root) {
4384         parseerror(parser, "failed to build accessor search tree");
4385         return false;
4386     }
4387     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4388         ast_delete(root);
4389         return false;
4390     }
4391     return true;
4392 }
4393
4394 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4395 {
4396     if (!parser_create_array_setter_proto(parser, array, funcname))
4397         return false;
4398     return parser_create_array_setter_impl(parser, array);
4399 }
4400
4401 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4402 {
4403     ast_expression *root = NULL;
4404     ast_value      *entity = NULL;
4405     ast_value      *index = NULL;
4406     ast_value      *value = NULL;
4407     ast_function   *func;
4408     ast_value      *fval;
4409
4410     if (!ast_istype(array->expression.next, ast_value)) {
4411         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4412         return false;
4413     }
4414
4415     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4416         return false;
4417     func = fval->constval.vfunc;
4418     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4419
4420     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4421     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4422     value  = ast_value_copy((ast_value*)array->expression.next);
4423     if (!entity || !index || !value) {
4424         parseerror(parser, "failed to create locals for array accessor");
4425         goto cleanup;
4426     }
4427     (void)!ast_value_set_name(value, "value"); /* not important */
4428     vec_push(fval->expression.params, entity);
4429     vec_push(fval->expression.params, index);
4430     vec_push(fval->expression.params, value);
4431
4432     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4433     if (!root) {
4434         parseerror(parser, "failed to build accessor search tree");
4435         goto cleanup;
4436     }
4437
4438     array->setter = fval;
4439     return ast_block_add_expr(func->blocks[0], root);
4440 cleanup:
4441     if (entity) ast_delete(entity);
4442     if (index)  ast_delete(index);
4443     if (value)  ast_delete(value);
4444     if (root)   ast_delete(root);
4445     ast_delete(func);
4446     ast_delete(fval);
4447     return false;
4448 }
4449
4450 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4451 {
4452     ast_value      *index = NULL;
4453     ast_value      *fval;
4454     ast_function   *func;
4455
4456     /* NOTE: checking array->expression.next rather than elemtype since
4457      * for fields elemtype is a temporary fieldtype.
4458      */
4459     if (!ast_istype(array->expression.next, ast_value)) {
4460         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4461         return NULL;
4462     }
4463
4464     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4465         return NULL;
4466     func = fval->constval.vfunc;
4467     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4468
4469     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4470
4471     if (!index) {
4472         parseerror(parser, "failed to create locals for array accessor");
4473         goto cleanup;
4474     }
4475     vec_push(fval->expression.params, index);
4476
4477     array->getter = fval;
4478     return fval;
4479 cleanup:
4480     if (index) ast_delete(index);
4481     ast_delete(func);
4482     ast_delete(fval);
4483     return NULL;
4484 }
4485
4486 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4487 {
4488     ast_expression *root = NULL;
4489
4490     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4491     if (!root) {
4492         parseerror(parser, "failed to build accessor search tree");
4493         return false;
4494     }
4495     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4496         ast_delete(root);
4497         return false;
4498     }
4499     return true;
4500 }
4501
4502 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4503 {
4504     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4505         return false;
4506     return parser_create_array_getter_impl(parser, array);
4507 }
4508
4509 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4510 {
4511     lex_ctx_t     ctx;
4512     size_t      i;
4513     ast_value **params;
4514     ast_value  *param;
4515     ast_value  *fval;
4516     bool        first = true;
4517     bool        variadic = false;
4518     ast_value  *varparam = NULL;
4519     char       *argcounter = NULL;
4520
4521     ctx = parser_ctx(parser);
4522
4523     /* for the sake of less code we parse-in in this function */
4524     if (!parser_next(parser)) {
4525         ast_delete(var);
4526         parseerror(parser, "expected parameter list");
4527         return NULL;
4528     }
4529
4530     params = NULL;
4531
4532     /* parse variables until we hit a closing paren */
4533     while (parser->tok != ')') {
4534         bool is_varargs = false;
4535
4536         if (!first) {
4537             /* there must be commas between them */
4538             if (parser->tok != ',') {
4539                 parseerror(parser, "expected comma or end of parameter list");
4540                 goto on_error;
4541             }
4542             if (!parser_next(parser)) {
4543                 parseerror(parser, "expected parameter");
4544                 goto on_error;
4545             }
4546         }
4547         first = false;
4548
4549         param = parse_typename(parser, NULL, NULL, &is_varargs);
4550         if (!param && !is_varargs)
4551             goto on_error;
4552         if (is_varargs) {
4553             /* '...' indicates a varargs function */
4554             variadic = true;
4555             if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4556                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4557                 goto on_error;
4558             }
4559             if (parser->tok == TOKEN_IDENT) {
4560                 argcounter = util_strdup(parser_tokval(parser));
4561                 if (!parser_next(parser) || parser->tok != ')') {
4562                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4563                     goto on_error;
4564                 }
4565             }
4566         } else {
4567             vec_push(params, param);
4568             if (param->expression.vtype >= TYPE_VARIANT) {
4569                 char tname[1024]; /* typename is reserved in C++ */
4570                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4571                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4572                 goto on_error;
4573             }
4574             /* type-restricted varargs */
4575             if (parser->tok == TOKEN_DOTS) {
4576                 variadic = true;
4577                 varparam = vec_last(params);
4578                 vec_pop(params);
4579                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4580                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4581                     goto on_error;
4582                 }
4583                 if (parser->tok == TOKEN_IDENT) {
4584                     argcounter = util_strdup(parser_tokval(parser));
4585                     if (!parser_next(parser) || parser->tok != ')') {
4586                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4587                         goto on_error;
4588                     }
4589                 }
4590             }
4591         }
4592     }
4593
4594     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4595         vec_free(params);
4596
4597     /* sanity check */
4598     if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4599         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4600
4601     /* parse-out */
4602     if (!parser_next(parser)) {
4603         parseerror(parser, "parse error after typename");
4604         goto on_error;
4605     }
4606
4607     /* now turn 'var' into a function type */
4608     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4609     fval->expression.next     = (ast_expression*)var;
4610     if (variadic)
4611         fval->expression.flags |= AST_FLAG_VARIADIC;
4612     var = fval;
4613
4614     var->expression.params   = params;
4615     var->expression.varparam = (ast_expression*)varparam;
4616     var->argcounter          = argcounter;
4617     params = NULL;
4618
4619     return var;
4620
4621 on_error:
4622     if (argcounter)
4623         mem_d(argcounter);
4624     if (varparam)
4625         ast_delete(varparam);
4626     ast_delete(var);
4627     for (i = 0; i < vec_size(params); ++i)
4628         ast_delete(params[i]);
4629     vec_free(params);
4630     return NULL;
4631 }
4632
4633 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4634 {
4635     ast_expression *cexp;
4636     ast_value      *cval, *tmp;
4637     lex_ctx_t ctx;
4638
4639     ctx = parser_ctx(parser);
4640
4641     if (!parser_next(parser)) {
4642         ast_delete(var);
4643         parseerror(parser, "expected array-size");
4644         return NULL;
4645     }
4646
4647     if (parser->tok != ']') {
4648         cexp = parse_expression_leave(parser, true, false, false);
4649
4650         if (!cexp || !ast_istype(cexp, ast_value)) {
4651             if (cexp)
4652                 ast_unref(cexp);
4653             ast_delete(var);
4654             parseerror(parser, "expected array-size as constant positive integer");
4655             return NULL;
4656         }
4657         cval = (ast_value*)cexp;
4658     }
4659     else {
4660         cexp = NULL;
4661         cval = NULL;
4662     }
4663
4664     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4665     tmp->expression.next = (ast_expression*)var;
4666     var = tmp;
4667
4668     if (cval) {
4669         if (cval->expression.vtype == TYPE_INTEGER)
4670             tmp->expression.count = cval->constval.vint;
4671         else if (cval->expression.vtype == TYPE_FLOAT)
4672             tmp->expression.count = cval->constval.vfloat;
4673         else {
4674             ast_unref(cexp);
4675             ast_delete(var);
4676             parseerror(parser, "array-size must be a positive integer constant");
4677             return NULL;
4678         }
4679
4680         ast_unref(cexp);
4681     } else {
4682         var->expression.count = -1;
4683         var->expression.flags |= AST_FLAG_ARRAY_INIT;
4684     }
4685
4686     if (parser->tok != ']') {
4687         ast_delete(var);
4688         parseerror(parser, "expected ']' after array-size");
4689         return NULL;
4690     }
4691     if (!parser_next(parser)) {
4692         ast_delete(var);
4693         parseerror(parser, "error after parsing array size");
4694         return NULL;
4695     }
4696     return var;
4697 }
4698
4699 /* Parse a complete typename.
4700  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4701  * but when parsing variables separated by comma
4702  * 'storebase' should point to where the base-type should be kept.
4703  * The base type makes up every bit of type information which comes *before* the
4704  * variable name.
4705  *
4706  * NOTE: The value must either be named, have a NULL name, or a name starting
4707  *       with '<'. In the first case, this will be the actual variable or type
4708  *       name, in the other cases it is assumed that the name will appear
4709  *       later, and an error is generated otherwise.
4710  *
4711  * The following will be parsed in its entirety:
4712  *     void() foo()
4713  * The 'basetype' in this case is 'void()'
4714  * and if there's a comma after it, say:
4715  *     void() foo(), bar
4716  * then the type-information 'void()' can be stored in 'storebase'
4717  */
4718 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4719 {
4720     ast_value *var, *tmp;
4721     lex_ctx_t    ctx;
4722
4723     const char *name = NULL;
4724     bool        isfield  = false;
4725     bool        wasarray = false;
4726     size_t      morefields = 0;
4727
4728     bool        vararg = (parser->tok == TOKEN_DOTS);
4729
4730     ctx = parser_ctx(parser);
4731
4732     /* types may start with a dot */
4733     if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4734         isfield = true;
4735         if (parser->tok == TOKEN_DOTS)
4736             morefields += 2;
4737         /* if we parsed a dot we need a typename now */
4738         if (!parser_next(parser)) {
4739             parseerror(parser, "expected typename for field definition");
4740             return NULL;
4741         }
4742
4743         /* Further dots are handled seperately because they won't be part of the
4744          * basetype
4745          */
4746         while (true) {
4747             if (parser->tok == '.')
4748                 ++morefields;
4749             else if (parser->tok == TOKEN_DOTS)
4750                 morefields += 3;
4751             else
4752                 break;
4753             vararg = false;
4754             if (!parser_next(parser)) {
4755                 parseerror(parser, "expected typename for field definition");
4756                 return NULL;
4757             }
4758         }
4759     }
4760     if (parser->tok == TOKEN_IDENT)
4761         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4762     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4763         if (vararg && is_vararg) {
4764             *is_vararg = true;
4765             return NULL;
4766         }
4767         parseerror(parser, "expected typename");
4768         return NULL;
4769     }
4770
4771     /* generate the basic type value */
4772     if (cached_typedef) {
4773         var = ast_value_copy(cached_typedef);
4774         ast_value_set_name(var, "<type(from_def)>");
4775     } else
4776         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4777
4778     for (; morefields; --morefields) {
4779         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4780         tmp->expression.next = (ast_expression*)var;
4781         var = tmp;
4782     }
4783
4784     /* do not yet turn into a field - remember:
4785      * .void() foo; is a field too
4786      * .void()() foo; is a function
4787      */
4788
4789     /* parse on */
4790     if (!parser_next(parser)) {
4791         ast_delete(var);
4792         parseerror(parser, "parse error after typename");
4793         return NULL;
4794     }
4795
4796     /* an opening paren now starts the parameter-list of a function
4797      * this is where original-QC has parameter lists.
4798      * We allow a single parameter list here.
4799      * Much like fteqcc we don't allow `float()() x`
4800      */
4801     if (parser->tok == '(') {
4802         var = parse_parameter_list(parser, var);
4803         if (!var)
4804             return NULL;
4805     }
4806
4807     /* store the base if requested */
4808     if (storebase) {
4809         *storebase = ast_value_copy(var);
4810         if (isfield) {
4811             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4812             tmp->expression.next = (ast_expression*)*storebase;
4813             *storebase = tmp;
4814         }
4815     }
4816
4817     /* there may be a name now */
4818     if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4819         if (!strcmp(parser_tokval(parser), "break"))
4820             (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4821         else if (parser->tok == TOKEN_KEYWORD)
4822             goto leave;
4823
4824         name = util_strdup(parser_tokval(parser));
4825
4826         /* parse on */
4827         if (!parser_next(parser)) {
4828             ast_delete(var);
4829             mem_d(name);
4830             parseerror(parser, "error after variable or field declaration");
4831             return NULL;
4832         }
4833     }
4834
4835     leave:
4836     /* now this may be an array */
4837     if (parser->tok == '[') {
4838         wasarray = true;
4839         var = parse_arraysize(parser, var);
4840         if (!var) {
4841             if (name) mem_d(name);
4842             return NULL;
4843         }
4844     }
4845
4846     /* This is the point where we can turn it into a field */
4847     if (isfield) {
4848         /* turn it into a field if desired */
4849         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4850         tmp->expression.next = (ast_expression*)var;
4851         var = tmp;
4852     }
4853
4854     /* now there may be function parens again */
4855     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4856         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4857     if (parser->tok == '(' && wasarray)
4858         parseerror(parser, "arrays as part of a return type is not supported");
4859     while (parser->tok == '(') {
4860         var = parse_parameter_list(parser, var);
4861         if (!var) {
4862             if (name) mem_d(name);
4863             return NULL;
4864         }
4865     }
4866
4867     /* finally name it */
4868     if (name) {
4869         if (!ast_value_set_name(var, name)) {
4870             ast_delete(var);
4871             mem_d(name);
4872             parseerror(parser, "internal error: failed to set name");
4873             return NULL;
4874         }
4875         /* free the name, ast_value_set_name duplicates */
4876         mem_d(name);
4877     }
4878
4879     return var;
4880 }
4881
4882 static bool parse_typedef(parser_t *parser)
4883 {
4884     ast_value      *typevar, *oldtype;
4885     ast_expression *old;
4886
4887     typevar = parse_typename(parser, NULL, NULL, NULL);
4888
4889     if (!typevar)
4890         return false;
4891
4892     /* while parsing types, the ast_value's get named '<something>' */
4893     if (!typevar->name || typevar->name[0] == '<') {
4894         parseerror(parser, "missing name in typedef");
4895         ast_delete(typevar);
4896         return false;
4897     }
4898
4899     if ( (old = parser_find_var(parser, typevar->name)) ) {
4900         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4901                    " -> `%s` has been declared here: %s:%i",
4902                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4903         ast_delete(typevar);
4904         return false;
4905     }
4906
4907     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4908         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4909                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4910         ast_delete(typevar);
4911         return false;
4912     }
4913
4914     vec_push(parser->_typedefs, typevar);
4915     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4916
4917     if (parser->tok != ';') {
4918         parseerror(parser, "expected semicolon after typedef");
4919         return false;
4920     }
4921     if (!parser_next(parser)) {
4922         parseerror(parser, "parse error after typedef");
4923         return false;
4924     }
4925
4926     return true;
4927 }
4928
4929 static const char *cvq_to_str(int cvq) {
4930     switch (cvq) {
4931         case CV_NONE:  return "none";
4932         case CV_VAR:   return "`var`";
4933         case CV_CONST: return "`const`";
4934         default:       return "<INVALID>";
4935     }
4936 }
4937
4938 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4939 {
4940     bool av, ao;
4941     if (proto->cvq != var->cvq) {
4942         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4943               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4944               parser->tok == '='))
4945         {
4946             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4947                                  "`%s` declared with different qualifiers: %s\n"
4948                                  " -> previous declaration here: %s:%i uses %s",
4949                                  var->name, cvq_to_str(var->cvq),
4950                                  ast_ctx(proto).file, ast_ctx(proto).line,
4951                                  cvq_to_str(proto->cvq));
4952         }
4953     }
4954     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4955     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4956     if (!av != !ao) {
4957         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4958                              "`%s` declared with different attributes%s\n"
4959                              " -> previous declaration here: %s:%i",
4960                              var->name, (av ? ": noreturn" : ""),
4961                              ast_ctx(proto).file, ast_ctx(proto).line,
4962                              (ao ? ": noreturn" : ""));
4963     }
4964     return true;
4965 }
4966
4967 static bool create_array_accessors(parser_t *parser, ast_value *var)
4968 {
4969     char name[1024];
4970     util_snprintf(name, sizeof(name), "%s##SET", var->name);
4971     if (!parser_create_array_setter(parser, var, name))
4972         return false;
4973     util_snprintf(name, sizeof(name), "%s##GET", var->name);
4974     if (!parser_create_array_getter(parser, var, var->expression.next, name))
4975         return false;
4976     return true;
4977 }
4978
4979 static bool parse_array(parser_t *parser, ast_value *array)
4980 {
4981     size_t i;
4982     if (array->initlist) {
4983         parseerror(parser, "array already initialized elsewhere");
4984         return false;
4985     }
4986     if (!parser_next(parser)) {
4987         parseerror(parser, "parse error in array initializer");
4988         return false;
4989     }
4990     i = 0;
4991     while (parser->tok != '}') {
4992         ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4993         if (!v)
4994             return false;
4995         if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4996             ast_unref(v);
4997             parseerror(parser, "initializing element must be a compile time constant");
4998             return false;
4999         }
5000         vec_push(array->initlist, v->constval);
5001         if (v->expression.vtype == TYPE_STRING) {
5002             array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5003             ++i;
5004         }
5005         ast_unref(v);
5006         if (parser->tok == '}')
5007             break;
5008         if (parser->tok != ',' || !parser_next(parser)) {
5009             parseerror(parser, "expected comma or '}' in element list");
5010             return false;
5011         }
5012     }
5013     if (!parser_next(parser) || parser->tok != ';') {
5014         parseerror(parser, "expected semicolon after initializer, got %s");
5015         return false;
5016     }
5017     /*
5018     if (!parser_next(parser)) {
5019         parseerror(parser, "parse error after initializer");
5020         return false;
5021     }
5022     */
5023
5024     if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5025         if (array->expression.count != (size_t)-1) {
5026             parseerror(parser, "array `%s' has already been initialized with %u elements",
5027                        array->name, (unsigned)array->expression.count);
5028         }
5029         array->expression.count = vec_size(array->initlist);
5030         if (!create_array_accessors(parser, array))
5031             return false;
5032     }
5033     return true;
5034 }
5035
5036 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)
5037 {
5038     ast_value *var;
5039     ast_value *proto;
5040     ast_expression *old;
5041     bool       was_end;
5042     size_t     i;
5043
5044     ast_value *basetype = NULL;
5045     bool      retval    = true;
5046     bool      isparam   = false;
5047     bool      isvector  = false;
5048     bool      cleanvar  = true;
5049     bool      wasarray  = false;
5050
5051     ast_member *me[3] = { NULL, NULL, NULL };
5052
5053     if (!localblock && is_static)
5054         parseerror(parser, "`static` qualifier is not supported in global scope");
5055
5056     /* get the first complete variable */
5057     var = parse_typename(parser, &basetype, cached_typedef, NULL);
5058     if (!var) {
5059         if (basetype)
5060             ast_delete(basetype);
5061         return false;
5062     }
5063
5064     /* while parsing types, the ast_value's get named '<something>' */
5065     if (!var->name || var->name[0] == '<') {
5066         parseerror(parser, "declaration does not declare anything");
5067         if (basetype)
5068             ast_delete(basetype);
5069         return false;
5070     }
5071
5072     while (true) {
5073         proto = NULL;
5074         wasarray = false;
5075
5076         /* Part 0: finish the type */
5077         if (parser->tok == '(') {
5078             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5079                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5080             var = parse_parameter_list(parser, var);
5081             if (!var) {
5082                 retval = false;
5083                 goto cleanup;
5084             }
5085         }
5086         /* we only allow 1-dimensional arrays */
5087         if (parser->tok == '[') {
5088             wasarray = true;
5089             var = parse_arraysize(parser, var);
5090             if (!var) {
5091                 retval = false;
5092                 goto cleanup;
5093             }
5094         }
5095         if (parser->tok == '(' && wasarray) {
5096             parseerror(parser, "arrays as part of a return type is not supported");
5097             /* we'll still parse the type completely for now */
5098         }
5099         /* for functions returning functions */
5100         while (parser->tok == '(') {
5101             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5102                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5103             var = parse_parameter_list(parser, var);
5104             if (!var) {
5105                 retval = false;
5106                 goto cleanup;
5107             }
5108         }
5109
5110         var->cvq = qualifier;
5111         var->expression.flags |= qflags;
5112
5113         /*
5114          * store the vstring back to var for alias and
5115          * deprecation messages.
5116          */
5117         if (var->expression.flags & AST_FLAG_DEPRECATED ||
5118             var->expression.flags & AST_FLAG_ALIAS)
5119             var->desc = vstring;
5120
5121         if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5122             parseerror(parser, "function aliases cannot be forward declared");
5123             retval = false;
5124             goto cleanup;
5125         }
5126
5127
5128         /* Part 1:
5129          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5130          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5131          * is then filled with the previous definition and the parameter-names replaced.
5132          */
5133         if (!strcmp(var->name, "nil")) {
5134             if (OPTS_FLAG(UNTYPED_NIL)) {
5135                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5136                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5137             } else
5138                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5139         }
5140         if (!localblock) {
5141             /* Deal with end_sys_ vars */
5142             was_end = false;
5143             if (!strcmp(var->name, "end_sys_globals")) {
5144                 var->uses++;
5145                 parser->crc_globals = vec_size(parser->globals);
5146                 was_end = true;
5147             }
5148             else if (!strcmp(var->name, "end_sys_fields")) {
5149                 var->uses++;
5150                 parser->crc_fields = vec_size(parser->fields);
5151                 was_end = true;
5152             }
5153             if (was_end && var->expression.vtype == TYPE_FIELD) {
5154                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5155                                  "global '%s' hint should not be a field",
5156                                  parser_tokval(parser)))
5157                 {
5158                     retval = false;
5159                     goto cleanup;
5160                 }
5161             }
5162
5163             if (!nofields && var->expression.vtype == TYPE_FIELD)
5164             {
5165                 /* deal with field declarations */
5166                 old = parser_find_field(parser, var->name);
5167                 if (old) {
5168                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5169                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5170                     {
5171                         retval = false;
5172                         goto cleanup;
5173                     }
5174                     ast_delete(var);
5175                     var = NULL;
5176                     goto skipvar;
5177                     /*
5178                     parseerror(parser, "field `%s` already declared here: %s:%i",
5179                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5180                     retval = false;
5181                     goto cleanup;
5182                     */
5183                 }
5184                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5185                     (old = parser_find_global(parser, var->name)))
5186                 {
5187                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5188                     parseerror(parser, "field `%s` already declared here: %s:%i",
5189                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5190                     retval = false;
5191                     goto cleanup;
5192                 }
5193             }
5194             else
5195             {
5196                 /* deal with other globals */
5197                 old = parser_find_global(parser, var->name);
5198                 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5199                 {
5200                     /* This is a function which had a prototype */
5201                     if (!ast_istype(old, ast_value)) {
5202                         parseerror(parser, "internal error: prototype is not an ast_value");
5203                         retval = false;
5204                         goto cleanup;
5205                     }
5206                     proto = (ast_value*)old;
5207                     proto->desc = var->desc;
5208                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5209                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5210                                    proto->name,
5211                                    ast_ctx(proto).file, ast_ctx(proto).line);
5212                         retval = false;
5213                         goto cleanup;
5214                     }
5215                     /* we need the new parameter-names */
5216                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5217                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5218                     if (!parser_check_qualifiers(parser, var, proto)) {
5219                         retval = false;
5220                         if (proto->desc)
5221                             mem_d(proto->desc);
5222                         proto = NULL;
5223                         goto cleanup;
5224                     }
5225                     proto->expression.flags |= var->expression.flags;
5226                     ast_delete(var);
5227                     var = proto;
5228                 }
5229                 else
5230                 {
5231                     /* other globals */
5232                     if (old) {
5233                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5234                                          "global `%s` already declared here: %s:%i",
5235                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5236                         {
5237                             retval = false;
5238                             goto cleanup;
5239                         }
5240                         proto = (ast_value*)old;
5241                         if (!ast_istype(old, ast_value)) {
5242                             parseerror(parser, "internal error: not an ast_value");
5243                             retval = false;
5244                             proto = NULL;
5245                             goto cleanup;
5246                         }
5247                         if (!parser_check_qualifiers(parser, var, proto)) {
5248                             retval = false;
5249                             proto = NULL;
5250                             goto cleanup;
5251                         }
5252                         proto->expression.flags |= var->expression.flags;
5253                         ast_delete(var);
5254                         var = proto;
5255                     }
5256                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5257                         (old = parser_find_field(parser, var->name)))
5258                     {
5259                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5260                         parseerror(parser, "global `%s` already declared here: %s:%i",
5261                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5262                         retval = false;
5263                         goto cleanup;
5264                     }
5265                 }
5266             }
5267         }
5268         else /* it's not a global */
5269         {
5270             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5271             if (old && !isparam) {
5272                 parseerror(parser, "local `%s` already declared here: %s:%i",
5273                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5274                 retval = false;
5275                 goto cleanup;
5276             }
5277             /* doing this here as the above is just for a single scope */
5278             old = parser_find_local(parser, var->name, 0, &isparam);
5279             if (old && isparam) {
5280                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5281                                  "local `%s` is shadowing a parameter", var->name))
5282                 {
5283                     parseerror(parser, "local `%s` already declared here: %s:%i",
5284                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5285                     retval = false;
5286                     goto cleanup;
5287                 }
5288                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5289                     ast_delete(var);
5290                     if (ast_istype(old, ast_value))
5291                         var = proto = (ast_value*)old;
5292                     else {
5293                         var = NULL;
5294                         goto skipvar;
5295                     }
5296                 }
5297             }
5298         }
5299
5300         /* in a noref section we simply bump the usecount */
5301         if (noref || parser->noref)
5302             var->uses++;
5303
5304         /* Part 2:
5305          * Create the global/local, and deal with vector types.
5306          */
5307         if (!proto) {
5308             if (var->expression.vtype == TYPE_VECTOR)
5309                 isvector = true;
5310             else if (var->expression.vtype == TYPE_FIELD &&
5311                      var->expression.next->vtype == TYPE_VECTOR)
5312                 isvector = true;
5313
5314             if (isvector) {
5315                 if (!create_vector_members(var, me)) {
5316                     retval = false;
5317                     goto cleanup;
5318                 }
5319             }
5320
5321             if (!localblock) {
5322                 /* deal with global variables, fields, functions */
5323                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5324                     var->isfield = true;
5325                     vec_push(parser->fields, (ast_expression*)var);
5326                     util_htset(parser->htfields, var->name, var);
5327                     if (isvector) {
5328                         for (i = 0; i < 3; ++i) {
5329                             vec_push(parser->fields, (ast_expression*)me[i]);
5330                             util_htset(parser->htfields, me[i]->name, me[i]);
5331                         }
5332                     }
5333                 }
5334                 else {
5335                     if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5336                         parser_addglobal(parser, var->name, (ast_expression*)var);
5337                         if (isvector) {
5338                             for (i = 0; i < 3; ++i) {
5339                                 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5340                             }
5341                         }
5342                     } else {
5343                         ast_expression *find  = parser_find_global(parser, var->desc);
5344
5345                         if (!find) {
5346                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5347                             return false;
5348                         }
5349
5350                         if (!ast_compare_type((ast_expression*)var, find)) {
5351                             char ty1[1024];
5352                             char ty2[1024];
5353
5354                             ast_type_to_string(find,                  ty1, sizeof(ty1));
5355                             ast_type_to_string((ast_expression*)var,  ty2, sizeof(ty2));
5356
5357                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5358                                 ty1, ty2, var->name
5359                             );
5360                             return false;
5361                         }
5362
5363                         /*
5364                          * add alias to aliases table and to corrector
5365                          * so corrections can apply for aliases as well.
5366                          */
5367                         util_htset(parser->aliases, var->name, find);
5368
5369                         /*
5370                          * add to corrector so corrections can work
5371                          * even for aliases too.
5372                          */
5373                         correct_add (
5374                              vec_last(parser->correct_variables),
5375                             &vec_last(parser->correct_variables_score),
5376                             var->name
5377                         );
5378
5379                         /* generate aliases for vector components */
5380                         if (isvector) {
5381                             char *buffer[3];
5382
5383                             util_asprintf(&buffer[0], "%s_x", var->desc);
5384                             util_asprintf(&buffer[1], "%s_y", var->desc);
5385                             util_asprintf(&buffer[2], "%s_z", var->desc);
5386
5387                             util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5388                             util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5389                             util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5390
5391                             mem_d(buffer[0]);
5392                             mem_d(buffer[1]);
5393                             mem_d(buffer[2]);
5394
5395                             /*
5396                              * add to corrector so corrections can work
5397                              * even for aliases too.
5398                              */
5399                             correct_add (
5400                                  vec_last(parser->correct_variables),
5401                                 &vec_last(parser->correct_variables_score),
5402                                 me[0]->name
5403                             );
5404                             correct_add (
5405                                  vec_last(parser->correct_variables),
5406                                 &vec_last(parser->correct_variables_score),
5407                                 me[1]->name
5408                             );
5409                             correct_add (
5410                                  vec_last(parser->correct_variables),
5411                                 &vec_last(parser->correct_variables_score),
5412                                 me[2]->name
5413                             );
5414                         }
5415                     }
5416                 }
5417             } else {
5418                 if (is_static) {
5419                     /* a static adds itself to be generated like any other global
5420                      * but is added to the local namespace instead
5421                      */
5422                     char   *defname = NULL;
5423                     size_t  prefix_len, ln;
5424
5425                     ln = strlen(parser->function->name);
5426                     vec_append(defname, ln, parser->function->name);
5427
5428                     vec_append(defname, 2, "::");
5429                     /* remember the length up to here */
5430                     prefix_len = vec_size(defname);
5431
5432                     /* Add it to the local scope */
5433                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5434
5435                     /* corrector */
5436                     correct_add (
5437                          vec_last(parser->correct_variables),
5438                         &vec_last(parser->correct_variables_score),
5439                         var->name
5440                     );
5441
5442                     /* now rename the global */
5443                     ln = strlen(var->name);
5444                     vec_append(defname, ln, var->name);
5445                     ast_value_set_name(var, defname);
5446
5447                     /* push it to the to-be-generated globals */
5448                     vec_push(parser->globals, (ast_expression*)var);
5449
5450                     /* same game for the vector members */
5451                     if (isvector) {
5452                         for (i = 0; i < 3; ++i) {
5453                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5454
5455                             /* corrector */
5456                             correct_add(
5457                                  vec_last(parser->correct_variables),
5458                                 &vec_last(parser->correct_variables_score),
5459                                 me[i]->name
5460                             );
5461
5462                             vec_shrinkto(defname, prefix_len);
5463                             ln = strlen(me[i]->name);
5464                             vec_append(defname, ln, me[i]->name);
5465                             ast_member_set_name(me[i], defname);
5466
5467                             vec_push(parser->globals, (ast_expression*)me[i]);
5468                         }
5469                     }
5470                     vec_free(defname);
5471                 } else {
5472                     vec_push(localblock->locals, var);
5473                     parser_addlocal(parser, var->name, (ast_expression*)var);
5474                     if (isvector) {
5475                         for (i = 0; i < 3; ++i) {
5476                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5477                             ast_block_collect(localblock, (ast_expression*)me[i]);
5478                         }
5479                     }
5480                 }
5481             }
5482         }
5483         me[0] = me[1] = me[2] = NULL;
5484         cleanvar = false;
5485         /* Part 2.2
5486          * deal with arrays
5487          */
5488         if (var->expression.vtype == TYPE_ARRAY) {
5489             if (var->expression.count != (size_t)-1) {
5490                 if (!create_array_accessors(parser, var))
5491                     goto cleanup;
5492             }
5493         }
5494         else if (!localblock && !nofields &&
5495                  var->expression.vtype == TYPE_FIELD &&
5496                  var->expression.next->vtype == TYPE_ARRAY)
5497         {
5498             char name[1024];
5499             ast_expression *telem;
5500             ast_value      *tfield;
5501             ast_value      *array = (ast_value*)var->expression.next;
5502
5503             if (!ast_istype(var->expression.next, ast_value)) {
5504                 parseerror(parser, "internal error: field element type must be an ast_value");
5505                 goto cleanup;
5506             }
5507
5508             util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5509             if (!parser_create_array_field_setter(parser, array, name))
5510                 goto cleanup;
5511
5512             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5513             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5514             tfield->expression.next = telem;
5515             util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5516             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5517                 ast_delete(tfield);
5518                 goto cleanup;
5519             }
5520             ast_delete(tfield);
5521         }
5522
5523 skipvar:
5524         if (parser->tok == ';') {
5525             ast_delete(basetype);
5526             if (!parser_next(parser)) {
5527                 parseerror(parser, "error after variable declaration");
5528                 return false;
5529             }
5530             return true;
5531         }
5532
5533         if (parser->tok == ',')
5534             goto another;
5535
5536         /*
5537         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5538         */
5539         if (!var) {
5540             parseerror(parser, "missing comma or semicolon while parsing variables");
5541             break;
5542         }
5543
5544         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5545             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5546                              "initializing expression turns variable `%s` into a constant in this standard",
5547                              var->name) )
5548             {
5549                 break;
5550             }
5551         }
5552
5553         if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5554             if (parser->tok != '=') {
5555                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5556                 break;
5557             }
5558
5559             if (!parser_next(parser)) {
5560                 parseerror(parser, "error parsing initializer");
5561                 break;
5562             }
5563         }
5564         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5565             parseerror(parser, "expected '=' before function body in this standard");
5566         }
5567
5568         if (parser->tok == '#') {
5569             ast_function *func   = NULL;
5570             ast_value    *number = NULL;
5571             float         fractional;
5572             float         integral;
5573             int           builtin_num;
5574
5575             if (localblock) {
5576                 parseerror(parser, "cannot declare builtins within functions");
5577                 break;
5578             }
5579             if (var->expression.vtype != TYPE_FUNCTION) {
5580                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5581                 break;
5582             }
5583             if (!parser_next(parser)) {
5584                 parseerror(parser, "expected builtin number");
5585                 break;
5586             }
5587
5588             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5589                 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5590                 if (!number) {
5591                     parseerror(parser, "builtin number expected");
5592                     break;
5593                 }
5594                 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5595                 {
5596                     ast_unref(number);
5597                     parseerror(parser, "builtin number must be a compile time constant");
5598                     break;
5599                 }
5600                 if (number->expression.vtype == TYPE_INTEGER)
5601                     builtin_num = number->constval.vint;
5602                 else if (number->expression.vtype == TYPE_FLOAT)
5603                     builtin_num = number->constval.vfloat;
5604                 else {
5605                     ast_unref(number);
5606                     parseerror(parser, "builtin number must be an integer constant");
5607                     break;
5608                 }
5609                 ast_unref(number);
5610
5611                 fractional = modff(builtin_num, &integral);
5612                 if (builtin_num < 0 || fractional != 0) {
5613                     parseerror(parser, "builtin number must be an integer greater than zero");
5614                     break;
5615                 }
5616
5617                 /* we only want the integral part anyways */
5618                 builtin_num = integral;
5619             } else if (parser->tok == TOKEN_INTCONST) {
5620                 builtin_num = parser_token(parser)->constval.i;
5621             } else {
5622                 parseerror(parser, "builtin number must be a compile time constant");
5623                 break;
5624             }
5625
5626             if (var->hasvalue) {
5627                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5628                                     "builtin `%s` has already been defined\n"
5629                                     " -> previous declaration here: %s:%i",
5630                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5631             }
5632             else
5633             {
5634                 func = ast_function_new(ast_ctx(var), var->name, var);
5635                 if (!func) {
5636                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5637                     break;
5638                 }
5639                 vec_push(parser->functions, func);
5640
5641                 func->builtin = -builtin_num-1;
5642             }
5643
5644             if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5645                     ? (parser->tok != ',' && parser->tok != ';')
5646                     : (!parser_next(parser)))
5647             {
5648                 parseerror(parser, "expected comma or semicolon");
5649                 if (func)
5650                     ast_function_delete(func);
5651                 var->constval.vfunc = NULL;
5652                 break;
5653             }
5654         }
5655         else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5656         {
5657             if (localblock) {
5658                 /* Note that fteqcc and most others don't even *have*
5659                  * local arrays, so this is not a high priority.
5660                  */
5661                 parseerror(parser, "TODO: initializers for local arrays");
5662                 break;
5663             }
5664
5665             var->hasvalue = true;
5666             if (!parse_array(parser, var))
5667                 break;
5668         }
5669         else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5670         {
5671             if (localblock) {
5672                 parseerror(parser, "cannot declare functions within functions");
5673                 break;
5674             }
5675
5676             if (proto)
5677                 ast_ctx(proto) = parser_ctx(parser);
5678
5679             if (!parse_function_body(parser, var))
5680                 break;
5681             ast_delete(basetype);
5682             for (i = 0; i < vec_size(parser->gotos); ++i)
5683                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5684             vec_free(parser->gotos);
5685             vec_free(parser->labels);
5686             return true;
5687         } else {
5688             ast_expression *cexp;
5689             ast_value      *cval;
5690
5691             cexp = parse_expression_leave(parser, true, false, false);
5692             if (!cexp)
5693                 break;
5694
5695             if (!localblock) {
5696                 cval = (ast_value*)cexp;
5697                 if (cval != parser->nil &&
5698                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5699                    )
5700                 {
5701                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5702                 }
5703                 else
5704                 {
5705                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5706                         qualifier != CV_VAR)
5707                     {
5708                         var->cvq = CV_CONST;
5709                     }
5710                     if (cval == parser->nil)
5711                         var->expression.flags |= AST_FLAG_INITIALIZED;
5712                     else
5713                     {
5714                         var->hasvalue = true;
5715                         if (cval->expression.vtype == TYPE_STRING)
5716                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5717                         else if (cval->expression.vtype == TYPE_FIELD)
5718                             var->constval.vfield = cval;
5719                         else
5720                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5721                         ast_unref(cval);
5722                     }
5723                 }
5724             } else {
5725                 int cvq;
5726                 shunt sy = { NULL, NULL, NULL, NULL };
5727                 cvq = var->cvq;
5728                 var->cvq = CV_NONE;
5729                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5730                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5731                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5732                 if (!parser_sy_apply_operator(parser, &sy))
5733                     ast_unref(cexp);
5734                 else {
5735                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5736                         parseerror(parser, "internal error: leaked operands");
5737                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5738                         break;
5739                 }
5740                 vec_free(sy.out);
5741                 vec_free(sy.ops);
5742                 vec_free(sy.argc);
5743                 var->cvq = cvq;
5744             }
5745         }
5746
5747 another:
5748         if (parser->tok == ',') {
5749             if (!parser_next(parser)) {
5750                 parseerror(parser, "expected another variable");
5751                 break;
5752             }
5753
5754             if (parser->tok != TOKEN_IDENT) {
5755                 parseerror(parser, "expected another variable");
5756                 break;
5757             }
5758             var = ast_value_copy(basetype);
5759             cleanvar = true;
5760             ast_value_set_name(var, parser_tokval(parser));
5761             if (!parser_next(parser)) {
5762                 parseerror(parser, "error parsing variable declaration");
5763                 break;
5764             }
5765             continue;
5766         }
5767
5768         if (parser->tok != ';') {
5769             parseerror(parser, "missing semicolon after variables");
5770             break;
5771         }
5772
5773         if (!parser_next(parser)) {
5774             parseerror(parser, "parse error after variable declaration");
5775             break;
5776         }
5777
5778         ast_delete(basetype);
5779         return true;
5780     }
5781
5782     if (cleanvar && var)
5783         ast_delete(var);
5784     ast_delete(basetype);
5785     return false;
5786
5787 cleanup:
5788     ast_delete(basetype);
5789     if (cleanvar && var)
5790         ast_delete(var);
5791     if (me[0]) ast_member_delete(me[0]);
5792     if (me[1]) ast_member_delete(me[1]);
5793     if (me[2]) ast_member_delete(me[2]);
5794     return retval;
5795 }
5796
5797 static bool parser_global_statement(parser_t *parser)
5798 {
5799     int        cvq       = CV_WRONG;
5800     bool       noref     = false;
5801     bool       is_static = false;
5802     uint32_t   qflags    = 0;
5803     ast_value *istype    = NULL;
5804     char      *vstring   = NULL;
5805
5806     if (parser->tok == TOKEN_IDENT)
5807         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5808
5809     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5810     {
5811         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5812     }
5813     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5814     {
5815         if (cvq == CV_WRONG)
5816             return false;
5817         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5818     }
5819     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5820     {
5821         return parse_enum(parser);
5822     }
5823     else if (parser->tok == TOKEN_KEYWORD)
5824     {
5825         if (!strcmp(parser_tokval(parser), "typedef")) {
5826             if (!parser_next(parser)) {
5827                 parseerror(parser, "expected type definition after 'typedef'");
5828                 return false;
5829             }
5830             return parse_typedef(parser);
5831         }
5832         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5833         return false;
5834     }
5835     else if (parser->tok == '#')
5836     {
5837         return parse_pragma(parser);
5838     }
5839     else if (parser->tok == '$')
5840     {
5841         if (!parser_next(parser)) {
5842             parseerror(parser, "parse error");
5843             return false;
5844         }
5845     }
5846     else
5847     {
5848         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5849         return false;
5850     }
5851     return true;
5852 }
5853
5854 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5855 {
5856     return util_crc16(old, str, strlen(str));
5857 }
5858
5859 static void progdefs_crc_file(const char *str)
5860 {
5861     /* write to progdefs.h here */
5862     (void)str;
5863 }
5864
5865 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5866 {
5867     old = progdefs_crc_sum(old, str);
5868     progdefs_crc_file(str);
5869     return old;
5870 }
5871
5872 static void generate_checksum(parser_t *parser, ir_builder *ir)
5873 {
5874     uint16_t   crc = 0xFFFF;
5875     size_t     i;
5876     ast_value *value;
5877
5878     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5879     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5880     /*
5881     progdefs_crc_file("\tint\tpad;\n");
5882     progdefs_crc_file("\tint\tofs_return[3];\n");
5883     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5884     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5885     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5886     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5887     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5888     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5889     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5890     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5891     */
5892     for (i = 0; i < parser->crc_globals; ++i) {
5893         if (!ast_istype(parser->globals[i], ast_value))
5894             continue;
5895         value = (ast_value*)(parser->globals[i]);
5896         switch (value->expression.vtype) {
5897             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5898             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5899             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5900             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5901             default:
5902                 crc = progdefs_crc_both(crc, "\tint\t");
5903                 break;
5904         }
5905         crc = progdefs_crc_both(crc, value->name);
5906         crc = progdefs_crc_both(crc, ";\n");
5907     }
5908     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5909     for (i = 0; i < parser->crc_fields; ++i) {
5910         if (!ast_istype(parser->fields[i], ast_value))
5911             continue;
5912         value = (ast_value*)(parser->fields[i]);
5913         switch (value->expression.next->vtype) {
5914             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5915             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5916             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5917             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5918             default:
5919                 crc = progdefs_crc_both(crc, "\tint\t");
5920                 break;
5921         }
5922         crc = progdefs_crc_both(crc, value->name);
5923         crc = progdefs_crc_both(crc, ";\n");
5924     }
5925     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5926     ir->code->crc = crc;
5927 }
5928
5929 parser_t *parser_create()
5930 {
5931     parser_t *parser;
5932     lex_ctx_t empty_ctx;
5933     size_t i;
5934
5935     parser = (parser_t*)mem_a(sizeof(parser_t));
5936     if (!parser)
5937         return NULL;
5938
5939     memset(parser, 0, sizeof(*parser));
5940
5941     for (i = 0; i < operator_count; ++i) {
5942         if (operators[i].id == opid1('=')) {
5943             parser->assign_op = operators+i;
5944             break;
5945         }
5946     }
5947     if (!parser->assign_op) {
5948         con_err("internal error: initializing parser: failed to find assign operator\n");
5949         mem_d(parser);
5950         return NULL;
5951     }
5952
5953     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5954     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5955     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5956     vec_push(parser->_blocktypedefs, 0);
5957
5958     parser->aliases = util_htnew(PARSER_HT_SIZE);
5959
5960     /* corrector */
5961     vec_push(parser->correct_variables, correct_trie_new());
5962     vec_push(parser->correct_variables_score, NULL);
5963
5964     empty_ctx.file   = "<internal>";
5965     empty_ctx.line   = 0;
5966     empty_ctx.column = 0;
5967     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5968     parser->nil->cvq = CV_CONST;
5969     if (OPTS_FLAG(UNTYPED_NIL))
5970         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5971
5972     parser->max_param_count = 1;
5973
5974     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5975     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5976     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5977
5978     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5979         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5980         parser->reserved_version->cvq = CV_CONST;
5981         parser->reserved_version->hasvalue = true;
5982         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5983         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5984     } else {
5985         parser->reserved_version = NULL;
5986     }
5987
5988     parser->fold   = fold_init  (parser);
5989     parser->intrin = intrin_init(parser);
5990     return parser;
5991 }
5992
5993 static bool parser_compile(parser_t *parser)
5994 {
5995     /* initial lexer/parser state */
5996     parser->lex->flags.noops = true;
5997
5998     if (parser_next(parser))
5999     {
6000         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6001         {
6002             if (!parser_global_statement(parser)) {
6003                 if (parser->tok == TOKEN_EOF)
6004                     parseerror(parser, "unexpected end of file");
6005                 else if (compile_errors)
6006                     parseerror(parser, "there have been errors, bailing out");
6007                 lex_close(parser->lex);
6008                 parser->lex = NULL;
6009                 return false;
6010             }
6011         }
6012     } else {
6013         parseerror(parser, "parse error");
6014         lex_close(parser->lex);
6015         parser->lex = NULL;
6016         return false;
6017     }
6018
6019     lex_close(parser->lex);
6020     parser->lex = NULL;
6021
6022     return !compile_errors;
6023 }
6024
6025 bool parser_compile_file(parser_t *parser, const char *filename)
6026 {
6027     parser->lex = lex_open(filename);
6028     if (!parser->lex) {
6029         con_err("failed to open file \"%s\"\n", filename);
6030         return false;
6031     }
6032     return parser_compile(parser);
6033 }
6034
6035 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6036 {
6037     parser->lex = lex_open_string(str, len, name);
6038     if (!parser->lex) {
6039         con_err("failed to create lexer for string \"%s\"\n", name);
6040         return false;
6041     }
6042     return parser_compile(parser);
6043 }
6044
6045 static void parser_remove_ast(parser_t *parser)
6046 {
6047     size_t i;
6048     if (parser->ast_cleaned)
6049         return;
6050     parser->ast_cleaned = true;
6051     for (i = 0; i < vec_size(parser->accessors); ++i) {
6052         ast_delete(parser->accessors[i]->constval.vfunc);
6053         parser->accessors[i]->constval.vfunc = NULL;
6054         ast_delete(parser->accessors[i]);
6055     }
6056     for (i = 0; i < vec_size(parser->functions); ++i) {
6057         ast_delete(parser->functions[i]);
6058     }
6059     for (i = 0; i < vec_size(parser->fields); ++i) {
6060         ast_delete(parser->fields[i]);
6061     }
6062     for (i = 0; i < vec_size(parser->globals); ++i) {
6063         ast_delete(parser->globals[i]);
6064     }
6065     vec_free(parser->accessors);
6066     vec_free(parser->functions);
6067     vec_free(parser->globals);
6068     vec_free(parser->fields);
6069
6070     for (i = 0; i < vec_size(parser->variables); ++i)
6071         util_htdel(parser->variables[i]);
6072     vec_free(parser->variables);
6073     vec_free(parser->_blocklocals);
6074     vec_free(parser->_locals);
6075
6076     /* corrector */
6077     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6078         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6079     }
6080     vec_free(parser->correct_variables);
6081     vec_free(parser->correct_variables_score);
6082
6083     for (i = 0; i < vec_size(parser->_typedefs); ++i)
6084         ast_delete(parser->_typedefs[i]);
6085     vec_free(parser->_typedefs);
6086     for (i = 0; i < vec_size(parser->typedefs); ++i)
6087         util_htdel(parser->typedefs[i]);
6088     vec_free(parser->typedefs);
6089     vec_free(parser->_blocktypedefs);
6090
6091     vec_free(parser->_block_ctx);
6092
6093     vec_free(parser->labels);
6094     vec_free(parser->gotos);
6095     vec_free(parser->breaks);
6096     vec_free(parser->continues);
6097
6098     ast_value_delete(parser->nil);
6099
6100     ast_value_delete(parser->const_vec[0]);
6101     ast_value_delete(parser->const_vec[1]);
6102     ast_value_delete(parser->const_vec[2]);
6103
6104     if (parser->reserved_version)
6105         ast_value_delete(parser->reserved_version);
6106
6107     util_htdel(parser->aliases);
6108     fold_cleanup(parser->fold);
6109     intrin_cleanup(parser->intrin);
6110 }
6111
6112 void parser_cleanup(parser_t *parser)
6113 {
6114     parser_remove_ast(parser);
6115     mem_d(parser);
6116 }
6117
6118 bool parser_finish(parser_t *parser, const char *output)
6119 {
6120     size_t i;
6121     ir_builder *ir;
6122     bool retval = true;
6123
6124     if (compile_errors) {
6125         con_out("*** there were compile errors\n");
6126         return false;
6127     }
6128
6129     ir = ir_builder_new("gmqcc_out");
6130     if (!ir) {
6131         con_out("failed to allocate builder\n");
6132         return false;
6133     }
6134
6135     for (i = 0; i < vec_size(parser->fields); ++i) {
6136         ast_value *field;
6137         bool hasvalue;
6138         if (!ast_istype(parser->fields[i], ast_value))
6139             continue;
6140         field = (ast_value*)parser->fields[i];
6141         hasvalue = field->hasvalue;
6142         field->hasvalue = false;
6143         if (!ast_global_codegen((ast_value*)field, ir, true)) {
6144             con_out("failed to generate field %s\n", field->name);
6145             ir_builder_delete(ir);
6146             return false;
6147         }
6148         if (hasvalue) {
6149             ir_value *ifld;
6150             ast_expression *subtype;
6151             field->hasvalue = true;
6152             subtype = field->expression.next;
6153             ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6154             if (subtype->vtype == TYPE_FIELD)
6155                 ifld->fieldtype = subtype->next->vtype;
6156             else if (subtype->vtype == TYPE_FUNCTION)
6157                 ifld->outtype = subtype->next->vtype;
6158             (void)!ir_value_set_field(field->ir_v, ifld);
6159         }
6160     }
6161     for (i = 0; i < vec_size(parser->globals); ++i) {
6162         ast_value *asvalue;
6163         if (!ast_istype(parser->globals[i], ast_value))
6164             continue;
6165         asvalue = (ast_value*)(parser->globals[i]);
6166         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6167             retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6168                                                 "unused global: `%s`", asvalue->name);
6169         }
6170         if (!ast_global_codegen(asvalue, ir, false)) {
6171             con_out("failed to generate global %s\n", asvalue->name);
6172             ir_builder_delete(ir);
6173             return false;
6174         }
6175     }
6176     /* Build function vararg accessor ast tree now before generating
6177      * immediates, because the accessors may add new immediates
6178      */
6179     for (i = 0; i < vec_size(parser->functions); ++i) {
6180         ast_function *f = parser->functions[i];
6181         if (f->varargs) {
6182             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6183                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6184                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6185                     con_out("failed to generate vararg setter for %s\n", f->name);
6186                     ir_builder_delete(ir);
6187                     return false;
6188                 }
6189                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6190                     con_out("failed to generate vararg getter for %s\n", f->name);
6191                     ir_builder_delete(ir);
6192                     return false;
6193                 }
6194             } else {
6195                 ast_delete(f->varargs);
6196                 f->varargs = NULL;
6197             }
6198         }
6199     }
6200     /* Now we can generate immediates */
6201     if (!fold_generate(parser->fold, ir))
6202         return false;
6203
6204     for (i = 0; i < vec_size(parser->globals); ++i) {
6205         ast_value *asvalue;
6206         if (!ast_istype(parser->globals[i], ast_value))
6207             continue;
6208         asvalue = (ast_value*)(parser->globals[i]);
6209         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6210         {
6211             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6212                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6213                                        "uninitialized constant: `%s`",
6214                                        asvalue->name);
6215             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6216                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6217                                        "uninitialized global: `%s`",
6218                                        asvalue->name);
6219         }
6220         if (!ast_generate_accessors(asvalue, ir)) {
6221             ir_builder_delete(ir);
6222             return false;
6223         }
6224     }
6225     for (i = 0; i < vec_size(parser->fields); ++i) {
6226         ast_value *asvalue;
6227         asvalue = (ast_value*)(parser->fields[i]->next);
6228
6229         if (!ast_istype((ast_expression*)asvalue, ast_value))
6230             continue;
6231         if (asvalue->expression.vtype != TYPE_ARRAY)
6232             continue;
6233         if (!ast_generate_accessors(asvalue, ir)) {
6234             ir_builder_delete(ir);
6235             return false;
6236         }
6237     }
6238     if (parser->reserved_version &&
6239         !ast_global_codegen(parser->reserved_version, ir, false))
6240     {
6241         con_out("failed to generate reserved::version");
6242         ir_builder_delete(ir);
6243         return false;
6244     }
6245     for (i = 0; i < vec_size(parser->functions); ++i) {
6246         ast_function *f = parser->functions[i];
6247         if (!ast_function_codegen(f, ir)) {
6248             con_out("failed to generate function %s\n", f->name);
6249             ir_builder_delete(ir);
6250             return false;
6251         }
6252     }
6253
6254     generate_checksum(parser, ir);
6255
6256     if (OPTS_OPTION_BOOL(OPTION_DUMP))
6257         ir_builder_dump(ir, con_out);
6258     for (i = 0; i < vec_size(parser->functions); ++i) {
6259         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6260             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6261             ir_builder_delete(ir);
6262             return false;
6263         }
6264     }
6265     parser_remove_ast(parser);
6266
6267     if (compile_Werrors) {
6268         con_out("*** there were warnings treated as errors\n");
6269         compile_show_werrors();
6270         retval = false;
6271     }
6272
6273     if (retval) {
6274         if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6275             ir_builder_dump(ir, con_out);
6276
6277         if (!ir_builder_generate(ir, output)) {
6278             con_out("*** failed to generate output file\n");
6279             ir_builder_delete(ir);
6280             return false;
6281         }
6282     }
6283     ir_builder_delete(ir);
6284     return retval;
6285 }