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