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