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