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