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