]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Make the varargs counter more stable, it'll now work with a function pointer with...
[xonotic/gmqcc.git] / parser.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Wolfgang Bumiller
4  *     Dale Weiler
5  * 
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include <stdio.h>
25 #include <stdarg.h>
26
27 #include "gmqcc.h"
28 #include "lexer.h"
29 #include "ast.h"
30
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS  2
33
34 #define PARSER_HT_SIZE    128
35 #define TYPEDEF_HT_SIZE   16
36
37 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         return false;
1422
1423     if (fid+1 == vec_size(sy->out)) {
1424         /* no arguments */
1425         paramcount = 0;
1426     } else if (fid+2 == vec_size(sy->out)) {
1427         ast_block *params;
1428         vec_shrinkby(sy->out, 1);
1429         params = sy->out[vec_size(sy->out)].block;
1430         if (!params) {
1431             /* 1 param */
1432             paramcount = 1;
1433             vec_push(call->params, sy->out[vec_size(sy->out)].out);
1434         } else {
1435             paramcount = vec_size(params->exprs);
1436             call->params = params->exprs;
1437             params->exprs = NULL;
1438             ast_delete(params);
1439         }
1440         if (parser->max_param_count < paramcount)
1441             parser->max_param_count = paramcount;
1442         (void)!ast_call_check_types(call);
1443     } else {
1444         parseerror(parser, "invalid function call");
1445         return false;
1446     }
1447
1448     if (ast_istype(fun, ast_value)) {
1449         funval = (ast_value*)fun;
1450         if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1451             !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1452         {
1453             call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1454         }
1455     }
1456
1457     /* overwrite fid, the function, with a call */
1458     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1459
1460     if (fun->expression.vtype != TYPE_FUNCTION) {
1461         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1462         return false;
1463     }
1464
1465     if (!fun->expression.next) {
1466         parseerror(parser, "could not determine function return type");
1467         return false;
1468     } else {
1469         ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1470
1471         if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1472             if (!fval) {
1473                 return !parsewarning(parser, WARN_DEPRECATED,
1474                         "call to function (which is marked deprecated)\n",
1475                         "-> it has been declared here: %s:%i",
1476                         ast_ctx(fun).file, ast_ctx(fun).line);
1477             }
1478             if (!fval->desc) {
1479                 return !parsewarning(parser, WARN_DEPRECATED,
1480                         "call to `%s` (which is marked deprecated)\n"
1481                         "-> `%s` declared here: %s:%i",
1482                         fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1483             }
1484             return !parsewarning(parser, WARN_DEPRECATED,
1485                     "call to `%s` (deprecated: %s)\n"
1486                     "-> `%s` declared here: %s:%i",
1487                     fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1488                     ast_ctx(fun).line);
1489         }
1490
1491         if (vec_size(fun->expression.params) != paramcount &&
1492             !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1493               vec_size(fun->expression.params) < paramcount))
1494         {
1495             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1496             if (fval)
1497                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1498                                      "too %s parameters for call to %s: expected %i, got %i\n"
1499                                      " -> `%s` has been declared here: %s:%i",
1500                                      fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1501                                      fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1502             else
1503                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1504                                      "too %s parameters for function call: expected %i, got %i\n"
1505                                      " -> it has been declared here: %s:%i",
1506                                      fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1507                                      ast_ctx(fun).file, (int)ast_ctx(fun).line);
1508         }
1509     }
1510
1511     return true;
1512 }
1513
1514 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1515 {
1516     if (!vec_size(sy->ops)) {
1517         parseerror(parser, "unmatched closing paren");
1518         return false;
1519     }
1520     /* this would for bit a + (x) because there are no operators inside (x)
1521     if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1522         parseerror(parser, "empty parenthesis expression");
1523         return false;
1524     }
1525     */
1526     while (vec_size(sy->ops)) {
1527         if (vec_last(sy->ops).paren == SY_PAREN_FUNC) {
1528             if (!parser_close_call(parser, sy))
1529                 return false;
1530             break;
1531         }
1532         if (vec_last(sy->ops).paren == SY_PAREN_EXPR) {
1533             if (!vec_size(sy->out)) {
1534                 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1535                 vec_shrinkby(sy->ops, 1);
1536                 return false;
1537             }
1538             vec_shrinkby(sy->ops, 1);
1539             return !functions_only;
1540         }
1541         if (vec_last(sy->ops).paren == SY_PAREN_INDEX) {
1542             if (functions_only)
1543                 return false;
1544             /* pop off the parenthesis */
1545             vec_shrinkby(sy->ops, 1);
1546             /* then apply the index operator */
1547             if (!parser_sy_apply_operator(parser, sy))
1548                 return false;
1549             return true;
1550         }
1551         if (vec_last(sy->ops).paren == SY_PAREN_TERNARY) {
1552             if (functions_only)
1553                 return false;
1554             if (vec_last(parser->pot) != POT_TERNARY1) {
1555                 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1556                 return false;
1557             }
1558             vec_last(parser->pot) = POT_TERNARY2;
1559             /* pop off the parenthesis */
1560             vec_shrinkby(sy->ops, 1);
1561             return true;
1562         }
1563         if (!parser_sy_apply_operator(parser, sy))
1564             return false;
1565     }
1566     return true;
1567 }
1568
1569 static void parser_reclassify_token(parser_t *parser)
1570 {
1571     size_t i;
1572     for (i = 0; i < operator_count; ++i) {
1573         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1574             parser->tok = TOKEN_OPERATOR;
1575             return;
1576         }
1577     }
1578 }
1579
1580 static ast_expression* parse_vararg_do(parser_t *parser)
1581 {
1582     ast_expression *idx, *out;
1583     ast_value      *typevar;
1584     ast_value      *funtype = parser->function->vtype;
1585
1586     lex_ctx ctx = parser_ctx(parser);
1587
1588     if (!parser_next(parser) || parser->tok != '(') {
1589         parseerror(parser, "expected parameter index and type in parenthesis");
1590         return NULL;
1591     }
1592     if (!parser_next(parser)) {
1593         parseerror(parser, "error parsing parameter index");
1594         return NULL;
1595     }
1596
1597     idx = parse_expression_leave(parser, true, false, false);
1598     if (!idx)
1599         return NULL;
1600
1601     if (parser->tok != ',') {
1602         ast_unref(idx);
1603         parseerror(parser, "expected comma after parameter index");
1604         return NULL;
1605     }
1606
1607     if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1608         ast_unref(idx);
1609         parseerror(parser, "expected typename for vararg");
1610         return NULL;
1611     }
1612
1613     typevar = parse_typename(parser, NULL, NULL);
1614     if (!typevar) {
1615         ast_unref(idx);
1616         return NULL;
1617     }
1618
1619     if (parser->tok != ')') {
1620         ast_unref(idx);
1621         ast_delete(typevar);
1622         parseerror(parser, "expected closing paren");
1623         return NULL;
1624     }
1625
1626 #if 0
1627     if (!parser_next(parser)) {
1628         ast_unref(idx);
1629         ast_delete(typevar);
1630         parseerror(parser, "parse error after vararg");
1631         return NULL;
1632     }
1633 #endif
1634
1635     if (!parser->function->varargs) {
1636         ast_unref(idx);
1637         ast_delete(typevar);
1638         parseerror(parser, "function has no variable argument list");
1639         return NULL;
1640     }
1641
1642     if (funtype->expression.varparam &&
1643         !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1644     {
1645         char ty1[1024];
1646         char ty2[1024];
1647         ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1648         ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1649         compile_error(ast_ctx(typevar),
1650                       "function was declared to take varargs of type `%s`, requested type is: %s",
1651                       ty2, ty1);
1652     }
1653
1654     out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1655     ast_type_adopt(out, typevar);
1656     ast_delete(typevar);
1657     return out;
1658 }
1659
1660 static ast_expression* parse_vararg(parser_t *parser)
1661 {
1662     bool             old_noops = parser->lex->flags.noops;
1663     enum parser_pot *old_pot   = parser->pot;
1664
1665     ast_expression *out;
1666
1667     parser->pot = NULL;
1668     parser->lex->flags.noops = true;
1669     out = parse_vararg_do(parser);
1670
1671     parser->pot              = old_pot;
1672     parser->lex->flags.noops = old_noops;
1673     return out;
1674 }
1675
1676 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1677 {
1678     ast_expression *expr = NULL;
1679     shunt sy;
1680     size_t i;
1681     bool wantop = false;
1682     /* only warn once about an assignment in a truth value because the current code
1683      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1684      */
1685     bool warn_truthvalue = true;
1686
1687     /* count the parens because an if starts with one, so the
1688      * end of a condition is an unmatched closing paren
1689      */
1690     int parens = 0;
1691     int ternaries = 0;
1692
1693     sy.out = NULL;
1694     sy.ops = NULL;
1695
1696     parser->lex->flags.noops = false;
1697
1698     parser_reclassify_token(parser);
1699
1700     while (true)
1701     {
1702         if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1703             parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1704         {
1705             /* a translatable string */
1706             ast_value *val;
1707
1708             if (wantop) {
1709                 parseerror(parser, "expected operator or end of statement, got constant");
1710                 goto onerr;
1711             }
1712
1713             parser->lex->flags.noops = true;
1714             if (!parser_next(parser) || parser->tok != '(') {
1715                 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1716                 goto onerr;
1717             }
1718             parser->lex->flags.noops = false;
1719             if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1720                 parseerror(parser, "expected a constant string in translatable-string extension");
1721                 goto onerr;
1722             }
1723             val = parser_const_string(parser, parser_tokval(parser), true);
1724             wantop = true;
1725             if (!val)
1726                 return NULL;
1727             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1728             DEBUGSHUNTDO(con_out("push string\n"));
1729
1730             if (!parser_next(parser) || parser->tok != ')') {
1731                 parseerror(parser, "expected closing paren after translatable string");
1732                 goto onerr;
1733             }
1734         }
1735         else if (parser->tok == TOKEN_DOTS)
1736         {
1737             ast_expression *va;
1738             if (!OPTS_FLAG(VARIADIC_ARGS)) {
1739                 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1740                 goto onerr;
1741             }
1742             if (wantop) {
1743                 parseerror(parser, "expected operator or end of statement");
1744                 goto onerr;
1745             }
1746             wantop = true;
1747             va = parse_vararg(parser);
1748             if (!va)
1749                 goto onerr;
1750             vec_push(sy.out, syexp(parser_ctx(parser), va));
1751             DEBUGSHUNTDO(con_out("push `...`\n"));
1752         }
1753         else if (parser->tok == TOKEN_IDENT)
1754         {
1755             const char     *ctoken = parser_tokval(parser);
1756             ast_expression *prev = vec_size(sy.out) ? vec_last(sy.out).out : NULL;
1757             ast_expression *var;
1758             if (wantop) {
1759                 parseerror(parser, "expected operator or end of statement");
1760                 goto onerr;
1761             }
1762             wantop = true;
1763             /* a_vector.{x,y,z} */
1764             if (!vec_size(sy.ops) ||
1765                 !vec_last(sy.ops).etype ||
1766                 operators[vec_last(sy.ops).etype-1].id != opid1('.') ||
1767                 (prev >= intrinsic_debug_typestring &&
1768                  prev <= intrinsic_debug_typestring))
1769             {
1770                 /* When adding more intrinsics, fix the above condition */
1771                 prev = NULL;
1772             }
1773             if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1774             {
1775                 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1776             } else {
1777                 var = parser_find_var(parser, parser_tokval(parser));
1778                 if (!var)
1779                     var = parser_find_field(parser, parser_tokval(parser));
1780             }
1781             if (!var && with_labels) {
1782                 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1783                 if (!with_labels) {
1784                     ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1785                     var = (ast_expression*)lbl;
1786                     vec_push(parser->labels, lbl);
1787                 }
1788             }
1789             if (!var) {
1790                 /* intrinsics */
1791                 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1792                     var = (ast_expression*)intrinsic_debug_typestring;
1793                 }
1794                 else
1795                 {
1796                     char *correct = NULL;
1797
1798                     /*
1799                      * sometimes people use preprocessing predefs without enabling them
1800                      * i've done this thousands of times already myself.  Lets check for
1801                      * it in the predef table.  And diagnose it better :)
1802                      */
1803                     if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1804                         for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1805                             if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1806                                 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1807                                 goto onerr;
1808                             }
1809                         }
1810                     }
1811
1812                     /*
1813                      * TODO: determine the best score for the identifier: be it
1814                      * a variable, a field.
1815                      *
1816                      * We should also consider adding correction tables for
1817                      * other things as well.
1818                      */
1819                     if (opts.correction) {
1820                         correction_t corr;
1821                         correct_init(&corr);
1822
1823                         for (i = 0; i < vec_size(parser->correct_variables); i++) {
1824                             correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1825                             if (strcmp(correct, parser_tokval(parser))) {
1826                                 break;
1827                             } else if (correct) {
1828                                 mem_d(correct);
1829                                 correct = NULL;
1830                             }
1831                         }
1832                         correct_free(&corr);
1833
1834                         if (correct) {
1835                             parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1836                             mem_d(correct);
1837                             goto onerr;
1838                         }
1839                     }
1840                     parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1841                     goto onerr;
1842                 }
1843             }
1844             else
1845             {
1846                 if (ast_istype(var, ast_value)) {
1847                     ((ast_value*)var)->uses++;
1848                 }
1849                 else if (ast_istype(var, ast_member)) {
1850                     ast_member *mem = (ast_member*)var;
1851                     if (ast_istype(mem->owner, ast_value))
1852                         ((ast_value*)(mem->owner))->uses++;
1853                 }
1854             }
1855             vec_push(sy.out, syexp(parser_ctx(parser), var));
1856             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1857         }
1858         else if (parser->tok == TOKEN_FLOATCONST) {
1859             ast_value *val;
1860             if (wantop) {
1861                 parseerror(parser, "expected operator or end of statement, got constant");
1862                 goto onerr;
1863             }
1864             wantop = true;
1865             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1866             if (!val)
1867                 return NULL;
1868             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1869             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1870         }
1871         else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1872             ast_value *val;
1873             if (wantop) {
1874                 parseerror(parser, "expected operator or end of statement, got constant");
1875                 goto onerr;
1876             }
1877             wantop = true;
1878             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1879             if (!val)
1880                 return NULL;
1881             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1882             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1883         }
1884         else if (parser->tok == TOKEN_STRINGCONST) {
1885             ast_value *val;
1886             if (wantop) {
1887                 parseerror(parser, "expected operator or end of statement, got constant");
1888                 goto onerr;
1889             }
1890             wantop = true;
1891             val = parser_const_string(parser, parser_tokval(parser), false);
1892             if (!val)
1893                 return NULL;
1894             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1895             DEBUGSHUNTDO(con_out("push string\n"));
1896         }
1897         else if (parser->tok == TOKEN_VECTORCONST) {
1898             ast_value *val;
1899             if (wantop) {
1900                 parseerror(parser, "expected operator or end of statement, got constant");
1901                 goto onerr;
1902             }
1903             wantop = true;
1904             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1905             if (!val)
1906                 return NULL;
1907             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1908             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1909                                 parser_token(parser)->constval.v.x,
1910                                 parser_token(parser)->constval.v.y,
1911                                 parser_token(parser)->constval.v.z));
1912         }
1913         else if (parser->tok == '(') {
1914             parseerror(parser, "internal error: '(' should be classified as operator");
1915             goto onerr;
1916         }
1917         else if (parser->tok == '[') {
1918             parseerror(parser, "internal error: '[' should be classified as operator");
1919             goto onerr;
1920         }
1921         else if (parser->tok == ')') {
1922             if (wantop) {
1923                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1924                 --parens;
1925                 if (parens < 0)
1926                     break;
1927                 /* we do expect an operator next */
1928                 /* closing an opening paren */
1929                 if (!parser_close_paren(parser, &sy, false))
1930                     goto onerr;
1931                 if (vec_last(parser->pot) != POT_PAREN) {
1932                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1933                     goto onerr;
1934                 }
1935                 vec_pop(parser->pot);
1936             } else {
1937                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1938                 --parens;
1939                 if (parens < 0)
1940                     break;
1941                 /* allowed for function calls */
1942                 if (!parser_close_paren(parser, &sy, true))
1943                     goto onerr;
1944                 if (vec_last(parser->pot) != POT_PAREN) {
1945                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1946                     goto onerr;
1947                 }
1948                 vec_pop(parser->pot);
1949             }
1950             wantop = true;
1951         }
1952         else if (parser->tok == ']') {
1953             if (!wantop)
1954                 parseerror(parser, "operand expected");
1955             --parens;
1956             if (parens < 0)
1957                 break;
1958             if (!parser_close_paren(parser, &sy, false))
1959                 goto onerr;
1960             if (vec_last(parser->pot) != POT_PAREN) {
1961                 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1962                 goto onerr;
1963             }
1964             vec_pop(parser->pot);
1965             wantop = true;
1966         }
1967         else if (parser->tok == TOKEN_TYPENAME) {
1968             parseerror(parser, "unexpected typename");
1969             goto onerr;
1970         }
1971         else if (parser->tok != TOKEN_OPERATOR) {
1972             if (wantop) {
1973                 parseerror(parser, "expected operator or end of statement");
1974                 goto onerr;
1975             }
1976             break;
1977         }
1978         else
1979         {
1980             /* classify the operator */
1981             const oper_info *op;
1982             const oper_info *olast = NULL;
1983             size_t o;
1984             for (o = 0; o < operator_count; ++o) {
1985                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1986                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1987                     !strcmp(parser_tokval(parser), operators[o].op))
1988                 {
1989                     break;
1990                 }
1991             }
1992             if (o == operator_count) {
1993                 /* no operator found... must be the end of the statement */
1994                 break;
1995             }
1996             /* found an operator */
1997             op = &operators[o];
1998
1999             /* when declaring variables, a comma starts a new variable */
2000             if (op->id == opid1(',') && !parens && stopatcomma) {
2001                 /* fixup the token */
2002                 parser->tok = ',';
2003                 break;
2004             }
2005
2006             /* a colon without a pervious question mark cannot be a ternary */
2007             if (!ternaries && op->id == opid2(':','?')) {
2008                 parser->tok = ':';
2009                 break;
2010             }
2011
2012             if (op->id == opid1(',')) {
2013                 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
2014                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2015                 }
2016             }
2017
2018             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
2019                 olast = &operators[vec_last(sy.ops).etype-1];
2020
2021 #define IsAssignOp(x) (\
2022                 (x) == opid1('=') || \
2023                 (x) == opid2('+','=') || \
2024                 (x) == opid2('-','=') || \
2025                 (x) == opid2('*','=') || \
2026                 (x) == opid2('/','=') || \
2027                 (x) == opid2('%','=') || \
2028                 (x) == opid2('&','=') || \
2029                 (x) == opid2('|','=') || \
2030                 (x) == opid3('&','~','=') \
2031                 )
2032             if (warn_truthvalue) {
2033                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2034                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2035                      (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
2036                    )
2037                 {
2038                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2039                     warn_truthvalue = false;
2040                 }
2041             }
2042
2043             while (olast && (
2044                     (op->prec < olast->prec) ||
2045                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2046             {
2047                 if (!parser_sy_apply_operator(parser, &sy))
2048                     goto onerr;
2049                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
2050                     olast = &operators[vec_last(sy.ops).etype-1];
2051                 else
2052                     olast = NULL;
2053             }
2054
2055             if (op->id == opid1('(')) {
2056                 if (wantop) {
2057                     size_t sycount = vec_size(sy.out);
2058                     DEBUGSHUNTDO(con_out("push [op] (\n"));
2059                     ++parens; vec_push(parser->pot, POT_PAREN);
2060                     /* we expected an operator, this is the function-call operator */
2061                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
2062                 } else {
2063                     ++parens; vec_push(parser->pot, POT_PAREN);
2064                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
2065                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
2066                 }
2067                 wantop = false;
2068             } else if (op->id == opid1('[')) {
2069                 if (!wantop) {
2070                     parseerror(parser, "unexpected array subscript");
2071                     goto onerr;
2072                 }
2073                 ++parens; vec_push(parser->pot, POT_PAREN);
2074                 /* push both the operator and the paren, this makes life easier */
2075                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2076                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
2077                 wantop = false;
2078             } else if (op->id == opid2('?',':')) {
2079                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2080                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
2081                 wantop = false;
2082                 ++ternaries;
2083                 vec_push(parser->pot, POT_TERNARY1);
2084             } else if (op->id == opid2(':','?')) {
2085                 if (!vec_size(parser->pot)) {
2086                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2087                     goto onerr;
2088                 }
2089                 if (vec_last(parser->pot) != POT_TERNARY1) {
2090                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2091                     goto onerr;
2092                 }
2093                 if (!parser_close_paren(parser, &sy, false))
2094                     goto onerr;
2095                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2096                 wantop = false;
2097                 --ternaries;
2098             } else {
2099                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
2100                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2101                 wantop = !!(op->flags & OP_SUFFIX);
2102             }
2103         }
2104         if (!parser_next(parser)) {
2105             goto onerr;
2106         }
2107         if (parser->tok == ';' ||
2108             (!parens && (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2109         {
2110             break;
2111         }
2112     }
2113
2114     while (vec_size(sy.ops)) {
2115         if (!parser_sy_apply_operator(parser, &sy))
2116             goto onerr;
2117     }
2118
2119     parser->lex->flags.noops = true;
2120     if (!vec_size(sy.out)) {
2121         parseerror(parser, "empty expression");
2122         expr = NULL;
2123     } else
2124         expr = sy.out[0].out;
2125     vec_free(sy.out);
2126     vec_free(sy.ops);
2127     DEBUGSHUNTDO(con_out("shunt done\n"));
2128     if (vec_size(parser->pot)) {
2129         parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
2130         return NULL;
2131     }
2132     vec_free(parser->pot);
2133     return expr;
2134
2135 onerr:
2136     parser->lex->flags.noops = true;
2137     for (i = 0; i < vec_size(sy.out); ++i) {
2138         if (sy.out[i].out)
2139             ast_unref(sy.out[i].out);
2140     }
2141     vec_free(sy.out);
2142     vec_free(sy.ops);
2143     return NULL;
2144 }
2145
2146 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2147 {
2148     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2149     if (!e)
2150         return NULL;
2151     if (parser->tok != ';') {
2152         parseerror(parser, "semicolon expected after expression");
2153         ast_unref(e);
2154         return NULL;
2155     }
2156     if (!parser_next(parser)) {
2157         ast_unref(e);
2158         return NULL;
2159     }
2160     return e;
2161 }
2162
2163 static void parser_enterblock(parser_t *parser)
2164 {
2165     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2166     vec_push(parser->_blocklocals, vec_size(parser->_locals));
2167     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2168     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2169     vec_push(parser->_block_ctx, parser_ctx(parser));
2170
2171     /* corrector */
2172     vec_push(parser->correct_variables, correct_trie_new());
2173     vec_push(parser->correct_variables_score, NULL);
2174 }
2175
2176 static bool parser_leaveblock(parser_t *parser)
2177 {
2178     bool   rv = true;
2179     size_t locals, typedefs;
2180
2181     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2182         parseerror(parser, "internal error: parser_leaveblock with no block");
2183         return false;
2184     }
2185
2186     util_htdel(vec_last(parser->variables));
2187     correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2188
2189     vec_pop(parser->variables);
2190     vec_pop(parser->correct_variables);
2191     vec_pop(parser->correct_variables_score);
2192     if (!vec_size(parser->_blocklocals)) {
2193         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2194         return false;
2195     }
2196
2197     locals = vec_last(parser->_blocklocals);
2198     vec_pop(parser->_blocklocals);
2199     while (vec_size(parser->_locals) != locals) {
2200         ast_expression *e = vec_last(parser->_locals);
2201         ast_value      *v = (ast_value*)e;
2202         vec_pop(parser->_locals);
2203         if (ast_istype(e, ast_value) && !v->uses) {
2204             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2205                 rv = false;
2206         }
2207     }
2208
2209     typedefs = vec_last(parser->_blocktypedefs);
2210     while (vec_size(parser->_typedefs) != typedefs) {
2211         ast_delete(vec_last(parser->_typedefs));
2212         vec_pop(parser->_typedefs);
2213     }
2214     util_htdel(vec_last(parser->typedefs));
2215     vec_pop(parser->typedefs);
2216
2217     vec_pop(parser->_block_ctx);
2218
2219     return rv;
2220 }
2221
2222 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2223 {
2224     vec_push(parser->_locals, e);
2225     util_htset(vec_last(parser->variables), name, (void*)e);
2226
2227     /* corrector */
2228     correct_add (
2229          vec_last(parser->correct_variables),
2230         &vec_last(parser->correct_variables_score),
2231         name
2232     );
2233 }
2234
2235 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2236 {
2237     vec_push(parser->globals, e);
2238     util_htset(parser->htglobals, name, e);
2239
2240     /* corrector */
2241     correct_add (
2242          parser->correct_variables[0],
2243         &parser->correct_variables_score[0],
2244         name
2245     );
2246 }
2247
2248 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2249 {
2250     bool       ifnot = false;
2251     ast_unary *unary;
2252     ast_expression *prev;
2253
2254     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2255     {
2256         prev = cond;
2257         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2258         if (!cond) {
2259             ast_unref(prev);
2260             parseerror(parser, "internal error: failed to process condition");
2261             return NULL;
2262         }
2263         ifnot = !ifnot;
2264     }
2265     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2266     {
2267         /* vector types need to be cast to true booleans */
2268         ast_binary *bin = (ast_binary*)cond;
2269         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2270         {
2271             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2272             prev = cond;
2273             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2274             if (!cond) {
2275                 ast_unref(prev);
2276                 parseerror(parser, "internal error: failed to process condition");
2277                 return NULL;
2278             }
2279             ifnot = !ifnot;
2280         }
2281     }
2282
2283     unary = (ast_unary*)cond;
2284     while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2285     {
2286         cond = unary->operand;
2287         unary->operand = NULL;
2288         ast_delete(unary);
2289         ifnot = !ifnot;
2290         unary = (ast_unary*)cond;
2291     }
2292
2293     if (!cond)
2294         parseerror(parser, "internal error: failed to process condition");
2295
2296     if (ifnot) *_ifnot = !*_ifnot;
2297     return cond;
2298 }
2299
2300 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2301 {
2302     ast_ifthen *ifthen;
2303     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2304     bool ifnot = false;
2305
2306     lex_ctx ctx = parser_ctx(parser);
2307
2308     (void)block; /* not touching */
2309
2310     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2311     if (!parser_next(parser)) {
2312         parseerror(parser, "expected condition or 'not'");
2313         return false;
2314     }
2315     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2316         ifnot = true;
2317         if (!parser_next(parser)) {
2318             parseerror(parser, "expected condition in parenthesis");
2319             return false;
2320         }
2321     }
2322     if (parser->tok != '(') {
2323         parseerror(parser, "expected 'if' condition in parenthesis");
2324         return false;
2325     }
2326     /* parse into the expression */
2327     if (!parser_next(parser)) {
2328         parseerror(parser, "expected 'if' condition after opening paren");
2329         return false;
2330     }
2331     /* parse the condition */
2332     cond = parse_expression_leave(parser, false, true, false);
2333     if (!cond)
2334         return false;
2335     /* closing paren */
2336     if (parser->tok != ')') {
2337         parseerror(parser, "expected closing paren after 'if' condition");
2338         ast_delete(cond);
2339         return false;
2340     }
2341     /* parse into the 'then' branch */
2342     if (!parser_next(parser)) {
2343         parseerror(parser, "expected statement for on-true branch of 'if'");
2344         ast_delete(cond);
2345         return false;
2346     }
2347     if (!parse_statement_or_block(parser, &ontrue)) {
2348         ast_delete(cond);
2349         return false;
2350     }
2351     if (!ontrue)
2352         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2353     /* check for an else */
2354     if (!strcmp(parser_tokval(parser), "else")) {
2355         /* parse into the 'else' branch */
2356         if (!parser_next(parser)) {
2357             parseerror(parser, "expected on-false branch after 'else'");
2358             ast_delete(ontrue);
2359             ast_delete(cond);
2360             return false;
2361         }
2362         if (!parse_statement_or_block(parser, &onfalse)) {
2363             ast_delete(ontrue);
2364             ast_delete(cond);
2365             return false;
2366         }
2367     }
2368
2369     cond = process_condition(parser, cond, &ifnot);
2370     if (!cond) {
2371         if (ontrue)  ast_delete(ontrue);
2372         if (onfalse) ast_delete(onfalse);
2373         return false;
2374     }
2375
2376     if (ifnot)
2377         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2378     else
2379         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2380     *out = (ast_expression*)ifthen;
2381     return true;
2382 }
2383
2384 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2385 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2386 {
2387     bool rv;
2388     char *label = NULL;
2389
2390     /* skip the 'while' and get the body */
2391     if (!parser_next(parser)) {
2392         if (OPTS_FLAG(LOOP_LABELS))
2393             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2394         else
2395             parseerror(parser, "expected 'while' condition in parenthesis");
2396         return false;
2397     }
2398
2399     if (parser->tok == ':') {
2400         if (!OPTS_FLAG(LOOP_LABELS))
2401             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2402         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2403             parseerror(parser, "expected loop label");
2404             return false;
2405         }
2406         label = util_strdup(parser_tokval(parser));
2407         if (!parser_next(parser)) {
2408             mem_d(label);
2409             parseerror(parser, "expected 'while' condition in parenthesis");
2410             return false;
2411         }
2412     }
2413
2414     if (parser->tok != '(') {
2415         parseerror(parser, "expected 'while' condition in parenthesis");
2416         return false;
2417     }
2418
2419     vec_push(parser->breaks, label);
2420     vec_push(parser->continues, label);
2421
2422     rv = parse_while_go(parser, block, out);
2423     if (label)
2424         mem_d(label);
2425     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2426         parseerror(parser, "internal error: label stack corrupted");
2427         rv = false;
2428         ast_delete(*out);
2429         *out = NULL;
2430     }
2431     else {
2432         vec_pop(parser->breaks);
2433         vec_pop(parser->continues);
2434     }
2435     return rv;
2436 }
2437
2438 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2439 {
2440     ast_loop *aloop;
2441     ast_expression *cond, *ontrue;
2442
2443     bool ifnot = false;
2444
2445     lex_ctx ctx = parser_ctx(parser);
2446
2447     (void)block; /* not touching */
2448
2449     /* parse into the expression */
2450     if (!parser_next(parser)) {
2451         parseerror(parser, "expected 'while' condition after opening paren");
2452         return false;
2453     }
2454     /* parse the condition */
2455     cond = parse_expression_leave(parser, false, true, false);
2456     if (!cond)
2457         return false;
2458     /* closing paren */
2459     if (parser->tok != ')') {
2460         parseerror(parser, "expected closing paren after 'while' condition");
2461         ast_delete(cond);
2462         return false;
2463     }
2464     /* parse into the 'then' branch */
2465     if (!parser_next(parser)) {
2466         parseerror(parser, "expected while-loop body");
2467         ast_delete(cond);
2468         return false;
2469     }
2470     if (!parse_statement_or_block(parser, &ontrue)) {
2471         ast_delete(cond);
2472         return false;
2473     }
2474
2475     cond = process_condition(parser, cond, &ifnot);
2476     if (!cond) {
2477         ast_delete(ontrue);
2478         return false;
2479     }
2480     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2481     *out = (ast_expression*)aloop;
2482     return true;
2483 }
2484
2485 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2486 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2487 {
2488     bool rv;
2489     char *label = NULL;
2490
2491     /* skip the 'do' and get the body */
2492     if (!parser_next(parser)) {
2493         if (OPTS_FLAG(LOOP_LABELS))
2494             parseerror(parser, "expected loop label or body");
2495         else
2496             parseerror(parser, "expected loop body");
2497         return false;
2498     }
2499
2500     if (parser->tok == ':') {
2501         if (!OPTS_FLAG(LOOP_LABELS))
2502             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2503         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2504             parseerror(parser, "expected loop label");
2505             return false;
2506         }
2507         label = util_strdup(parser_tokval(parser));
2508         if (!parser_next(parser)) {
2509             mem_d(label);
2510             parseerror(parser, "expected loop body");
2511             return false;
2512         }
2513     }
2514
2515     vec_push(parser->breaks, label);
2516     vec_push(parser->continues, label);
2517
2518     rv = parse_dowhile_go(parser, block, out);
2519     if (label)
2520         mem_d(label);
2521     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2522         parseerror(parser, "internal error: label stack corrupted");
2523         rv = false;
2524         ast_delete(*out);
2525         *out = NULL;
2526     }
2527     else {
2528         vec_pop(parser->breaks);
2529         vec_pop(parser->continues);
2530     }
2531     return rv;
2532 }
2533
2534 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2535 {
2536     ast_loop *aloop;
2537     ast_expression *cond, *ontrue;
2538
2539     bool ifnot = false;
2540
2541     lex_ctx ctx = parser_ctx(parser);
2542
2543     (void)block; /* not touching */
2544
2545     if (!parse_statement_or_block(parser, &ontrue))
2546         return false;
2547
2548     /* expect the "while" */
2549     if (parser->tok != TOKEN_KEYWORD ||
2550         strcmp(parser_tokval(parser), "while"))
2551     {
2552         parseerror(parser, "expected 'while' and condition");
2553         ast_delete(ontrue);
2554         return false;
2555     }
2556
2557     /* skip the 'while' and check for opening paren */
2558     if (!parser_next(parser) || parser->tok != '(') {
2559         parseerror(parser, "expected 'while' condition in parenthesis");
2560         ast_delete(ontrue);
2561         return false;
2562     }
2563     /* parse into the expression */
2564     if (!parser_next(parser)) {
2565         parseerror(parser, "expected 'while' condition after opening paren");
2566         ast_delete(ontrue);
2567         return false;
2568     }
2569     /* parse the condition */
2570     cond = parse_expression_leave(parser, false, true, false);
2571     if (!cond)
2572         return false;
2573     /* closing paren */
2574     if (parser->tok != ')') {
2575         parseerror(parser, "expected closing paren after 'while' condition");
2576         ast_delete(ontrue);
2577         ast_delete(cond);
2578         return false;
2579     }
2580     /* parse on */
2581     if (!parser_next(parser) || parser->tok != ';') {
2582         parseerror(parser, "expected semicolon after condition");
2583         ast_delete(ontrue);
2584         ast_delete(cond);
2585         return false;
2586     }
2587
2588     if (!parser_next(parser)) {
2589         parseerror(parser, "parse error");
2590         ast_delete(ontrue);
2591         ast_delete(cond);
2592         return false;
2593     }
2594
2595     cond = process_condition(parser, cond, &ifnot);
2596     if (!cond) {
2597         ast_delete(ontrue);
2598         return false;
2599     }
2600     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2601     *out = (ast_expression*)aloop;
2602     return true;
2603 }
2604
2605 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2606 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2607 {
2608     bool rv;
2609     char *label = NULL;
2610
2611     /* skip the 'for' and check for opening paren */
2612     if (!parser_next(parser)) {
2613         if (OPTS_FLAG(LOOP_LABELS))
2614             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2615         else
2616             parseerror(parser, "expected 'for' expressions in parenthesis");
2617         return false;
2618     }
2619
2620     if (parser->tok == ':') {
2621         if (!OPTS_FLAG(LOOP_LABELS))
2622             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2623         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2624             parseerror(parser, "expected loop label");
2625             return false;
2626         }
2627         label = util_strdup(parser_tokval(parser));
2628         if (!parser_next(parser)) {
2629             mem_d(label);
2630             parseerror(parser, "expected 'for' expressions in parenthesis");
2631             return false;
2632         }
2633     }
2634
2635     if (parser->tok != '(') {
2636         parseerror(parser, "expected 'for' expressions in parenthesis");
2637         return false;
2638     }
2639
2640     vec_push(parser->breaks, label);
2641     vec_push(parser->continues, label);
2642
2643     rv = parse_for_go(parser, block, out);
2644     if (label)
2645         mem_d(label);
2646     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2647         parseerror(parser, "internal error: label stack corrupted");
2648         rv = false;
2649         ast_delete(*out);
2650         *out = NULL;
2651     }
2652     else {
2653         vec_pop(parser->breaks);
2654         vec_pop(parser->continues);
2655     }
2656     return rv;
2657 }
2658 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2659 {
2660     ast_loop       *aloop;
2661     ast_expression *initexpr, *cond, *increment, *ontrue;
2662     ast_value      *typevar;
2663
2664     bool retval = true;
2665     bool ifnot  = false;
2666
2667     lex_ctx ctx = parser_ctx(parser);
2668
2669     parser_enterblock(parser);
2670
2671     initexpr  = NULL;
2672     cond      = NULL;
2673     increment = NULL;
2674     ontrue    = NULL;
2675
2676     /* parse into the expression */
2677     if (!parser_next(parser)) {
2678         parseerror(parser, "expected 'for' initializer after opening paren");
2679         goto onerr;
2680     }
2681
2682     typevar = NULL;
2683     if (parser->tok == TOKEN_IDENT)
2684         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2685
2686     if (typevar || parser->tok == TOKEN_TYPENAME) {
2687 #if 0
2688         if (opts.standard != COMPILER_GMQCC) {
2689             if (parsewarning(parser, WARN_EXTENSIONS,
2690                              "current standard does not allow variable declarations in for-loop initializers"))
2691                 goto onerr;
2692         }
2693 #endif
2694         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2695             goto onerr;
2696     }
2697     else if (parser->tok != ';')
2698     {
2699         initexpr = parse_expression_leave(parser, false, false, false);
2700         if (!initexpr)
2701             goto onerr;
2702     }
2703
2704     /* move on to condition */
2705     if (parser->tok != ';') {
2706         parseerror(parser, "expected semicolon after for-loop initializer");
2707         goto onerr;
2708     }
2709     if (!parser_next(parser)) {
2710         parseerror(parser, "expected for-loop condition");
2711         goto onerr;
2712     }
2713
2714     /* parse the condition */
2715     if (parser->tok != ';') {
2716         cond = parse_expression_leave(parser, false, true, false);
2717         if (!cond)
2718             goto onerr;
2719     }
2720
2721     /* move on to incrementor */
2722     if (parser->tok != ';') {
2723         parseerror(parser, "expected semicolon after for-loop initializer");
2724         goto onerr;
2725     }
2726     if (!parser_next(parser)) {
2727         parseerror(parser, "expected for-loop condition");
2728         goto onerr;
2729     }
2730
2731     /* parse the incrementor */
2732     if (parser->tok != ')') {
2733         increment = parse_expression_leave(parser, false, false, false);
2734         if (!increment)
2735             goto onerr;
2736         if (!ast_side_effects(increment)) {
2737             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2738                 goto onerr;
2739         }
2740     }
2741
2742     /* closing paren */
2743     if (parser->tok != ')') {
2744         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2745         goto onerr;
2746     }
2747     /* parse into the 'then' branch */
2748     if (!parser_next(parser)) {
2749         parseerror(parser, "expected for-loop body");
2750         goto onerr;
2751     }
2752     if (!parse_statement_or_block(parser, &ontrue))
2753         goto onerr;
2754
2755     if (cond) {
2756         cond = process_condition(parser, cond, &ifnot);
2757         if (!cond)
2758             goto onerr;
2759     }
2760     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2761     *out = (ast_expression*)aloop;
2762
2763     if (!parser_leaveblock(parser))
2764         retval = false;
2765     return retval;
2766 onerr:
2767     if (initexpr)  ast_delete(initexpr);
2768     if (cond)      ast_delete(cond);
2769     if (increment) ast_delete(increment);
2770     (void)!parser_leaveblock(parser);
2771     return false;
2772 }
2773
2774 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2775 {
2776     ast_expression *exp = NULL;
2777     ast_return     *ret = NULL;
2778     ast_value      *expected = parser->function->vtype;
2779
2780     lex_ctx ctx = parser_ctx(parser);
2781
2782     (void)block; /* not touching */
2783
2784     if (!parser_next(parser)) {
2785         parseerror(parser, "expected return expression");
2786         return false;
2787     }
2788
2789     if (parser->tok != ';') {
2790         exp = parse_expression(parser, false, false);
2791         if (!exp)
2792             return false;
2793
2794         if (exp->expression.vtype != TYPE_NIL &&
2795             exp->expression.vtype != expected->expression.next->expression.vtype)
2796         {
2797             parseerror(parser, "return with invalid expression");
2798         }
2799
2800         ret = ast_return_new(ctx, exp);
2801         if (!ret) {
2802             ast_delete(exp);
2803             return false;
2804         }
2805     } else {
2806         if (!parser_next(parser))
2807             parseerror(parser, "parse error");
2808         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2809             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2810         }
2811         ret = ast_return_new(ctx, NULL);
2812     }
2813     *out = (ast_expression*)ret;
2814     return true;
2815 }
2816
2817 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2818 {
2819     size_t       i;
2820     unsigned int levels = 0;
2821     lex_ctx      ctx = parser_ctx(parser);
2822     const char **loops = (is_continue ? parser->continues : parser->breaks);
2823
2824     (void)block; /* not touching */
2825     if (!parser_next(parser)) {
2826         parseerror(parser, "expected semicolon or loop label");
2827         return false;
2828     }
2829
2830     if (!vec_size(loops)) {
2831         if (is_continue)
2832             parseerror(parser, "`continue` can only be used inside loops");
2833         else
2834             parseerror(parser, "`break` can only be used inside loops or switches");
2835     }
2836
2837     if (parser->tok == TOKEN_IDENT) {
2838         if (!OPTS_FLAG(LOOP_LABELS))
2839             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2840         i = vec_size(loops);
2841         while (i--) {
2842             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2843                 break;
2844             if (!i) {
2845                 parseerror(parser, "no such loop to %s: `%s`",
2846                            (is_continue ? "continue" : "break out of"),
2847                            parser_tokval(parser));
2848                 return false;
2849             }
2850             ++levels;
2851         }
2852         if (!parser_next(parser)) {
2853             parseerror(parser, "expected semicolon");
2854             return false;
2855         }
2856     }
2857
2858     if (parser->tok != ';') {
2859         parseerror(parser, "expected semicolon");
2860         return false;
2861     }
2862
2863     if (!parser_next(parser))
2864         parseerror(parser, "parse error");
2865
2866     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2867     return true;
2868 }
2869
2870 /* returns true when it was a variable qualifier, false otherwise!
2871  * on error, cvq is set to CV_WRONG
2872  */
2873 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2874 {
2875     bool had_const    = false;
2876     bool had_var      = false;
2877     bool had_noref    = false;
2878     bool had_attrib   = false;
2879     bool had_static   = false;
2880     uint32_t flags    = 0;
2881
2882     *cvq = CV_NONE;
2883     for (;;) {
2884         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2885             had_attrib = true;
2886             /* parse an attribute */
2887             if (!parser_next(parser)) {
2888                 parseerror(parser, "expected attribute after `[[`");
2889                 *cvq = CV_WRONG;
2890                 return false;
2891             }
2892             if (!strcmp(parser_tokval(parser), "noreturn")) {
2893                 flags |= AST_FLAG_NORETURN;
2894                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2895                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2896                     *cvq = CV_WRONG;
2897                     return false;
2898                 }
2899             }
2900             else if (!strcmp(parser_tokval(parser), "noref")) {
2901                 had_noref = true;
2902                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2903                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2904                     *cvq = CV_WRONG;
2905                     return false;
2906                 }
2907             }
2908             else if (!strcmp(parser_tokval(parser), "inline")) {
2909                 flags |= AST_FLAG_INLINE;
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
2917
2918             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2919                 flags   |= AST_FLAG_DEPRECATED;
2920                 *message = NULL;
2921
2922                 if (!parser_next(parser)) {
2923                     parseerror(parser, "parse error in attribute");
2924                     goto argerr;
2925                 }
2926
2927                 if (parser->tok == '(') {
2928                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2929                         parseerror(parser, "`deprecated` attribute missing parameter");
2930                         goto argerr;
2931                     }
2932
2933                     *message = util_strdup(parser_tokval(parser));
2934
2935                     if (!parser_next(parser)) {
2936                         parseerror(parser, "parse error in attribute");
2937                         goto argerr;
2938                     }
2939
2940                     if(parser->tok != ')') {
2941                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2942                         goto argerr;
2943                     }
2944
2945                     if (!parser_next(parser)) {
2946                         parseerror(parser, "parse error in attribute");
2947                         goto argerr;
2948                     }
2949                 }
2950                 /* no message */
2951                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2952                     parseerror(parser, "`deprecated` attribute expected `]]`");
2953
2954                     argerr: /* ugly */
2955                     if (*message) mem_d(*message);
2956                     *message = NULL;
2957                     *cvq     = CV_WRONG;
2958                     return false;
2959                 }
2960             }
2961             else
2962             {
2963                 /* Skip tokens until we hit a ]] */
2964                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2965                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2966                     if (!parser_next(parser)) {
2967                         parseerror(parser, "error inside attribute");
2968                         *cvq = CV_WRONG;
2969                         return false;
2970                     }
2971                 }
2972             }
2973         }
2974         else if (with_local && !strcmp(parser_tokval(parser), "static"))
2975             had_static = true;
2976         else if (!strcmp(parser_tokval(parser), "const"))
2977             had_const = true;
2978         else if (!strcmp(parser_tokval(parser), "var"))
2979             had_var = true;
2980         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2981             had_var = true;
2982         else if (!strcmp(parser_tokval(parser), "noref"))
2983             had_noref = true;
2984         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2985             return false;
2986         }
2987         else
2988             break;
2989         if (!parser_next(parser))
2990             goto onerr;
2991     }
2992     if (had_const)
2993         *cvq = CV_CONST;
2994     else if (had_var)
2995         *cvq = CV_VAR;
2996     else
2997         *cvq = CV_NONE;
2998     *noref     = had_noref;
2999     *is_static = had_static;
3000     *_flags    = flags;
3001     return true;
3002 onerr:
3003     parseerror(parser, "parse error after variable qualifier");
3004     *cvq = CV_WRONG;
3005     return true;
3006 }
3007
3008 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3009 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3010 {
3011     bool rv;
3012     char *label = NULL;
3013
3014     /* skip the 'while' and get the body */
3015     if (!parser_next(parser)) {
3016         if (OPTS_FLAG(LOOP_LABELS))
3017             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3018         else
3019             parseerror(parser, "expected 'switch' operand in parenthesis");
3020         return false;
3021     }
3022
3023     if (parser->tok == ':') {
3024         if (!OPTS_FLAG(LOOP_LABELS))
3025             parseerror(parser, "labeled loops not activated, try using -floop-labels");
3026         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3027             parseerror(parser, "expected loop label");
3028             return false;
3029         }
3030         label = util_strdup(parser_tokval(parser));
3031         if (!parser_next(parser)) {
3032             mem_d(label);
3033             parseerror(parser, "expected 'switch' operand in parenthesis");
3034             return false;
3035         }
3036     }
3037
3038     if (parser->tok != '(') {
3039         parseerror(parser, "expected 'switch' operand in parenthesis");
3040         return false;
3041     }
3042
3043     vec_push(parser->breaks, label);
3044
3045     rv = parse_switch_go(parser, block, out);
3046     if (label)
3047         mem_d(label);
3048     if (vec_last(parser->breaks) != label) {
3049         parseerror(parser, "internal error: label stack corrupted");
3050         rv = false;
3051         ast_delete(*out);
3052         *out = NULL;
3053     }
3054     else {
3055         vec_pop(parser->breaks);
3056     }
3057     return rv;
3058 }
3059
3060 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3061 {
3062     ast_expression *operand;
3063     ast_value      *opval;
3064     ast_value      *typevar;
3065     ast_switch     *switchnode;
3066     ast_switch_case swcase;
3067
3068     int  cvq;
3069     bool noref, is_static;
3070     uint32_t qflags = 0;
3071
3072     lex_ctx ctx = parser_ctx(parser);
3073
3074     (void)block; /* not touching */
3075     (void)opval;
3076
3077     /* parse into the expression */
3078     if (!parser_next(parser)) {
3079         parseerror(parser, "expected switch operand");
3080         return false;
3081     }
3082     /* parse the operand */
3083     operand = parse_expression_leave(parser, false, false, false);
3084     if (!operand)
3085         return false;
3086
3087     switchnode = ast_switch_new(ctx, operand);
3088
3089     /* closing paren */
3090     if (parser->tok != ')') {
3091         ast_delete(switchnode);
3092         parseerror(parser, "expected closing paren after 'switch' operand");
3093         return false;
3094     }
3095
3096     /* parse over the opening paren */
3097     if (!parser_next(parser) || parser->tok != '{') {
3098         ast_delete(switchnode);
3099         parseerror(parser, "expected list of cases");
3100         return false;
3101     }
3102
3103     if (!parser_next(parser)) {
3104         ast_delete(switchnode);
3105         parseerror(parser, "expected 'case' or 'default'");
3106         return false;
3107     }
3108
3109     /* new block; allow some variables to be declared here */
3110     parser_enterblock(parser);
3111     while (true) {
3112         typevar = NULL;
3113         if (parser->tok == TOKEN_IDENT)
3114             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3115         if (typevar || parser->tok == TOKEN_TYPENAME) {
3116             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3117                 ast_delete(switchnode);
3118                 return false;
3119             }
3120             continue;
3121         }
3122         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3123         {
3124             if (cvq == CV_WRONG) {
3125                 ast_delete(switchnode);
3126                 return false;
3127             }
3128             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3129                 ast_delete(switchnode);
3130                 return false;
3131             }
3132             continue;
3133         }
3134         break;
3135     }
3136
3137     /* case list! */
3138     while (parser->tok != '}') {
3139         ast_block *caseblock;
3140
3141         if (!strcmp(parser_tokval(parser), "case")) {
3142             if (!parser_next(parser)) {
3143                 ast_delete(switchnode);
3144                 parseerror(parser, "expected expression for case");
3145                 return false;
3146             }
3147             swcase.value = parse_expression_leave(parser, false, false, false);
3148             if (!swcase.value) {
3149                 ast_delete(switchnode);
3150                 parseerror(parser, "expected expression for case");
3151                 return false;
3152             }
3153             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3154                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3155                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3156                     ast_unref(operand);
3157                     return false;
3158                 }
3159             }
3160         }
3161         else if (!strcmp(parser_tokval(parser), "default")) {
3162             swcase.value = NULL;
3163             if (!parser_next(parser)) {
3164                 ast_delete(switchnode);
3165                 parseerror(parser, "expected colon");
3166                 return false;
3167             }
3168         }
3169         else {
3170             ast_delete(switchnode);
3171             parseerror(parser, "expected 'case' or 'default'");
3172             return false;
3173         }
3174
3175         /* Now the colon and body */
3176         if (parser->tok != ':') {
3177             if (swcase.value) ast_unref(swcase.value);
3178             ast_delete(switchnode);
3179             parseerror(parser, "expected colon");
3180             return false;
3181         }
3182
3183         if (!parser_next(parser)) {
3184             if (swcase.value) ast_unref(swcase.value);
3185             ast_delete(switchnode);
3186             parseerror(parser, "expected statements or case");
3187             return false;
3188         }
3189         caseblock = ast_block_new(parser_ctx(parser));
3190         if (!caseblock) {
3191             if (swcase.value) ast_unref(swcase.value);
3192             ast_delete(switchnode);
3193             return false;
3194         }
3195         swcase.code = (ast_expression*)caseblock;
3196         vec_push(switchnode->cases, swcase);
3197         while (true) {
3198             ast_expression *expr;
3199             if (parser->tok == '}')
3200                 break;
3201             if (parser->tok == TOKEN_KEYWORD) {
3202                 if (!strcmp(parser_tokval(parser), "case") ||
3203                     !strcmp(parser_tokval(parser), "default"))
3204                 {
3205                     break;
3206                 }
3207             }
3208             if (!parse_statement(parser, caseblock, &expr, true)) {
3209                 ast_delete(switchnode);
3210                 return false;
3211             }
3212             if (!expr)
3213                 continue;
3214             if (!ast_block_add_expr(caseblock, expr)) {
3215                 ast_delete(switchnode);
3216                 return false;
3217             }
3218         }
3219     }
3220
3221     parser_leaveblock(parser);
3222
3223     /* closing paren */
3224     if (parser->tok != '}') {
3225         ast_delete(switchnode);
3226         parseerror(parser, "expected closing paren of case list");
3227         return false;
3228     }
3229     if (!parser_next(parser)) {
3230         ast_delete(switchnode);
3231         parseerror(parser, "parse error after switch");
3232         return false;
3233     }
3234     *out = (ast_expression*)switchnode;
3235     return true;
3236 }
3237
3238 /* parse computed goto sides */
3239 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3240     ast_expression *on_true;
3241     ast_expression *on_false;
3242     ast_expression *cond;
3243
3244     if (!*side)
3245         return NULL;
3246
3247     if (ast_istype(*side, ast_ternary)) {
3248         ast_ternary *tern = (ast_ternary*)*side;
3249         on_true  = parse_goto_computed(parser, &tern->on_true);
3250         on_false = parse_goto_computed(parser, &tern->on_false);
3251
3252         if (!on_true || !on_false) {
3253             parseerror(parser, "expected label or expression in ternary");
3254             if (on_true) ast_unref(on_true);
3255             if (on_false) ast_unref(on_false);
3256             return NULL;
3257         }
3258
3259         cond = tern->cond;
3260         tern->cond = NULL;
3261         ast_delete(tern);
3262         *side = NULL;
3263         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3264     } else if (ast_istype(*side, ast_label)) {
3265         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3266         ast_goto_set_label(gt, ((ast_label*)*side));
3267         *side = NULL;
3268         return (ast_expression*)gt;
3269     }
3270     return NULL;
3271 }
3272
3273 static bool parse_goto(parser_t *parser, ast_expression **out)
3274 {
3275     ast_goto       *gt = NULL;
3276     ast_expression *lbl;
3277
3278     if (!parser_next(parser))
3279         return false;
3280
3281     if (parser->tok != TOKEN_IDENT) {
3282         ast_expression *expression;
3283
3284         /* could be an expression i.e computed goto :-) */
3285         if (parser->tok != '(') {
3286             parseerror(parser, "expected label name after `goto`");
3287             return false;
3288         }
3289
3290         /* failed to parse expression for goto */
3291         if (!(expression = parse_expression(parser, false, true)) ||
3292             !(*out = parse_goto_computed(parser, &expression))) {
3293             parseerror(parser, "invalid goto expression");
3294             ast_unref(expression);
3295             return false;
3296         }
3297
3298         return true;
3299     }
3300
3301     /* not computed goto */
3302     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3303     lbl = parser_find_label(parser, gt->name);
3304     if (lbl) {
3305         if (!ast_istype(lbl, ast_label)) {
3306             parseerror(parser, "internal error: label is not an ast_label");
3307             ast_delete(gt);
3308             return false;
3309         }
3310         ast_goto_set_label(gt, (ast_label*)lbl);
3311     }
3312     else
3313         vec_push(parser->gotos, gt);
3314
3315     if (!parser_next(parser) || parser->tok != ';') {
3316         parseerror(parser, "semicolon expected after goto label");
3317         return false;
3318     }
3319     if (!parser_next(parser)) {
3320         parseerror(parser, "parse error after goto");
3321         return false;
3322     }
3323
3324     *out = (ast_expression*)gt;
3325     return true;
3326 }
3327
3328 static bool parse_skipwhite(parser_t *parser)
3329 {
3330     do {
3331         if (!parser_next(parser))
3332             return false;
3333     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3334     return parser->tok < TOKEN_ERROR;
3335 }
3336
3337 static bool parse_eol(parser_t *parser)
3338 {
3339     if (!parse_skipwhite(parser))
3340         return false;
3341     return parser->tok == TOKEN_EOL;
3342 }
3343
3344 static bool parse_pragma_do(parser_t *parser)
3345 {
3346     if (!parser_next(parser) ||
3347         parser->tok != TOKEN_IDENT ||
3348         strcmp(parser_tokval(parser), "pragma"))
3349     {
3350         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3351         return false;
3352     }
3353     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3354         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3355         return false;
3356     }
3357
3358     if (!strcmp(parser_tokval(parser), "noref")) {
3359         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3360             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3361             return false;
3362         }
3363         parser->noref = !!parser_token(parser)->constval.i;
3364         if (!parse_eol(parser)) {
3365             parseerror(parser, "parse error after `noref` pragma");
3366             return false;
3367         }
3368     }
3369     else
3370     {
3371         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3372         return false;
3373     }
3374
3375     return true;
3376 }
3377
3378 static bool parse_pragma(parser_t *parser)
3379 {
3380     bool rv;
3381     parser->lex->flags.preprocessing = true;
3382     parser->lex->flags.mergelines = true;
3383     rv = parse_pragma_do(parser);
3384     if (parser->tok != TOKEN_EOL) {
3385         parseerror(parser, "junk after pragma");
3386         rv = false;
3387     }
3388     parser->lex->flags.preprocessing = false;
3389     parser->lex->flags.mergelines = false;
3390     if (!parser_next(parser)) {
3391         parseerror(parser, "parse error after pragma");
3392         rv = false;
3393     }
3394     return rv;
3395 }
3396
3397 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3398 {
3399     bool       noref, is_static;
3400     int        cvq     = CV_NONE;
3401     uint32_t   qflags  = 0;
3402     ast_value *typevar = NULL;
3403     char      *vstring = NULL;
3404
3405     *out = NULL;
3406
3407     if (parser->tok == TOKEN_IDENT)
3408         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3409
3410     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3411     {
3412         /* local variable */
3413         if (!block) {
3414             parseerror(parser, "cannot declare a variable from here");
3415             return false;
3416         }
3417         if (opts.standard == COMPILER_QCC) {
3418             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3419                 return false;
3420         }
3421         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3422             return false;
3423         return true;
3424     }
3425     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3426     {
3427         if (cvq == CV_WRONG)
3428             return false;
3429         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3430     }
3431     else if (parser->tok == TOKEN_KEYWORD)
3432     {
3433         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3434         {
3435             char ty[1024];
3436             ast_value *tdef;
3437
3438             if (!parser_next(parser)) {
3439                 parseerror(parser, "parse error after __builtin_debug_printtype");
3440                 return false;
3441             }
3442
3443             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3444             {
3445                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3446                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3447                 if (!parser_next(parser)) {
3448                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3449                     return false;
3450                 }
3451             }
3452             else
3453             {
3454                 if (!parse_statement(parser, block, out, allow_cases))
3455                     return false;
3456                 if (!*out)
3457                     con_out("__builtin_debug_printtype: got no output node\n");
3458                 else
3459                 {
3460                     ast_type_to_string(*out, ty, sizeof(ty));
3461                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3462                 }
3463             }
3464             return true;
3465         }
3466         else if (!strcmp(parser_tokval(parser), "return"))
3467         {
3468             return parse_return(parser, block, out);
3469         }
3470         else if (!strcmp(parser_tokval(parser), "if"))
3471         {
3472             return parse_if(parser, block, out);
3473         }
3474         else if (!strcmp(parser_tokval(parser), "while"))
3475         {
3476             return parse_while(parser, block, out);
3477         }
3478         else if (!strcmp(parser_tokval(parser), "do"))
3479         {
3480             return parse_dowhile(parser, block, out);
3481         }
3482         else if (!strcmp(parser_tokval(parser), "for"))
3483         {
3484             if (opts.standard == COMPILER_QCC) {
3485                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3486                     return false;
3487             }
3488             return parse_for(parser, block, out);
3489         }
3490         else if (!strcmp(parser_tokval(parser), "break"))
3491         {
3492             return parse_break_continue(parser, block, out, false);
3493         }
3494         else if (!strcmp(parser_tokval(parser), "continue"))
3495         {
3496             return parse_break_continue(parser, block, out, true);
3497         }
3498         else if (!strcmp(parser_tokval(parser), "switch"))
3499         {
3500             return parse_switch(parser, block, out);
3501         }
3502         else if (!strcmp(parser_tokval(parser), "case") ||
3503                  !strcmp(parser_tokval(parser), "default"))
3504         {
3505             if (!allow_cases) {
3506                 parseerror(parser, "unexpected 'case' label");
3507                 return false;
3508             }
3509             return true;
3510         }
3511         else if (!strcmp(parser_tokval(parser), "goto"))
3512         {
3513             return parse_goto(parser, out);
3514         }
3515         else if (!strcmp(parser_tokval(parser), "typedef"))
3516         {
3517             if (!parser_next(parser)) {
3518                 parseerror(parser, "expected type definition after 'typedef'");
3519                 return false;
3520             }
3521             return parse_typedef(parser);
3522         }
3523         parseerror(parser, "Unexpected keyword");
3524         return false;
3525     }
3526     else if (parser->tok == '{')
3527     {
3528         ast_block *inner;
3529         inner = parse_block(parser);
3530         if (!inner)
3531             return false;
3532         *out = (ast_expression*)inner;
3533         return true;
3534     }
3535     else if (parser->tok == ':')
3536     {
3537         size_t i;
3538         ast_label *label;
3539         if (!parser_next(parser)) {
3540             parseerror(parser, "expected label name");
3541             return false;
3542         }
3543         if (parser->tok != TOKEN_IDENT) {
3544             parseerror(parser, "label must be an identifier");
3545             return false;
3546         }
3547         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3548         if (label) {
3549             if (!label->undefined) {
3550                 parseerror(parser, "label `%s` already defined", label->name);
3551                 return false;
3552             }
3553             label->undefined = false;
3554         }
3555         else {
3556             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3557             vec_push(parser->labels, label);
3558         }
3559         *out = (ast_expression*)label;
3560         if (!parser_next(parser)) {
3561             parseerror(parser, "parse error after label");
3562             return false;
3563         }
3564         for (i = 0; i < vec_size(parser->gotos); ++i) {
3565             if (!strcmp(parser->gotos[i]->name, label->name)) {
3566                 ast_goto_set_label(parser->gotos[i], label);
3567                 vec_remove(parser->gotos, i, 1);
3568                 --i;
3569             }
3570         }
3571         return true;
3572     }
3573     else if (parser->tok == ';')
3574     {
3575         if (!parser_next(parser)) {
3576             parseerror(parser, "parse error after empty statement");
3577             return false;
3578         }
3579         return true;
3580     }
3581     else
3582     {
3583         ast_expression *exp = parse_expression(parser, false, false);
3584         if (!exp)
3585             return false;
3586         *out = exp;
3587         if (!ast_side_effects(exp)) {
3588             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3589                 return false;
3590         }
3591         return true;
3592     }
3593 }
3594
3595 static bool parse_enum(parser_t *parser)
3596 {
3597     qcfloat     num = 0;
3598     ast_value **values = NULL;
3599     ast_value  *var = NULL;
3600     ast_value  *asvalue;
3601
3602     ast_expression *old;
3603
3604     if (!parser_next(parser) || parser->tok != '{') {
3605         parseerror(parser, "expected `{` after `enum` keyword");
3606         return false;
3607     }
3608
3609     while (true) {
3610         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3611             if (parser->tok == '}') {
3612                 /* allow an empty enum */
3613                 break;
3614             }
3615             parseerror(parser, "expected identifier or `}`");
3616             goto onerror;
3617         }
3618
3619         old = parser_find_field(parser, parser_tokval(parser));
3620         if (!old)
3621             old = parser_find_global(parser, parser_tokval(parser));
3622         if (old) {
3623             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3624                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3625             goto onerror;
3626         }
3627
3628         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3629         vec_push(values, var);
3630         var->cvq             = CV_CONST;
3631         var->hasvalue        = true;
3632         var->constval.vfloat = num++;
3633
3634         parser_addglobal(parser, var->name, (ast_expression*)var);
3635
3636         if (!parser_next(parser)) {
3637             parseerror(parser, "expected `=`, `}` or comma after identifier");
3638             goto onerror;
3639         }
3640
3641         if (parser->tok == ',')
3642             continue;
3643         if (parser->tok == '}')
3644             break;
3645         if (parser->tok != '=') {
3646             parseerror(parser, "expected `=`, `}` or comma after identifier");
3647             goto onerror;
3648         }
3649
3650         if (!parser_next(parser)) {
3651             parseerror(parser, "expected expression after `=`");
3652             goto onerror;
3653         }
3654
3655         /* We got a value! */
3656         old = parse_expression_leave(parser, true, false, false);
3657         asvalue = (ast_value*)old;
3658         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3659             compile_error(ast_ctx(var), "constant value or expression expected");
3660             goto onerror;
3661         }
3662         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3663
3664         if (parser->tok == '}')
3665             break;
3666         if (parser->tok != ',') {
3667             parseerror(parser, "expected `}` or comma after expression");
3668             goto onerror;
3669         }
3670     }
3671
3672     if (parser->tok != '}') {
3673         parseerror(parser, "internal error: breaking without `}`");
3674         goto onerror;
3675     }
3676
3677     if (!parser_next(parser) || parser->tok != ';') {
3678         parseerror(parser, "expected semicolon after enumeration");
3679         goto onerror;
3680     }
3681
3682     if (!parser_next(parser)) {
3683         parseerror(parser, "parse error after enumeration");
3684         goto onerror;
3685     }
3686
3687     vec_free(values);
3688     return true;
3689
3690 onerror:
3691     vec_free(values);
3692     return false;
3693 }
3694
3695 static bool parse_block_into(parser_t *parser, ast_block *block)
3696 {
3697     bool   retval = true;
3698
3699     parser_enterblock(parser);
3700
3701     if (!parser_next(parser)) { /* skip the '{' */
3702         parseerror(parser, "expected function body");
3703         goto cleanup;
3704     }
3705
3706     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3707     {
3708         ast_expression *expr = NULL;
3709         if (parser->tok == '}')
3710             break;
3711
3712         if (!parse_statement(parser, block, &expr, false)) {
3713             /* parseerror(parser, "parse error"); */
3714             block = NULL;
3715             goto cleanup;
3716         }
3717         if (!expr)
3718             continue;
3719         if (!ast_block_add_expr(block, expr)) {
3720             ast_delete(block);
3721             block = NULL;
3722             goto cleanup;
3723         }
3724     }
3725
3726     if (parser->tok != '}') {
3727         block = NULL;
3728     } else {
3729         (void)parser_next(parser);
3730     }
3731
3732 cleanup:
3733     if (!parser_leaveblock(parser))
3734         retval = false;
3735     return retval && !!block;
3736 }
3737
3738 static ast_block* parse_block(parser_t *parser)
3739 {
3740     ast_block *block;
3741     block = ast_block_new(parser_ctx(parser));
3742     if (!block)
3743         return NULL;
3744     if (!parse_block_into(parser, block)) {
3745         ast_block_delete(block);
3746         return NULL;
3747     }
3748     return block;
3749 }
3750
3751 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3752 {
3753     if (parser->tok == '{') {
3754         *out = (ast_expression*)parse_block(parser);
3755         return !!*out;
3756     }
3757     return parse_statement(parser, NULL, out, false);
3758 }
3759
3760 static bool create_vector_members(ast_value *var, ast_member **me)
3761 {
3762     size_t i;
3763     size_t len = strlen(var->name);
3764
3765     for (i = 0; i < 3; ++i) {
3766         char *name = (char*)mem_a(len+3);
3767         memcpy(name, var->name, len);
3768         name[len+0] = '_';
3769         name[len+1] = 'x'+i;
3770         name[len+2] = 0;
3771         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3772         mem_d(name);
3773         if (!me[i])
3774             break;
3775     }
3776     if (i == 3)
3777         return true;
3778
3779     /* unroll */
3780     do { ast_member_delete(me[--i]); } while(i);
3781     return false;
3782 }
3783
3784 static bool parse_function_body(parser_t *parser, ast_value *var)
3785 {
3786     ast_block      *block = NULL;
3787     ast_function   *func;
3788     ast_function   *old;
3789     size_t          parami;
3790
3791     ast_expression *framenum  = NULL;
3792     ast_expression *nextthink = NULL;
3793     /* None of the following have to be deleted */
3794     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3795     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3796     bool            has_frame_think;
3797
3798     bool retval = true;
3799
3800     has_frame_think = false;
3801     old = parser->function;
3802
3803     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3804         parseerror(parser, "gotos/labels leaking");
3805         return false;
3806     }
3807
3808     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3809         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3810                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3811         {
3812             return false;
3813         }
3814     }
3815
3816     if (parser->tok == '[') {
3817         /* got a frame definition: [ framenum, nextthink ]
3818          * this translates to:
3819          * self.frame = framenum;
3820          * self.nextthink = time + 0.1;
3821          * self.think = nextthink;
3822          */
3823         nextthink = NULL;
3824
3825         fld_think     = parser_find_field(parser, "think");
3826         fld_nextthink = parser_find_field(parser, "nextthink");
3827         fld_frame     = parser_find_field(parser, "frame");
3828         if (!fld_think || !fld_nextthink || !fld_frame) {
3829             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3830             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3831             return false;
3832         }
3833         gbl_time      = parser_find_global(parser, "time");
3834         gbl_self      = parser_find_global(parser, "self");
3835         if (!gbl_time || !gbl_self) {
3836             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3837             parseerror(parser, "please declare the following globals: `time`, `self`");
3838             return false;
3839         }
3840
3841         if (!parser_next(parser))
3842             return false;
3843
3844         framenum = parse_expression_leave(parser, true, false, false);
3845         if (!framenum) {
3846             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3847             return false;
3848         }
3849         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3850             ast_unref(framenum);
3851             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3852             return false;
3853         }
3854
3855         if (parser->tok != ',') {
3856             ast_unref(framenum);
3857             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3858             parseerror(parser, "Got a %i\n", parser->tok);
3859             return false;
3860         }
3861
3862         if (!parser_next(parser)) {
3863             ast_unref(framenum);
3864             return false;
3865         }
3866
3867         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3868         {
3869             /* qc allows the use of not-yet-declared functions here
3870              * - this automatically creates a prototype */
3871             ast_value      *thinkfunc;
3872             ast_expression *functype = fld_think->expression.next;
3873
3874             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3875             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3876                 ast_unref(framenum);
3877                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3878                 return false;
3879             }
3880
3881             if (!parser_next(parser)) {
3882                 ast_unref(framenum);
3883                 ast_delete(thinkfunc);
3884                 return false;
3885             }
3886
3887             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3888
3889             nextthink = (ast_expression*)thinkfunc;
3890
3891         } else {
3892             nextthink = parse_expression_leave(parser, true, false, false);
3893             if (!nextthink) {
3894                 ast_unref(framenum);
3895                 parseerror(parser, "expected a think-function in [frame,think] notation");
3896                 return false;
3897             }
3898         }
3899
3900         if (!ast_istype(nextthink, ast_value)) {
3901             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3902             retval = false;
3903         }
3904
3905         if (retval && parser->tok != ']') {
3906             parseerror(parser, "expected closing `]` for [frame,think] notation");
3907             retval = false;
3908         }
3909
3910         if (retval && !parser_next(parser)) {
3911             retval = false;
3912         }
3913
3914         if (retval && parser->tok != '{') {
3915             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3916             retval = false;
3917         }
3918
3919         if (!retval) {
3920             ast_unref(nextthink);
3921             ast_unref(framenum);
3922             return false;
3923         }
3924
3925         has_frame_think = true;
3926     }
3927
3928     block = ast_block_new(parser_ctx(parser));
3929     if (!block) {
3930         parseerror(parser, "failed to allocate block");
3931         if (has_frame_think) {
3932             ast_unref(nextthink);
3933             ast_unref(framenum);
3934         }
3935         return false;
3936     }
3937
3938     if (has_frame_think) {
3939         lex_ctx ctx;
3940         ast_expression *self_frame;
3941         ast_expression *self_nextthink;
3942         ast_expression *self_think;
3943         ast_expression *time_plus_1;
3944         ast_store *store_frame;
3945         ast_store *store_nextthink;
3946         ast_store *store_think;
3947
3948         ctx = parser_ctx(parser);
3949         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3950         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3951         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3952
3953         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3954                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3955
3956         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3957             if (self_frame)     ast_delete(self_frame);
3958             if (self_nextthink) ast_delete(self_nextthink);
3959             if (self_think)     ast_delete(self_think);
3960             if (time_plus_1)    ast_delete(time_plus_1);
3961             retval = false;
3962         }
3963
3964         if (retval)
3965         {
3966             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3967             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3968             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3969
3970             if (!store_frame) {
3971                 ast_delete(self_frame);
3972                 retval = false;
3973             }
3974             if (!store_nextthink) {
3975                 ast_delete(self_nextthink);
3976                 retval = false;
3977             }
3978             if (!store_think) {
3979                 ast_delete(self_think);
3980                 retval = false;
3981             }
3982             if (!retval) {
3983                 if (store_frame)     ast_delete(store_frame);
3984                 if (store_nextthink) ast_delete(store_nextthink);
3985                 if (store_think)     ast_delete(store_think);
3986                 retval = false;
3987             }
3988             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3989                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3990                 !ast_block_add_expr(block, (ast_expression*)store_think))
3991             {
3992                 retval = false;
3993             }
3994         }
3995
3996         if (!retval) {
3997             parseerror(parser, "failed to generate code for [frame,think]");
3998             ast_unref(nextthink);
3999             ast_unref(framenum);
4000             ast_delete(block);
4001             return false;
4002         }
4003     }
4004
4005     func = ast_function_new(ast_ctx(var), var->name, var);
4006     if (!func) {
4007         parseerror(parser, "failed to allocate function for `%s`", var->name);
4008         ast_block_delete(block);
4009         goto enderr;
4010     }
4011     vec_push(parser->functions, func);
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             goto enderrfn;
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     if (var->argcounter) {
4039         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4040         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4041         func->argc = argc;
4042     }
4043
4044     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4045         char name[1024];
4046         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4047         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4048         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4049         varargs->expression.count = 0;
4050         snprintf(name, sizeof(name), "%s##va##SET", var->name);
4051         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4052             ast_delete(varargs);
4053             ast_block_delete(block);
4054             goto enderrfn;
4055         }
4056         snprintf(name, sizeof(name), "%s##va##GET", var->name);
4057         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4058             ast_delete(varargs);
4059             ast_block_delete(block);
4060             goto enderrfn;
4061         }
4062         func->varargs = varargs;
4063
4064         func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4065     }
4066
4067     parser->function = func;
4068     if (!parse_block_into(parser, block)) {
4069         ast_block_delete(block);
4070         goto enderrfn;
4071     }
4072
4073     vec_push(func->blocks, block);
4074
4075     parser->function = old;
4076     if (!parser_leaveblock(parser))
4077         retval = false;
4078     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4079         parseerror(parser, "internal error: local scopes left");
4080         retval = false;
4081     }
4082
4083     if (parser->tok == ';')
4084         return parser_next(parser);
4085     else if (opts.standard == COMPILER_QCC)
4086         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4087     return retval;
4088
4089 enderrfn:
4090     (void)!parser_leaveblock(parser);
4091     vec_pop(parser->functions);
4092     ast_function_delete(func);
4093     var->constval.vfunc = NULL;
4094
4095 enderr:
4096     parser->function = old;
4097     return false;
4098 }
4099
4100 static ast_expression *array_accessor_split(
4101     parser_t  *parser,
4102     ast_value *array,
4103     ast_value *index,
4104     size_t     middle,
4105     ast_expression *left,
4106     ast_expression *right
4107     )
4108 {
4109     ast_ifthen *ifthen;
4110     ast_binary *cmp;
4111
4112     lex_ctx ctx = ast_ctx(array);
4113
4114     if (!left || !right) {
4115         if (left)  ast_delete(left);
4116         if (right) ast_delete(right);
4117         return NULL;
4118     }
4119
4120     cmp = ast_binary_new(ctx, INSTR_LT,
4121                          (ast_expression*)index,
4122                          (ast_expression*)parser_const_float(parser, middle));
4123     if (!cmp) {
4124         ast_delete(left);
4125         ast_delete(right);
4126         parseerror(parser, "internal error: failed to create comparison for array setter");
4127         return NULL;
4128     }
4129
4130     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4131     if (!ifthen) {
4132         ast_delete(cmp); /* will delete left and right */
4133         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4134         return NULL;
4135     }
4136
4137     return (ast_expression*)ifthen;
4138 }
4139
4140 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4141 {
4142     lex_ctx ctx = ast_ctx(array);
4143
4144     if (from+1 == afterend) {
4145         /* set this value */
4146         ast_block       *block;
4147         ast_return      *ret;
4148         ast_array_index *subscript;
4149         ast_store       *st;
4150         int assignop = type_store_instr[value->expression.vtype];
4151
4152         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4153             assignop = INSTR_STORE_V;
4154
4155         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4156         if (!subscript)
4157             return NULL;
4158
4159         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4160         if (!st) {
4161             ast_delete(subscript);
4162             return NULL;
4163         }
4164
4165         block = ast_block_new(ctx);
4166         if (!block) {
4167             ast_delete(st);
4168             return NULL;
4169         }
4170
4171         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4172             ast_delete(block);
4173             return NULL;
4174         }
4175
4176         ret = ast_return_new(ctx, NULL);
4177         if (!ret) {
4178             ast_delete(block);
4179             return NULL;
4180         }
4181
4182         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4183             ast_delete(block);
4184             return NULL;
4185         }
4186
4187         return (ast_expression*)block;
4188     } else {
4189         ast_expression *left, *right;
4190         size_t diff = afterend - from;
4191         size_t middle = from + diff/2;
4192         left  = array_setter_node(parser, array, index, value, from, middle);
4193         right = array_setter_node(parser, array, index, value, middle, afterend);
4194         return array_accessor_split(parser, array, index, middle, left, right);
4195     }
4196 }
4197
4198 static ast_expression *array_field_setter_node(
4199     parser_t  *parser,
4200     ast_value *array,
4201     ast_value *entity,
4202     ast_value *index,
4203     ast_value *value,
4204     size_t     from,
4205     size_t     afterend)
4206 {
4207     lex_ctx ctx = ast_ctx(array);
4208
4209     if (from+1 == afterend) {
4210         /* set this value */
4211         ast_block       *block;
4212         ast_return      *ret;
4213         ast_entfield    *entfield;
4214         ast_array_index *subscript;
4215         ast_store       *st;
4216         int assignop = type_storep_instr[value->expression.vtype];
4217
4218         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4219             assignop = INSTR_STOREP_V;
4220
4221         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4222         if (!subscript)
4223             return NULL;
4224
4225         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4226         subscript->expression.vtype = TYPE_FIELD;
4227
4228         entfield = ast_entfield_new_force(ctx,
4229                                           (ast_expression*)entity,
4230                                           (ast_expression*)subscript,
4231                                           (ast_expression*)subscript);
4232         if (!entfield) {
4233             ast_delete(subscript);
4234             return NULL;
4235         }
4236
4237         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4238         if (!st) {
4239             ast_delete(entfield);
4240             return NULL;
4241         }
4242
4243         block = ast_block_new(ctx);
4244         if (!block) {
4245             ast_delete(st);
4246             return NULL;
4247         }
4248
4249         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4250             ast_delete(block);
4251             return NULL;
4252         }
4253
4254         ret = ast_return_new(ctx, NULL);
4255         if (!ret) {
4256             ast_delete(block);
4257             return NULL;
4258         }
4259
4260         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4261             ast_delete(block);
4262             return NULL;
4263         }
4264
4265         return (ast_expression*)block;
4266     } else {
4267         ast_expression *left, *right;
4268         size_t diff = afterend - from;
4269         size_t middle = from + diff/2;
4270         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4271         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4272         return array_accessor_split(parser, array, index, middle, left, right);
4273     }
4274 }
4275
4276 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4277 {
4278     lex_ctx ctx = ast_ctx(array);
4279
4280     if (from+1 == afterend) {
4281         ast_return      *ret;
4282         ast_array_index *subscript;
4283
4284         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4285         if (!subscript)
4286             return NULL;
4287
4288         ret = ast_return_new(ctx, (ast_expression*)subscript);
4289         if (!ret) {
4290             ast_delete(subscript);
4291             return NULL;
4292         }
4293
4294         return (ast_expression*)ret;
4295     } else {
4296         ast_expression *left, *right;
4297         size_t diff = afterend - from;
4298         size_t middle = from + diff/2;
4299         left  = array_getter_node(parser, array, index, from, middle);
4300         right = array_getter_node(parser, array, index, middle, afterend);
4301         return array_accessor_split(parser, array, index, middle, left, right);
4302     }
4303 }
4304
4305 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4306 {
4307     ast_function   *func = NULL;
4308     ast_value      *fval = NULL;
4309     ast_block      *body = NULL;
4310
4311     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4312     if (!fval) {
4313         parseerror(parser, "failed to create accessor function value");
4314         return false;
4315     }
4316
4317     func = ast_function_new(ast_ctx(array), funcname, fval);
4318     if (!func) {
4319         ast_delete(fval);
4320         parseerror(parser, "failed to create accessor function node");
4321         return false;
4322     }
4323
4324     body = ast_block_new(ast_ctx(array));
4325     if (!body) {
4326         parseerror(parser, "failed to create block for array accessor");
4327         ast_delete(fval);
4328         ast_delete(func);
4329         return false;
4330     }
4331
4332     vec_push(func->blocks, body);
4333     *out = fval;
4334
4335     vec_push(parser->accessors, fval);
4336
4337     return true;
4338 }
4339
4340 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4341 {
4342     ast_value      *index = NULL;
4343     ast_value      *value = NULL;
4344     ast_function   *func;
4345     ast_value      *fval;
4346
4347     if (!ast_istype(array->expression.next, ast_value)) {
4348         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4349         return NULL;
4350     }
4351
4352     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4353         return NULL;
4354     func = fval->constval.vfunc;
4355     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4356
4357     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4358     value = ast_value_copy((ast_value*)array->expression.next);
4359
4360     if (!index || !value) {
4361         parseerror(parser, "failed to create locals for array accessor");
4362         goto cleanup;
4363     }
4364     (void)!ast_value_set_name(value, "value"); /* not important */
4365     vec_push(fval->expression.params, index);
4366     vec_push(fval->expression.params, value);
4367
4368     array->setter = fval;
4369     return fval;
4370 cleanup:
4371     if (index) ast_delete(index);
4372     if (value) ast_delete(value);
4373     ast_delete(func);
4374     ast_delete(fval);
4375     return NULL;
4376 }
4377
4378 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4379 {
4380     ast_expression *root = NULL;
4381     root = array_setter_node(parser, array,
4382                              array->setter->expression.params[0],
4383                              array->setter->expression.params[1],
4384                              0, array->expression.count);
4385     if (!root) {
4386         parseerror(parser, "failed to build accessor search tree");
4387         return false;
4388     }
4389     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4390         ast_delete(root);
4391         return false;
4392     }
4393     return true;
4394 }
4395
4396 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4397 {
4398     if (!parser_create_array_setter_proto(parser, array, funcname))
4399         return false;
4400     return parser_create_array_setter_impl(parser, array);
4401 }
4402
4403 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4404 {
4405     ast_expression *root = NULL;
4406     ast_value      *entity = NULL;
4407     ast_value      *index = NULL;
4408     ast_value      *value = NULL;
4409     ast_function   *func;
4410     ast_value      *fval;
4411
4412     if (!ast_istype(array->expression.next, ast_value)) {
4413         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4414         return false;
4415     }
4416
4417     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4418         return false;
4419     func = fval->constval.vfunc;
4420     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4421
4422     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4423     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4424     value  = ast_value_copy((ast_value*)array->expression.next);
4425     if (!entity || !index || !value) {
4426         parseerror(parser, "failed to create locals for array accessor");
4427         goto cleanup;
4428     }
4429     (void)!ast_value_set_name(value, "value"); /* not important */
4430     vec_push(fval->expression.params, entity);
4431     vec_push(fval->expression.params, index);
4432     vec_push(fval->expression.params, value);
4433
4434     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4435     if (!root) {
4436         parseerror(parser, "failed to build accessor search tree");
4437         goto cleanup;
4438     }
4439
4440     array->setter = fval;
4441     return ast_block_add_expr(func->blocks[0], root);
4442 cleanup:
4443     if (entity) ast_delete(entity);
4444     if (index)  ast_delete(index);
4445     if (value)  ast_delete(value);
4446     if (root)   ast_delete(root);
4447     ast_delete(func);
4448     ast_delete(fval);
4449     return false;
4450 }
4451
4452 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4453 {
4454     ast_value      *index = NULL;
4455     ast_value      *fval;
4456     ast_function   *func;
4457
4458     /* NOTE: checking array->expression.next rather than elemtype since
4459      * for fields elemtype is a temporary fieldtype.
4460      */
4461     if (!ast_istype(array->expression.next, ast_value)) {
4462         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4463         return NULL;
4464     }
4465
4466     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4467         return NULL;
4468     func = fval->constval.vfunc;
4469     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4470
4471     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4472
4473     if (!index) {
4474         parseerror(parser, "failed to create locals for array accessor");
4475         goto cleanup;
4476     }
4477     vec_push(fval->expression.params, index);
4478
4479     array->getter = fval;
4480     return fval;
4481 cleanup:
4482     if (index) ast_delete(index);
4483     ast_delete(func);
4484     ast_delete(fval);
4485     return NULL;
4486 }
4487
4488 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4489 {
4490     ast_expression *root = NULL;
4491
4492     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4493     if (!root) {
4494         parseerror(parser, "failed to build accessor search tree");
4495         return false;
4496     }
4497     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4498         ast_delete(root);
4499         return false;
4500     }
4501     return true;
4502 }
4503
4504 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4505 {
4506     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4507         return false;
4508     return parser_create_array_getter_impl(parser, array);
4509 }
4510
4511 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4512 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4513 {
4514     lex_ctx     ctx;
4515     size_t      i;
4516     ast_value **params;
4517     ast_value  *param;
4518     ast_value  *fval;
4519     bool        first = true;
4520     bool        variadic = false;
4521     ast_value  *varparam = NULL;
4522     char       *argcounter = NULL;
4523
4524     ctx = parser_ctx(parser);
4525
4526     /* for the sake of less code we parse-in in this function */
4527     if (!parser_next(parser)) {
4528         parseerror(parser, "expected parameter list");
4529         return NULL;
4530     }
4531
4532     params = NULL;
4533
4534     /* parse variables until we hit a closing paren */
4535     while (parser->tok != ')') {
4536         if (!first) {
4537             /* there must be commas between them */
4538             if (parser->tok != ',') {
4539                 parseerror(parser, "expected comma or end of parameter list");
4540                 goto on_error;
4541             }
4542             if (!parser_next(parser)) {
4543                 parseerror(parser, "expected parameter");
4544                 goto on_error;
4545             }
4546         }
4547         first = false;
4548
4549         if (parser->tok == TOKEN_DOTS) {
4550             /* '...' indicates a varargs function */
4551             variadic = true;
4552             if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4553                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4554                 goto on_error;
4555             }
4556             if (parser->tok == TOKEN_IDENT) {
4557                 argcounter = util_strdup(parser_tokval(parser));
4558                 if (!parser_next(parser) || parser->tok != ')') {
4559                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4560                     goto on_error;
4561                 }
4562             }
4563         }
4564         else
4565         {
4566             /* for anything else just parse a typename */
4567             param = parse_typename(parser, NULL, NULL);
4568             if (!param)
4569                 goto on_error;
4570             vec_push(params, param);
4571             if (param->expression.vtype >= TYPE_VARIANT) {
4572                 char tname[1024]; /* typename is reserved in C++ */
4573                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4574                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4575                 goto on_error;
4576             }
4577             /* type-restricted varargs */
4578             if (parser->tok == TOKEN_DOTS) {
4579                 variadic = true;
4580                 varparam = vec_last(params);
4581                 vec_pop(params);
4582                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4583                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4584                     goto on_error;
4585                 }
4586                 if (parser->tok == TOKEN_IDENT) {
4587                     argcounter = util_strdup(parser_tokval(parser));
4588                     if (!parser_next(parser) || parser->tok != ')') {
4589                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4590                         goto on_error;
4591                     }
4592                 }
4593             }
4594         }
4595     }
4596
4597     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4598         vec_free(params);
4599
4600     /* sanity check */
4601     if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4602         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4603
4604     /* parse-out */
4605     if (!parser_next(parser)) {
4606         parseerror(parser, "parse error after typename");
4607         goto on_error;
4608     }
4609
4610     /* now turn 'var' into a function type */
4611     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4612     fval->expression.next     = (ast_expression*)var;
4613     if (variadic)
4614         fval->expression.flags |= AST_FLAG_VARIADIC;
4615     var = fval;
4616
4617     var->expression.params   = params;
4618     var->expression.varparam = (ast_expression*)varparam;
4619     var->argcounter          = argcounter;
4620     params = NULL;
4621
4622     return var;
4623
4624 on_error:
4625     if (argcounter)
4626         mem_d(argcounter);
4627     ast_delete(var);
4628     for (i = 0; i < vec_size(params); ++i)
4629         ast_delete(params[i]);
4630     vec_free(params);
4631     return NULL;
4632 }
4633
4634 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4635 {
4636     ast_expression *cexp;
4637     ast_value      *cval, *tmp;
4638     lex_ctx ctx;
4639
4640     ctx = parser_ctx(parser);
4641
4642     if (!parser_next(parser)) {
4643         ast_delete(var);
4644         parseerror(parser, "expected array-size");
4645         return NULL;
4646     }
4647
4648     cexp = parse_expression_leave(parser, true, false, false);
4649
4650     if (!cexp || !ast_istype(cexp, ast_value)) {
4651         if (cexp)
4652             ast_unref(cexp);
4653         ast_delete(var);
4654         parseerror(parser, "expected array-size as constant positive integer");
4655         return NULL;
4656     }
4657     cval = (ast_value*)cexp;
4658
4659     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4660     tmp->expression.next = (ast_expression*)var;
4661     var = tmp;
4662
4663     if (cval->expression.vtype == TYPE_INTEGER)
4664         tmp->expression.count = cval->constval.vint;
4665     else if (cval->expression.vtype == TYPE_FLOAT)
4666         tmp->expression.count = cval->constval.vfloat;
4667     else {
4668         ast_unref(cexp);
4669         ast_delete(var);
4670         parseerror(parser, "array-size must be a positive integer constant");
4671         return NULL;
4672     }
4673     ast_unref(cexp);
4674
4675     if (parser->tok != ']') {
4676         ast_delete(var);
4677         parseerror(parser, "expected ']' after array-size");
4678         return NULL;
4679     }
4680     if (!parser_next(parser)) {
4681         ast_delete(var);
4682         parseerror(parser, "error after parsing array size");
4683         return NULL;
4684     }
4685     return var;
4686 }
4687
4688 /* Parse a complete typename.
4689  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4690  * but when parsing variables separated by comma
4691  * 'storebase' should point to where the base-type should be kept.
4692  * The base type makes up every bit of type information which comes *before* the
4693  * variable name.
4694  *
4695  * The following will be parsed in its entirety:
4696  *     void() foo()
4697  * The 'basetype' in this case is 'void()'
4698  * and if there's a comma after it, say:
4699  *     void() foo(), bar
4700  * then the type-information 'void()' can be stored in 'storebase'
4701  */
4702 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4703 {
4704     ast_value *var, *tmp;
4705     lex_ctx    ctx;
4706
4707     const char *name = NULL;
4708     bool        isfield  = false;
4709     bool        wasarray = false;
4710     size_t      morefields = 0;
4711
4712     ctx = parser_ctx(parser);
4713
4714     /* types may start with a dot */
4715     if (parser->tok == '.') {
4716         isfield = true;
4717         /* if we parsed a dot we need a typename now */
4718         if (!parser_next(parser)) {
4719             parseerror(parser, "expected typename for field definition");
4720             return NULL;
4721         }
4722
4723         /* Further dots are handled seperately because they won't be part of the
4724          * basetype
4725          */
4726         while (parser->tok == '.') {
4727             ++morefields;
4728             if (!parser_next(parser)) {
4729                 parseerror(parser, "expected typename for field definition");
4730                 return NULL;
4731             }
4732         }
4733     }
4734     if (parser->tok == TOKEN_IDENT)
4735         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4736     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4737         parseerror(parser, "expected typename");
4738         return NULL;
4739     }
4740
4741     /* generate the basic type value */
4742     if (cached_typedef) {
4743         var = ast_value_copy(cached_typedef);
4744         ast_value_set_name(var, "<type(from_def)>");
4745     } else
4746         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4747
4748     for (; morefields; --morefields) {
4749         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4750         tmp->expression.next = (ast_expression*)var;
4751         var = tmp;
4752     }
4753
4754     /* do not yet turn into a field - remember:
4755      * .void() foo; is a field too
4756      * .void()() foo; is a function
4757      */
4758
4759     /* parse on */
4760     if (!parser_next(parser)) {
4761         ast_delete(var);
4762         parseerror(parser, "parse error after typename");
4763         return NULL;
4764     }
4765
4766     /* an opening paren now starts the parameter-list of a function
4767      * this is where original-QC has parameter lists.
4768      * We allow a single parameter list here.
4769      * Much like fteqcc we don't allow `float()() x`
4770      */
4771     if (parser->tok == '(') {
4772         var = parse_parameter_list(parser, var);
4773         if (!var)
4774             return NULL;
4775     }
4776
4777     /* store the base if requested */
4778     if (storebase) {
4779         *storebase = ast_value_copy(var);
4780         if (isfield) {
4781             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4782             tmp->expression.next = (ast_expression*)*storebase;
4783             *storebase = tmp;
4784         }
4785     }
4786
4787     /* there may be a name now */
4788     if (parser->tok == TOKEN_IDENT) {
4789         name = util_strdup(parser_tokval(parser));
4790         /* parse on */
4791         if (!parser_next(parser)) {
4792             ast_delete(var);
4793             parseerror(parser, "error after variable or field declaration");
4794             return NULL;
4795         }
4796     }
4797
4798     /* now this may be an array */
4799     if (parser->tok == '[') {
4800         wasarray = true;
4801         var = parse_arraysize(parser, var);
4802         if (!var)
4803             return NULL;
4804     }
4805
4806     /* This is the point where we can turn it into a field */
4807     if (isfield) {
4808         /* turn it into a field if desired */
4809         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4810         tmp->expression.next = (ast_expression*)var;
4811         var = tmp;
4812     }
4813
4814     /* now there may be function parens again */
4815     if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4816         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4817     if (parser->tok == '(' && wasarray)
4818         parseerror(parser, "arrays as part of a return type is not supported");
4819     while (parser->tok == '(') {
4820         var = parse_parameter_list(parser, var);
4821         if (!var) {
4822             if (name)
4823                 mem_d((void*)name);
4824             return NULL;
4825         }
4826     }
4827
4828     /* finally name it */
4829     if (name) {
4830         if (!ast_value_set_name(var, name)) {
4831             ast_delete(var);
4832             parseerror(parser, "internal error: failed to set name");
4833             return NULL;
4834         }
4835         /* free the name, ast_value_set_name duplicates */
4836         mem_d((void*)name);
4837     }
4838
4839     return var;
4840 }
4841
4842 static bool parse_typedef(parser_t *parser)
4843 {
4844     ast_value      *typevar, *oldtype;
4845     ast_expression *old;
4846
4847     typevar = parse_typename(parser, NULL, NULL);
4848
4849     if (!typevar)
4850         return false;
4851
4852     if ( (old = parser_find_var(parser, typevar->name)) ) {
4853         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4854                    " -> `%s` has been declared here: %s:%i",
4855                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4856         ast_delete(typevar);
4857         return false;
4858     }
4859
4860     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4861         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4862                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4863         ast_delete(typevar);
4864         return false;
4865     }
4866
4867     vec_push(parser->_typedefs, typevar);
4868     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4869
4870     if (parser->tok != ';') {
4871         parseerror(parser, "expected semicolon after typedef");
4872         return false;
4873     }
4874     if (!parser_next(parser)) {
4875         parseerror(parser, "parse error after typedef");
4876         return false;
4877     }
4878
4879     return true;
4880 }
4881
4882 static const char *cvq_to_str(int cvq) {
4883     switch (cvq) {
4884         case CV_NONE:  return "none";
4885         case CV_VAR:   return "`var`";
4886         case CV_CONST: return "`const`";
4887         default:       return "<INVALID>";
4888     }
4889 }
4890
4891 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4892 {
4893     bool av, ao;
4894     if (proto->cvq != var->cvq) {
4895         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4896               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4897               parser->tok == '='))
4898         {
4899             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4900                                  "`%s` declared with different qualifiers: %s\n"
4901                                  " -> previous declaration here: %s:%i uses %s",
4902                                  var->name, cvq_to_str(var->cvq),
4903                                  ast_ctx(proto).file, ast_ctx(proto).line,
4904                                  cvq_to_str(proto->cvq));
4905         }
4906     }
4907     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4908     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4909     if (!av != !ao) {
4910         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4911                              "`%s` declared with different attributes%s\n"
4912                              " -> previous declaration here: %s:%i",
4913                              var->name, (av ? ": noreturn" : ""),
4914                              ast_ctx(proto).file, ast_ctx(proto).line,
4915                              (ao ? ": noreturn" : ""));
4916     }
4917     return true;
4918 }
4919
4920 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)
4921 {
4922     ast_value *var;
4923     ast_value *proto;
4924     ast_expression *old;
4925     bool       was_end;
4926     size_t     i;
4927
4928     ast_value *basetype = NULL;
4929     bool      retval    = true;
4930     bool      isparam   = false;
4931     bool      isvector  = false;
4932     bool      cleanvar  = true;
4933     bool      wasarray  = false;
4934
4935     ast_member *me[3];
4936
4937     if (!localblock && is_static)
4938         parseerror(parser, "`static` qualifier is not supported in global scope");
4939
4940     /* get the first complete variable */
4941     var = parse_typename(parser, &basetype, cached_typedef);
4942     if (!var) {
4943         if (basetype)
4944             ast_delete(basetype);
4945         return false;
4946     }
4947
4948     while (true) {
4949         proto = NULL;
4950         wasarray = false;
4951
4952         /* Part 0: finish the type */
4953         if (parser->tok == '(') {
4954             if (opts.standard == COMPILER_QCC)
4955                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4956             var = parse_parameter_list(parser, var);
4957             if (!var) {
4958                 retval = false;
4959                 goto cleanup;
4960             }
4961         }
4962         /* we only allow 1-dimensional arrays */
4963         if (parser->tok == '[') {
4964             wasarray = true;
4965             var = parse_arraysize(parser, var);
4966             if (!var) {
4967                 retval = false;
4968                 goto cleanup;
4969             }
4970         }
4971         if (parser->tok == '(' && wasarray) {
4972             parseerror(parser, "arrays as part of a return type is not supported");
4973             /* we'll still parse the type completely for now */
4974         }
4975         /* for functions returning functions */
4976         while (parser->tok == '(') {
4977             if (opts.standard == COMPILER_QCC)
4978                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4979             var = parse_parameter_list(parser, var);
4980             if (!var) {
4981                 retval = false;
4982                 goto cleanup;
4983             }
4984         }
4985
4986         var->cvq = qualifier;
4987         var->expression.flags |= qflags;
4988         if (var->expression.flags & AST_FLAG_DEPRECATED)
4989             var->desc = vstring;
4990
4991         /* Part 1:
4992          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4993          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4994          * is then filled with the previous definition and the parameter-names replaced.
4995          */
4996         if (!strcmp(var->name, "nil")) {
4997             if (OPTS_FLAG(UNTYPED_NIL)) {
4998                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4999                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5000             } else
5001                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5002         }
5003         if (!localblock) {
5004             /* Deal with end_sys_ vars */
5005             was_end = false;
5006             if (!strcmp(var->name, "end_sys_globals")) {
5007                 var->uses++;
5008                 parser->crc_globals = vec_size(parser->globals);
5009                 was_end = true;
5010             }
5011             else if (!strcmp(var->name, "end_sys_fields")) {
5012                 var->uses++;
5013                 parser->crc_fields = vec_size(parser->fields);
5014                 was_end = true;
5015             }
5016             if (was_end && var->expression.vtype == TYPE_FIELD) {
5017                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5018                                  "global '%s' hint should not be a field",
5019                                  parser_tokval(parser)))
5020                 {
5021                     retval = false;
5022                     goto cleanup;
5023                 }
5024             }
5025
5026             if (!nofields && var->expression.vtype == TYPE_FIELD)
5027             {
5028                 /* deal with field declarations */
5029                 old = parser_find_field(parser, var->name);
5030                 if (old) {
5031                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5032                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5033                     {
5034                         retval = false;
5035                         goto cleanup;
5036                     }
5037                     ast_delete(var);
5038                     var = NULL;
5039                     goto skipvar;
5040                     /*
5041                     parseerror(parser, "field `%s` already declared here: %s:%i",
5042                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5043                     retval = false;
5044                     goto cleanup;
5045                     */
5046                 }
5047                 if ((opts.standard == COMPILER_QCC || opts.standard == COMPILER_FTEQCC) &&
5048                     (old = parser_find_global(parser, var->name)))
5049                 {
5050                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5051                     parseerror(parser, "field `%s` already declared here: %s:%i",
5052                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5053                     retval = false;
5054                     goto cleanup;
5055                 }
5056             }
5057             else
5058             {
5059                 /* deal with other globals */
5060                 old = parser_find_global(parser, var->name);
5061                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5062                 {
5063                     /* This is a function which had a prototype */
5064                     if (!ast_istype(old, ast_value)) {
5065                         parseerror(parser, "internal error: prototype is not an ast_value");
5066                         retval = false;
5067                         goto cleanup;
5068                     }
5069                     proto = (ast_value*)old;
5070                     proto->desc = var->desc;
5071                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5072                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5073                                    proto->name,
5074                                    ast_ctx(proto).file, ast_ctx(proto).line);
5075                         retval = false;
5076                         goto cleanup;
5077                     }
5078                     /* we need the new parameter-names */
5079                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5080                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5081                     if (!parser_check_qualifiers(parser, var, proto)) {
5082                         retval = false;
5083                         if (proto->desc) 
5084                             mem_d(proto->desc);
5085                         proto = NULL;
5086                         goto cleanup;
5087                     }
5088                     proto->expression.flags |= var->expression.flags;
5089                     ast_delete(var);
5090                     var = proto;
5091                 }
5092                 else
5093                 {
5094                     /* other globals */
5095                     if (old) {
5096                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5097                                          "global `%s` already declared here: %s:%i",
5098                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5099                         {
5100                             retval = false;
5101                             goto cleanup;
5102                         }
5103                         proto = (ast_value*)old;
5104                         if (!ast_istype(old, ast_value)) {
5105                             parseerror(parser, "internal error: not an ast_value");
5106                             retval = false;
5107                             proto = NULL;
5108                             goto cleanup;
5109                         }
5110                         if (!parser_check_qualifiers(parser, var, proto)) {
5111                             retval = false;
5112                             proto = NULL;
5113                             goto cleanup;
5114                         }
5115                         proto->expression.flags |= var->expression.flags;
5116                         ast_delete(var);
5117                         var = proto;
5118                     }
5119                     if (opts.standard == COMPILER_QCC &&
5120                         (old = parser_find_field(parser, var->name)))
5121                     {
5122                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5123                         parseerror(parser, "global `%s` already declared here: %s:%i",
5124                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5125                         retval = false;
5126                         goto cleanup;
5127                     }
5128                 }
5129             }
5130         }
5131         else /* it's not a global */
5132         {
5133             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5134             if (old && !isparam) {
5135                 parseerror(parser, "local `%s` already declared here: %s:%i",
5136                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5137                 retval = false;
5138                 goto cleanup;
5139             }
5140             old = parser_find_local(parser, var->name, 0, &isparam);
5141             if (old && isparam) {
5142                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5143                                  "local `%s` is shadowing a parameter", var->name))
5144                 {
5145                     parseerror(parser, "local `%s` already declared here: %s:%i",
5146                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5147                     retval = false;
5148                     goto cleanup;
5149                 }
5150                 if (opts.standard != COMPILER_GMQCC) {
5151                     ast_delete(var);
5152                     var = NULL;
5153                     goto skipvar;
5154                 }
5155             }
5156         }
5157
5158         /* in a noref section we simply bump the usecount */
5159         if (noref || parser->noref)
5160             var->uses++;
5161
5162         /* Part 2:
5163          * Create the global/local, and deal with vector types.
5164          */
5165         if (!proto) {
5166             if (var->expression.vtype == TYPE_VECTOR)
5167                 isvector = true;
5168             else if (var->expression.vtype == TYPE_FIELD &&
5169                      var->expression.next->expression.vtype == TYPE_VECTOR)
5170                 isvector = true;
5171
5172             if (isvector) {
5173                 if (!create_vector_members(var, me)) {
5174                     retval = false;
5175                     goto cleanup;
5176                 }
5177             }
5178
5179             if (!localblock) {
5180                 /* deal with global variables, fields, functions */
5181                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5182                     var->isfield = true;
5183                     vec_push(parser->fields, (ast_expression*)var);
5184                     util_htset(parser->htfields, var->name, var);
5185                     if (isvector) {
5186                         for (i = 0; i < 3; ++i) {
5187                             vec_push(parser->fields, (ast_expression*)me[i]);
5188                             util_htset(parser->htfields, me[i]->name, me[i]);
5189                         }
5190                     }
5191                 }
5192                 else {
5193                     parser_addglobal(parser, var->name, (ast_expression*)var);
5194                     if (isvector) {
5195                         for (i = 0; i < 3; ++i) {
5196                             parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5197                         }
5198                     }
5199                 }
5200             } else {
5201                 if (is_static) {
5202                     /* a static adds itself to be generated like any other global
5203                      * but is added to the local namespace instead
5204                      */
5205                     char   *defname = NULL;
5206                     size_t  prefix_len, ln;
5207
5208                     ln = strlen(parser->function->name);
5209                     vec_append(defname, ln, parser->function->name);
5210
5211                     vec_append(defname, 2, "::");
5212                     /* remember the length up to here */
5213                     prefix_len = vec_size(defname);
5214
5215                     /* Add it to the local scope */
5216                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5217
5218                     /* corrector */
5219                     correct_add (
5220                          vec_last(parser->correct_variables),
5221                         &vec_last(parser->correct_variables_score),
5222                         var->name
5223                     );
5224
5225                     /* now rename the global */
5226                     ln = strlen(var->name);
5227                     vec_append(defname, ln, var->name);
5228                     ast_value_set_name(var, defname);
5229
5230                     /* push it to the to-be-generated globals */
5231                     vec_push(parser->globals, (ast_expression*)var);
5232
5233                     /* same game for the vector members */
5234                     if (isvector) {
5235                         for (i = 0; i < 3; ++i) {
5236                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5237
5238                             /* corrector */
5239                             correct_add(
5240                                  vec_last(parser->correct_variables),
5241                                 &vec_last(parser->correct_variables_score),
5242                                 me[i]->name
5243                             );
5244
5245                             vec_shrinkto(defname, prefix_len);
5246                             ln = strlen(me[i]->name);
5247                             vec_append(defname, ln, me[i]->name);
5248                             ast_member_set_name(me[i], defname);
5249
5250                             vec_push(parser->globals, (ast_expression*)me[i]);
5251                         }
5252                     }
5253                     vec_free(defname);
5254                 } else {
5255                     vec_push(localblock->locals, var);
5256                     parser_addlocal(parser, var->name, (ast_expression*)var);
5257                     if (isvector) {
5258                         for (i = 0; i < 3; ++i) {
5259                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5260                             ast_block_collect(localblock, (ast_expression*)me[i]);
5261                         }
5262                     }
5263                 }
5264             }
5265         }
5266         me[0] = me[1] = me[2] = NULL;
5267         cleanvar = false;
5268         /* Part 2.2
5269          * deal with arrays
5270          */
5271         if (var->expression.vtype == TYPE_ARRAY) {
5272             char name[1024];
5273             snprintf(name, sizeof(name), "%s##SET", var->name);
5274             if (!parser_create_array_setter(parser, var, name))
5275                 goto cleanup;
5276             snprintf(name, sizeof(name), "%s##GET", var->name);
5277             if (!parser_create_array_getter(parser, var, var->expression.next, name))
5278                 goto cleanup;
5279         }
5280         else if (!localblock && !nofields &&
5281                  var->expression.vtype == TYPE_FIELD &&
5282                  var->expression.next->expression.vtype == TYPE_ARRAY)
5283         {
5284             char name[1024];
5285             ast_expression *telem;
5286             ast_value      *tfield;
5287             ast_value      *array = (ast_value*)var->expression.next;
5288
5289             if (!ast_istype(var->expression.next, ast_value)) {
5290                 parseerror(parser, "internal error: field element type must be an ast_value");
5291                 goto cleanup;
5292             }
5293
5294             snprintf(name, sizeof(name), "%s##SETF", var->name);
5295             if (!parser_create_array_field_setter(parser, array, name))
5296                 goto cleanup;
5297
5298             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5299             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5300             tfield->expression.next = telem;
5301             snprintf(name, sizeof(name), "%s##GETFP", var->name);
5302             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5303                 ast_delete(tfield);
5304                 goto cleanup;
5305             }
5306             ast_delete(tfield);
5307         }
5308
5309 skipvar:
5310         if (parser->tok == ';') {
5311             ast_delete(basetype);
5312             if (!parser_next(parser)) {
5313                 parseerror(parser, "error after variable declaration");
5314                 return false;
5315             }
5316             return true;
5317         }
5318
5319         if (parser->tok == ',')
5320             goto another;
5321
5322         /*
5323         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5324         */
5325         if (!var) {
5326             parseerror(parser, "missing comma or semicolon while parsing variables");
5327             break;
5328         }
5329
5330         if (localblock && opts.standard == COMPILER_QCC) {
5331             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5332                              "initializing expression turns variable `%s` into a constant in this standard",
5333                              var->name) )
5334             {
5335                 break;
5336             }
5337         }
5338
5339         if (parser->tok != '{') {
5340             if (parser->tok != '=') {
5341                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5342                 break;
5343             }
5344
5345             if (!parser_next(parser)) {
5346                 parseerror(parser, "error parsing initializer");
5347                 break;
5348             }
5349         }
5350         else if (opts.standard == COMPILER_QCC) {
5351             parseerror(parser, "expected '=' before function body in this standard");
5352         }
5353
5354         if (parser->tok == '#') {
5355             ast_function *func = NULL;
5356
5357             if (localblock) {
5358                 parseerror(parser, "cannot declare builtins within functions");
5359                 break;
5360             }
5361             if (var->expression.vtype != TYPE_FUNCTION) {
5362                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5363                 break;
5364             }
5365             if (!parser_next(parser)) {
5366                 parseerror(parser, "expected builtin number");
5367                 break;
5368             }
5369             if (parser->tok != TOKEN_INTCONST) {
5370                 parseerror(parser, "builtin number must be an integer constant");
5371                 break;
5372             }
5373             if (parser_token(parser)->constval.i < 0) {
5374                 parseerror(parser, "builtin number must be an integer greater than zero");
5375                 break;
5376             }
5377
5378             if (var->hasvalue) {
5379                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5380                                     "builtin `%s` has already been defined\n"
5381                                     " -> previous declaration here: %s:%i",
5382                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5383             }
5384             else
5385             {
5386                 func = ast_function_new(ast_ctx(var), var->name, var);
5387                 if (!func) {
5388                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5389                     break;
5390                 }
5391                 vec_push(parser->functions, func);
5392
5393                 func->builtin = -parser_token(parser)->constval.i-1;
5394             }
5395
5396             if (!parser_next(parser)) {
5397                 parseerror(parser, "expected comma or semicolon");
5398                 if (func)
5399                     ast_function_delete(func);
5400                 var->constval.vfunc = NULL;
5401                 break;
5402             }
5403         }
5404         else if (parser->tok == '{' || parser->tok == '[')
5405         {
5406             if (localblock) {
5407                 parseerror(parser, "cannot declare functions within functions");
5408                 break;
5409             }
5410
5411             if (proto)
5412                 ast_ctx(proto) = parser_ctx(parser);
5413
5414             if (!parse_function_body(parser, var))
5415                 break;
5416             ast_delete(basetype);
5417             for (i = 0; i < vec_size(parser->gotos); ++i)
5418                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5419             vec_free(parser->gotos);
5420             vec_free(parser->labels);
5421             return true;
5422         } else {
5423             ast_expression *cexp;
5424             ast_value      *cval;
5425
5426             cexp = parse_expression_leave(parser, true, false, false);
5427             if (!cexp)
5428                 break;
5429
5430             if (!localblock) {
5431                 cval = (ast_value*)cexp;
5432                 if (cval != parser->nil &&
5433                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5434                    )
5435                 {
5436                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5437                 }
5438                 else
5439                 {
5440                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5441                         qualifier != CV_VAR)
5442                     {
5443                         var->cvq = CV_CONST;
5444                     }
5445                     if (cval == parser->nil)
5446                         var->expression.flags |= AST_FLAG_INITIALIZED;
5447                     else
5448                     {
5449                         var->hasvalue = true;
5450                         if (cval->expression.vtype == TYPE_STRING)
5451                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5452                         else if (cval->expression.vtype == TYPE_FIELD)
5453                             var->constval.vfield = cval;
5454                         else
5455                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5456                         ast_unref(cval);
5457                     }
5458                 }
5459             } else {
5460                 int cvq;
5461                 shunt sy = { NULL, NULL };
5462                 cvq = var->cvq;
5463                 var->cvq = CV_NONE;
5464                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5465                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5466                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5467                 if (!parser_sy_apply_operator(parser, &sy))
5468                     ast_unref(cexp);
5469                 else {
5470                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5471                         parseerror(parser, "internal error: leaked operands");
5472                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5473                         break;
5474                 }
5475                 vec_free(sy.out);
5476                 vec_free(sy.ops);
5477                 var->cvq = cvq;
5478             }
5479         }
5480
5481 another:
5482         if (parser->tok == ',') {
5483             if (!parser_next(parser)) {
5484                 parseerror(parser, "expected another variable");
5485                 break;
5486             }
5487
5488             if (parser->tok != TOKEN_IDENT) {
5489                 parseerror(parser, "expected another variable");
5490                 break;
5491             }
5492             var = ast_value_copy(basetype);
5493             cleanvar = true;
5494             ast_value_set_name(var, parser_tokval(parser));
5495             if (!parser_next(parser)) {
5496                 parseerror(parser, "error parsing variable declaration");
5497                 break;
5498             }
5499             continue;
5500         }
5501
5502         if (parser->tok != ';') {
5503             parseerror(parser, "missing semicolon after variables");
5504             break;
5505         }
5506
5507         if (!parser_next(parser)) {
5508             parseerror(parser, "parse error after variable declaration");
5509             break;
5510         }
5511
5512         ast_delete(basetype);
5513         return true;
5514     }
5515
5516     if (cleanvar && var)
5517         ast_delete(var);
5518     ast_delete(basetype);
5519     return false;
5520
5521 cleanup:
5522     ast_delete(basetype);
5523     if (cleanvar && var)
5524         ast_delete(var);
5525     if (me[0]) ast_member_delete(me[0]);
5526     if (me[1]) ast_member_delete(me[1]);
5527     if (me[2]) ast_member_delete(me[2]);
5528     return retval;
5529 }
5530
5531 static bool parser_global_statement(parser_t *parser)
5532 {
5533     int        cvq       = CV_WRONG;
5534     bool       noref     = false;
5535     bool       is_static = false;
5536     uint32_t   qflags    = 0;
5537     ast_value *istype    = NULL;
5538     char      *vstring   = NULL;
5539
5540     if (parser->tok == TOKEN_IDENT)
5541         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5542
5543     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5544     {
5545         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5546     }
5547     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5548     {
5549         if (cvq == CV_WRONG)
5550             return false;
5551         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5552     }
5553     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5554     {
5555         return parse_enum(parser);
5556     }
5557     else if (parser->tok == TOKEN_KEYWORD)
5558     {
5559         if (!strcmp(parser_tokval(parser), "typedef")) {
5560             if (!parser_next(parser)) {
5561                 parseerror(parser, "expected type definition after 'typedef'");
5562                 return false;
5563             }
5564             return parse_typedef(parser);
5565         }
5566         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5567         return false;
5568     }
5569     else if (parser->tok == '#')
5570     {
5571         return parse_pragma(parser);
5572     }
5573     else if (parser->tok == '$')
5574     {
5575         if (!parser_next(parser)) {
5576             parseerror(parser, "parse error");
5577             return false;
5578         }
5579     }
5580     else
5581     {
5582         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5583         return false;
5584     }
5585     return true;
5586 }
5587
5588 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5589 {
5590     return util_crc16(old, str, strlen(str));
5591 }
5592
5593 static void progdefs_crc_file(const char *str)
5594 {
5595     /* write to progdefs.h here */
5596     (void)str;
5597 }
5598
5599 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5600 {
5601     old = progdefs_crc_sum(old, str);
5602     progdefs_crc_file(str);
5603     return old;
5604 }
5605
5606 static void generate_checksum(parser_t *parser)
5607 {
5608     uint16_t   crc = 0xFFFF;
5609     size_t     i;
5610     ast_value *value;
5611
5612     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5613     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5614     /*
5615     progdefs_crc_file("\tint\tpad;\n");
5616     progdefs_crc_file("\tint\tofs_return[3];\n");
5617     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5618     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5619     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5620     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5621     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5622     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5623     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5624     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5625     */
5626     for (i = 0; i < parser->crc_globals; ++i) {
5627         if (!ast_istype(parser->globals[i], ast_value))
5628             continue;
5629         value = (ast_value*)(parser->globals[i]);
5630         switch (value->expression.vtype) {
5631             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5632             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5633             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5634             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5635             default:
5636                 crc = progdefs_crc_both(crc, "\tint\t");
5637                 break;
5638         }
5639         crc = progdefs_crc_both(crc, value->name);
5640         crc = progdefs_crc_both(crc, ";\n");
5641     }
5642     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5643     for (i = 0; i < parser->crc_fields; ++i) {
5644         if (!ast_istype(parser->fields[i], ast_value))
5645             continue;
5646         value = (ast_value*)(parser->fields[i]);
5647         switch (value->expression.next->expression.vtype) {
5648             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5649             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5650             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5651             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5652             default:
5653                 crc = progdefs_crc_both(crc, "\tint\t");
5654                 break;
5655         }
5656         crc = progdefs_crc_both(crc, value->name);
5657         crc = progdefs_crc_both(crc, ";\n");
5658     }
5659     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5660
5661     code_crc = crc;
5662 }
5663
5664 static parser_t *parser;
5665
5666 bool parser_init()
5667 {
5668     lex_ctx empty_ctx;
5669     size_t i;
5670
5671     parser = (parser_t*)mem_a(sizeof(parser_t));
5672     if (!parser)
5673         return false;
5674
5675     memset(parser, 0, sizeof(*parser));
5676
5677     for (i = 0; i < operator_count; ++i) {
5678         if (operators[i].id == opid1('=')) {
5679             parser->assign_op = operators+i;
5680             break;
5681         }
5682     }
5683     if (!parser->assign_op) {
5684         printf("internal error: initializing parser: failed to find assign operator\n");
5685         mem_d(parser);
5686         return false;
5687     }
5688
5689     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5690     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5691     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5692     vec_push(parser->_blocktypedefs, 0);
5693
5694     /* corrector */
5695     vec_push(parser->correct_variables, correct_trie_new());
5696     vec_push(parser->correct_variables_score, NULL);
5697
5698     empty_ctx.file = "<internal>";
5699     empty_ctx.line = 0;
5700     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5701     parser->nil->cvq = CV_CONST;
5702     if (OPTS_FLAG(UNTYPED_NIL))
5703         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5704
5705     parser->max_param_count = 1;
5706
5707     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5708     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5709     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5710
5711     if (opts.add_info) {
5712         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5713         parser->reserved_version->cvq = CV_CONST;
5714         parser->reserved_version->hasvalue = true;
5715         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5716         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5717     } else {
5718         parser->reserved_version = NULL;
5719     }
5720     return true;
5721 }
5722
5723 bool parser_compile()
5724 {
5725     /* initial lexer/parser state */
5726     parser->lex->flags.noops = true;
5727
5728     if (parser_next(parser))
5729     {
5730         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5731         {
5732             if (!parser_global_statement(parser)) {
5733                 if (parser->tok == TOKEN_EOF)
5734                     parseerror(parser, "unexpected eof");
5735                 else if (compile_errors)
5736                     parseerror(parser, "there have been errors, bailing out");
5737                 lex_close(parser->lex);
5738                 parser->lex = NULL;
5739                 return false;
5740             }
5741         }
5742     } else {
5743         parseerror(parser, "parse error");
5744         lex_close(parser->lex);
5745         parser->lex = NULL;
5746         return false;
5747     }
5748
5749     lex_close(parser->lex);
5750     parser->lex = NULL;
5751
5752     return !compile_errors;
5753 }
5754
5755 bool parser_compile_file(const char *filename)
5756 {
5757     parser->lex = lex_open(filename);
5758     if (!parser->lex) {
5759         con_err("failed to open file \"%s\"\n", filename);
5760         return false;
5761     }
5762     return parser_compile();
5763 }
5764
5765 bool parser_compile_string(const char *name, const char *str, size_t len)
5766 {
5767     parser->lex = lex_open_string(str, len, name);
5768     if (!parser->lex) {
5769         con_err("failed to create lexer for string \"%s\"\n", name);
5770         return false;
5771     }
5772     return parser_compile();
5773 }
5774
5775 void parser_cleanup()
5776 {
5777     size_t i;
5778     for (i = 0; i < vec_size(parser->accessors); ++i) {
5779         ast_delete(parser->accessors[i]->constval.vfunc);
5780         parser->accessors[i]->constval.vfunc = NULL;
5781         ast_delete(parser->accessors[i]);
5782     }
5783     for (i = 0; i < vec_size(parser->functions); ++i) {
5784         ast_delete(parser->functions[i]);
5785     }
5786     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5787         ast_delete(parser->imm_vector[i]);
5788     }
5789     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5790         ast_delete(parser->imm_string[i]);
5791     }
5792     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5793         ast_delete(parser->imm_float[i]);
5794     }
5795     for (i = 0; i < vec_size(parser->fields); ++i) {
5796         ast_delete(parser->fields[i]);
5797     }
5798     for (i = 0; i < vec_size(parser->globals); ++i) {
5799         ast_delete(parser->globals[i]);
5800     }
5801     vec_free(parser->accessors);
5802     vec_free(parser->functions);
5803     vec_free(parser->imm_vector);
5804     vec_free(parser->imm_string);
5805     vec_free(parser->imm_float);
5806     vec_free(parser->globals);
5807     vec_free(parser->fields);
5808
5809     for (i = 0; i < vec_size(parser->variables); ++i)
5810         util_htdel(parser->variables[i]);
5811     vec_free(parser->variables);
5812     vec_free(parser->_blocklocals);
5813     vec_free(parser->_locals);
5814
5815     /* corrector */
5816     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5817         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5818     }
5819     vec_free(parser->correct_variables);
5820     vec_free(parser->correct_variables_score);
5821
5822
5823     for (i = 0; i < vec_size(parser->_typedefs); ++i)
5824         ast_delete(parser->_typedefs[i]);
5825     vec_free(parser->_typedefs);
5826     for (i = 0; i < vec_size(parser->typedefs); ++i)
5827         util_htdel(parser->typedefs[i]);
5828     vec_free(parser->typedefs);
5829     vec_free(parser->_blocktypedefs);
5830
5831     vec_free(parser->_block_ctx);
5832
5833     vec_free(parser->labels);
5834     vec_free(parser->gotos);
5835     vec_free(parser->breaks);
5836     vec_free(parser->continues);
5837
5838     ast_value_delete(parser->nil);
5839
5840     ast_value_delete(parser->const_vec[0]);
5841     ast_value_delete(parser->const_vec[1]);
5842     ast_value_delete(parser->const_vec[2]);
5843
5844     mem_d(parser);
5845 }
5846
5847 bool parser_finish(const char *output)
5848 {
5849     size_t i;
5850     ir_builder *ir;
5851     bool retval = true;
5852
5853     if (compile_errors) {
5854         con_out("*** there were compile errors\n");
5855         return false;
5856     }
5857
5858     ir = ir_builder_new("gmqcc_out");
5859     if (!ir) {
5860         con_out("failed to allocate builder\n");
5861         return false;
5862     }
5863
5864     for (i = 0; i < vec_size(parser->fields); ++i) {
5865         ast_value *field;
5866         bool hasvalue;
5867         if (!ast_istype(parser->fields[i], ast_value))
5868             continue;
5869         field = (ast_value*)parser->fields[i];
5870         hasvalue = field->hasvalue;
5871         field->hasvalue = false;
5872         if (!ast_global_codegen((ast_value*)field, ir, true)) {
5873             con_out("failed to generate field %s\n", field->name);
5874             ir_builder_delete(ir);
5875             return false;
5876         }
5877         if (hasvalue) {
5878             ir_value *ifld;
5879             ast_expression *subtype;
5880             field->hasvalue = true;
5881             subtype = field->expression.next;
5882             ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5883             if (subtype->expression.vtype == TYPE_FIELD)
5884                 ifld->fieldtype = subtype->expression.next->expression.vtype;
5885             else if (subtype->expression.vtype == TYPE_FUNCTION)
5886                 ifld->outtype = subtype->expression.next->expression.vtype;
5887             (void)!ir_value_set_field(field->ir_v, ifld);
5888         }
5889     }
5890     for (i = 0; i < vec_size(parser->globals); ++i) {
5891         ast_value *asvalue;
5892         if (!ast_istype(parser->globals[i], ast_value))
5893             continue;
5894         asvalue = (ast_value*)(parser->globals[i]);
5895         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5896             retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5897                                            "unused global: `%s`", asvalue->name);
5898         }
5899         if (!ast_global_codegen(asvalue, ir, false)) {
5900             con_out("failed to generate global %s\n", asvalue->name);
5901             ir_builder_delete(ir);
5902             return false;
5903         }
5904     }
5905     /* Build function vararg accessor ast tree now before generating
5906      * immediates, because the accessors may add new immediates
5907      */
5908     for (i = 0; i < vec_size(parser->functions); ++i) {
5909         ast_function *f = parser->functions[i];
5910         if (f->varargs) {
5911             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
5912                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
5913                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
5914                     con_out("failed to generate vararg setter for %s\n", f->name);
5915                     ir_builder_delete(ir);
5916                     return false;
5917                 }
5918                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
5919                     con_out("failed to generate vararg getter for %s\n", f->name);
5920                     ir_builder_delete(ir);
5921                     return false;
5922                 }
5923             } else {
5924                 ast_delete(f->varargs);
5925                 f->varargs = NULL;
5926             }
5927         }
5928     }
5929     /* Now we can generate immediates */
5930     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5931         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5932             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5933             ir_builder_delete(ir);
5934             return false;
5935         }
5936     }
5937     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5938         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5939             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5940             ir_builder_delete(ir);
5941             return false;
5942         }
5943     }
5944     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5945         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5946             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5947             ir_builder_delete(ir);
5948             return false;
5949         }
5950     }
5951     for (i = 0; i < vec_size(parser->globals); ++i) {
5952         ast_value *asvalue;
5953         if (!ast_istype(parser->globals[i], ast_value))
5954             continue;
5955         asvalue = (ast_value*)(parser->globals[i]);
5956         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5957         {
5958             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5959                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5960                                        "uninitialized constant: `%s`",
5961                                        asvalue->name);
5962             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5963                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5964                                        "uninitialized global: `%s`",
5965                                        asvalue->name);
5966         }
5967         if (!ast_generate_accessors(asvalue, ir)) {
5968             ir_builder_delete(ir);
5969             return false;
5970         }
5971     }
5972     for (i = 0; i < vec_size(parser->fields); ++i) {
5973         ast_value *asvalue;
5974         asvalue = (ast_value*)(parser->fields[i]->expression.next);
5975
5976         if (!ast_istype((ast_expression*)asvalue, ast_value))
5977             continue;
5978         if (asvalue->expression.vtype != TYPE_ARRAY)
5979             continue;
5980         if (!ast_generate_accessors(asvalue, ir)) {
5981             ir_builder_delete(ir);
5982             return false;
5983         }
5984     }
5985     if (parser->reserved_version &&
5986         !ast_global_codegen(parser->reserved_version, ir, false))
5987     {
5988         con_out("failed to generate reserved::version");
5989         ir_builder_delete(ir);
5990         return false;
5991     }
5992     for (i = 0; i < vec_size(parser->functions); ++i) {
5993         ast_function *f = parser->functions[i];
5994         if (!ast_function_codegen(f, ir)) {
5995             con_out("failed to generate function %s\n", f->name);
5996             ir_builder_delete(ir);
5997             return false;
5998         }
5999     }
6000     if (opts.dump)
6001         ir_builder_dump(ir, con_out);
6002     for (i = 0; i < vec_size(parser->functions); ++i) {
6003         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6004             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6005             ir_builder_delete(ir);
6006             return false;
6007         }
6008     }
6009
6010     if (compile_Werrors) {
6011         con_out("*** there were warnings treated as errors\n");
6012         compile_show_werrors();
6013         retval = false;
6014     }
6015
6016     if (retval) {
6017         if (opts.dumpfin)
6018             ir_builder_dump(ir, con_out);
6019
6020         generate_checksum(parser);
6021
6022         if (!ir_builder_generate(ir, output)) {
6023             con_out("*** failed to generate output file\n");
6024             ir_builder_delete(ir);
6025             return false;
6026         }
6027     }
6028
6029     ir_builder_delete(ir);
6030     return retval;
6031 }