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