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