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