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