]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Make it compile as C++ code too
[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             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         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             } else {
1903                 var = intrin_func(parser, parser_tokval(parser));
1904             }
1905
1906             if (!var) {
1907                 char *correct = NULL;
1908                 size_t i;
1909
1910                 /*
1911                  * sometimes people use preprocessing predefs without enabling them
1912                  * i've done this thousands of times already myself.  Lets check for
1913                  * it in the predef table.  And diagnose it better :)
1914                  */
1915                 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1916                     for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1917                         if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1918                             parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1919                             return false;
1920                         }
1921                     }
1922                 }
1923
1924                 /*
1925                  * TODO: determine the best score for the identifier: be it
1926                  * a variable, a field.
1927                  *
1928                  * We should also consider adding correction tables for
1929                  * other things as well.
1930                  */
1931                 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1932                     correction_t corr;
1933                     correct_init(&corr);
1934
1935                     for (i = 0; i < vec_size(parser->correct_variables); i++) {
1936                         correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1937                         if (strcmp(correct, parser_tokval(parser))) {
1938                             break;
1939                         } else if (correct) {
1940                             mem_d(correct);
1941                             correct = NULL;
1942                         }
1943                     }
1944                     correct_free(&corr);
1945
1946                     if (correct) {
1947                         parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1948                         mem_d(correct);
1949                         return false;
1950                     }
1951                 }
1952                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1953                 return false;
1954             }
1955         }
1956         else
1957         {
1958             if (ast_istype(var, ast_value)) {
1959                 ((ast_value*)var)->uses++;
1960             }
1961             else if (ast_istype(var, ast_member)) {
1962                 ast_member *mem = (ast_member*)var;
1963                 if (ast_istype(mem->owner, ast_value))
1964                     ((ast_value*)(mem->owner))->uses++;
1965             }
1966         }
1967         vec_push(sy->out, syexp(parser_ctx(parser), var));
1968         return true;
1969     }
1970     parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1971     return false;
1972 }
1973
1974 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1975 {
1976     ast_expression *expr = NULL;
1977     shunt sy;
1978     size_t i;
1979     bool wantop = false;
1980     /* only warn once about an assignment in a truth value because the current code
1981      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1982      */
1983     bool warn_truthvalue = true;
1984
1985     /* count the parens because an if starts with one, so the
1986      * end of a condition is an unmatched closing paren
1987      */
1988     int ternaries = 0;
1989
1990     memset(&sy, 0, sizeof(sy));
1991
1992     parser->lex->flags.noops = false;
1993
1994     parser_reclassify_token(parser);
1995
1996     while (true)
1997     {
1998         if (parser->tok == TOKEN_TYPENAME) {
1999             parseerror(parser, "unexpected typename");
2000             goto onerr;
2001         }
2002
2003         if (parser->tok == TOKEN_OPERATOR)
2004         {
2005             /* classify the operator */
2006             const oper_info *op;
2007             const oper_info *olast = NULL;
2008             size_t o;
2009             for (o = 0; o < operator_count; ++o) {
2010                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2011                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2012                     !strcmp(parser_tokval(parser), operators[o].op))
2013                 {
2014                     break;
2015                 }
2016             }
2017             if (o == operator_count) {
2018                 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2019                 goto onerr;
2020             }
2021             /* found an operator */
2022             op = &operators[o];
2023
2024             /* when declaring variables, a comma starts a new variable */
2025             if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2026                 /* fixup the token */
2027                 parser->tok = ',';
2028                 break;
2029             }
2030
2031             /* a colon without a pervious question mark cannot be a ternary */
2032             if (!ternaries && op->id == opid2(':','?')) {
2033                 parser->tok = ':';
2034                 break;
2035             }
2036
2037             if (op->id == opid1(',')) {
2038                 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2039                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2040                 }
2041             }
2042
2043             if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2044                 olast = &operators[vec_last(sy.ops).etype-1];
2045
2046 #define IsAssignOp(x) (\
2047                 (x) == opid1('=') || \
2048                 (x) == opid2('+','=') || \
2049                 (x) == opid2('-','=') || \
2050                 (x) == opid2('*','=') || \
2051                 (x) == opid2('/','=') || \
2052                 (x) == opid2('%','=') || \
2053                 (x) == opid2('&','=') || \
2054                 (x) == opid2('|','=') || \
2055                 (x) == opid3('&','~','=') \
2056                 )
2057             if (warn_truthvalue) {
2058                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2059                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2060                      (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2061                    )
2062                 {
2063                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2064                     warn_truthvalue = false;
2065                 }
2066             }
2067
2068             while (olast && (
2069                     (op->prec < olast->prec) ||
2070                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2071             {
2072                 if (!parser_sy_apply_operator(parser, &sy))
2073                     goto onerr;
2074                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2075                     olast = &operators[vec_last(sy.ops).etype-1];
2076                 else
2077                     olast = NULL;
2078             }
2079
2080             if (op->id == opid1('(')) {
2081                 if (wantop) {
2082                     size_t sycount = vec_size(sy.out);
2083                     /* we expected an operator, this is the function-call operator */
2084                     vec_push(sy.paren, PAREN_FUNC);
2085                     vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2086                     vec_push(sy.argc, 0);
2087                 } else {
2088                     vec_push(sy.paren, PAREN_EXPR);
2089                     vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2090                 }
2091                 wantop = false;
2092             } else if (op->id == opid1('[')) {
2093                 if (!wantop) {
2094                     parseerror(parser, "unexpected array subscript");
2095                     goto onerr;
2096                 }
2097                 vec_push(sy.paren, PAREN_INDEX);
2098                 /* push both the operator and the paren, this makes life easier */
2099                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2100                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2101                 wantop = false;
2102             } else if (op->id == opid2('?',':')) {
2103                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2104                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2105                 wantop = false;
2106                 ++ternaries;
2107                 vec_push(sy.paren, PAREN_TERNARY1);
2108             } else if (op->id == opid2(':','?')) {
2109                 if (!vec_size(sy.paren)) {
2110                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2111                     goto onerr;
2112                 }
2113                 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2114                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2115                     goto onerr;
2116                 }
2117                 if (!parser_close_paren(parser, &sy))
2118                     goto onerr;
2119                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2120                 wantop = false;
2121                 --ternaries;
2122             } else {
2123                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2124                 wantop = !!(op->flags & OP_SUFFIX);
2125             }
2126         }
2127         else if (parser->tok == ')') {
2128             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2129                 if (!parser_sy_apply_operator(parser, &sy))
2130                     goto onerr;
2131             }
2132             if (!vec_size(sy.paren))
2133                 break;
2134             if (wantop) {
2135                 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2136                     parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2137                     goto onerr;
2138                 }
2139                 if (!parser_close_paren(parser, &sy))
2140                     goto onerr;
2141             } else {
2142                 /* must be a function call without parameters */
2143                 if (vec_last(sy.paren) != PAREN_FUNC) {
2144                     parseerror(parser, "closing paren in invalid position");
2145                     goto onerr;
2146                 }
2147                 if (!parser_close_paren(parser, &sy))
2148                     goto onerr;
2149             }
2150             wantop = true;
2151         }
2152         else if (parser->tok == '(') {
2153             parseerror(parser, "internal error: '(' should be classified as operator");
2154             goto onerr;
2155         }
2156         else if (parser->tok == '[') {
2157             parseerror(parser, "internal error: '[' should be classified as operator");
2158             goto onerr;
2159         }
2160         else if (parser->tok == ']') {
2161             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2162                 if (!parser_sy_apply_operator(parser, &sy))
2163                     goto onerr;
2164             }
2165             if (!vec_size(sy.paren))
2166                 break;
2167             if (vec_last(sy.paren) != PAREN_INDEX) {
2168                 parseerror(parser, "mismatched parentheses, unexpected ']'");
2169                 goto onerr;
2170             }
2171             if (!parser_close_paren(parser, &sy))
2172                 goto onerr;
2173             wantop = true;
2174         }
2175         else if (!wantop) {
2176             if (!parse_sya_operand(parser, &sy, with_labels))
2177                 goto onerr;
2178 #if 0
2179             if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2180                 vec_last(sy.argc)++;
2181 #endif
2182             wantop = true;
2183         }
2184         else {
2185             parseerror(parser, "expected operator or end of statement");
2186             goto onerr;
2187         }
2188
2189         if (!parser_next(parser)) {
2190             goto onerr;
2191         }
2192         if (parser->tok == ';' ||
2193             ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2194             (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2195         {
2196             break;
2197         }
2198     }
2199
2200     while (vec_size(sy.ops)) {
2201         if (!parser_sy_apply_operator(parser, &sy))
2202             goto onerr;
2203     }
2204
2205     parser->lex->flags.noops = true;
2206     if (!vec_size(sy.out)) {
2207         parseerror(parser, "empty expression");
2208         expr = NULL;
2209     } else
2210         expr = sy.out[0].out;
2211     vec_free(sy.out);
2212     vec_free(sy.ops);
2213     if (vec_size(sy.paren)) {
2214         parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2215         return NULL;
2216     }
2217     vec_free(sy.paren);
2218     vec_free(sy.argc);
2219     return expr;
2220
2221 onerr:
2222     parser->lex->flags.noops = true;
2223     for (i = 0; i < vec_size(sy.out); ++i) {
2224         if (sy.out[i].out)
2225             ast_unref(sy.out[i].out);
2226     }
2227     vec_free(sy.out);
2228     vec_free(sy.ops);
2229     vec_free(sy.paren);
2230     vec_free(sy.argc);
2231     return NULL;
2232 }
2233
2234 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2235 {
2236     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2237     if (!e)
2238         return NULL;
2239     if (parser->tok != ';') {
2240         parseerror(parser, "semicolon expected after expression");
2241         ast_unref(e);
2242         return NULL;
2243     }
2244     if (!parser_next(parser)) {
2245         ast_unref(e);
2246         return NULL;
2247     }
2248     return e;
2249 }
2250
2251 static void parser_enterblock(parser_t *parser)
2252 {
2253     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2254     vec_push(parser->_blocklocals, vec_size(parser->_locals));
2255     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2256     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2257     vec_push(parser->_block_ctx, parser_ctx(parser));
2258
2259     /* corrector */
2260     vec_push(parser->correct_variables, correct_trie_new());
2261     vec_push(parser->correct_variables_score, NULL);
2262 }
2263
2264 static bool parser_leaveblock(parser_t *parser)
2265 {
2266     bool   rv = true;
2267     size_t locals, typedefs;
2268
2269     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2270         parseerror(parser, "internal error: parser_leaveblock with no block");
2271         return false;
2272     }
2273
2274     util_htdel(vec_last(parser->variables));
2275     correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2276
2277     vec_pop(parser->variables);
2278     vec_pop(parser->correct_variables);
2279     vec_pop(parser->correct_variables_score);
2280     if (!vec_size(parser->_blocklocals)) {
2281         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2282         return false;
2283     }
2284
2285     locals = vec_last(parser->_blocklocals);
2286     vec_pop(parser->_blocklocals);
2287     while (vec_size(parser->_locals) != locals) {
2288         ast_expression *e = vec_last(parser->_locals);
2289         ast_value      *v = (ast_value*)e;
2290         vec_pop(parser->_locals);
2291         if (ast_istype(e, ast_value) && !v->uses) {
2292             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2293                 rv = false;
2294         }
2295     }
2296
2297     typedefs = vec_last(parser->_blocktypedefs);
2298     while (vec_size(parser->_typedefs) != typedefs) {
2299         ast_delete(vec_last(parser->_typedefs));
2300         vec_pop(parser->_typedefs);
2301     }
2302     util_htdel(vec_last(parser->typedefs));
2303     vec_pop(parser->typedefs);
2304
2305     vec_pop(parser->_block_ctx);
2306
2307     return rv;
2308 }
2309
2310 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2311 {
2312     vec_push(parser->_locals, e);
2313     util_htset(vec_last(parser->variables), name, (void*)e);
2314
2315     /* corrector */
2316     correct_add (
2317          vec_last(parser->correct_variables),
2318         &vec_last(parser->correct_variables_score),
2319         name
2320     );
2321 }
2322
2323 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2324 {
2325     vec_push(parser->globals, e);
2326     util_htset(parser->htglobals, name, e);
2327
2328     /* corrector */
2329     correct_add (
2330          parser->correct_variables[0],
2331         &parser->correct_variables_score[0],
2332         name
2333     );
2334 }
2335
2336 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2337 {
2338     bool       ifnot = false;
2339     ast_unary *unary;
2340     ast_expression *prev;
2341
2342     if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2343         char ty[1024];
2344         ast_type_to_string(cond, ty, sizeof(ty));
2345         compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2346     }
2347
2348     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2349     {
2350         prev = cond;
2351         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2352         if (!cond) {
2353             ast_unref(prev);
2354             parseerror(parser, "internal error: failed to process condition");
2355             return NULL;
2356         }
2357         ifnot = !ifnot;
2358     }
2359     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2360     {
2361         /* vector types need to be cast to true booleans */
2362         ast_binary *bin = (ast_binary*)cond;
2363         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2364         {
2365             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2366             prev = cond;
2367             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2368             if (!cond) {
2369                 ast_unref(prev);
2370                 parseerror(parser, "internal error: failed to process condition");
2371                 return NULL;
2372             }
2373             ifnot = !ifnot;
2374         }
2375     }
2376
2377     unary = (ast_unary*)cond;
2378     while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2379     {
2380         cond = unary->operand;
2381         unary->operand = NULL;
2382         ast_delete(unary);
2383         ifnot = !ifnot;
2384         unary = (ast_unary*)cond;
2385     }
2386
2387     if (!cond)
2388         parseerror(parser, "internal error: failed to process condition");
2389
2390     if (ifnot) *_ifnot = !*_ifnot;
2391     return cond;
2392 }
2393
2394 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2395 {
2396     ast_ifthen *ifthen;
2397     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2398     bool ifnot = false;
2399
2400     lex_ctx ctx = parser_ctx(parser);
2401
2402     (void)block; /* not touching */
2403
2404     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2405     if (!parser_next(parser)) {
2406         parseerror(parser, "expected condition or 'not'");
2407         return false;
2408     }
2409     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2410         ifnot = true;
2411         if (!parser_next(parser)) {
2412             parseerror(parser, "expected condition in parenthesis");
2413             return false;
2414         }
2415     }
2416     if (parser->tok != '(') {
2417         parseerror(parser, "expected 'if' condition in parenthesis");
2418         return false;
2419     }
2420     /* parse into the expression */
2421     if (!parser_next(parser)) {
2422         parseerror(parser, "expected 'if' condition after opening paren");
2423         return false;
2424     }
2425     /* parse the condition */
2426     cond = parse_expression_leave(parser, false, true, false);
2427     if (!cond)
2428         return false;
2429     /* closing paren */
2430     if (parser->tok != ')') {
2431         parseerror(parser, "expected closing paren after 'if' condition");
2432         ast_delete(cond);
2433         return false;
2434     }
2435     /* parse into the 'then' branch */
2436     if (!parser_next(parser)) {
2437         parseerror(parser, "expected statement for on-true branch of 'if'");
2438         ast_delete(cond);
2439         return false;
2440     }
2441     if (!parse_statement_or_block(parser, &ontrue)) {
2442         ast_delete(cond);
2443         return false;
2444     }
2445     if (!ontrue)
2446         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2447     /* check for an else */
2448     if (!strcmp(parser_tokval(parser), "else")) {
2449         /* parse into the 'else' branch */
2450         if (!parser_next(parser)) {
2451             parseerror(parser, "expected on-false branch after 'else'");
2452             ast_delete(ontrue);
2453             ast_delete(cond);
2454             return false;
2455         }
2456         if (!parse_statement_or_block(parser, &onfalse)) {
2457             ast_delete(ontrue);
2458             ast_delete(cond);
2459             return false;
2460         }
2461     }
2462
2463     cond = process_condition(parser, cond, &ifnot);
2464     if (!cond) {
2465         if (ontrue)  ast_delete(ontrue);
2466         if (onfalse) ast_delete(onfalse);
2467         return false;
2468     }
2469
2470     if (ifnot)
2471         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2472     else
2473         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2474     *out = (ast_expression*)ifthen;
2475     return true;
2476 }
2477
2478 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2479 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2480 {
2481     bool rv;
2482     char *label = NULL;
2483
2484     /* skip the 'while' and get the body */
2485     if (!parser_next(parser)) {
2486         if (OPTS_FLAG(LOOP_LABELS))
2487             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2488         else
2489             parseerror(parser, "expected 'while' condition in parenthesis");
2490         return false;
2491     }
2492
2493     if (parser->tok == ':') {
2494         if (!OPTS_FLAG(LOOP_LABELS))
2495             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2496         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2497             parseerror(parser, "expected loop label");
2498             return false;
2499         }
2500         label = util_strdup(parser_tokval(parser));
2501         if (!parser_next(parser)) {
2502             mem_d(label);
2503             parseerror(parser, "expected 'while' condition in parenthesis");
2504             return false;
2505         }
2506     }
2507
2508     if (parser->tok != '(') {
2509         parseerror(parser, "expected 'while' condition in parenthesis");
2510         return false;
2511     }
2512
2513     vec_push(parser->breaks, label);
2514     vec_push(parser->continues, label);
2515
2516     rv = parse_while_go(parser, block, out);
2517     if (label)
2518         mem_d(label);
2519     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2520         parseerror(parser, "internal error: label stack corrupted");
2521         rv = false;
2522         ast_delete(*out);
2523         *out = NULL;
2524     }
2525     else {
2526         vec_pop(parser->breaks);
2527         vec_pop(parser->continues);
2528     }
2529     return rv;
2530 }
2531
2532 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2533 {
2534     ast_loop *aloop;
2535     ast_expression *cond, *ontrue;
2536
2537     bool ifnot = false;
2538
2539     lex_ctx ctx = parser_ctx(parser);
2540
2541     (void)block; /* not touching */
2542
2543     /* parse into the expression */
2544     if (!parser_next(parser)) {
2545         parseerror(parser, "expected 'while' condition after opening paren");
2546         return false;
2547     }
2548     /* parse the condition */
2549     cond = parse_expression_leave(parser, false, true, false);
2550     if (!cond)
2551         return false;
2552     /* closing paren */
2553     if (parser->tok != ')') {
2554         parseerror(parser, "expected closing paren after 'while' condition");
2555         ast_delete(cond);
2556         return false;
2557     }
2558     /* parse into the 'then' branch */
2559     if (!parser_next(parser)) {
2560         parseerror(parser, "expected while-loop body");
2561         ast_delete(cond);
2562         return false;
2563     }
2564     if (!parse_statement_or_block(parser, &ontrue)) {
2565         ast_delete(cond);
2566         return false;
2567     }
2568
2569     cond = process_condition(parser, cond, &ifnot);
2570     if (!cond) {
2571         ast_delete(ontrue);
2572         return false;
2573     }
2574     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2575     *out = (ast_expression*)aloop;
2576     return true;
2577 }
2578
2579 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2580 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2581 {
2582     bool rv;
2583     char *label = NULL;
2584
2585     /* skip the 'do' and get the body */
2586     if (!parser_next(parser)) {
2587         if (OPTS_FLAG(LOOP_LABELS))
2588             parseerror(parser, "expected loop label or body");
2589         else
2590             parseerror(parser, "expected loop body");
2591         return false;
2592     }
2593
2594     if (parser->tok == ':') {
2595         if (!OPTS_FLAG(LOOP_LABELS))
2596             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2597         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2598             parseerror(parser, "expected loop label");
2599             return false;
2600         }
2601         label = util_strdup(parser_tokval(parser));
2602         if (!parser_next(parser)) {
2603             mem_d(label);
2604             parseerror(parser, "expected loop body");
2605             return false;
2606         }
2607     }
2608
2609     vec_push(parser->breaks, label);
2610     vec_push(parser->continues, label);
2611
2612     rv = parse_dowhile_go(parser, block, out);
2613     if (label)
2614         mem_d(label);
2615     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2616         parseerror(parser, "internal error: label stack corrupted");
2617         rv = false;
2618         ast_delete(*out);
2619         *out = NULL;
2620     }
2621     else {
2622         vec_pop(parser->breaks);
2623         vec_pop(parser->continues);
2624     }
2625     return rv;
2626 }
2627
2628 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2629 {
2630     ast_loop *aloop;
2631     ast_expression *cond, *ontrue;
2632
2633     bool ifnot = false;
2634
2635     lex_ctx ctx = parser_ctx(parser);
2636
2637     (void)block; /* not touching */
2638
2639     if (!parse_statement_or_block(parser, &ontrue))
2640         return false;
2641
2642     /* expect the "while" */
2643     if (parser->tok != TOKEN_KEYWORD ||
2644         strcmp(parser_tokval(parser), "while"))
2645     {
2646         parseerror(parser, "expected 'while' and condition");
2647         ast_delete(ontrue);
2648         return false;
2649     }
2650
2651     /* skip the 'while' and check for opening paren */
2652     if (!parser_next(parser) || parser->tok != '(') {
2653         parseerror(parser, "expected 'while' condition in parenthesis");
2654         ast_delete(ontrue);
2655         return false;
2656     }
2657     /* parse into the expression */
2658     if (!parser_next(parser)) {
2659         parseerror(parser, "expected 'while' condition after opening paren");
2660         ast_delete(ontrue);
2661         return false;
2662     }
2663     /* parse the condition */
2664     cond = parse_expression_leave(parser, false, true, false);
2665     if (!cond)
2666         return false;
2667     /* closing paren */
2668     if (parser->tok != ')') {
2669         parseerror(parser, "expected closing paren after 'while' condition");
2670         ast_delete(ontrue);
2671         ast_delete(cond);
2672         return false;
2673     }
2674     /* parse on */
2675     if (!parser_next(parser) || parser->tok != ';') {
2676         parseerror(parser, "expected semicolon after condition");
2677         ast_delete(ontrue);
2678         ast_delete(cond);
2679         return false;
2680     }
2681
2682     if (!parser_next(parser)) {
2683         parseerror(parser, "parse error");
2684         ast_delete(ontrue);
2685         ast_delete(cond);
2686         return false;
2687     }
2688
2689     cond = process_condition(parser, cond, &ifnot);
2690     if (!cond) {
2691         ast_delete(ontrue);
2692         return false;
2693     }
2694     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2695     *out = (ast_expression*)aloop;
2696     return true;
2697 }
2698
2699 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2700 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2701 {
2702     bool rv;
2703     char *label = NULL;
2704
2705     /* skip the 'for' and check for opening paren */
2706     if (!parser_next(parser)) {
2707         if (OPTS_FLAG(LOOP_LABELS))
2708             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2709         else
2710             parseerror(parser, "expected 'for' expressions in parenthesis");
2711         return false;
2712     }
2713
2714     if (parser->tok == ':') {
2715         if (!OPTS_FLAG(LOOP_LABELS))
2716             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2717         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2718             parseerror(parser, "expected loop label");
2719             return false;
2720         }
2721         label = util_strdup(parser_tokval(parser));
2722         if (!parser_next(parser)) {
2723             mem_d(label);
2724             parseerror(parser, "expected 'for' expressions in parenthesis");
2725             return false;
2726         }
2727     }
2728
2729     if (parser->tok != '(') {
2730         parseerror(parser, "expected 'for' expressions in parenthesis");
2731         return false;
2732     }
2733
2734     vec_push(parser->breaks, label);
2735     vec_push(parser->continues, label);
2736
2737     rv = parse_for_go(parser, block, out);
2738     if (label)
2739         mem_d(label);
2740     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2741         parseerror(parser, "internal error: label stack corrupted");
2742         rv = false;
2743         ast_delete(*out);
2744         *out = NULL;
2745     }
2746     else {
2747         vec_pop(parser->breaks);
2748         vec_pop(parser->continues);
2749     }
2750     return rv;
2751 }
2752 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2753 {
2754     ast_loop       *aloop;
2755     ast_expression *initexpr, *cond, *increment, *ontrue;
2756     ast_value      *typevar;
2757
2758     bool retval = true;
2759     bool ifnot  = false;
2760
2761     lex_ctx ctx = parser_ctx(parser);
2762
2763     parser_enterblock(parser);
2764
2765     initexpr  = NULL;
2766     cond      = NULL;
2767     increment = NULL;
2768     ontrue    = NULL;
2769
2770     /* parse into the expression */
2771     if (!parser_next(parser)) {
2772         parseerror(parser, "expected 'for' initializer after opening paren");
2773         goto onerr;
2774     }
2775
2776     typevar = NULL;
2777     if (parser->tok == TOKEN_IDENT)
2778         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2779
2780     if (typevar || parser->tok == TOKEN_TYPENAME) {
2781 #if 0
2782         if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2783             if (parsewarning(parser, WARN_EXTENSIONS,
2784                              "current standard does not allow variable declarations in for-loop initializers"))
2785                 goto onerr;
2786         }
2787 #endif
2788         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2789             goto onerr;
2790     }
2791     else if (parser->tok != ';')
2792     {
2793         initexpr = parse_expression_leave(parser, false, false, false);
2794         if (!initexpr)
2795             goto onerr;
2796     }
2797
2798     /* move on to condition */
2799     if (parser->tok != ';') {
2800         parseerror(parser, "expected semicolon after for-loop initializer");
2801         goto onerr;
2802     }
2803     if (!parser_next(parser)) {
2804         parseerror(parser, "expected for-loop condition");
2805         goto onerr;
2806     }
2807
2808     /* parse the condition */
2809     if (parser->tok != ';') {
2810         cond = parse_expression_leave(parser, false, true, false);
2811         if (!cond)
2812             goto onerr;
2813     }
2814
2815     /* move on to incrementor */
2816     if (parser->tok != ';') {
2817         parseerror(parser, "expected semicolon after for-loop initializer");
2818         goto onerr;
2819     }
2820     if (!parser_next(parser)) {
2821         parseerror(parser, "expected for-loop condition");
2822         goto onerr;
2823     }
2824
2825     /* parse the incrementor */
2826     if (parser->tok != ')') {
2827         lex_ctx condctx = parser_ctx(parser);
2828         increment = parse_expression_leave(parser, false, false, false);
2829         if (!increment)
2830             goto onerr;
2831         if (!ast_side_effects(increment)) {
2832             if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2833                 goto onerr;
2834         }
2835     }
2836
2837     /* closing paren */
2838     if (parser->tok != ')') {
2839         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2840         goto onerr;
2841     }
2842     /* parse into the 'then' branch */
2843     if (!parser_next(parser)) {
2844         parseerror(parser, "expected for-loop body");
2845         goto onerr;
2846     }
2847     if (!parse_statement_or_block(parser, &ontrue))
2848         goto onerr;
2849
2850     if (cond) {
2851         cond = process_condition(parser, cond, &ifnot);
2852         if (!cond)
2853             goto onerr;
2854     }
2855     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2856     *out = (ast_expression*)aloop;
2857
2858     if (!parser_leaveblock(parser))
2859         retval = false;
2860     return retval;
2861 onerr:
2862     if (initexpr)  ast_delete(initexpr);
2863     if (cond)      ast_delete(cond);
2864     if (increment) ast_delete(increment);
2865     (void)!parser_leaveblock(parser);
2866     return false;
2867 }
2868
2869 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2870 {
2871     ast_expression *exp = NULL;
2872     ast_return     *ret = NULL;
2873     ast_value      *expected = parser->function->vtype;
2874
2875     lex_ctx ctx = parser_ctx(parser);
2876
2877     (void)block; /* not touching */
2878
2879     if (!parser_next(parser)) {
2880         parseerror(parser, "expected return expression");
2881         return false;
2882     }
2883
2884     if (parser->tok != ';') {
2885         exp = parse_expression(parser, false, false);
2886         if (!exp)
2887             return false;
2888
2889         if (exp->expression.vtype != TYPE_NIL &&
2890             exp->expression.vtype != expected->expression.next->expression.vtype)
2891         {
2892             parseerror(parser, "return with invalid expression");
2893         }
2894
2895         ret = ast_return_new(ctx, exp);
2896         if (!ret) {
2897             ast_delete(exp);
2898             return false;
2899         }
2900     } else {
2901         if (!parser_next(parser))
2902             parseerror(parser, "parse error");
2903         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2904             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2905         }
2906         ret = ast_return_new(ctx, NULL);
2907     }
2908     *out = (ast_expression*)ret;
2909     return true;
2910 }
2911
2912 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2913 {
2914     size_t       i;
2915     unsigned int levels = 0;
2916     lex_ctx      ctx = parser_ctx(parser);
2917     const char **loops = (is_continue ? parser->continues : parser->breaks);
2918
2919     (void)block; /* not touching */
2920     if (!parser_next(parser)) {
2921         parseerror(parser, "expected semicolon or loop label");
2922         return false;
2923     }
2924
2925     if (!vec_size(loops)) {
2926         if (is_continue)
2927             parseerror(parser, "`continue` can only be used inside loops");
2928         else
2929             parseerror(parser, "`break` can only be used inside loops or switches");
2930     }
2931
2932     if (parser->tok == TOKEN_IDENT) {
2933         if (!OPTS_FLAG(LOOP_LABELS))
2934             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2935         i = vec_size(loops);
2936         while (i--) {
2937             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2938                 break;
2939             if (!i) {
2940                 parseerror(parser, "no such loop to %s: `%s`",
2941                            (is_continue ? "continue" : "break out of"),
2942                            parser_tokval(parser));
2943                 return false;
2944             }
2945             ++levels;
2946         }
2947         if (!parser_next(parser)) {
2948             parseerror(parser, "expected semicolon");
2949             return false;
2950         }
2951     }
2952
2953     if (parser->tok != ';') {
2954         parseerror(parser, "expected semicolon");
2955         return false;
2956     }
2957
2958     if (!parser_next(parser))
2959         parseerror(parser, "parse error");
2960
2961     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2962     return true;
2963 }
2964
2965 /* returns true when it was a variable qualifier, false otherwise!
2966  * on error, cvq is set to CV_WRONG
2967  */
2968 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2969 {
2970     bool had_const    = false;
2971     bool had_var      = false;
2972     bool had_noref    = false;
2973     bool had_attrib   = false;
2974     bool had_static   = false;
2975     uint32_t flags    = 0;
2976
2977     *cvq = CV_NONE;
2978     for (;;) {
2979         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2980             had_attrib = true;
2981             /* parse an attribute */
2982             if (!parser_next(parser)) {
2983                 parseerror(parser, "expected attribute after `[[`");
2984                 *cvq = CV_WRONG;
2985                 return false;
2986             }
2987             if (!strcmp(parser_tokval(parser), "noreturn")) {
2988                 flags |= AST_FLAG_NORETURN;
2989                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2990                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2991                     *cvq = CV_WRONG;
2992                     return false;
2993                 }
2994             }
2995             else if (!strcmp(parser_tokval(parser), "noref")) {
2996                 had_noref = true;
2997                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2998                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2999                     *cvq = CV_WRONG;
3000                     return false;
3001                 }
3002             }
3003             else if (!strcmp(parser_tokval(parser), "inline")) {
3004                 flags |= AST_FLAG_INLINE;
3005                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3006                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3007                     *cvq = CV_WRONG;
3008                     return false;
3009                 }
3010             }
3011             else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3012                 flags   |= AST_FLAG_ALIAS;
3013                 *message = NULL;
3014
3015                 if (!parser_next(parser)) {
3016                     parseerror(parser, "parse error in attribute");
3017                     goto argerr;
3018                 }
3019
3020                 if (parser->tok == '(') {
3021                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3022                         parseerror(parser, "`alias` attribute missing parameter");
3023                         goto argerr;
3024                     }
3025
3026                     *message = util_strdup(parser_tokval(parser));
3027
3028                     if (!parser_next(parser)) {
3029                         parseerror(parser, "parse error in attribute");
3030                         goto argerr;
3031                     }
3032
3033                     if (parser->tok != ')') {
3034                         parseerror(parser, "`alias` attribute expected `)` after parameter");
3035                         goto argerr;
3036                     }
3037
3038                     if (!parser_next(parser)) {
3039                         parseerror(parser, "parse error in attribute");
3040                         goto argerr;
3041                     }
3042                 }
3043
3044                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3045                     parseerror(parser, "`alias` attribute expected `]]`");
3046                     goto argerr;
3047                 }
3048             }
3049             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3050                 flags   |= AST_FLAG_DEPRECATED;
3051                 *message = NULL;
3052
3053                 if (!parser_next(parser)) {
3054                     parseerror(parser, "parse error in attribute");
3055                     goto argerr;
3056                 }
3057
3058                 if (parser->tok == '(') {
3059                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3060                         parseerror(parser, "`deprecated` attribute missing parameter");
3061                         goto argerr;
3062                     }
3063
3064                     *message = util_strdup(parser_tokval(parser));
3065
3066                     if (!parser_next(parser)) {
3067                         parseerror(parser, "parse error in attribute");
3068                         goto argerr;
3069                     }
3070
3071                     if(parser->tok != ')') {
3072                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3073                         goto argerr;
3074                     }
3075
3076                     if (!parser_next(parser)) {
3077                         parseerror(parser, "parse error in attribute");
3078                         goto argerr;
3079                     }
3080                 }
3081                 /* no message */
3082                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3083                     parseerror(parser, "`deprecated` attribute expected `]]`");
3084
3085                     argerr: /* ugly */
3086                     if (*message) mem_d(*message);
3087                     *message = NULL;
3088                     *cvq     = CV_WRONG;
3089                     return false;
3090                 }
3091             }
3092             else
3093             {
3094                 /* Skip tokens until we hit a ]] */
3095                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3096                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3097                     if (!parser_next(parser)) {
3098                         parseerror(parser, "error inside attribute");
3099                         *cvq = CV_WRONG;
3100                         return false;
3101                     }
3102                 }
3103             }
3104         }
3105         else if (with_local && !strcmp(parser_tokval(parser), "static"))
3106             had_static = true;
3107         else if (!strcmp(parser_tokval(parser), "const"))
3108             had_const = true;
3109         else if (!strcmp(parser_tokval(parser), "var"))
3110             had_var = true;
3111         else if (with_local && !strcmp(parser_tokval(parser), "local"))
3112             had_var = true;
3113         else if (!strcmp(parser_tokval(parser), "noref"))
3114             had_noref = true;
3115         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3116             return false;
3117         }
3118         else
3119             break;
3120         if (!parser_next(parser))
3121             goto onerr;
3122     }
3123     if (had_const)
3124         *cvq = CV_CONST;
3125     else if (had_var)
3126         *cvq = CV_VAR;
3127     else
3128         *cvq = CV_NONE;
3129     *noref     = had_noref;
3130     *is_static = had_static;
3131     *_flags    = flags;
3132     return true;
3133 onerr:
3134     parseerror(parser, "parse error after variable qualifier");
3135     *cvq = CV_WRONG;
3136     return true;
3137 }
3138
3139 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3140 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3141 {
3142     bool rv;
3143     char *label = NULL;
3144
3145     /* skip the 'while' and get the body */
3146     if (!parser_next(parser)) {
3147         if (OPTS_FLAG(LOOP_LABELS))
3148             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3149         else
3150             parseerror(parser, "expected 'switch' operand in parenthesis");
3151         return false;
3152     }
3153
3154     if (parser->tok == ':') {
3155         if (!OPTS_FLAG(LOOP_LABELS))
3156             parseerror(parser, "labeled loops not activated, try using -floop-labels");
3157         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3158             parseerror(parser, "expected loop label");
3159             return false;
3160         }
3161         label = util_strdup(parser_tokval(parser));
3162         if (!parser_next(parser)) {
3163             mem_d(label);
3164             parseerror(parser, "expected 'switch' operand in parenthesis");
3165             return false;
3166         }
3167     }
3168
3169     if (parser->tok != '(') {
3170         parseerror(parser, "expected 'switch' operand in parenthesis");
3171         return false;
3172     }
3173
3174     vec_push(parser->breaks, label);
3175
3176     rv = parse_switch_go(parser, block, out);
3177     if (label)
3178         mem_d(label);
3179     if (vec_last(parser->breaks) != label) {
3180         parseerror(parser, "internal error: label stack corrupted");
3181         rv = false;
3182         ast_delete(*out);
3183         *out = NULL;
3184     }
3185     else {
3186         vec_pop(parser->breaks);
3187     }
3188     return rv;
3189 }
3190
3191 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3192 {
3193     ast_expression *operand;
3194     ast_value      *opval;
3195     ast_value      *typevar;
3196     ast_switch     *switchnode;
3197     ast_switch_case swcase;
3198
3199     int  cvq;
3200     bool noref, is_static;
3201     uint32_t qflags = 0;
3202
3203     lex_ctx ctx = parser_ctx(parser);
3204
3205     (void)block; /* not touching */
3206     (void)opval;
3207
3208     /* parse into the expression */
3209     if (!parser_next(parser)) {
3210         parseerror(parser, "expected switch operand");
3211         return false;
3212     }
3213     /* parse the operand */
3214     operand = parse_expression_leave(parser, false, false, false);
3215     if (!operand)
3216         return false;
3217
3218     switchnode = ast_switch_new(ctx, operand);
3219
3220     /* closing paren */
3221     if (parser->tok != ')') {
3222         ast_delete(switchnode);
3223         parseerror(parser, "expected closing paren after 'switch' operand");
3224         return false;
3225     }
3226
3227     /* parse over the opening paren */
3228     if (!parser_next(parser) || parser->tok != '{') {
3229         ast_delete(switchnode);
3230         parseerror(parser, "expected list of cases");
3231         return false;
3232     }
3233
3234     if (!parser_next(parser)) {
3235         ast_delete(switchnode);
3236         parseerror(parser, "expected 'case' or 'default'");
3237         return false;
3238     }
3239
3240     /* new block; allow some variables to be declared here */
3241     parser_enterblock(parser);
3242     while (true) {
3243         typevar = NULL;
3244         if (parser->tok == TOKEN_IDENT)
3245             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3246         if (typevar || parser->tok == TOKEN_TYPENAME) {
3247             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3248                 ast_delete(switchnode);
3249                 return false;
3250             }
3251             continue;
3252         }
3253         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3254         {
3255             if (cvq == CV_WRONG) {
3256                 ast_delete(switchnode);
3257                 return false;
3258             }
3259             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3260                 ast_delete(switchnode);
3261                 return false;
3262             }
3263             continue;
3264         }
3265         break;
3266     }
3267
3268     /* case list! */
3269     while (parser->tok != '}') {
3270         ast_block *caseblock;
3271
3272         if (!strcmp(parser_tokval(parser), "case")) {
3273             if (!parser_next(parser)) {
3274                 ast_delete(switchnode);
3275                 parseerror(parser, "expected expression for case");
3276                 return false;
3277             }
3278             swcase.value = parse_expression_leave(parser, false, false, false);
3279             if (!swcase.value) {
3280                 ast_delete(switchnode);
3281                 parseerror(parser, "expected expression for case");
3282                 return false;
3283             }
3284             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3285                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3286                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3287                     ast_unref(operand);
3288                     return false;
3289                 }
3290             }
3291         }
3292         else if (!strcmp(parser_tokval(parser), "default")) {
3293             swcase.value = NULL;
3294             if (!parser_next(parser)) {
3295                 ast_delete(switchnode);
3296                 parseerror(parser, "expected colon");
3297                 return false;
3298             }
3299         }
3300         else {
3301             ast_delete(switchnode);
3302             parseerror(parser, "expected 'case' or 'default'");
3303             return false;
3304         }
3305
3306         /* Now the colon and body */
3307         if (parser->tok != ':') {
3308             if (swcase.value) ast_unref(swcase.value);
3309             ast_delete(switchnode);
3310             parseerror(parser, "expected colon");
3311             return false;
3312         }
3313
3314         if (!parser_next(parser)) {
3315             if (swcase.value) ast_unref(swcase.value);
3316             ast_delete(switchnode);
3317             parseerror(parser, "expected statements or case");
3318             return false;
3319         }
3320         caseblock = ast_block_new(parser_ctx(parser));
3321         if (!caseblock) {
3322             if (swcase.value) ast_unref(swcase.value);
3323             ast_delete(switchnode);
3324             return false;
3325         }
3326         swcase.code = (ast_expression*)caseblock;
3327         vec_push(switchnode->cases, swcase);
3328         while (true) {
3329             ast_expression *expr;
3330             if (parser->tok == '}')
3331                 break;
3332             if (parser->tok == TOKEN_KEYWORD) {
3333                 if (!strcmp(parser_tokval(parser), "case") ||
3334                     !strcmp(parser_tokval(parser), "default"))
3335                 {
3336                     break;
3337                 }
3338             }
3339             if (!parse_statement(parser, caseblock, &expr, true)) {
3340                 ast_delete(switchnode);
3341                 return false;
3342             }
3343             if (!expr)
3344                 continue;
3345             if (!ast_block_add_expr(caseblock, expr)) {
3346                 ast_delete(switchnode);
3347                 return false;
3348             }
3349         }
3350     }
3351
3352     parser_leaveblock(parser);
3353
3354     /* closing paren */
3355     if (parser->tok != '}') {
3356         ast_delete(switchnode);
3357         parseerror(parser, "expected closing paren of case list");
3358         return false;
3359     }
3360     if (!parser_next(parser)) {
3361         ast_delete(switchnode);
3362         parseerror(parser, "parse error after switch");
3363         return false;
3364     }
3365     *out = (ast_expression*)switchnode;
3366     return true;
3367 }
3368
3369 /* parse computed goto sides */
3370 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3371     ast_expression *on_true;
3372     ast_expression *on_false;
3373     ast_expression *cond;
3374
3375     if (!*side)
3376         return NULL;
3377
3378     if (ast_istype(*side, ast_ternary)) {
3379         ast_ternary *tern = (ast_ternary*)*side;
3380         on_true  = parse_goto_computed(parser, &tern->on_true);
3381         on_false = parse_goto_computed(parser, &tern->on_false);
3382
3383         if (!on_true || !on_false) {
3384             parseerror(parser, "expected label or expression in ternary");
3385             if (on_true) ast_unref(on_true);
3386             if (on_false) ast_unref(on_false);
3387             return NULL;
3388         }
3389
3390         cond = tern->cond;
3391         tern->cond = NULL;
3392         ast_delete(tern);
3393         *side = NULL;
3394         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3395     } else if (ast_istype(*side, ast_label)) {
3396         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3397         ast_goto_set_label(gt, ((ast_label*)*side));
3398         *side = NULL;
3399         return (ast_expression*)gt;
3400     }
3401     return NULL;
3402 }
3403
3404 static bool parse_goto(parser_t *parser, ast_expression **out)
3405 {
3406     ast_goto       *gt = NULL;
3407     ast_expression *lbl;
3408
3409     if (!parser_next(parser))
3410         return false;
3411
3412     if (parser->tok != TOKEN_IDENT) {
3413         ast_expression *expression;
3414
3415         /* could be an expression i.e computed goto :-) */
3416         if (parser->tok != '(') {
3417             parseerror(parser, "expected label name after `goto`");
3418             return false;
3419         }
3420
3421         /* failed to parse expression for goto */
3422         if (!(expression = parse_expression(parser, false, true)) ||
3423             !(*out = parse_goto_computed(parser, &expression))) {
3424             parseerror(parser, "invalid goto expression");
3425             ast_unref(expression);
3426             return false;
3427         }
3428
3429         return true;
3430     }
3431
3432     /* not computed goto */
3433     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3434     lbl = parser_find_label(parser, gt->name);
3435     if (lbl) {
3436         if (!ast_istype(lbl, ast_label)) {
3437             parseerror(parser, "internal error: label is not an ast_label");
3438             ast_delete(gt);
3439             return false;
3440         }
3441         ast_goto_set_label(gt, (ast_label*)lbl);
3442     }
3443     else
3444         vec_push(parser->gotos, gt);
3445
3446     if (!parser_next(parser) || parser->tok != ';') {
3447         parseerror(parser, "semicolon expected after goto label");
3448         return false;
3449     }
3450     if (!parser_next(parser)) {
3451         parseerror(parser, "parse error after goto");
3452         return false;
3453     }
3454
3455     *out = (ast_expression*)gt;
3456     return true;
3457 }
3458
3459 static bool parse_skipwhite(parser_t *parser)
3460 {
3461     do {
3462         if (!parser_next(parser))
3463             return false;
3464     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3465     return parser->tok < TOKEN_ERROR;
3466 }
3467
3468 static bool parse_eol(parser_t *parser)
3469 {
3470     if (!parse_skipwhite(parser))
3471         return false;
3472     return parser->tok == TOKEN_EOL;
3473 }
3474
3475 static bool parse_pragma_do(parser_t *parser)
3476 {
3477     if (!parser_next(parser) ||
3478         parser->tok != TOKEN_IDENT ||
3479         strcmp(parser_tokval(parser), "pragma"))
3480     {
3481         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3482         return false;
3483     }
3484     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3485         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3486         return false;
3487     }
3488
3489     if (!strcmp(parser_tokval(parser), "noref")) {
3490         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3491             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3492             return false;
3493         }
3494         parser->noref = !!parser_token(parser)->constval.i;
3495         if (!parse_eol(parser)) {
3496             parseerror(parser, "parse error after `noref` pragma");
3497             return false;
3498         }
3499     }
3500     else
3501     {
3502         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3503         return false;
3504     }
3505
3506     return true;
3507 }
3508
3509 static bool parse_pragma(parser_t *parser)
3510 {
3511     bool rv;
3512     parser->lex->flags.preprocessing = true;
3513     parser->lex->flags.mergelines = true;
3514     rv = parse_pragma_do(parser);
3515     if (parser->tok != TOKEN_EOL) {
3516         parseerror(parser, "junk after pragma");
3517         rv = false;
3518     }
3519     parser->lex->flags.preprocessing = false;
3520     parser->lex->flags.mergelines = false;
3521     if (!parser_next(parser)) {
3522         parseerror(parser, "parse error after pragma");
3523         rv = false;
3524     }
3525     return rv;
3526 }
3527
3528 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3529 {
3530     bool       noref, is_static;
3531     int        cvq     = CV_NONE;
3532     uint32_t   qflags  = 0;
3533     ast_value *typevar = NULL;
3534     char      *vstring = NULL;
3535
3536     *out = NULL;
3537
3538     if (parser->tok == TOKEN_IDENT)
3539         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3540
3541     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3542     {
3543         /* local variable */
3544         if (!block) {
3545             parseerror(parser, "cannot declare a variable from here");
3546             return false;
3547         }
3548         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3549             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3550                 return false;
3551         }
3552         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3553             return false;
3554         return true;
3555     }
3556     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3557     {
3558         if (cvq == CV_WRONG)
3559             return false;
3560         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3561     }
3562     else if (parser->tok == TOKEN_KEYWORD)
3563     {
3564         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3565         {
3566             char ty[1024];
3567             ast_value *tdef;
3568
3569             if (!parser_next(parser)) {
3570                 parseerror(parser, "parse error after __builtin_debug_printtype");
3571                 return false;
3572             }
3573
3574             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3575             {
3576                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3577                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3578                 if (!parser_next(parser)) {
3579                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3580                     return false;
3581                 }
3582             }
3583             else
3584             {
3585                 if (!parse_statement(parser, block, out, allow_cases))
3586                     return false;
3587                 if (!*out)
3588                     con_out("__builtin_debug_printtype: got no output node\n");
3589                 else
3590                 {
3591                     ast_type_to_string(*out, ty, sizeof(ty));
3592                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3593                 }
3594             }
3595             return true;
3596         }
3597         else if (!strcmp(parser_tokval(parser), "return"))
3598         {
3599             return parse_return(parser, block, out);
3600         }
3601         else if (!strcmp(parser_tokval(parser), "if"))
3602         {
3603             return parse_if(parser, block, out);
3604         }
3605         else if (!strcmp(parser_tokval(parser), "while"))
3606         {
3607             return parse_while(parser, block, out);
3608         }
3609         else if (!strcmp(parser_tokval(parser), "do"))
3610         {
3611             return parse_dowhile(parser, block, out);
3612         }
3613         else if (!strcmp(parser_tokval(parser), "for"))
3614         {
3615             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3616                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3617                     return false;
3618             }
3619             return parse_for(parser, block, out);
3620         }
3621         else if (!strcmp(parser_tokval(parser), "break"))
3622         {
3623             return parse_break_continue(parser, block, out, false);
3624         }
3625         else if (!strcmp(parser_tokval(parser), "continue"))
3626         {
3627             return parse_break_continue(parser, block, out, true);
3628         }
3629         else if (!strcmp(parser_tokval(parser), "switch"))
3630         {
3631             return parse_switch(parser, block, out);
3632         }
3633         else if (!strcmp(parser_tokval(parser), "case") ||
3634                  !strcmp(parser_tokval(parser), "default"))
3635         {
3636             if (!allow_cases) {
3637                 parseerror(parser, "unexpected 'case' label");
3638                 return false;
3639             }
3640             return true;
3641         }
3642         else if (!strcmp(parser_tokval(parser), "goto"))
3643         {
3644             return parse_goto(parser, out);
3645         }
3646         else if (!strcmp(parser_tokval(parser), "typedef"))
3647         {
3648             if (!parser_next(parser)) {
3649                 parseerror(parser, "expected type definition after 'typedef'");
3650                 return false;
3651             }
3652             return parse_typedef(parser);
3653         }
3654         parseerror(parser, "Unexpected keyword");
3655         return false;
3656     }
3657     else if (parser->tok == '{')
3658     {
3659         ast_block *inner;
3660         inner = parse_block(parser);
3661         if (!inner)
3662             return false;
3663         *out = (ast_expression*)inner;
3664         return true;
3665     }
3666     else if (parser->tok == ':')
3667     {
3668         size_t i;
3669         ast_label *label;
3670         if (!parser_next(parser)) {
3671             parseerror(parser, "expected label name");
3672             return false;
3673         }
3674         if (parser->tok != TOKEN_IDENT) {
3675             parseerror(parser, "label must be an identifier");
3676             return false;
3677         }
3678         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3679         if (label) {
3680             if (!label->undefined) {
3681                 parseerror(parser, "label `%s` already defined", label->name);
3682                 return false;
3683             }
3684             label->undefined = false;
3685         }
3686         else {
3687             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3688             vec_push(parser->labels, label);
3689         }
3690         *out = (ast_expression*)label;
3691         if (!parser_next(parser)) {
3692             parseerror(parser, "parse error after label");
3693             return false;
3694         }
3695         for (i = 0; i < vec_size(parser->gotos); ++i) {
3696             if (!strcmp(parser->gotos[i]->name, label->name)) {
3697                 ast_goto_set_label(parser->gotos[i], label);
3698                 vec_remove(parser->gotos, i, 1);
3699                 --i;
3700             }
3701         }
3702         return true;
3703     }
3704     else if (parser->tok == ';')
3705     {
3706         if (!parser_next(parser)) {
3707             parseerror(parser, "parse error after empty statement");
3708             return false;
3709         }
3710         return true;
3711     }
3712     else
3713     {
3714         lex_ctx ctx = parser_ctx(parser);
3715         ast_expression *exp = parse_expression(parser, false, false);
3716         if (!exp)
3717             return false;
3718         *out = exp;
3719         if (!ast_side_effects(exp)) {
3720             if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3721                 return false;
3722         }
3723         return true;
3724     }
3725 }
3726
3727 static bool parse_enum(parser_t *parser)
3728 {
3729     bool        flag = false;
3730     bool        reverse = false;
3731     qcfloat     num = 0;
3732     ast_value **values = NULL;
3733     ast_value  *var = NULL;
3734     ast_value  *asvalue;
3735
3736     ast_expression *old;
3737
3738     if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3739         parseerror(parser, "expected `{` or `:` after `enum` keyword");
3740         return false;
3741     }
3742
3743     /* enumeration attributes (can add more later) */
3744     if (parser->tok == ':') {
3745         if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3746             parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3747             return false;
3748         }
3749
3750         /* attributes? */
3751         if (!strcmp(parser_tokval(parser), "flag")) {
3752             num  = 1;
3753             flag = true;
3754         }
3755         else if (!strcmp(parser_tokval(parser), "reverse")) {
3756             reverse = true;
3757         }
3758         else {
3759             parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3760             return false;
3761         }
3762
3763         if (!parser_next(parser) || parser->tok != '{') {
3764             parseerror(parser, "expected `{` after enum attribute ");
3765             return false;
3766         }
3767     }
3768
3769     while (true) {
3770         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3771             if (parser->tok == '}') {
3772                 /* allow an empty enum */
3773                 break;
3774             }
3775             parseerror(parser, "expected identifier or `}`");
3776             goto onerror;
3777         }
3778
3779         old = parser_find_field(parser, parser_tokval(parser));
3780         if (!old)
3781             old = parser_find_global(parser, parser_tokval(parser));
3782         if (old) {
3783             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3784                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3785             goto onerror;
3786         }
3787
3788         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3789         vec_push(values, var);
3790         var->cvq             = CV_CONST;
3791         var->hasvalue        = true;
3792
3793         /* for flagged enumerations increment in POTs of TWO */
3794         var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3795         parser_addglobal(parser, var->name, (ast_expression*)var);
3796
3797         if (!parser_next(parser)) {
3798             parseerror(parser, "expected `=`, `}` or comma after identifier");
3799             goto onerror;
3800         }
3801
3802         if (parser->tok == ',')
3803             continue;
3804         if (parser->tok == '}')
3805             break;
3806         if (parser->tok != '=') {
3807             parseerror(parser, "expected `=`, `}` or comma after identifier");
3808             goto onerror;
3809         }
3810
3811         if (!parser_next(parser)) {
3812             parseerror(parser, "expected expression after `=`");
3813             goto onerror;
3814         }
3815
3816         /* We got a value! */
3817         old = parse_expression_leave(parser, true, false, false);
3818         asvalue = (ast_value*)old;
3819         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3820             compile_error(ast_ctx(var), "constant value or expression expected");
3821             goto onerror;
3822         }
3823         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3824
3825         if (parser->tok == '}')
3826             break;
3827         if (parser->tok != ',') {
3828             parseerror(parser, "expected `}` or comma after expression");
3829             goto onerror;
3830         }
3831     }
3832
3833     /* patch them all (for reversed attribute) */
3834     if (reverse) {
3835         size_t i;
3836         for (i = 0; i < vec_size(values); i++)
3837             values[i]->constval.vfloat = vec_size(values) - i - 1;
3838     }
3839
3840     if (parser->tok != '}') {
3841         parseerror(parser, "internal error: breaking without `}`");
3842         goto onerror;
3843     }
3844
3845     if (!parser_next(parser) || parser->tok != ';') {
3846         parseerror(parser, "expected semicolon after enumeration");
3847         goto onerror;
3848     }
3849
3850     if (!parser_next(parser)) {
3851         parseerror(parser, "parse error after enumeration");
3852         goto onerror;
3853     }
3854
3855     vec_free(values);
3856     return true;
3857
3858 onerror:
3859     vec_free(values);
3860     return false;
3861 }
3862
3863 static bool parse_block_into(parser_t *parser, ast_block *block)
3864 {
3865     bool   retval = true;
3866
3867     parser_enterblock(parser);
3868
3869     if (!parser_next(parser)) { /* skip the '{' */
3870         parseerror(parser, "expected function body");
3871         goto cleanup;
3872     }
3873
3874     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3875     {
3876         ast_expression *expr = NULL;
3877         if (parser->tok == '}')
3878             break;
3879
3880         if (!parse_statement(parser, block, &expr, false)) {
3881             /* parseerror(parser, "parse error"); */
3882             block = NULL;
3883             goto cleanup;
3884         }
3885         if (!expr)
3886             continue;
3887         if (!ast_block_add_expr(block, expr)) {
3888             ast_delete(block);
3889             block = NULL;
3890             goto cleanup;
3891         }
3892     }
3893
3894     if (parser->tok != '}') {
3895         block = NULL;
3896     } else {
3897         (void)parser_next(parser);
3898     }
3899
3900 cleanup:
3901     if (!parser_leaveblock(parser))
3902         retval = false;
3903     return retval && !!block;
3904 }
3905
3906 static ast_block* parse_block(parser_t *parser)
3907 {
3908     ast_block *block;
3909     block = ast_block_new(parser_ctx(parser));
3910     if (!block)
3911         return NULL;
3912     if (!parse_block_into(parser, block)) {
3913         ast_block_delete(block);
3914         return NULL;
3915     }
3916     return block;
3917 }
3918
3919 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3920 {
3921     if (parser->tok == '{') {
3922         *out = (ast_expression*)parse_block(parser);
3923         return !!*out;
3924     }
3925     return parse_statement(parser, NULL, out, false);
3926 }
3927
3928 static bool create_vector_members(ast_value *var, ast_member **me)
3929 {
3930     size_t i;
3931     size_t len = strlen(var->name);
3932
3933     for (i = 0; i < 3; ++i) {
3934         char *name = (char*)mem_a(len+3);
3935         memcpy(name, var->name, len);
3936         name[len+0] = '_';
3937         name[len+1] = 'x'+i;
3938         name[len+2] = 0;
3939         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3940         mem_d(name);
3941         if (!me[i])
3942             break;
3943     }
3944     if (i == 3)
3945         return true;
3946
3947     /* unroll */
3948     do { ast_member_delete(me[--i]); } while(i);
3949     return false;
3950 }
3951
3952 static bool parse_function_body(parser_t *parser, ast_value *var)
3953 {
3954     ast_block      *block = NULL;
3955     ast_function   *func;
3956     ast_function   *old;
3957     size_t          parami;
3958
3959     ast_expression *framenum  = NULL;
3960     ast_expression *nextthink = NULL;
3961     /* None of the following have to be deleted */
3962     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3963     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3964     bool            has_frame_think;
3965
3966     bool retval = true;
3967
3968     has_frame_think = false;
3969     old = parser->function;
3970
3971     if (var->expression.flags & AST_FLAG_ALIAS) {
3972         parseerror(parser, "function aliases cannot have bodies");
3973         return false;
3974     }
3975
3976     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3977         parseerror(parser, "gotos/labels leaking");
3978         return false;
3979     }
3980
3981     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3982         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3983                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3984         {
3985             return false;
3986         }
3987     }
3988
3989     if (parser->tok == '[') {
3990         /* got a frame definition: [ framenum, nextthink ]
3991          * this translates to:
3992          * self.frame = framenum;
3993          * self.nextthink = time + 0.1;
3994          * self.think = nextthink;
3995          */
3996         nextthink = NULL;
3997
3998         fld_think     = parser_find_field(parser, "think");
3999         fld_nextthink = parser_find_field(parser, "nextthink");
4000         fld_frame     = parser_find_field(parser, "frame");
4001         if (!fld_think || !fld_nextthink || !fld_frame) {
4002             parseerror(parser, "cannot use [frame,think] notation without the required fields");
4003             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4004             return false;
4005         }
4006         gbl_time      = parser_find_global(parser, "time");
4007         gbl_self      = parser_find_global(parser, "self");
4008         if (!gbl_time || !gbl_self) {
4009             parseerror(parser, "cannot use [frame,think] notation without the required globals");
4010             parseerror(parser, "please declare the following globals: `time`, `self`");
4011             return false;
4012         }
4013
4014         if (!parser_next(parser))
4015             return false;
4016
4017         framenum = parse_expression_leave(parser, true, false, false);
4018         if (!framenum) {
4019             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4020             return false;
4021         }
4022         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4023             ast_unref(framenum);
4024             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4025             return false;
4026         }
4027
4028         if (parser->tok != ',') {
4029             ast_unref(framenum);
4030             parseerror(parser, "expected comma after frame number in [frame,think] notation");
4031             parseerror(parser, "Got a %i\n", parser->tok);
4032             return false;
4033         }
4034
4035         if (!parser_next(parser)) {
4036             ast_unref(framenum);
4037             return false;
4038         }
4039
4040         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4041         {
4042             /* qc allows the use of not-yet-declared functions here
4043              * - this automatically creates a prototype */
4044             ast_value      *thinkfunc;
4045             ast_expression *functype = fld_think->expression.next;
4046
4047             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4048             if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4049                 ast_unref(framenum);
4050                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4051                 return false;
4052             }
4053             ast_type_adopt(thinkfunc, functype);
4054
4055             if (!parser_next(parser)) {
4056                 ast_unref(framenum);
4057                 ast_delete(thinkfunc);
4058                 return false;
4059             }
4060
4061             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4062
4063             nextthink = (ast_expression*)thinkfunc;
4064
4065         } else {
4066             nextthink = parse_expression_leave(parser, true, false, false);
4067             if (!nextthink) {
4068                 ast_unref(framenum);
4069                 parseerror(parser, "expected a think-function in [frame,think] notation");
4070                 return false;
4071             }
4072         }
4073
4074         if (!ast_istype(nextthink, ast_value)) {
4075             parseerror(parser, "think-function in [frame,think] notation must be a constant");
4076             retval = false;
4077         }
4078
4079         if (retval && parser->tok != ']') {
4080             parseerror(parser, "expected closing `]` for [frame,think] notation");
4081             retval = false;
4082         }
4083
4084         if (retval && !parser_next(parser)) {
4085             retval = false;
4086         }
4087
4088         if (retval && parser->tok != '{') {
4089             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4090             retval = false;
4091         }
4092
4093         if (!retval) {
4094             ast_unref(nextthink);
4095             ast_unref(framenum);
4096             return false;
4097         }
4098
4099         has_frame_think = true;
4100     }
4101
4102     block = ast_block_new(parser_ctx(parser));
4103     if (!block) {
4104         parseerror(parser, "failed to allocate block");
4105         if (has_frame_think) {
4106             ast_unref(nextthink);
4107             ast_unref(framenum);
4108         }
4109         return false;
4110     }
4111
4112     if (has_frame_think) {
4113         lex_ctx ctx;
4114         ast_expression *self_frame;
4115         ast_expression *self_nextthink;
4116         ast_expression *self_think;
4117         ast_expression *time_plus_1;
4118         ast_store *store_frame;
4119         ast_store *store_nextthink;
4120         ast_store *store_think;
4121
4122         ctx = parser_ctx(parser);
4123         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4124         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4125         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4126
4127         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4128                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4129
4130         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4131             if (self_frame)     ast_delete(self_frame);
4132             if (self_nextthink) ast_delete(self_nextthink);
4133             if (self_think)     ast_delete(self_think);
4134             if (time_plus_1)    ast_delete(time_plus_1);
4135             retval = false;
4136         }
4137
4138         if (retval)
4139         {
4140             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
4141             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
4142             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
4143
4144             if (!store_frame) {
4145                 ast_delete(self_frame);
4146                 retval = false;
4147             }
4148             if (!store_nextthink) {
4149                 ast_delete(self_nextthink);
4150                 retval = false;
4151             }
4152             if (!store_think) {
4153                 ast_delete(self_think);
4154                 retval = false;
4155             }
4156             if (!retval) {
4157                 if (store_frame)     ast_delete(store_frame);
4158                 if (store_nextthink) ast_delete(store_nextthink);
4159                 if (store_think)     ast_delete(store_think);
4160                 retval = false;
4161             }
4162             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4163                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4164                 !ast_block_add_expr(block, (ast_expression*)store_think))
4165             {
4166                 retval = false;
4167             }
4168         }
4169
4170         if (!retval) {
4171             parseerror(parser, "failed to generate code for [frame,think]");
4172             ast_unref(nextthink);
4173             ast_unref(framenum);
4174             ast_delete(block);
4175             return false;
4176         }
4177     }
4178
4179     if (var->hasvalue) {
4180         parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4181         ast_block_delete(block);
4182         goto enderr;
4183     }
4184
4185     func = ast_function_new(ast_ctx(var), var->name, var);
4186     if (!func) {
4187         parseerror(parser, "failed to allocate function for `%s`", var->name);
4188         ast_block_delete(block);
4189         goto enderr;
4190     }
4191     vec_push(parser->functions, func);
4192
4193     parser_enterblock(parser);
4194
4195     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4196         size_t     e;
4197         ast_value *param = var->expression.params[parami];
4198         ast_member *me[3];
4199
4200         if (param->expression.vtype != TYPE_VECTOR &&
4201             (param->expression.vtype != TYPE_FIELD ||
4202              param->expression.next->expression.vtype != TYPE_VECTOR))
4203         {
4204             continue;
4205         }
4206
4207         if (!create_vector_members(param, me)) {
4208             ast_block_delete(block);
4209             goto enderrfn;
4210         }
4211
4212         for (e = 0; e < 3; ++e) {
4213             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4214             ast_block_collect(block, (ast_expression*)me[e]);
4215         }
4216     }
4217
4218     if (var->argcounter) {
4219         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4220         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4221         func->argc = argc;
4222     }
4223
4224     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4225         char name[1024];
4226         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4227         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4228         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4229         varargs->expression.count = 0;
4230         snprintf(name, sizeof(name), "%s##va##SET", var->name);
4231         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4232             ast_delete(varargs);
4233             ast_block_delete(block);
4234             goto enderrfn;
4235         }
4236         snprintf(name, sizeof(name), "%s##va##GET", var->name);
4237         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4238             ast_delete(varargs);
4239             ast_block_delete(block);
4240             goto enderrfn;
4241         }
4242         func->varargs = varargs;
4243
4244         func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4245     }
4246
4247     parser->function = func;
4248     if (!parse_block_into(parser, block)) {
4249         ast_block_delete(block);
4250         goto enderrfn;
4251     }
4252
4253     vec_push(func->blocks, block);
4254
4255     parser->function = old;
4256     if (!parser_leaveblock(parser))
4257         retval = false;
4258     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4259         parseerror(parser, "internal error: local scopes left");
4260         retval = false;
4261     }
4262
4263     if (parser->tok == ';')
4264         return parser_next(parser);
4265     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4266         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4267     return retval;
4268
4269 enderrfn:
4270     (void)!parser_leaveblock(parser);
4271     vec_pop(parser->functions);
4272     ast_function_delete(func);
4273     var->constval.vfunc = NULL;
4274
4275 enderr:
4276     parser->function = old;
4277     return false;
4278 }
4279
4280 static ast_expression *array_accessor_split(
4281     parser_t  *parser,
4282     ast_value *array,
4283     ast_value *index,
4284     size_t     middle,
4285     ast_expression *left,
4286     ast_expression *right
4287     )
4288 {
4289     ast_ifthen *ifthen;
4290     ast_binary *cmp;
4291
4292     lex_ctx ctx = ast_ctx(array);
4293
4294     if (!left || !right) {
4295         if (left)  ast_delete(left);
4296         if (right) ast_delete(right);
4297         return NULL;
4298     }
4299
4300     cmp = ast_binary_new(ctx, INSTR_LT,
4301                          (ast_expression*)index,
4302                          (ast_expression*)parser_const_float(parser, middle));
4303     if (!cmp) {
4304         ast_delete(left);
4305         ast_delete(right);
4306         parseerror(parser, "internal error: failed to create comparison for array setter");
4307         return NULL;
4308     }
4309
4310     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4311     if (!ifthen) {
4312         ast_delete(cmp); /* will delete left and right */
4313         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4314         return NULL;
4315     }
4316
4317     return (ast_expression*)ifthen;
4318 }
4319
4320 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4321 {
4322     lex_ctx ctx = ast_ctx(array);
4323
4324     if (from+1 == afterend) {
4325         /* set this value */
4326         ast_block       *block;
4327         ast_return      *ret;
4328         ast_array_index *subscript;
4329         ast_store       *st;
4330         int assignop = type_store_instr[value->expression.vtype];
4331
4332         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4333             assignop = INSTR_STORE_V;
4334
4335         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4336         if (!subscript)
4337             return NULL;
4338
4339         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4340         if (!st) {
4341             ast_delete(subscript);
4342             return NULL;
4343         }
4344
4345         block = ast_block_new(ctx);
4346         if (!block) {
4347             ast_delete(st);
4348             return NULL;
4349         }
4350
4351         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4352             ast_delete(block);
4353             return NULL;
4354         }
4355
4356         ret = ast_return_new(ctx, NULL);
4357         if (!ret) {
4358             ast_delete(block);
4359             return NULL;
4360         }
4361
4362         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4363             ast_delete(block);
4364             return NULL;
4365         }
4366
4367         return (ast_expression*)block;
4368     } else {
4369         ast_expression *left, *right;
4370         size_t diff = afterend - from;
4371         size_t middle = from + diff/2;
4372         left  = array_setter_node(parser, array, index, value, from, middle);
4373         right = array_setter_node(parser, array, index, value, middle, afterend);
4374         return array_accessor_split(parser, array, index, middle, left, right);
4375     }
4376 }
4377
4378 static ast_expression *array_field_setter_node(
4379     parser_t  *parser,
4380     ast_value *array,
4381     ast_value *entity,
4382     ast_value *index,
4383     ast_value *value,
4384     size_t     from,
4385     size_t     afterend)
4386 {
4387     lex_ctx ctx = ast_ctx(array);
4388
4389     if (from+1 == afterend) {
4390         /* set this value */
4391         ast_block       *block;
4392         ast_return      *ret;
4393         ast_entfield    *entfield;
4394         ast_array_index *subscript;
4395         ast_store       *st;
4396         int assignop = type_storep_instr[value->expression.vtype];
4397
4398         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4399             assignop = INSTR_STOREP_V;
4400
4401         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4402         if (!subscript)
4403             return NULL;
4404
4405         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4406         subscript->expression.vtype = TYPE_FIELD;
4407
4408         entfield = ast_entfield_new_force(ctx,
4409                                           (ast_expression*)entity,
4410                                           (ast_expression*)subscript,
4411                                           (ast_expression*)subscript);
4412         if (!entfield) {
4413             ast_delete(subscript);
4414             return NULL;
4415         }
4416
4417         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4418         if (!st) {
4419             ast_delete(entfield);
4420             return NULL;
4421         }
4422
4423         block = ast_block_new(ctx);
4424         if (!block) {
4425             ast_delete(st);
4426             return NULL;
4427         }
4428
4429         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4430             ast_delete(block);
4431             return NULL;
4432         }
4433
4434         ret = ast_return_new(ctx, NULL);
4435         if (!ret) {
4436             ast_delete(block);
4437             return NULL;
4438         }
4439
4440         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4441             ast_delete(block);
4442             return NULL;
4443         }
4444
4445         return (ast_expression*)block;
4446     } else {
4447         ast_expression *left, *right;
4448         size_t diff = afterend - from;
4449         size_t middle = from + diff/2;
4450         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4451         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4452         return array_accessor_split(parser, array, index, middle, left, right);
4453     }
4454 }
4455
4456 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4457 {
4458     lex_ctx ctx = ast_ctx(array);
4459
4460     if (from+1 == afterend) {
4461         ast_return      *ret;
4462         ast_array_index *subscript;
4463
4464         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4465         if (!subscript)
4466             return NULL;
4467
4468         ret = ast_return_new(ctx, (ast_expression*)subscript);
4469         if (!ret) {
4470             ast_delete(subscript);
4471             return NULL;
4472         }
4473
4474         return (ast_expression*)ret;
4475     } else {
4476         ast_expression *left, *right;
4477         size_t diff = afterend - from;
4478         size_t middle = from + diff/2;
4479         left  = array_getter_node(parser, array, index, from, middle);
4480         right = array_getter_node(parser, array, index, middle, afterend);
4481         return array_accessor_split(parser, array, index, middle, left, right);
4482     }
4483 }
4484
4485 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4486 {
4487     ast_function   *func = NULL;
4488     ast_value      *fval = NULL;
4489     ast_block      *body = NULL;
4490
4491     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4492     if (!fval) {
4493         parseerror(parser, "failed to create accessor function value");
4494         return false;
4495     }
4496
4497     func = ast_function_new(ast_ctx(array), funcname, fval);
4498     if (!func) {
4499         ast_delete(fval);
4500         parseerror(parser, "failed to create accessor function node");
4501         return false;
4502     }
4503
4504     body = ast_block_new(ast_ctx(array));
4505     if (!body) {
4506         parseerror(parser, "failed to create block for array accessor");
4507         ast_delete(fval);
4508         ast_delete(func);
4509         return false;
4510     }
4511
4512     vec_push(func->blocks, body);
4513     *out = fval;
4514
4515     vec_push(parser->accessors, fval);
4516
4517     return true;
4518 }
4519
4520 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4521 {
4522     ast_value      *index = NULL;
4523     ast_value      *value = NULL;
4524     ast_function   *func;
4525     ast_value      *fval;
4526
4527     if (!ast_istype(array->expression.next, ast_value)) {
4528         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4529         return NULL;
4530     }
4531
4532     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4533         return NULL;
4534     func = fval->constval.vfunc;
4535     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4536
4537     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4538     value = ast_value_copy((ast_value*)array->expression.next);
4539
4540     if (!index || !value) {
4541         parseerror(parser, "failed to create locals for array accessor");
4542         goto cleanup;
4543     }
4544     (void)!ast_value_set_name(value, "value"); /* not important */
4545     vec_push(fval->expression.params, index);
4546     vec_push(fval->expression.params, value);
4547
4548     array->setter = fval;
4549     return fval;
4550 cleanup:
4551     if (index) ast_delete(index);
4552     if (value) ast_delete(value);
4553     ast_delete(func);
4554     ast_delete(fval);
4555     return NULL;
4556 }
4557
4558 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4559 {
4560     ast_expression *root = NULL;
4561     root = array_setter_node(parser, array,
4562                              array->setter->expression.params[0],
4563                              array->setter->expression.params[1],
4564                              0, array->expression.count);
4565     if (!root) {
4566         parseerror(parser, "failed to build accessor search tree");
4567         return false;
4568     }
4569     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4570         ast_delete(root);
4571         return false;
4572     }
4573     return true;
4574 }
4575
4576 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4577 {
4578     if (!parser_create_array_setter_proto(parser, array, funcname))
4579         return false;
4580     return parser_create_array_setter_impl(parser, array);
4581 }
4582
4583 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4584 {
4585     ast_expression *root = NULL;
4586     ast_value      *entity = NULL;
4587     ast_value      *index = NULL;
4588     ast_value      *value = NULL;
4589     ast_function   *func;
4590     ast_value      *fval;
4591
4592     if (!ast_istype(array->expression.next, ast_value)) {
4593         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4594         return false;
4595     }
4596
4597     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4598         return false;
4599     func = fval->constval.vfunc;
4600     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4601
4602     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4603     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4604     value  = ast_value_copy((ast_value*)array->expression.next);
4605     if (!entity || !index || !value) {
4606         parseerror(parser, "failed to create locals for array accessor");
4607         goto cleanup;
4608     }
4609     (void)!ast_value_set_name(value, "value"); /* not important */
4610     vec_push(fval->expression.params, entity);
4611     vec_push(fval->expression.params, index);
4612     vec_push(fval->expression.params, value);
4613
4614     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4615     if (!root) {
4616         parseerror(parser, "failed to build accessor search tree");
4617         goto cleanup;
4618     }
4619
4620     array->setter = fval;
4621     return ast_block_add_expr(func->blocks[0], root);
4622 cleanup:
4623     if (entity) ast_delete(entity);
4624     if (index)  ast_delete(index);
4625     if (value)  ast_delete(value);
4626     if (root)   ast_delete(root);
4627     ast_delete(func);
4628     ast_delete(fval);
4629     return false;
4630 }
4631
4632 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4633 {
4634     ast_value      *index = NULL;
4635     ast_value      *fval;
4636     ast_function   *func;
4637
4638     /* NOTE: checking array->expression.next rather than elemtype since
4639      * for fields elemtype is a temporary fieldtype.
4640      */
4641     if (!ast_istype(array->expression.next, ast_value)) {
4642         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4643         return NULL;
4644     }
4645
4646     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4647         return NULL;
4648     func = fval->constval.vfunc;
4649     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4650
4651     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4652
4653     if (!index) {
4654         parseerror(parser, "failed to create locals for array accessor");
4655         goto cleanup;
4656     }
4657     vec_push(fval->expression.params, index);
4658
4659     array->getter = fval;
4660     return fval;
4661 cleanup:
4662     if (index) ast_delete(index);
4663     ast_delete(func);
4664     ast_delete(fval);
4665     return NULL;
4666 }
4667
4668 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4669 {
4670     ast_expression *root = NULL;
4671
4672     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4673     if (!root) {
4674         parseerror(parser, "failed to build accessor search tree");
4675         return false;
4676     }
4677     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4678         ast_delete(root);
4679         return false;
4680     }
4681     return true;
4682 }
4683
4684 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4685 {
4686     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4687         return false;
4688     return parser_create_array_getter_impl(parser, array);
4689 }
4690
4691 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4692 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4693 {
4694     lex_ctx     ctx;
4695     size_t      i;
4696     ast_value **params;
4697     ast_value  *param;
4698     ast_value  *fval;
4699     bool        first = true;
4700     bool        variadic = false;
4701     ast_value  *varparam = NULL;
4702     char       *argcounter = NULL;
4703
4704     ctx = parser_ctx(parser);
4705
4706     /* for the sake of less code we parse-in in this function */
4707     if (!parser_next(parser)) {
4708         parseerror(parser, "expected parameter list");
4709         return NULL;
4710     }
4711
4712     params = NULL;
4713
4714     /* parse variables until we hit a closing paren */
4715     while (parser->tok != ')') {
4716         if (!first) {
4717             /* there must be commas between them */
4718             if (parser->tok != ',') {
4719                 parseerror(parser, "expected comma or end of parameter list");
4720                 goto on_error;
4721             }
4722             if (!parser_next(parser)) {
4723                 parseerror(parser, "expected parameter");
4724                 goto on_error;
4725             }
4726         }
4727         first = false;
4728
4729         if (parser->tok == TOKEN_DOTS) {
4730             /* '...' indicates a varargs function */
4731             variadic = true;
4732             if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4733                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4734                 goto on_error;
4735             }
4736             if (parser->tok == TOKEN_IDENT) {
4737                 argcounter = util_strdup(parser_tokval(parser));
4738                 if (!parser_next(parser) || parser->tok != ')') {
4739                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4740                     goto on_error;
4741                 }
4742             }
4743         }
4744         else
4745         {
4746             /* for anything else just parse a typename */
4747             param = parse_typename(parser, NULL, NULL);
4748             if (!param)
4749                 goto on_error;
4750             vec_push(params, param);
4751             if (param->expression.vtype >= TYPE_VARIANT) {
4752                 char tname[1024]; /* typename is reserved in C++ */
4753                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4754                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4755                 goto on_error;
4756             }
4757             /* type-restricted varargs */
4758             if (parser->tok == TOKEN_DOTS) {
4759                 variadic = true;
4760                 varparam = vec_last(params);
4761                 vec_pop(params);
4762                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4763                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4764                     goto on_error;
4765                 }
4766                 if (parser->tok == TOKEN_IDENT) {
4767                     argcounter = util_strdup(parser_tokval(parser));
4768                     if (!parser_next(parser) || parser->tok != ')') {
4769                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4770                         goto on_error;
4771                     }
4772                 }
4773             }
4774         }
4775     }
4776
4777     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4778         vec_free(params);
4779
4780     /* sanity check */
4781     if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4782         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4783
4784     /* parse-out */
4785     if (!parser_next(parser)) {
4786         parseerror(parser, "parse error after typename");
4787         goto on_error;
4788     }
4789
4790     /* now turn 'var' into a function type */
4791     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4792     fval->expression.next     = (ast_expression*)var;
4793     if (variadic)
4794         fval->expression.flags |= AST_FLAG_VARIADIC;
4795     var = fval;
4796
4797     var->expression.params   = params;
4798     var->expression.varparam = (ast_expression*)varparam;
4799     var->argcounter          = argcounter;
4800     params = NULL;
4801
4802     return var;
4803
4804 on_error:
4805     if (argcounter)
4806         mem_d(argcounter);
4807     if (varparam)
4808         ast_delete(varparam);
4809     ast_delete(var);
4810     for (i = 0; i < vec_size(params); ++i)
4811         ast_delete(params[i]);
4812     vec_free(params);
4813     return NULL;
4814 }
4815
4816 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4817 {
4818     ast_expression *cexp;
4819     ast_value      *cval, *tmp;
4820     lex_ctx ctx;
4821
4822     ctx = parser_ctx(parser);
4823
4824     if (!parser_next(parser)) {
4825         ast_delete(var);
4826         parseerror(parser, "expected array-size");
4827         return NULL;
4828     }
4829
4830     cexp = parse_expression_leave(parser, true, false, false);
4831
4832     if (!cexp || !ast_istype(cexp, ast_value)) {
4833         if (cexp)
4834             ast_unref(cexp);
4835         ast_delete(var);
4836         parseerror(parser, "expected array-size as constant positive integer");
4837         return NULL;
4838     }
4839     cval = (ast_value*)cexp;
4840
4841     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4842     tmp->expression.next = (ast_expression*)var;
4843     var = tmp;
4844
4845     if (cval->expression.vtype == TYPE_INTEGER)
4846         tmp->expression.count = cval->constval.vint;
4847     else if (cval->expression.vtype == TYPE_FLOAT)
4848         tmp->expression.count = cval->constval.vfloat;
4849     else {
4850         ast_unref(cexp);
4851         ast_delete(var);
4852         parseerror(parser, "array-size must be a positive integer constant");
4853         return NULL;
4854     }
4855     ast_unref(cexp);
4856
4857     if (parser->tok != ']') {
4858         ast_delete(var);
4859         parseerror(parser, "expected ']' after array-size");
4860         return NULL;
4861     }
4862     if (!parser_next(parser)) {
4863         ast_delete(var);
4864         parseerror(parser, "error after parsing array size");
4865         return NULL;
4866     }
4867     return var;
4868 }
4869
4870 /* Parse a complete typename.
4871  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4872  * but when parsing variables separated by comma
4873  * 'storebase' should point to where the base-type should be kept.
4874  * The base type makes up every bit of type information which comes *before* the
4875  * variable name.
4876  *
4877  * The following will be parsed in its entirety:
4878  *     void() foo()
4879  * The 'basetype' in this case is 'void()'
4880  * and if there's a comma after it, say:
4881  *     void() foo(), bar
4882  * then the type-information 'void()' can be stored in 'storebase'
4883  */
4884 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4885 {
4886     ast_value *var, *tmp;
4887     lex_ctx    ctx;
4888
4889     const char *name = NULL;
4890     bool        isfield  = false;
4891     bool        wasarray = false;
4892     size_t      morefields = 0;
4893
4894     ctx = parser_ctx(parser);
4895
4896     /* types may start with a dot */
4897     if (parser->tok == '.') {
4898         isfield = true;
4899         /* if we parsed a dot we need a typename now */
4900         if (!parser_next(parser)) {
4901             parseerror(parser, "expected typename for field definition");
4902             return NULL;
4903         }
4904
4905         /* Further dots are handled seperately because they won't be part of the
4906          * basetype
4907          */
4908         while (parser->tok == '.') {
4909             ++morefields;
4910             if (!parser_next(parser)) {
4911                 parseerror(parser, "expected typename for field definition");
4912                 return NULL;
4913             }
4914         }
4915     }
4916     if (parser->tok == TOKEN_IDENT)
4917         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4918     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4919         parseerror(parser, "expected typename");
4920         return NULL;
4921     }
4922
4923     /* generate the basic type value */
4924     if (cached_typedef) {
4925         var = ast_value_copy(cached_typedef);
4926         ast_value_set_name(var, "<type(from_def)>");
4927     } else
4928         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4929
4930     for (; morefields; --morefields) {
4931         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4932         tmp->expression.next = (ast_expression*)var;
4933         var = tmp;
4934     }
4935
4936     /* do not yet turn into a field - remember:
4937      * .void() foo; is a field too
4938      * .void()() foo; is a function
4939      */
4940
4941     /* parse on */
4942     if (!parser_next(parser)) {
4943         ast_delete(var);
4944         parseerror(parser, "parse error after typename");
4945         return NULL;
4946     }
4947
4948     /* an opening paren now starts the parameter-list of a function
4949      * this is where original-QC has parameter lists.
4950      * We allow a single parameter list here.
4951      * Much like fteqcc we don't allow `float()() x`
4952      */
4953     if (parser->tok == '(') {
4954         var = parse_parameter_list(parser, var);
4955         if (!var)
4956             return NULL;
4957     }
4958
4959     /* store the base if requested */
4960     if (storebase) {
4961         *storebase = ast_value_copy(var);
4962         if (isfield) {
4963             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4964             tmp->expression.next = (ast_expression*)*storebase;
4965             *storebase = tmp;
4966         }
4967     }
4968
4969     /* there may be a name now */
4970     if (parser->tok == TOKEN_IDENT) {
4971         name = util_strdup(parser_tokval(parser));
4972         /* parse on */
4973         if (!parser_next(parser)) {
4974             ast_delete(var);
4975             parseerror(parser, "error after variable or field declaration");
4976             return NULL;
4977         }
4978     }
4979
4980     /* now this may be an array */
4981     if (parser->tok == '[') {
4982         wasarray = true;
4983         var = parse_arraysize(parser, var);
4984         if (!var)
4985             return NULL;
4986     }
4987
4988     /* This is the point where we can turn it into a field */
4989     if (isfield) {
4990         /* turn it into a field if desired */
4991         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4992         tmp->expression.next = (ast_expression*)var;
4993         var = tmp;
4994     }
4995
4996     /* now there may be function parens again */
4997     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4998         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4999     if (parser->tok == '(' && wasarray)
5000         parseerror(parser, "arrays as part of a return type is not supported");
5001     while (parser->tok == '(') {
5002         var = parse_parameter_list(parser, var);
5003         if (!var) {
5004             if (name)
5005                 mem_d((void*)name);
5006             return NULL;
5007         }
5008     }
5009
5010     /* finally name it */
5011     if (name) {
5012         if (!ast_value_set_name(var, name)) {
5013             ast_delete(var);
5014             parseerror(parser, "internal error: failed to set name");
5015             return NULL;
5016         }
5017         /* free the name, ast_value_set_name duplicates */
5018         mem_d((void*)name);
5019     }
5020
5021     return var;
5022 }
5023
5024 static bool parse_typedef(parser_t *parser)
5025 {
5026     ast_value      *typevar, *oldtype;
5027     ast_expression *old;
5028
5029     typevar = parse_typename(parser, NULL, NULL);
5030
5031     if (!typevar)
5032         return false;
5033
5034     if ( (old = parser_find_var(parser, typevar->name)) ) {
5035         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5036                    " -> `%s` has been declared here: %s:%i",
5037                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5038         ast_delete(typevar);
5039         return false;
5040     }
5041
5042     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5043         parseerror(parser, "type `%s` has already been declared here: %s:%i",
5044                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5045         ast_delete(typevar);
5046         return false;
5047     }
5048
5049     vec_push(parser->_typedefs, typevar);
5050     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5051
5052     if (parser->tok != ';') {
5053         parseerror(parser, "expected semicolon after typedef");
5054         return false;
5055     }
5056     if (!parser_next(parser)) {
5057         parseerror(parser, "parse error after typedef");
5058         return false;
5059     }
5060
5061     return true;
5062 }
5063
5064 static const char *cvq_to_str(int cvq) {
5065     switch (cvq) {
5066         case CV_NONE:  return "none";
5067         case CV_VAR:   return "`var`";
5068         case CV_CONST: return "`const`";
5069         default:       return "<INVALID>";
5070     }
5071 }
5072
5073 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5074 {
5075     bool av, ao;
5076     if (proto->cvq != var->cvq) {
5077         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5078               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5079               parser->tok == '='))
5080         {
5081             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5082                                  "`%s` declared with different qualifiers: %s\n"
5083                                  " -> previous declaration here: %s:%i uses %s",
5084                                  var->name, cvq_to_str(var->cvq),
5085                                  ast_ctx(proto).file, ast_ctx(proto).line,
5086                                  cvq_to_str(proto->cvq));
5087         }
5088     }
5089     av = (var  ->expression.flags & AST_FLAG_NORETURN);
5090     ao = (proto->expression.flags & AST_FLAG_NORETURN);
5091     if (!av != !ao) {
5092         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5093                              "`%s` declared with different attributes%s\n"
5094                              " -> previous declaration here: %s:%i",
5095                              var->name, (av ? ": noreturn" : ""),
5096                              ast_ctx(proto).file, ast_ctx(proto).line,
5097                              (ao ? ": noreturn" : ""));
5098     }
5099     return true;
5100 }
5101
5102 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)
5103 {
5104     ast_value *var;
5105     ast_value *proto;
5106     ast_expression *old;
5107     bool       was_end;
5108     size_t     i;
5109
5110     ast_value *basetype = NULL;
5111     bool      retval    = true;
5112     bool      isparam   = false;
5113     bool      isvector  = false;
5114     bool      cleanvar  = true;
5115     bool      wasarray  = false;
5116
5117     ast_member *me[3];
5118
5119     if (!localblock && is_static)
5120         parseerror(parser, "`static` qualifier is not supported in global scope");
5121
5122     /* get the first complete variable */
5123     var = parse_typename(parser, &basetype, cached_typedef);
5124     if (!var) {
5125         if (basetype)
5126             ast_delete(basetype);
5127         return false;
5128     }
5129
5130     while (true) {
5131         proto = NULL;
5132         wasarray = false;
5133
5134         /* Part 0: finish the type */
5135         if (parser->tok == '(') {
5136             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5137                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5138             var = parse_parameter_list(parser, var);
5139             if (!var) {
5140                 retval = false;
5141                 goto cleanup;
5142             }
5143         }
5144         /* we only allow 1-dimensional arrays */
5145         if (parser->tok == '[') {
5146             wasarray = true;
5147             var = parse_arraysize(parser, var);
5148             if (!var) {
5149                 retval = false;
5150                 goto cleanup;
5151             }
5152         }
5153         if (parser->tok == '(' && wasarray) {
5154             parseerror(parser, "arrays as part of a return type is not supported");
5155             /* we'll still parse the type completely for now */
5156         }
5157         /* for functions returning functions */
5158         while (parser->tok == '(') {
5159             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5160                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5161             var = parse_parameter_list(parser, var);
5162             if (!var) {
5163                 retval = false;
5164                 goto cleanup;
5165             }
5166         }
5167
5168         var->cvq = qualifier;
5169         var->expression.flags |= qflags;
5170
5171         /*
5172          * store the vstring back to var for alias and
5173          * deprecation messages.
5174          */
5175         if (var->expression.flags & AST_FLAG_DEPRECATED ||
5176             var->expression.flags & AST_FLAG_ALIAS)
5177             var->desc = vstring;
5178
5179         /* Part 1:
5180          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5181          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5182          * is then filled with the previous definition and the parameter-names replaced.
5183          */
5184         if (!strcmp(var->name, "nil")) {
5185             if (OPTS_FLAG(UNTYPED_NIL)) {
5186                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5187                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5188             } else
5189                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5190         }
5191         if (!localblock) {
5192             /* Deal with end_sys_ vars */
5193             was_end = false;
5194             if (!strcmp(var->name, "end_sys_globals")) {
5195                 var->uses++;
5196                 parser->crc_globals = vec_size(parser->globals);
5197                 was_end = true;
5198             }
5199             else if (!strcmp(var->name, "end_sys_fields")) {
5200                 var->uses++;
5201                 parser->crc_fields = vec_size(parser->fields);
5202                 was_end = true;
5203             }
5204             if (was_end && var->expression.vtype == TYPE_FIELD) {
5205                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5206                                  "global '%s' hint should not be a field",
5207                                  parser_tokval(parser)))
5208                 {
5209                     retval = false;
5210                     goto cleanup;
5211                 }
5212             }
5213
5214             if (!nofields && var->expression.vtype == TYPE_FIELD)
5215             {
5216                 /* deal with field declarations */
5217                 old = parser_find_field(parser, var->name);
5218                 if (old) {
5219                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5220                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5221                     {
5222                         retval = false;
5223                         goto cleanup;
5224                     }
5225                     ast_delete(var);
5226                     var = NULL;
5227                     goto skipvar;
5228                     /*
5229                     parseerror(parser, "field `%s` already declared here: %s:%i",
5230                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5231                     retval = false;
5232                     goto cleanup;
5233                     */
5234                 }
5235                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5236                     (old = parser_find_global(parser, var->name)))
5237                 {
5238                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5239                     parseerror(parser, "field `%s` already declared here: %s:%i",
5240                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5241                     retval = false;
5242                     goto cleanup;
5243                 }
5244             }
5245             else
5246             {
5247                 /* deal with other globals */
5248                 old = parser_find_global(parser, var->name);
5249                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5250                 {
5251                     /* This is a function which had a prototype */
5252                     if (!ast_istype(old, ast_value)) {
5253                         parseerror(parser, "internal error: prototype is not an ast_value");
5254                         retval = false;
5255                         goto cleanup;
5256                     }
5257                     proto = (ast_value*)old;
5258                     proto->desc = var->desc;
5259                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5260                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5261                                    proto->name,
5262                                    ast_ctx(proto).file, ast_ctx(proto).line);
5263                         retval = false;
5264                         goto cleanup;
5265                     }
5266                     /* we need the new parameter-names */
5267                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5268                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5269                     if (!parser_check_qualifiers(parser, var, proto)) {
5270                         retval = false;
5271                         if (proto->desc)
5272                             mem_d(proto->desc);
5273                         proto = NULL;
5274                         goto cleanup;
5275                     }
5276                     proto->expression.flags |= var->expression.flags;
5277                     ast_delete(var);
5278                     var = proto;
5279                 }
5280                 else
5281                 {
5282                     /* other globals */
5283                     if (old) {
5284                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5285                                          "global `%s` already declared here: %s:%i",
5286                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5287                         {
5288                             retval = false;
5289                             goto cleanup;
5290                         }
5291                         proto = (ast_value*)old;
5292                         if (!ast_istype(old, ast_value)) {
5293                             parseerror(parser, "internal error: not an ast_value");
5294                             retval = false;
5295                             proto = NULL;
5296                             goto cleanup;
5297                         }
5298                         if (!parser_check_qualifiers(parser, var, proto)) {
5299                             retval = false;
5300                             proto = NULL;
5301                             goto cleanup;
5302                         }
5303                         proto->expression.flags |= var->expression.flags;
5304                         ast_delete(var);
5305                         var = proto;
5306                     }
5307                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5308                         (old = parser_find_field(parser, var->name)))
5309                     {
5310                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5311                         parseerror(parser, "global `%s` already declared here: %s:%i",
5312                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5313                         retval = false;
5314                         goto cleanup;
5315                     }
5316                 }
5317             }
5318         }
5319         else /* it's not a global */
5320         {
5321             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5322             if (old && !isparam) {
5323                 parseerror(parser, "local `%s` already declared here: %s:%i",
5324                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5325                 retval = false;
5326                 goto cleanup;
5327             }
5328             old = parser_find_local(parser, var->name, 0, &isparam);
5329             if (old && isparam) {
5330                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5331                                  "local `%s` is shadowing a parameter", var->name))
5332                 {
5333                     parseerror(parser, "local `%s` already declared here: %s:%i",
5334                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5335                     retval = false;
5336                     goto cleanup;
5337                 }
5338                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5339                     ast_delete(var);
5340                     var = NULL;
5341                     goto skipvar;
5342                 }
5343             }
5344         }
5345
5346         /* in a noref section we simply bump the usecount */
5347         if (noref || parser->noref)
5348             var->uses++;
5349
5350         /* Part 2:
5351          * Create the global/local, and deal with vector types.
5352          */
5353         if (!proto) {
5354             if (var->expression.vtype == TYPE_VECTOR)
5355                 isvector = true;
5356             else if (var->expression.vtype == TYPE_FIELD &&
5357                      var->expression.next->expression.vtype == TYPE_VECTOR)
5358                 isvector = true;
5359
5360             if (isvector) {
5361                 if (!create_vector_members(var, me)) {
5362                     retval = false;
5363                     goto cleanup;
5364                 }
5365             }
5366
5367             if (!localblock) {
5368                 /* deal with global variables, fields, functions */
5369                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5370                     var->isfield = true;
5371                     vec_push(parser->fields, (ast_expression*)var);
5372                     util_htset(parser->htfields, var->name, var);
5373                     if (isvector) {
5374                         for (i = 0; i < 3; ++i) {
5375                             vec_push(parser->fields, (ast_expression*)me[i]);
5376                             util_htset(parser->htfields, me[i]->name, me[i]);
5377                         }
5378                     }
5379                 }
5380                 else {
5381                     if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5382                         parser_addglobal(parser, var->name, (ast_expression*)var);
5383                         if (isvector) {
5384                             for (i = 0; i < 3; ++i) {
5385                                 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5386                             }
5387                         }
5388                     } else {
5389                         ast_expression *find  = parser_find_global(parser, var->desc);
5390
5391                         if (!find) {
5392                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5393                             return false;
5394                         }
5395
5396                         if (var->expression.vtype != find->expression.vtype) {
5397                             char ty1[1024];
5398                             char ty2[1024];
5399
5400                             ast_type_to_string(find,                  ty1, sizeof(ty1));
5401                             ast_type_to_string((ast_expression*)var,  ty2, sizeof(ty2));
5402
5403                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5404                                 ty1, ty2, var->name
5405                             );
5406                             return false;
5407                         }
5408
5409                         /*
5410                          * add alias to aliases table and to corrector
5411                          * so corrections can apply for aliases as well.
5412                          */
5413                         util_htset(parser->aliases, var->name, find);
5414
5415                         /*
5416                          * add to corrector so corrections can work
5417                          * even for aliases too.
5418                          */
5419                         correct_add (
5420                              vec_last(parser->correct_variables),
5421                             &vec_last(parser->correct_variables_score),
5422                             var->name
5423                         );
5424
5425                         /* generate aliases for vector components */
5426                         if (isvector) {
5427                             char *buffer[3];
5428
5429                             util_asprintf(&buffer[0], "%s_x", var->desc);
5430                             util_asprintf(&buffer[1], "%s_y", var->desc);
5431                             util_asprintf(&buffer[2], "%s_z", var->desc);
5432
5433                             util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5434                             util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5435                             util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5436
5437                             mem_d(buffer[0]);
5438                             mem_d(buffer[1]);
5439                             mem_d(buffer[2]);
5440
5441                             /*
5442                              * add to corrector so corrections can work
5443                              * even for aliases too.
5444                              */
5445                             correct_add (
5446                                  vec_last(parser->correct_variables),
5447                                 &vec_last(parser->correct_variables_score),
5448                                 me[0]->name
5449                             );
5450                             correct_add (
5451                                  vec_last(parser->correct_variables),
5452                                 &vec_last(parser->correct_variables_score),
5453                                 me[1]->name
5454                             );
5455                             correct_add (
5456                                  vec_last(parser->correct_variables),
5457                                 &vec_last(parser->correct_variables_score),
5458                                 me[2]->name
5459                             );
5460                         }
5461                     }
5462                 }
5463             } else {
5464                 if (is_static) {
5465                     /* a static adds itself to be generated like any other global
5466                      * but is added to the local namespace instead
5467                      */
5468                     char   *defname = NULL;
5469                     size_t  prefix_len, ln;
5470
5471                     ln = strlen(parser->function->name);
5472                     vec_append(defname, ln, parser->function->name);
5473
5474                     vec_append(defname, 2, "::");
5475                     /* remember the length up to here */
5476                     prefix_len = vec_size(defname);
5477
5478                     /* Add it to the local scope */
5479                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5480
5481                     /* corrector */
5482                     correct_add (
5483                          vec_last(parser->correct_variables),
5484                         &vec_last(parser->correct_variables_score),
5485                         var->name
5486                     );
5487
5488                     /* now rename the global */
5489                     ln = strlen(var->name);
5490                     vec_append(defname, ln, var->name);
5491                     ast_value_set_name(var, defname);
5492
5493                     /* push it to the to-be-generated globals */
5494                     vec_push(parser->globals, (ast_expression*)var);
5495
5496                     /* same game for the vector members */
5497                     if (isvector) {
5498                         for (i = 0; i < 3; ++i) {
5499                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5500
5501                             /* corrector */
5502                             correct_add(
5503                                  vec_last(parser->correct_variables),
5504                                 &vec_last(parser->correct_variables_score),
5505                                 me[i]->name
5506                             );
5507
5508                             vec_shrinkto(defname, prefix_len);
5509                             ln = strlen(me[i]->name);
5510                             vec_append(defname, ln, me[i]->name);
5511                             ast_member_set_name(me[i], defname);
5512
5513                             vec_push(parser->globals, (ast_expression*)me[i]);
5514                         }
5515                     }
5516                     vec_free(defname);
5517                 } else {
5518                     vec_push(localblock->locals, var);
5519                     parser_addlocal(parser, var->name, (ast_expression*)var);
5520                     if (isvector) {
5521                         for (i = 0; i < 3; ++i) {
5522                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5523                             ast_block_collect(localblock, (ast_expression*)me[i]);
5524                         }
5525                     }
5526                 }
5527             }
5528         }
5529         me[0] = me[1] = me[2] = NULL;
5530         cleanvar = false;
5531         /* Part 2.2
5532          * deal with arrays
5533          */
5534         if (var->expression.vtype == TYPE_ARRAY) {
5535             char name[1024];
5536             snprintf(name, sizeof(name), "%s##SET", var->name);
5537             if (!parser_create_array_setter(parser, var, name))
5538                 goto cleanup;
5539             snprintf(name, sizeof(name), "%s##GET", var->name);
5540             if (!parser_create_array_getter(parser, var, var->expression.next, name))
5541                 goto cleanup;
5542         }
5543         else if (!localblock && !nofields &&
5544                  var->expression.vtype == TYPE_FIELD &&
5545                  var->expression.next->expression.vtype == TYPE_ARRAY)
5546         {
5547             char name[1024];
5548             ast_expression *telem;
5549             ast_value      *tfield;
5550             ast_value      *array = (ast_value*)var->expression.next;
5551
5552             if (!ast_istype(var->expression.next, ast_value)) {
5553                 parseerror(parser, "internal error: field element type must be an ast_value");
5554                 goto cleanup;
5555             }
5556
5557             snprintf(name, sizeof(name), "%s##SETF", var->name);
5558             if (!parser_create_array_field_setter(parser, array, name))
5559                 goto cleanup;
5560
5561             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5562             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5563             tfield->expression.next = telem;
5564             snprintf(name, sizeof(name), "%s##GETFP", var->name);
5565             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5566                 ast_delete(tfield);
5567                 goto cleanup;
5568             }
5569             ast_delete(tfield);
5570         }
5571
5572 skipvar:
5573         if (parser->tok == ';') {
5574             ast_delete(basetype);
5575             if (!parser_next(parser)) {
5576                 parseerror(parser, "error after variable declaration");
5577                 return false;
5578             }
5579             return true;
5580         }
5581
5582         if (parser->tok == ',')
5583             goto another;
5584
5585         /*
5586         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5587         */
5588         if (!var) {
5589             parseerror(parser, "missing comma or semicolon while parsing variables");
5590             break;
5591         }
5592
5593         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5594             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5595                              "initializing expression turns variable `%s` into a constant in this standard",
5596                              var->name) )
5597             {
5598                 break;
5599             }
5600         }
5601
5602         if (parser->tok != '{') {
5603             if (parser->tok != '=') {
5604                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5605                 break;
5606             }
5607
5608             if (!parser_next(parser)) {
5609                 parseerror(parser, "error parsing initializer");
5610                 break;
5611             }
5612         }
5613         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5614             parseerror(parser, "expected '=' before function body in this standard");
5615         }
5616
5617         if (parser->tok == '#') {
5618             ast_function *func = NULL;
5619
5620             if (localblock) {
5621                 parseerror(parser, "cannot declare builtins within functions");
5622                 break;
5623             }
5624             if (var->expression.vtype != TYPE_FUNCTION) {
5625                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5626                 break;
5627             }
5628             if (!parser_next(parser)) {
5629                 parseerror(parser, "expected builtin number");
5630                 break;
5631             }
5632             if (parser->tok != TOKEN_INTCONST) {
5633                 parseerror(parser, "builtin number must be an integer constant");
5634                 break;
5635             }
5636             if (parser_token(parser)->constval.i < 0) {
5637                 parseerror(parser, "builtin number must be an integer greater than zero");
5638                 break;
5639             }
5640
5641             if (var->hasvalue) {
5642                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5643                                     "builtin `%s` has already been defined\n"
5644                                     " -> previous declaration here: %s:%i",
5645                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5646             }
5647             else
5648             {
5649                 func = ast_function_new(ast_ctx(var), var->name, var);
5650                 if (!func) {
5651                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5652                     break;
5653                 }
5654                 vec_push(parser->functions, func);
5655
5656                 func->builtin = -parser_token(parser)->constval.i-1;
5657             }
5658
5659             if (!parser_next(parser)) {
5660                 parseerror(parser, "expected comma or semicolon");
5661                 if (func)
5662                     ast_function_delete(func);
5663                 var->constval.vfunc = NULL;
5664                 break;
5665             }
5666         }
5667         else if (parser->tok == '{' || parser->tok == '[')
5668         {
5669             if (localblock) {
5670                 parseerror(parser, "cannot declare functions within functions");
5671                 break;
5672             }
5673
5674             if (proto)
5675                 ast_ctx(proto) = parser_ctx(parser);
5676
5677             if (!parse_function_body(parser, var))
5678                 break;
5679             ast_delete(basetype);
5680             for (i = 0; i < vec_size(parser->gotos); ++i)
5681                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5682             vec_free(parser->gotos);
5683             vec_free(parser->labels);
5684             return true;
5685         } else {
5686             ast_expression *cexp;
5687             ast_value      *cval;
5688
5689             cexp = parse_expression_leave(parser, true, false, false);
5690             if (!cexp)
5691                 break;
5692
5693             if (!localblock) {
5694                 cval = (ast_value*)cexp;
5695                 if (cval != parser->nil &&
5696                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5697                    )
5698                 {
5699                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5700                 }
5701                 else
5702                 {
5703                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5704                         qualifier != CV_VAR)
5705                     {
5706                         var->cvq = CV_CONST;
5707                     }
5708                     if (cval == parser->nil)
5709                         var->expression.flags |= AST_FLAG_INITIALIZED;
5710                     else
5711                     {
5712                         var->hasvalue = true;
5713                         if (cval->expression.vtype == TYPE_STRING)
5714                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5715                         else if (cval->expression.vtype == TYPE_FIELD)
5716                             var->constval.vfield = cval;
5717                         else
5718                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5719                         ast_unref(cval);
5720                     }
5721                 }
5722             } else {
5723                 int cvq;
5724                 shunt sy = { NULL, NULL, NULL, NULL };
5725                 cvq = var->cvq;
5726                 var->cvq = CV_NONE;
5727                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5728                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5729                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5730                 if (!parser_sy_apply_operator(parser, &sy))
5731                     ast_unref(cexp);
5732                 else {
5733                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5734                         parseerror(parser, "internal error: leaked operands");
5735                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5736                         break;
5737                 }
5738                 vec_free(sy.out);
5739                 vec_free(sy.ops);
5740                 var->cvq = cvq;
5741             }
5742         }
5743
5744 another:
5745         if (parser->tok == ',') {
5746             if (!parser_next(parser)) {
5747                 parseerror(parser, "expected another variable");
5748                 break;
5749             }
5750
5751             if (parser->tok != TOKEN_IDENT) {
5752                 parseerror(parser, "expected another variable");
5753                 break;
5754             }
5755             var = ast_value_copy(basetype);
5756             cleanvar = true;
5757             ast_value_set_name(var, parser_tokval(parser));
5758             if (!parser_next(parser)) {
5759                 parseerror(parser, "error parsing variable declaration");
5760                 break;
5761             }
5762             continue;
5763         }
5764
5765         if (parser->tok != ';') {
5766             parseerror(parser, "missing semicolon after variables");
5767             break;
5768         }
5769
5770         if (!parser_next(parser)) {
5771             parseerror(parser, "parse error after variable declaration");
5772             break;
5773         }
5774
5775         ast_delete(basetype);
5776         return true;
5777     }
5778
5779     if (cleanvar && var)
5780         ast_delete(var);
5781     ast_delete(basetype);
5782     return false;
5783
5784 cleanup:
5785     ast_delete(basetype);
5786     if (cleanvar && var)
5787         ast_delete(var);
5788     if (me[0]) ast_member_delete(me[0]);
5789     if (me[1]) ast_member_delete(me[1]);
5790     if (me[2]) ast_member_delete(me[2]);
5791     return retval;
5792 }
5793
5794 static bool parser_global_statement(parser_t *parser)
5795 {
5796     int        cvq       = CV_WRONG;
5797     bool       noref     = false;
5798     bool       is_static = false;
5799     uint32_t   qflags    = 0;
5800     ast_value *istype    = NULL;
5801     char      *vstring   = NULL;
5802
5803     if (parser->tok == TOKEN_IDENT)
5804         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5805
5806     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5807     {
5808         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5809     }
5810     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5811     {
5812         if (cvq == CV_WRONG)
5813             return false;
5814         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5815     }
5816     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5817     {
5818         return parse_enum(parser);
5819     }
5820     else if (parser->tok == TOKEN_KEYWORD)
5821     {
5822         if (!strcmp(parser_tokval(parser), "typedef")) {
5823             if (!parser_next(parser)) {
5824                 parseerror(parser, "expected type definition after 'typedef'");
5825                 return false;
5826             }
5827             return parse_typedef(parser);
5828         }
5829         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5830         return false;
5831     }
5832     else if (parser->tok == '#')
5833     {
5834         return parse_pragma(parser);
5835     }
5836     else if (parser->tok == '$')
5837     {
5838         if (!parser_next(parser)) {
5839             parseerror(parser, "parse error");
5840             return false;
5841         }
5842     }
5843     else
5844     {
5845         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5846         return false;
5847     }
5848     return true;
5849 }
5850
5851 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5852 {
5853     return util_crc16(old, str, strlen(str));
5854 }
5855
5856 static void progdefs_crc_file(const char *str)
5857 {
5858     /* write to progdefs.h here */
5859     (void)str;
5860 }
5861
5862 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5863 {
5864     old = progdefs_crc_sum(old, str);
5865     progdefs_crc_file(str);
5866     return old;
5867 }
5868
5869 static void generate_checksum(parser_t *parser)
5870 {
5871     uint16_t   crc = 0xFFFF;
5872     size_t     i;
5873     ast_value *value;
5874
5875     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5876     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5877     /*
5878     progdefs_crc_file("\tint\tpad;\n");
5879     progdefs_crc_file("\tint\tofs_return[3];\n");
5880     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5881     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5882     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5883     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5884     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5885     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5886     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5887     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5888     */
5889     for (i = 0; i < parser->crc_globals; ++i) {
5890         if (!ast_istype(parser->globals[i], ast_value))
5891             continue;
5892         value = (ast_value*)(parser->globals[i]);
5893         switch (value->expression.vtype) {
5894             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5895             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5896             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5897             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5898             default:
5899                 crc = progdefs_crc_both(crc, "\tint\t");
5900                 break;
5901         }
5902         crc = progdefs_crc_both(crc, value->name);
5903         crc = progdefs_crc_both(crc, ";\n");
5904     }
5905     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5906     for (i = 0; i < parser->crc_fields; ++i) {
5907         if (!ast_istype(parser->fields[i], ast_value))
5908             continue;
5909         value = (ast_value*)(parser->fields[i]);
5910         switch (value->expression.next->expression.vtype) {
5911             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5912             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5913             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5914             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5915             default:
5916                 crc = progdefs_crc_both(crc, "\tint\t");
5917                 break;
5918         }
5919         crc = progdefs_crc_both(crc, value->name);
5920         crc = progdefs_crc_both(crc, ";\n");
5921     }
5922     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5923
5924     code_crc = crc;
5925 }
5926
5927 parser_t *parser_create()
5928 {
5929     parser_t *parser;
5930     lex_ctx empty_ctx;
5931     size_t i;
5932
5933     parser = (parser_t*)mem_a(sizeof(parser_t));
5934     if (!parser)
5935         return NULL;
5936
5937     memset(parser, 0, sizeof(*parser));
5938
5939     for (i = 0; i < operator_count; ++i) {
5940         if (operators[i].id == opid1('=')) {
5941             parser->assign_op = operators+i;
5942             break;
5943         }
5944     }
5945     if (!parser->assign_op) {
5946         printf("internal error: initializing parser: failed to find assign operator\n");
5947         mem_d(parser);
5948         return NULL;
5949     }
5950
5951     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5952     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5953     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5954     vec_push(parser->_blocktypedefs, 0);
5955
5956     parser->aliases = util_htnew(PARSER_HT_SIZE);
5957
5958     parser->ht_imm_string = util_htnew(512);
5959
5960     /* corrector */
5961     vec_push(parser->correct_variables, correct_trie_new());
5962     vec_push(parser->correct_variables_score, NULL);
5963
5964     empty_ctx.file = "<internal>";
5965     empty_ctx.line = 0;
5966     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5967     parser->nil->cvq = CV_CONST;
5968     if (OPTS_FLAG(UNTYPED_NIL))
5969         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5970
5971     parser->max_param_count = 1;
5972
5973     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5974     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5975     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5976
5977     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5978         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5979         parser->reserved_version->cvq = CV_CONST;
5980         parser->reserved_version->hasvalue = true;
5981         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5982         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5983     } else {
5984         parser->reserved_version = NULL;
5985     }
5986
5987     return parser;
5988 }
5989
5990 bool parser_compile(parser_t *parser)
5991 {
5992     /* initial lexer/parser state */
5993     parser->lex->flags.noops = true;
5994
5995     if (parser_next(parser))
5996     {
5997         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5998         {
5999             if (!parser_global_statement(parser)) {
6000                 if (parser->tok == TOKEN_EOF)
6001                     parseerror(parser, "unexpected eof");
6002                 else if (compile_errors)
6003                     parseerror(parser, "there have been errors, bailing out");
6004                 lex_close(parser->lex);
6005                 parser->lex = NULL;
6006                 return false;
6007             }
6008         }
6009     } else {
6010         parseerror(parser, "parse error");
6011         lex_close(parser->lex);
6012         parser->lex = NULL;
6013         return false;
6014     }
6015
6016     lex_close(parser->lex);
6017     parser->lex = NULL;
6018
6019     return !compile_errors;
6020 }
6021
6022 bool parser_compile_file(parser_t *parser, const char *filename)
6023 {
6024     parser->lex = lex_open(filename);
6025     if (!parser->lex) {
6026         con_err("failed to open file \"%s\"\n", filename);
6027         return false;
6028     }
6029     return parser_compile(parser);
6030 }
6031
6032 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6033 {
6034     parser->lex = lex_open_string(str, len, name);
6035     if (!parser->lex) {
6036         con_err("failed to create lexer for string \"%s\"\n", name);
6037         return false;
6038     }
6039     return parser_compile(parser);
6040 }
6041
6042 void parser_cleanup(parser_t *parser)
6043 {
6044     size_t i;
6045     for (i = 0; i < vec_size(parser->accessors); ++i) {
6046         ast_delete(parser->accessors[i]->constval.vfunc);
6047         parser->accessors[i]->constval.vfunc = NULL;
6048         ast_delete(parser->accessors[i]);
6049     }
6050     for (i = 0; i < vec_size(parser->functions); ++i) {
6051         ast_delete(parser->functions[i]);
6052     }
6053     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6054         ast_delete(parser->imm_vector[i]);
6055     }
6056     for (i = 0; i < vec_size(parser->imm_string); ++i) {
6057         ast_delete(parser->imm_string[i]);
6058     }
6059     for (i = 0; i < vec_size(parser->imm_float); ++i) {
6060         ast_delete(parser->imm_float[i]);
6061     }
6062     for (i = 0; i < vec_size(parser->fields); ++i) {
6063         ast_delete(parser->fields[i]);
6064     }
6065     for (i = 0; i < vec_size(parser->globals); ++i) {
6066         ast_delete(parser->globals[i]);
6067     }
6068     vec_free(parser->accessors);
6069     vec_free(parser->functions);
6070     vec_free(parser->imm_vector);
6071     vec_free(parser->imm_string);
6072     util_htdel(parser->ht_imm_string);
6073     vec_free(parser->imm_float);
6074     vec_free(parser->globals);
6075     vec_free(parser->fields);
6076
6077     for (i = 0; i < vec_size(parser->variables); ++i)
6078         util_htdel(parser->variables[i]);
6079     vec_free(parser->variables);
6080     vec_free(parser->_blocklocals);
6081     vec_free(parser->_locals);
6082
6083     /* corrector */
6084     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6085         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6086     }
6087     vec_free(parser->correct_variables);
6088     vec_free(parser->correct_variables_score);
6089
6090
6091     for (i = 0; i < vec_size(parser->_typedefs); ++i)
6092         ast_delete(parser->_typedefs[i]);
6093     vec_free(parser->_typedefs);
6094     for (i = 0; i < vec_size(parser->typedefs); ++i)
6095         util_htdel(parser->typedefs[i]);
6096     vec_free(parser->typedefs);
6097     vec_free(parser->_blocktypedefs);
6098
6099     vec_free(parser->_block_ctx);
6100
6101     vec_free(parser->labels);
6102     vec_free(parser->gotos);
6103     vec_free(parser->breaks);
6104     vec_free(parser->continues);
6105
6106     ast_value_delete(parser->nil);
6107
6108     ast_value_delete(parser->const_vec[0]);
6109     ast_value_delete(parser->const_vec[1]);
6110     ast_value_delete(parser->const_vec[2]);
6111
6112     util_htdel(parser->aliases);
6113
6114     intrin_intrinsics_destroy(parser);
6115
6116     mem_d(parser);
6117 }
6118
6119 bool parser_finish(parser_t *parser, const char *output)
6120 {
6121     size_t i;
6122     ir_builder *ir;
6123     bool retval = true;
6124
6125     if (compile_errors) {
6126         con_out("*** there were compile errors\n");
6127         return false;
6128     }
6129
6130     ir = ir_builder_new("gmqcc_out");
6131     if (!ir) {
6132         con_out("failed to allocate builder\n");
6133         return false;
6134     }
6135
6136     for (i = 0; i < vec_size(parser->fields); ++i) {
6137         ast_value *field;
6138         bool hasvalue;
6139         if (!ast_istype(parser->fields[i], ast_value))
6140             continue;
6141         field = (ast_value*)parser->fields[i];
6142         hasvalue = field->hasvalue;
6143         field->hasvalue = false;
6144         if (!ast_global_codegen((ast_value*)field, ir, true)) {
6145             con_out("failed to generate field %s\n", field->name);
6146             ir_builder_delete(ir);
6147             return false;
6148         }
6149         if (hasvalue) {
6150             ir_value *ifld;
6151             ast_expression *subtype;
6152             field->hasvalue = true;
6153             subtype = field->expression.next;
6154             ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6155             if (subtype->expression.vtype == TYPE_FIELD)
6156                 ifld->fieldtype = subtype->expression.next->expression.vtype;
6157             else if (subtype->expression.vtype == TYPE_FUNCTION)
6158                 ifld->outtype = subtype->expression.next->expression.vtype;
6159             (void)!ir_value_set_field(field->ir_v, ifld);
6160         }
6161     }
6162     for (i = 0; i < vec_size(parser->globals); ++i) {
6163         ast_value *asvalue;
6164         if (!ast_istype(parser->globals[i], ast_value))
6165             continue;
6166         asvalue = (ast_value*)(parser->globals[i]);
6167         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6168             retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6169                                                 "unused global: `%s`", asvalue->name);
6170         }
6171         if (!ast_global_codegen(asvalue, ir, false)) {
6172             con_out("failed to generate global %s\n", asvalue->name);
6173             ir_builder_delete(ir);
6174             return false;
6175         }
6176     }
6177     /* Build function vararg accessor ast tree now before generating
6178      * immediates, because the accessors may add new immediates
6179      */
6180     for (i = 0; i < vec_size(parser->functions); ++i) {
6181         ast_function *f = parser->functions[i];
6182         if (f->varargs) {
6183             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6184                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6185                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6186                     con_out("failed to generate vararg setter for %s\n", f->name);
6187                     ir_builder_delete(ir);
6188                     return false;
6189                 }
6190                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6191                     con_out("failed to generate vararg getter for %s\n", f->name);
6192                     ir_builder_delete(ir);
6193                     return false;
6194                 }
6195             } else {
6196                 ast_delete(f->varargs);
6197                 f->varargs = NULL;
6198             }
6199         }
6200     }
6201     /* Now we can generate immediates */
6202     for (i = 0; i < vec_size(parser->imm_float); ++i) {
6203         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6204             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6205             ir_builder_delete(ir);
6206             return false;
6207         }
6208     }
6209     for (i = 0; i < vec_size(parser->imm_string); ++i) {
6210         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6211             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6212             ir_builder_delete(ir);
6213             return false;
6214         }
6215     }
6216     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6217         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6218             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6219             ir_builder_delete(ir);
6220             return false;
6221         }
6222     }
6223     for (i = 0; i < vec_size(parser->globals); ++i) {
6224         ast_value *asvalue;
6225         if (!ast_istype(parser->globals[i], ast_value))
6226             continue;
6227         asvalue = (ast_value*)(parser->globals[i]);
6228         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6229         {
6230             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6231                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6232                                        "uninitialized constant: `%s`",
6233                                        asvalue->name);
6234             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6235                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6236                                        "uninitialized global: `%s`",
6237                                        asvalue->name);
6238         }
6239         if (!ast_generate_accessors(asvalue, ir)) {
6240             ir_builder_delete(ir);
6241             return false;
6242         }
6243     }
6244     for (i = 0; i < vec_size(parser->fields); ++i) {
6245         ast_value *asvalue;
6246         asvalue = (ast_value*)(parser->fields[i]->expression.next);
6247
6248         if (!ast_istype((ast_expression*)asvalue, ast_value))
6249             continue;
6250         if (asvalue->expression.vtype != TYPE_ARRAY)
6251             continue;
6252         if (!ast_generate_accessors(asvalue, ir)) {
6253             ir_builder_delete(ir);
6254             return false;
6255         }
6256     }
6257     if (parser->reserved_version &&
6258         !ast_global_codegen(parser->reserved_version, ir, false))
6259     {
6260         con_out("failed to generate reserved::version");
6261         ir_builder_delete(ir);
6262         return false;
6263     }
6264     for (i = 0; i < vec_size(parser->functions); ++i) {
6265         ast_function *f = parser->functions[i];
6266         if (!ast_function_codegen(f, ir)) {
6267             con_out("failed to generate function %s\n", f->name);
6268             ir_builder_delete(ir);
6269             return false;
6270         }
6271     }
6272     if (OPTS_OPTION_BOOL(OPTION_DUMP))
6273         ir_builder_dump(ir, con_out);
6274     for (i = 0; i < vec_size(parser->functions); ++i) {
6275         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6276             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6277             ir_builder_delete(ir);
6278             return false;
6279         }
6280     }
6281
6282     if (compile_Werrors) {
6283         con_out("*** there were warnings treated as errors\n");
6284         compile_show_werrors();
6285         retval = false;
6286     }
6287
6288     if (retval) {
6289         if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6290             ir_builder_dump(ir, con_out);
6291
6292         generate_checksum(parser);
6293
6294         if (!ir_builder_generate(ir, output)) {
6295             con_out("*** failed to generate output file\n");
6296             ir_builder_delete(ir);
6297             return false;
6298         }
6299     }
6300
6301     ir_builder_delete(ir);
6302     return retval;
6303 }