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