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