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