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