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