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