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