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