]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Merge branch 'master' of github.com:graphitemaster/gmqcc
[xonotic/gmqcc.git] / parser.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdio.h>
24 #include <stdarg.h>
25
26 #include "gmqcc.h"
27 #include "lexer.h"
28
29 #define PARSER_HT_FIELDS  0
30 #define PARSER_HT_GLOBALS 1
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS  2
33
34 #define PARSER_HT_SIZE    1024
35 #define TYPEDEF_HT_SIZE   16
36
37 typedef struct {
38     lex_file *lex;
39     int      tok;
40
41     ast_expression **globals;
42     ast_expression **fields;
43     ast_function **functions;
44     ast_value    **imm_float;
45     ast_value    **imm_string;
46     ast_value    **imm_vector;
47     size_t         translated;
48
49     /* must be deleted first, they reference immediates and values */
50     ast_value    **accessors;
51
52     ast_value *imm_float_zero;
53     ast_value *imm_float_one;
54     ast_value *imm_vector_zero;
55
56     size_t crc_globals;
57     size_t crc_fields;
58
59     ast_function *function;
60
61     /* All the labels the function defined...
62      * Should they be in ast_function instead?
63      */
64     ast_label **labels;
65     ast_goto  **gotos;
66
67     /* A list of hashtables for each scope */
68     ht *variables;
69     ht htfields;
70     ht htglobals;
71     ht *typedefs;
72
73     /* not to be used directly, we use the hash table */
74     ast_expression **_locals;
75     size_t          *_blocklocals;
76     ast_value      **_typedefs;
77     size_t          *_blocktypedefs;
78     lex_ctx         *_block_ctx;
79
80     size_t errors;
81
82     /* we store the '=' operator info */
83     const oper_info *assign_op;
84
85     /* TYPE_FIELD -> parser_find_fields is used instead of find_var
86      * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
87      * anything else: type error
88      */
89     qcint  memberof;
90
91     /* Keep track of our ternary vs parenthesis nesting state.
92      * If we reach a 'comma' operator in a ternary without a paren,
93      * we shall trigger -Wternary-precedence.
94      */
95     enum { POT_PAREN, POT_TERNARY1, POT_TERNARY2 } *pot;
96 } parser_t;
97
98 static void parser_enterblock(parser_t *parser);
99 static bool parser_leaveblock(parser_t *parser);
100 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
101 static bool parse_typedef(parser_t *parser);
102 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef);
103 static ast_block* parse_block(parser_t *parser);
104 static bool parse_block_into(parser_t *parser, ast_block *block);
105 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
106 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
107 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
108 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
109
110 static void parseerror(parser_t *parser, const char *fmt, ...)
111 {
112         va_list ap;
113
114         parser->errors++;
115
116         va_start(ap, fmt);
117     con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
118         va_end(ap);
119 }
120
121 /* returns true if it counts as an error */
122 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
123 {
124         va_list ap;
125         int lvl = LVL_WARNING;
126
127     if (!OPTS_WARN(warntype))
128         return false;
129
130     if (opts_werror) {
131             parser->errors++;
132             lvl = LVL_ERROR;
133         }
134
135         va_start(ap, fmt);
136     con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
137         va_end(ap);
138
139         return opts_werror;
140 }
141
142 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
143 {
144         va_list ap;
145         int lvl = LVL_WARNING;
146
147     if (!OPTS_WARN(warntype))
148         return false;
149
150     if (opts_werror)
151             lvl = LVL_ERROR;
152
153         va_start(ap, fmt);
154     con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
155         va_end(ap);
156
157         return opts_werror;
158 }
159
160 /**********************************************************************
161  * some maths used for constant folding
162  */
163
164 vector vec3_add(vector a, vector b)
165 {
166     vector out;
167     out.x = a.x + b.x;
168     out.y = a.y + b.y;
169     out.z = a.z + b.z;
170     return out;
171 }
172
173 vector vec3_sub(vector a, vector b)
174 {
175     vector out;
176     out.x = a.x - b.x;
177     out.y = a.y - b.y;
178     out.z = a.z - b.z;
179     return out;
180 }
181
182 qcfloat vec3_mulvv(vector a, vector b)
183 {
184     return (a.x * b.x + a.y * b.y + a.z * b.z);
185 }
186
187 vector vec3_mulvf(vector a, float b)
188 {
189     vector out;
190     out.x = a.x * b;
191     out.y = a.y * b;
192     out.z = a.z * b;
193     return out;
194 }
195
196 /**********************************************************************
197  * parsing
198  */
199
200 bool parser_next(parser_t *parser)
201 {
202     /* lex_do kills the previous token */
203     parser->tok = lex_do(parser->lex);
204     if (parser->tok == TOKEN_EOF)
205         return true;
206     if (parser->tok >= TOKEN_ERROR) {
207         parseerror(parser, "lex error");
208         return false;
209     }
210     return true;
211 }
212
213 #define parser_tokval(p) ((p)->lex->tok.value)
214 #define parser_token(p)  (&((p)->lex->tok))
215 #define parser_ctx(p)    ((p)->lex->tok.ctx)
216
217 static ast_value* parser_const_float(parser_t *parser, double d)
218 {
219     size_t i;
220     ast_value *out;
221     for (i = 0; i < vec_size(parser->imm_float); ++i) {
222         const double compare = parser->imm_float[i]->constval.vfloat;
223         if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
224             return parser->imm_float[i];
225     }
226     out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
227     out->cvq      = CV_CONST;
228     out->hasvalue = true;
229     out->constval.vfloat = d;
230     vec_push(parser->imm_float, out);
231     return out;
232 }
233
234 static ast_value* parser_const_float_0(parser_t *parser)
235 {
236     if (!parser->imm_float_zero)
237         parser->imm_float_zero = parser_const_float(parser, 0);
238     return parser->imm_float_zero;
239 }
240
241 static ast_value* parser_const_float_1(parser_t *parser)
242 {
243     if (!parser->imm_float_one)
244         parser->imm_float_one = parser_const_float(parser, 1);
245     return parser->imm_float_one;
246 }
247
248 static char *parser_strdup(const char *str)
249 {
250     if (str && !*str) {
251         /* actually dup empty strings */
252         char *out = mem_a(1);
253         *out = 0;
254         return out;
255     }
256     return util_strdup(str);
257 }
258
259 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
260 {
261     size_t i;
262     ast_value *out;
263     for (i = 0; i < vec_size(parser->imm_string); ++i) {
264         if (!strcmp(parser->imm_string[i]->constval.vstring, str))
265             return parser->imm_string[i];
266     }
267     if (dotranslate) {
268         char name[32];
269         snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
270         out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
271     } else
272         out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
273     out->cvq      = CV_CONST;
274     out->hasvalue = true;
275     out->constval.vstring = parser_strdup(str);
276     vec_push(parser->imm_string, out);
277     return out;
278 }
279
280 static ast_value* parser_const_vector(parser_t *parser, vector v)
281 {
282     size_t i;
283     ast_value *out;
284     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
285         if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
286             return parser->imm_vector[i];
287     }
288     out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
289     out->cvq      = CV_CONST;
290     out->hasvalue = true;
291     out->constval.vvec = v;
292     vec_push(parser->imm_vector, out);
293     return out;
294 }
295
296 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
297 {
298     vector v;
299     v.x = x;
300     v.y = y;
301     v.z = z;
302     return parser_const_vector(parser, v);
303 }
304
305 static ast_value* parser_const_vector_0(parser_t *parser)
306 {
307     if (!parser->imm_vector_zero)
308         parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
309     return parser->imm_vector_zero;
310 }
311
312 static ast_expression* parser_find_field(parser_t *parser, const char *name)
313 {
314     return util_htget(parser->htfields, name);
315 }
316
317 static ast_expression* parser_find_global(parser_t *parser, const char *name)
318 {
319     return util_htget(parser->htglobals, name);
320 }
321
322 static ast_expression* parser_find_param(parser_t *parser, const char *name)
323 {
324     size_t i;
325     ast_value *fun;
326     if (!parser->function)
327         return NULL;
328     fun = parser->function->vtype;
329     for (i = 0; i < vec_size(fun->expression.params); ++i) {
330         if (!strcmp(fun->expression.params[i]->name, name))
331             return (ast_expression*)(fun->expression.params[i]);
332     }
333     return NULL;
334 }
335
336 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
337 {
338     size_t          i, hash;
339     ast_expression *e;
340
341     hash = util_hthash(parser->htglobals, name);
342
343     *isparam = false;
344     for (i = vec_size(parser->variables); i > upto;) {
345         --i;
346         if ( (e = util_htgeth(parser->variables[i], name, hash)) )
347             return e;
348     }
349     *isparam = true;
350     return parser_find_param(parser, name);
351 }
352
353 static ast_expression* parser_find_var(parser_t *parser, const char *name)
354 {
355     bool dummy;
356     ast_expression *v;
357     v         = parser_find_local(parser, name, 0, &dummy);
358     if (!v) v = parser_find_global(parser, name);
359     return v;
360 }
361
362 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
363 {
364     size_t     i, hash;
365     ast_value *e;
366     hash = util_hthash(parser->typedefs[0], name);
367
368     for (i = vec_size(parser->typedefs); i > upto;) {
369         --i;
370         if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
371             return e;
372     }
373     return NULL;
374 }
375
376 typedef struct
377 {
378     size_t etype; /* 0 = expression, others are operators */
379     int             paren;
380     size_t          off;
381     ast_expression *out;
382     ast_block      *block; /* for commas and function calls */
383     lex_ctx ctx;
384 } sy_elem;
385 typedef struct
386 {
387     sy_elem *out;
388     sy_elem *ops;
389 } shunt;
390
391 #define SY_PAREN_EXPR '('
392 #define SY_PAREN_FUNC 'f'
393 #define SY_PAREN_INDEX '['
394 #define SY_PAREN_TERNARY '?'
395
396 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
397     sy_elem e;
398     e.etype = 0;
399     e.off   = 0;
400     e.out   = v;
401     e.block = NULL;
402     e.ctx   = ctx;
403     e.paren = 0;
404     return e;
405 }
406
407 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
408     sy_elem e;
409     e.etype = 0;
410     e.off   = 0;
411     e.out   = (ast_expression*)v;
412     e.block = v;
413     e.ctx   = ctx;
414     e.paren = 0;
415     return e;
416 }
417
418 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
419     sy_elem e;
420     e.etype = 1 + (op - operators);
421     e.off   = 0;
422     e.out   = NULL;
423     e.block = NULL;
424     e.ctx   = ctx;
425     e.paren = 0;
426     return e;
427 }
428
429 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
430     sy_elem e;
431     e.etype = 0;
432     e.off   = off;
433     e.out   = NULL;
434     e.block = NULL;
435     e.ctx   = ctx;
436     e.paren = p;
437     return e;
438 }
439
440 #ifdef DEBUGSHUNT
441 # define DEBUGSHUNTDO(x) x
442 #else
443 # define DEBUGSHUNTDO(x)
444 #endif
445
446 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
447  * so we need to rotate it to become ent.(foo[n]).
448  */
449 static bool rotate_entfield_array_index_nodes(ast_expression **out)
450 {
451     ast_array_index *index;
452     ast_entfield    *entfield;
453
454     ast_value       *field;
455     ast_expression  *sub;
456     ast_expression  *entity;
457
458     lex_ctx ctx = ast_ctx(*out);
459
460     if (!ast_istype(*out, ast_array_index))
461         return false;
462     index = (ast_array_index*)*out;
463
464     if (!ast_istype(index->array, ast_entfield))
465         return false;
466     entfield = (ast_entfield*)index->array;
467
468     if (!ast_istype(entfield->field, ast_value))
469         return false;
470     field = (ast_value*)entfield->field;
471
472     sub    = index->index;
473     entity = entfield->entity;
474
475     ast_delete(index);
476
477     index = ast_array_index_new(ctx, (ast_expression*)field, sub);
478     entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
479     *out = (ast_expression*)entfield;
480
481     return true;
482 }
483
484 static bool parser_sy_pop(parser_t *parser, shunt *sy)
485 {
486     const oper_info *op;
487     lex_ctx ctx;
488     ast_expression *out = NULL;
489     ast_expression *exprs[3];
490     ast_block      *blocks[3];
491     ast_value      *asvalue[3];
492     ast_binstore   *asbinstore;
493     size_t i, assignop, addop, subop;
494     qcint  generated_op = 0;
495
496     char ty1[1024];
497     char ty2[1024];
498
499     if (!vec_size(sy->ops)) {
500         parseerror(parser, "internal error: missing operator");
501         return false;
502     }
503
504     if (vec_last(sy->ops).paren) {
505         parseerror(parser, "unmatched parenthesis");
506         return false;
507     }
508
509     op = &operators[vec_last(sy->ops).etype - 1];
510     ctx = vec_last(sy->ops).ctx;
511
512     DEBUGSHUNTDO(con_out("apply %s\n", op->op));
513
514     if (vec_size(sy->out) < op->operands) {
515         parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
516                    op->op, (int)op->id);
517         return false;
518     }
519
520     vec_shrinkby(sy->ops, 1);
521
522     /* op(:?) has no input and no output */
523     if (!op->operands)
524         return true;
525
526     vec_shrinkby(sy->out, op->operands);
527     for (i = 0; i < op->operands; ++i) {
528         exprs[i]  = sy->out[vec_size(sy->out)+i].out;
529         blocks[i] = sy->out[vec_size(sy->out)+i].block;
530         asvalue[i] = (ast_value*)exprs[i];
531     }
532
533     if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
534         parseerror(parser, "internal error: operator cannot be applied on empty blocks");
535         return false;
536     }
537
538 #define NotSameType(T) \
539              (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
540               exprs[0]->expression.vtype != T)
541 #define CanConstFold1(A) \
542              (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST))
543 #define CanConstFold(A, B) \
544              (CanConstFold1(A) && CanConstFold1(B))
545 #define ConstV(i) (asvalue[(i)]->constval.vvec)
546 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
547 #define ConstS(i) (asvalue[(i)]->constval.vstring)
548     switch (op->id)
549     {
550         default:
551             parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
552             return false;
553
554         case opid1('.'):
555             if (exprs[0]->expression.vtype == TYPE_ENTITY) {
556                 if (exprs[1]->expression.vtype != TYPE_FIELD) {
557                     parseerror(parser, "type error: right hand of member-operand should be an entity-field");
558                     return false;
559                 }
560                 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
561             }
562             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
563                 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
564                 return false;
565             }
566             else {
567                 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
568                 return false;
569             }
570             break;
571
572         case opid1('['):
573             if (exprs[0]->expression.vtype != TYPE_ARRAY &&
574                 !(exprs[0]->expression.vtype == TYPE_FIELD &&
575                   exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
576             {
577                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
578                 parseerror(parser, "cannot index value of type %s", ty1);
579                 return false;
580             }
581             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
582                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
583                 parseerror(parser, "index must be of type float, not %s", ty1);
584                 return false;
585             }
586             out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
587             if (rotate_entfield_array_index_nodes(&out))
588             {
589 #if 0
590                 /* This is not broken in fteqcc anymore */
591                 if (opts_standard != COMPILER_GMQCC) {
592                     /* this error doesn't need to make us bail out */
593                     (void)!parsewarning(parser, WARN_EXTENSIONS,
594                                         "accessing array-field members of an entity without parenthesis\n"
595                                         " -> this is an extension from -std=gmqcc");
596                 }
597 #endif
598             }
599             break;
600
601         case opid1(','):
602             if (blocks[0]) {
603                 ast_block_add_expr(blocks[0], exprs[1]);
604             } else {
605                 blocks[0] = ast_block_new(ctx);
606                 ast_block_add_expr(blocks[0], exprs[0]);
607                 ast_block_add_expr(blocks[0], exprs[1]);
608             }
609             if (!ast_block_set_type(blocks[0], exprs[1]))
610                 return false;
611
612             vec_push(sy->out, syblock(ctx, blocks[0]));
613             return true;
614
615         case opid2('+','P'):
616             out = exprs[0];
617             break;
618         case opid2('-','P'):
619             switch (exprs[0]->expression.vtype) {
620                 case TYPE_FLOAT:
621                     if (CanConstFold1(exprs[0]))
622                         out = (ast_expression*)parser_const_float(parser, -ConstF(0));
623                     else
624                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
625                                                               (ast_expression*)parser_const_float_0(parser),
626                                                               exprs[0]);
627                     break;
628                 case TYPE_VECTOR:
629                     if (CanConstFold1(exprs[0]))
630                         out = (ast_expression*)parser_const_vector_f(parser,
631                             -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
632                     else
633                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
634                                                               (ast_expression*)parser_const_vector_0(parser),
635                                                               exprs[0]);
636                     break;
637                 default:
638                 parseerror(parser, "invalid types used in expression: cannot negate type %s",
639                            type_name[exprs[0]->expression.vtype]);
640                 return false;
641             }
642             break;
643
644         case opid2('!','P'):
645             switch (exprs[0]->expression.vtype) {
646                 case TYPE_FLOAT:
647                     if (CanConstFold1(exprs[0]))
648                         out = (ast_expression*)parser_const_float(parser, !ConstF(0));
649                     else
650                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
651                     break;
652                 case TYPE_VECTOR:
653                     if (CanConstFold1(exprs[0]))
654                         out = (ast_expression*)parser_const_float(parser,
655                             (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
656                     else
657                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
658                     break;
659                 case TYPE_STRING:
660                     if (CanConstFold1(exprs[0]))
661                         out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
662                     else
663                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
664                     break;
665                 /* we don't constant-fold NOT for these types */
666                 case TYPE_ENTITY:
667                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
668                     break;
669                 case TYPE_FUNCTION:
670                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
671                     break;
672                 default:
673                 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
674                            type_name[exprs[0]->expression.vtype]);
675                 return false;
676             }
677             break;
678
679         case opid1('+'):
680             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
681                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
682             {
683                 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
684                            type_name[exprs[0]->expression.vtype],
685                            type_name[exprs[1]->expression.vtype]);
686                 return false;
687             }
688             switch (exprs[0]->expression.vtype) {
689                 case TYPE_FLOAT:
690                     if (CanConstFold(exprs[0], exprs[1]))
691                     {
692                         out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
693                     }
694                     else
695                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
696                     break;
697                 case TYPE_VECTOR:
698                     if (CanConstFold(exprs[0], exprs[1]))
699                         out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
700                     else
701                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
702                     break;
703                 default:
704                     parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
705                                type_name[exprs[0]->expression.vtype],
706                                type_name[exprs[1]->expression.vtype]);
707                     return false;
708             };
709             break;
710         case opid1('-'):
711             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
712                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
713             {
714                 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
715                            type_name[exprs[1]->expression.vtype],
716                            type_name[exprs[0]->expression.vtype]);
717                 return false;
718             }
719             switch (exprs[0]->expression.vtype) {
720                 case TYPE_FLOAT:
721                     if (CanConstFold(exprs[0], exprs[1]))
722                         out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
723                     else
724                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
725                     break;
726                 case TYPE_VECTOR:
727                     if (CanConstFold(exprs[0], exprs[1]))
728                         out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
729                     else
730                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
731                     break;
732                 default:
733                     parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
734                                type_name[exprs[1]->expression.vtype],
735                                type_name[exprs[0]->expression.vtype]);
736                     return false;
737             };
738             break;
739         case opid1('*'):
740             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
741                 exprs[0]->expression.vtype != TYPE_VECTOR &&
742                 exprs[0]->expression.vtype != TYPE_FLOAT &&
743                 exprs[1]->expression.vtype != TYPE_VECTOR &&
744                 exprs[1]->expression.vtype != TYPE_FLOAT)
745             {
746                 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
747                            type_name[exprs[1]->expression.vtype],
748                            type_name[exprs[0]->expression.vtype]);
749                 return false;
750             }
751             switch (exprs[0]->expression.vtype) {
752                 case TYPE_FLOAT:
753                     if (exprs[1]->expression.vtype == TYPE_VECTOR)
754                     {
755                         if (CanConstFold(exprs[0], exprs[1]))
756                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
757                         else
758                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
759                     }
760                     else
761                     {
762                         if (CanConstFold(exprs[0], exprs[1]))
763                             out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
764                         else
765                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
766                     }
767                     break;
768                 case TYPE_VECTOR:
769                     if (exprs[1]->expression.vtype == TYPE_FLOAT)
770                     {
771                         if (CanConstFold(exprs[0], exprs[1]))
772                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
773                         else
774                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
775                     }
776                     else
777                     {
778                         if (CanConstFold(exprs[0], exprs[1]))
779                             out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
780                         else
781                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
782                     }
783                     break;
784                 default:
785                     parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
786                                type_name[exprs[1]->expression.vtype],
787                                type_name[exprs[0]->expression.vtype]);
788                     return false;
789             };
790             break;
791         case opid1('/'):
792             if (NotSameType(TYPE_FLOAT)) {
793                 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
794                            type_name[exprs[0]->expression.vtype],
795                            type_name[exprs[1]->expression.vtype]);
796                 return false;
797             }
798             if (CanConstFold(exprs[0], exprs[1]))
799                 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
800             else
801                 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
802             break;
803         case opid1('%'):
804         case opid2('%','='):
805             parseerror(parser, "qc does not have a modulo operator");
806             return false;
807         case opid1('|'):
808         case opid1('&'):
809             if (NotSameType(TYPE_FLOAT)) {
810                 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
811                            type_name[exprs[0]->expression.vtype],
812                            type_name[exprs[1]->expression.vtype]);
813                 return false;
814             }
815             if (CanConstFold(exprs[0], exprs[1]))
816                 out = (ast_expression*)parser_const_float(parser,
817                     (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
818                                             (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
819             else
820                 out = (ast_expression*)ast_binary_new(ctx,
821                     (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
822                     exprs[0], exprs[1]);
823             break;
824         case opid1('^'):
825             parseerror(parser, "TODO: bitxor");
826             return false;
827
828         case opid2('<','<'):
829         case opid2('>','>'):
830         case opid3('<','<','='):
831         case opid3('>','>','='):
832             parseerror(parser, "TODO: shifts");
833             return false;
834
835         case opid2('|','|'):
836             generated_op += 1; /* INSTR_OR */
837         case opid2('&','&'):
838             generated_op += INSTR_AND;
839 #if 0
840             if (NotSameType(TYPE_FLOAT)) {
841                 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
842                            type_name[exprs[0]->expression.vtype],
843                            type_name[exprs[1]->expression.vtype]);
844                 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
845                 parseerror(parser, "TODO: optional early out");
846                 return false;
847             }
848 #endif
849             if (opts_standard == COMPILER_GMQCC)
850                 con_out("TODO: early out logic\n");
851             if (CanConstFold(exprs[0], exprs[1]))
852                 out = (ast_expression*)parser_const_float(parser,
853                     (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
854             else
855                 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
856             break;
857
858         case opid2('?',':'):
859             if (vec_last(parser->pot) != POT_TERNARY2) {
860                 parseerror(parser, "mismatched parenthesis/ternary");
861                 return false;
862             }
863             vec_pop(parser->pot);
864             if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
865                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
866                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
867                 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
868                 return false;
869             }
870             if (CanConstFold1(exprs[0]))
871                 out = (ConstF(0) ? exprs[1] : exprs[2]);
872             else
873                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
874             break;
875
876         case opid1('>'):
877             generated_op += 1; /* INSTR_GT */
878         case opid1('<'):
879             generated_op += 1; /* INSTR_LT */
880         case opid2('>', '='):
881             generated_op += 1; /* INSTR_GE */
882         case opid2('<', '='):
883             generated_op += INSTR_LE;
884             if (NotSameType(TYPE_FLOAT)) {
885                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
886                            type_name[exprs[0]->expression.vtype],
887                            type_name[exprs[1]->expression.vtype]);
888                 return false;
889             }
890             out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
891             break;
892         case opid2('!', '='):
893             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
894                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
895                            type_name[exprs[0]->expression.vtype],
896                            type_name[exprs[1]->expression.vtype]);
897                 return false;
898             }
899             out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
900             break;
901         case opid2('=', '='):
902             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
903                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
904                            type_name[exprs[0]->expression.vtype],
905                            type_name[exprs[1]->expression.vtype]);
906                 return false;
907             }
908             out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
909             break;
910
911         case opid1('='):
912             if (ast_istype(exprs[0], ast_entfield)) {
913                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
914                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
915                     exprs[0]->expression.vtype == TYPE_FIELD &&
916                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
917                 {
918                     assignop = type_storep_instr[TYPE_VECTOR];
919                 }
920                 else
921                     assignop = type_storep_instr[exprs[0]->expression.vtype];
922                 if (!ast_compare_type(field->expression.next, exprs[1])) {
923                     ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
924                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
925                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
926                         field->expression.next->expression.vtype == TYPE_FUNCTION &&
927                         exprs[1]->expression.vtype == TYPE_FUNCTION)
928                     {
929                         if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
930                                          "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
931                         {
932                             parser->errors++;
933                         }
934                     }
935                     else
936                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
937                 }
938             }
939             else
940             {
941                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
942                     exprs[0]->expression.vtype == TYPE_FIELD &&
943                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
944                 {
945                     assignop = type_store_instr[TYPE_VECTOR];
946                 }
947                 else {
948                     assignop = type_store_instr[exprs[0]->expression.vtype];
949                 }
950
951                 if (assignop == AINSTR_END) {
952                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
953                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
954                     parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
955                 }
956                 else if (!ast_compare_type(exprs[0], exprs[1])) {
957                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
958                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
959                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
960                         exprs[0]->expression.vtype == TYPE_FUNCTION &&
961                         exprs[1]->expression.vtype == TYPE_FUNCTION)
962                     {
963                         if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
964                                          "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
965                         {
966                             parser->errors++;
967                         }
968                     }
969                     else
970                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
971                 }
972             }
973             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
974                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
975             }
976             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
977             break;
978         case opid3('+','+','P'):
979         case opid3('-','-','P'):
980             /* prefix ++ */
981             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
982                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
983                 parseerror(parser, "invalid type for prefix increment: %s", ty1);
984                 return false;
985             }
986             if (op->id == opid3('+','+','P'))
987                 addop = INSTR_ADD_F;
988             else
989                 addop = INSTR_SUB_F;
990             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
991                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
992             }
993             if (ast_istype(exprs[0], ast_entfield)) {
994                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
995                                                         exprs[0],
996                                                         (ast_expression*)parser_const_float_1(parser));
997             } else {
998                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
999                                                         exprs[0],
1000                                                         (ast_expression*)parser_const_float_1(parser));
1001             }
1002             break;
1003         case opid3('S','+','+'):
1004         case opid3('S','-','-'):
1005             /* prefix ++ */
1006             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1007                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1008                 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1009                 return false;
1010             }
1011             if (op->id == opid3('S','+','+')) {
1012                 addop = INSTR_ADD_F;
1013                 subop = INSTR_SUB_F;
1014             } else {
1015                 addop = INSTR_SUB_F;
1016                 subop = INSTR_ADD_F;
1017             }
1018             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1019                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1020             }
1021             if (ast_istype(exprs[0], ast_entfield)) {
1022                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1023                                                         exprs[0],
1024                                                         (ast_expression*)parser_const_float_1(parser));
1025             } else {
1026                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1027                                                         exprs[0],
1028                                                         (ast_expression*)parser_const_float_1(parser));
1029             }
1030             if (!out)
1031                 return false;
1032             out = (ast_expression*)ast_binary_new(ctx, subop,
1033                                                   out,
1034                                                   (ast_expression*)parser_const_float_1(parser));
1035             break;
1036         case opid2('+','='):
1037         case opid2('-','='):
1038             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1039                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1040             {
1041                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1042                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1043                 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1044                            ty1, ty2);
1045                 return false;
1046             }
1047             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1048                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1049             }
1050             if (ast_istype(exprs[0], ast_entfield))
1051                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1052             else
1053                 assignop = type_store_instr[exprs[0]->expression.vtype];
1054             switch (exprs[0]->expression.vtype) {
1055                 case TYPE_FLOAT:
1056                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1057                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1058                                                             exprs[0], exprs[1]);
1059                     break;
1060                 case TYPE_VECTOR:
1061                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1062                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1063                                                             exprs[0], exprs[1]);
1064                     break;
1065                 default:
1066                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1067                                type_name[exprs[0]->expression.vtype],
1068                                type_name[exprs[1]->expression.vtype]);
1069                     return false;
1070             };
1071             break;
1072         case opid2('*','='):
1073         case opid2('/','='):
1074             if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1075                 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1076                   exprs[0]->expression.vtype == TYPE_VECTOR))
1077             {
1078                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1079                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1080                 parseerror(parser, "invalid types used in expression: %s and %s",
1081                            ty1, ty2);
1082                 return false;
1083             }
1084             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1085                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1086             }
1087             if (ast_istype(exprs[0], ast_entfield))
1088                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1089             else
1090                 assignop = type_store_instr[exprs[0]->expression.vtype];
1091             switch (exprs[0]->expression.vtype) {
1092                 case TYPE_FLOAT:
1093                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1094                                                             (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1095                                                             exprs[0], exprs[1]);
1096                     break;
1097                 case TYPE_VECTOR:
1098                     if (op->id == opid2('*','=')) {
1099                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1100                                                                 exprs[0], exprs[1]);
1101                     } else {
1102                         /* there's no DIV_VF */
1103                         out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1104                                                               (ast_expression*)parser_const_float_1(parser),
1105                                                               exprs[1]);
1106                         if (!out)
1107                             return false;
1108                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1109                                                                 exprs[0], out);
1110                     }
1111                     break;
1112                 default:
1113                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1114                                type_name[exprs[0]->expression.vtype],
1115                                type_name[exprs[1]->expression.vtype]);
1116                     return false;
1117             };
1118             break;
1119         case opid2('&','='):
1120         case opid2('|','='):
1121             if (NotSameType(TYPE_FLOAT)) {
1122                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1123                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1124                 parseerror(parser, "invalid types used in expression: %s and %s",
1125                            ty1, ty2);
1126                 return false;
1127             }
1128             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1129                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1130             }
1131             if (ast_istype(exprs[0], ast_entfield))
1132                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1133             else
1134                 assignop = type_store_instr[exprs[0]->expression.vtype];
1135             out = (ast_expression*)ast_binstore_new(ctx, assignop,
1136                                                     (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1137                                                     exprs[0], exprs[1]);
1138             break;
1139         case opid3('&','~','='):
1140             /* This is like: a &= ~(b);
1141              * But QC has no bitwise-not, so we implement it as
1142              * a -= a & (b);
1143              */
1144             if (NotSameType(TYPE_FLOAT)) {
1145                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1146                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1147                 parseerror(parser, "invalid types used in expression: %s and %s",
1148                            ty1, ty2);
1149                 return false;
1150             }
1151             if (ast_istype(exprs[0], ast_entfield))
1152                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1153             else
1154                 assignop = type_store_instr[exprs[0]->expression.vtype];
1155             out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1156             if (!out)
1157                 return false;
1158             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1159                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1160             }
1161             asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1162             asbinstore->keep_dest = true;
1163             out = (ast_expression*)asbinstore;
1164             break;
1165     }
1166 #undef NotSameType
1167
1168     if (!out) {
1169         parseerror(parser, "failed to apply operand %s", op->op);
1170         return false;
1171     }
1172
1173     DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1174     vec_push(sy->out, syexp(ctx, out));
1175     return true;
1176 }
1177
1178 static bool parser_close_call(parser_t *parser, shunt *sy)
1179 {
1180     /* was a function call */
1181     ast_expression *fun;
1182     ast_call       *call;
1183
1184     size_t          fid;
1185     size_t          paramcount;
1186
1187     vec_shrinkby(sy->ops, 1);
1188     fid = sy->ops[vec_size(sy->ops)].off;
1189
1190     /* out[fid] is the function
1191      * everything above is parameters...
1192      * 0 params = nothing
1193      * 1 params = ast_expression
1194      * more = ast_block
1195      */
1196
1197     if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1198         parseerror(parser, "internal error: function call needs function and parameter list...");
1199         return false;
1200     }
1201
1202     fun = sy->out[fid].out;
1203
1204     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1205     if (!call) {
1206         parseerror(parser, "out of memory");
1207         return false;
1208     }
1209
1210     if (fid+1 == vec_size(sy->out)) {
1211         /* no arguments */
1212         paramcount = 0;
1213     } else if (fid+2 == vec_size(sy->out)) {
1214         ast_block *params;
1215         vec_shrinkby(sy->out, 1);
1216         params = sy->out[vec_size(sy->out)].block;
1217         if (!params) {
1218             /* 1 param */
1219             paramcount = 1;
1220             vec_push(call->params, sy->out[vec_size(sy->out)].out);
1221         } else {
1222             paramcount = vec_size(params->exprs);
1223             call->params = params->exprs;
1224             params->exprs = NULL;
1225             ast_delete(params);
1226         }
1227         if (!ast_call_check_types(call))
1228             parser->errors++;
1229     } else {
1230         parseerror(parser, "invalid function call");
1231         return false;
1232     }
1233
1234     /* overwrite fid, the function, with a call */
1235     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1236
1237     if (fun->expression.vtype != TYPE_FUNCTION) {
1238         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1239         return false;
1240     }
1241
1242     if (!fun->expression.next) {
1243         parseerror(parser, "could not determine function return type");
1244         return false;
1245     } else {
1246         if (vec_size(fun->expression.params) != paramcount &&
1247             !(fun->expression.variadic &&
1248               vec_size(fun->expression.params) < paramcount))
1249         {
1250             ast_value *fval;
1251             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1252
1253             fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1254             if (opts_standard == COMPILER_GMQCC)
1255             {
1256                 if (fval)
1257                     parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1258                                " -> `%s` has been declared here: %s:%i",
1259                                fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1260                                fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1261                 else
1262                     parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1263                                " -> `%s` has been declared here: %s:%i",
1264                                fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1265                                fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1266                 return false;
1267             }
1268             else
1269             {
1270                 if (fval)
1271                     return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1272                                          "too %s parameters for call to %s: expected %i, got %i\n"
1273                                          " -> `%s` has been declared here: %s:%i",
1274                                          fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1275                                          fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1276                 else
1277                     return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1278                                          "too %s parameters for function call: expected %i, got %i\n"
1279                                          " -> `%s` has been declared here: %s:%i",
1280                                          fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1281                                          fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1282             }
1283         }
1284     }
1285
1286     return true;
1287 }
1288
1289 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1290 {
1291     if (!vec_size(sy->ops)) {
1292         parseerror(parser, "unmatched closing paren");
1293         return false;
1294     }
1295     /* this would for bit a + (x) because there are no operators inside (x)
1296     if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1297         parseerror(parser, "empty parenthesis expression");
1298         return false;
1299     }
1300     */
1301     while (vec_size(sy->ops)) {
1302         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1303             if (!parser_close_call(parser, sy))
1304                 return false;
1305             break;
1306         }
1307         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1308             vec_shrinkby(sy->ops, 1);
1309             return !functions_only;
1310         }
1311         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1312             if (functions_only)
1313                 return false;
1314             /* pop off the parenthesis */
1315             vec_shrinkby(sy->ops, 1);
1316             /* then apply the index operator */
1317             if (!parser_sy_pop(parser, sy))
1318                 return false;
1319             return true;
1320         }
1321         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1322             if (functions_only)
1323                 return false;
1324             if (vec_last(parser->pot) != POT_TERNARY1) {
1325                 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1326                 return false;
1327             }
1328             vec_last(parser->pot) = POT_TERNARY2;
1329             /* pop off the parenthesis */
1330             vec_shrinkby(sy->ops, 1);
1331             return true;
1332         }
1333         if (!parser_sy_pop(parser, sy))
1334             return false;
1335     }
1336     return true;
1337 }
1338
1339 static void parser_reclassify_token(parser_t *parser)
1340 {
1341     size_t i;
1342     for (i = 0; i < operator_count; ++i) {
1343         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1344             parser->tok = TOKEN_OPERATOR;
1345             return;
1346         }
1347     }
1348 }
1349
1350 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1351 {
1352     ast_expression *expr = NULL;
1353     shunt sy;
1354     bool wantop = false;
1355     bool gotmemberof = false;
1356
1357     /* count the parens because an if starts with one, so the
1358      * end of a condition is an unmatched closing paren
1359      */
1360     int parens = 0;
1361     int ternaries = 0;
1362
1363     sy.out = NULL;
1364     sy.ops = NULL;
1365
1366     parser->lex->flags.noops = false;
1367
1368     parser_reclassify_token(parser);
1369
1370     while (true)
1371     {
1372         if (gotmemberof)
1373             gotmemberof = false;
1374         else
1375             parser->memberof = 0;
1376
1377         if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1378             parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1379         {
1380             /* a translatable string */
1381             ast_value *val;
1382
1383             if (wantop) {
1384                 parseerror(parser, "expected operator or end of statement, got constant");
1385                 goto onerr;
1386             }
1387
1388             parser->lex->flags.noops = true;
1389             if (!parser_next(parser) || parser->tok != '(') {
1390                 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1391                 goto onerr;
1392             }
1393             parser->lex->flags.noops = false;
1394             if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1395                 parseerror(parser, "expected a constant string in translatable-string extension");
1396                 goto onerr;
1397             }
1398             val = parser_const_string(parser, parser_tokval(parser), true);
1399             wantop = true;
1400             if (!val)
1401                 return false;
1402             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1403             DEBUGSHUNTDO(con_out("push string\n"));
1404
1405             if (!parser_next(parser) || parser->tok != ')') {
1406                 parseerror(parser, "expected closing paren after translatable string");
1407                 goto onerr;
1408             }
1409         }
1410         else if (parser->tok == TOKEN_IDENT)
1411         {
1412             ast_expression *var;
1413             if (wantop) {
1414                 parseerror(parser, "expected operator or end of statement");
1415                 goto onerr;
1416             }
1417             wantop = true;
1418             /* variable */
1419             if (opts_standard == COMPILER_GMQCC)
1420             {
1421                 if (parser->memberof == TYPE_ENTITY) {
1422                     /* still get vars first since there could be a fieldpointer */
1423                     var = parser_find_var(parser, parser_tokval(parser));
1424                     if (!var)
1425                         var = parser_find_field(parser, parser_tokval(parser));
1426                 }
1427                 else if (parser->memberof == TYPE_VECTOR)
1428                 {
1429                     parseerror(parser, "TODO: implement effective vector member access");
1430                     goto onerr;
1431                 }
1432                 else if (parser->memberof) {
1433                     parseerror(parser, "namespace for member not found");
1434                     goto onerr;
1435                 }
1436                 else
1437                     var = parser_find_var(parser, parser_tokval(parser));
1438             } else {
1439                 var = parser_find_var(parser, parser_tokval(parser));
1440                 if (!var)
1441                     var = parser_find_field(parser, parser_tokval(parser));
1442             }
1443             if (!var) {
1444                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1445                 goto onerr;
1446             }
1447             if (ast_istype(var, ast_value)) {
1448                 ((ast_value*)var)->uses++;
1449             }
1450             else if (ast_istype(var, ast_member)) {
1451                 ast_member *mem = (ast_member*)var;
1452                 if (ast_istype(mem->owner, ast_value))
1453                     ((ast_value*)(mem->owner))->uses++;
1454             }
1455             vec_push(sy.out, syexp(parser_ctx(parser), var));
1456             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1457         }
1458         else if (parser->tok == TOKEN_FLOATCONST) {
1459             ast_value *val;
1460             if (wantop) {
1461                 parseerror(parser, "expected operator or end of statement, got constant");
1462                 goto onerr;
1463             }
1464             wantop = true;
1465             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1466             if (!val)
1467                 return false;
1468             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1469             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1470         }
1471         else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1472             ast_value *val;
1473             if (wantop) {
1474                 parseerror(parser, "expected operator or end of statement, got constant");
1475                 goto onerr;
1476             }
1477             wantop = true;
1478             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1479             if (!val)
1480                 return false;
1481             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1482             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1483         }
1484         else if (parser->tok == TOKEN_STRINGCONST) {
1485             ast_value *val;
1486             if (wantop) {
1487                 parseerror(parser, "expected operator or end of statement, got constant");
1488                 goto onerr;
1489             }
1490             wantop = true;
1491             val = parser_const_string(parser, parser_tokval(parser), false);
1492             if (!val)
1493                 return false;
1494             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1495             DEBUGSHUNTDO(con_out("push string\n"));
1496         }
1497         else if (parser->tok == TOKEN_VECTORCONST) {
1498             ast_value *val;
1499             if (wantop) {
1500                 parseerror(parser, "expected operator or end of statement, got constant");
1501                 goto onerr;
1502             }
1503             wantop = true;
1504             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1505             if (!val)
1506                 return false;
1507             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1508             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1509                                 parser_token(parser)->constval.v.x,
1510                                 parser_token(parser)->constval.v.y,
1511                                 parser_token(parser)->constval.v.z));
1512         }
1513         else if (parser->tok == '(') {
1514             parseerror(parser, "internal error: '(' should be classified as operator");
1515             goto onerr;
1516         }
1517         else if (parser->tok == '[') {
1518             parseerror(parser, "internal error: '[' should be classified as operator");
1519             goto onerr;
1520         }
1521         else if (parser->tok == ')') {
1522             if (wantop) {
1523                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1524                 --parens;
1525                 if (parens < 0)
1526                     break;
1527                 /* we do expect an operator next */
1528                 /* closing an opening paren */
1529                 if (!parser_close_paren(parser, &sy, false))
1530                     goto onerr;
1531                 if (vec_last(parser->pot) != POT_PAREN) {
1532                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1533                     goto onerr;
1534                 }
1535                 vec_pop(parser->pot);
1536             } else {
1537                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1538                 --parens;
1539                 if (parens < 0)
1540                     break;
1541                 /* allowed for function calls */
1542                 if (!parser_close_paren(parser, &sy, true))
1543                     goto onerr;
1544                 if (vec_last(parser->pot) != POT_PAREN) {
1545                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1546                     goto onerr;
1547                 }
1548                 vec_pop(parser->pot);
1549             }
1550             wantop = true;
1551         }
1552         else if (parser->tok == ']') {
1553             if (!wantop)
1554                 parseerror(parser, "operand expected");
1555             --parens;
1556             if (parens < 0)
1557                 break;
1558             if (!parser_close_paren(parser, &sy, false))
1559                 goto onerr;
1560             if (vec_last(parser->pot) != POT_PAREN) {
1561                 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1562                 goto onerr;
1563             }
1564             vec_pop(parser->pot);
1565             wantop = true;
1566         }
1567         else if (parser->tok != TOKEN_OPERATOR) {
1568             if (wantop) {
1569                 parseerror(parser, "expected operator or end of statement");
1570                 goto onerr;
1571             }
1572             break;
1573         }
1574         else
1575         {
1576             /* classify the operator */
1577             const oper_info *op;
1578             const oper_info *olast = NULL;
1579             size_t o;
1580             for (o = 0; o < operator_count; ++o) {
1581                 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1582                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1583                     !strcmp(parser_tokval(parser), operators[o].op))
1584                 {
1585                     break;
1586                 }
1587             }
1588             if (o == operator_count) {
1589                 /* no operator found... must be the end of the statement */
1590                 break;
1591             }
1592             /* found an operator */
1593             op = &operators[o];
1594
1595             /* when declaring variables, a comma starts a new variable */
1596             if (op->id == opid1(',') && !parens && stopatcomma) {
1597                 /* fixup the token */
1598                 parser->tok = ',';
1599                 break;
1600             }
1601
1602             /* a colon without a pervious question mark cannot be a ternary */
1603             if (!ternaries && op->id == opid2(':','?')) {
1604                 parser->tok = ':';
1605                 break;
1606             }
1607
1608             if (op->id == opid1(',')) {
1609                 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1610                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1611                 }
1612             }
1613
1614             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1615                 olast = &operators[vec_last(sy.ops).etype-1];
1616
1617             while (olast && (
1618                     (op->prec < olast->prec) ||
1619                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1620             {
1621                 if (!parser_sy_pop(parser, &sy))
1622                     goto onerr;
1623                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1624                     olast = &operators[vec_last(sy.ops).etype-1];
1625                 else
1626                     olast = NULL;
1627             }
1628
1629             if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1630                 /* for gmqcc standard: open up the namespace of the previous type */
1631                 ast_expression *prevex = vec_last(sy.out).out;
1632                 if (!prevex) {
1633                     parseerror(parser, "unexpected member operator");
1634                     goto onerr;
1635                 }
1636                 if (prevex->expression.vtype == TYPE_ENTITY)
1637                     parser->memberof = TYPE_ENTITY;
1638                 else if (prevex->expression.vtype == TYPE_VECTOR)
1639                     parser->memberof = TYPE_VECTOR;
1640                 else {
1641                     parseerror(parser, "type error: type has no members");
1642                     goto onerr;
1643                 }
1644                 gotmemberof = true;
1645             }
1646
1647             if (op->id == opid1('(')) {
1648                 if (wantop) {
1649                     size_t sycount = vec_size(sy.out);
1650                     DEBUGSHUNTDO(con_out("push [op] (\n"));
1651                     ++parens; vec_push(parser->pot, POT_PAREN);
1652                     /* we expected an operator, this is the function-call operator */
1653                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1654                 } else {
1655                     ++parens; vec_push(parser->pot, POT_PAREN);
1656                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1657                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
1658                 }
1659                 wantop = false;
1660             } else if (op->id == opid1('[')) {
1661                 if (!wantop) {
1662                     parseerror(parser, "unexpected array subscript");
1663                     goto onerr;
1664                 }
1665                 ++parens; vec_push(parser->pot, POT_PAREN);
1666                 /* push both the operator and the paren, this makes life easier */
1667                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1668                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1669                 wantop = false;
1670             } else if (op->id == opid2('?',':')) {
1671                 wantop = false;
1672                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1673                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1674                 wantop = false;
1675                 ++ternaries;
1676                 vec_push(parser->pot, POT_TERNARY1);
1677             } else if (op->id == opid2(':','?')) {
1678                 if (!vec_size(parser->pot)) {
1679                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1680                     goto onerr;
1681                 }
1682                 if (vec_last(parser->pot) != POT_TERNARY1) {
1683                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1684                     goto onerr;
1685                 }
1686                 if (!parser_close_paren(parser, &sy, false))
1687                     goto onerr;
1688                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1689                 wantop = false;
1690                 --ternaries;
1691             } else {
1692                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1693                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1694                 wantop = !!(op->flags & OP_SUFFIX);
1695             }
1696         }
1697         if (!parser_next(parser)) {
1698             goto onerr;
1699         }
1700         if (parser->tok == ';' ||
1701             (!parens && parser->tok == ']'))
1702         {
1703             break;
1704         }
1705     }
1706
1707     while (vec_size(sy.ops)) {
1708         if (!parser_sy_pop(parser, &sy))
1709             goto onerr;
1710     }
1711
1712     parser->lex->flags.noops = true;
1713     if (!vec_size(sy.out)) {
1714         parseerror(parser, "empty expression");
1715         expr = NULL;
1716     } else
1717         expr = sy.out[0].out;
1718     vec_free(sy.out);
1719     vec_free(sy.ops);
1720     DEBUGSHUNTDO(con_out("shunt done\n"));
1721     if (vec_size(parser->pot)) {
1722         parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1723         return NULL;
1724     }
1725     vec_free(parser->pot);
1726     return expr;
1727
1728 onerr:
1729     parser->lex->flags.noops = true;
1730     vec_free(sy.out);
1731     vec_free(sy.ops);
1732     return NULL;
1733 }
1734
1735 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1736 {
1737     ast_expression *e = parse_expression_leave(parser, stopatcomma);
1738     if (!e)
1739         return NULL;
1740     if (!parser_next(parser)) {
1741         ast_delete(e);
1742         return NULL;
1743     }
1744     return e;
1745 }
1746
1747 static void parser_enterblock(parser_t *parser)
1748 {
1749     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1750     vec_push(parser->_blocklocals, vec_size(parser->_locals));
1751     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1752     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1753     vec_push(parser->_block_ctx, parser_ctx(parser));
1754 }
1755
1756 static bool parser_leaveblock(parser_t *parser)
1757 {
1758     bool   rv = true;
1759     size_t locals, typedefs;
1760
1761     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1762         parseerror(parser, "internal error: parser_leaveblock with no block");
1763         return false;
1764     }
1765
1766     util_htdel(vec_last(parser->variables));
1767     vec_pop(parser->variables);
1768     if (!vec_size(parser->_blocklocals)) {
1769         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1770         return false;
1771     }
1772
1773     locals = vec_last(parser->_blocklocals);
1774     vec_pop(parser->_blocklocals);
1775     while (vec_size(parser->_locals) != locals) {
1776         ast_expression *e = vec_last(parser->_locals);
1777         ast_value      *v = (ast_value*)e;
1778         vec_pop(parser->_locals);
1779         if (ast_istype(e, ast_value) && !v->uses) {
1780             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1781                 parser->errors++;
1782                 rv = false;
1783             }
1784         }
1785     }
1786
1787     typedefs = vec_last(parser->_blocktypedefs);
1788     while (vec_size(parser->_typedefs) != typedefs) {
1789         ast_delete(vec_last(parser->_typedefs));
1790         vec_pop(parser->_typedefs);
1791     }
1792     util_htdel(vec_last(parser->typedefs));
1793     vec_pop(parser->typedefs);
1794
1795     vec_pop(parser->_block_ctx);
1796     return rv;
1797 }
1798
1799 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1800 {
1801     vec_push(parser->_locals, e);
1802     util_htset(vec_last(parser->variables), name, (void*)e);
1803 }
1804
1805 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1806 {
1807     ast_ifthen *ifthen;
1808     ast_expression *cond, *ontrue, *onfalse = NULL;
1809     bool ifnot = false;
1810
1811     lex_ctx ctx = parser_ctx(parser);
1812
1813     (void)block; /* not touching */
1814
1815     /* skip the 'if', parse an optional 'not' and check for an opening paren */
1816     if (!parser_next(parser)) {
1817         parseerror(parser, "expected condition or 'not'");
1818         return false;
1819     }
1820     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1821         ifnot = true;
1822         if (!parser_next(parser)) {
1823             parseerror(parser, "expected condition in parenthesis");
1824             return false;
1825         }
1826     }
1827     if (parser->tok != '(') {
1828         parseerror(parser, "expected 'if' condition in parenthesis");
1829         return false;
1830     }
1831     /* parse into the expression */
1832     if (!parser_next(parser)) {
1833         parseerror(parser, "expected 'if' condition after opening paren");
1834         return false;
1835     }
1836     /* parse the condition */
1837     cond = parse_expression_leave(parser, false);
1838     if (!cond)
1839         return false;
1840     /* closing paren */
1841     if (parser->tok != ')') {
1842         parseerror(parser, "expected closing paren after 'if' condition");
1843         ast_delete(cond);
1844         return false;
1845     }
1846     /* parse into the 'then' branch */
1847     if (!parser_next(parser)) {
1848         parseerror(parser, "expected statement for on-true branch of 'if'");
1849         ast_delete(cond);
1850         return false;
1851     }
1852     if (!parse_statement_or_block(parser, &ontrue)) {
1853         ast_delete(cond);
1854         return false;
1855     }
1856     /* check for an else */
1857     if (!strcmp(parser_tokval(parser), "else")) {
1858         /* parse into the 'else' branch */
1859         if (!parser_next(parser)) {
1860             parseerror(parser, "expected on-false branch after 'else'");
1861             ast_delete(ontrue);
1862             ast_delete(cond);
1863             return false;
1864         }
1865         if (!parse_statement_or_block(parser, &onfalse)) {
1866             ast_delete(ontrue);
1867             ast_delete(cond);
1868             return false;
1869         }
1870     }
1871
1872     if (ifnot)
1873         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1874     else
1875         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1876     *out = (ast_expression*)ifthen;
1877     return true;
1878 }
1879
1880 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1881 {
1882     ast_loop *aloop;
1883     ast_expression *cond, *ontrue;
1884
1885     lex_ctx ctx = parser_ctx(parser);
1886
1887     (void)block; /* not touching */
1888
1889     /* skip the 'while' and check for opening paren */
1890     if (!parser_next(parser) || parser->tok != '(') {
1891         parseerror(parser, "expected 'while' condition in parenthesis");
1892         return false;
1893     }
1894     /* parse into the expression */
1895     if (!parser_next(parser)) {
1896         parseerror(parser, "expected 'while' condition after opening paren");
1897         return false;
1898     }
1899     /* parse the condition */
1900     cond = parse_expression_leave(parser, false);
1901     if (!cond)
1902         return false;
1903     /* closing paren */
1904     if (parser->tok != ')') {
1905         parseerror(parser, "expected closing paren after 'while' condition");
1906         ast_delete(cond);
1907         return false;
1908     }
1909     /* parse into the 'then' branch */
1910     if (!parser_next(parser)) {
1911         parseerror(parser, "expected while-loop body");
1912         ast_delete(cond);
1913         return false;
1914     }
1915     if (!parse_statement_or_block(parser, &ontrue)) {
1916         ast_delete(cond);
1917         return false;
1918     }
1919
1920     aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1921     *out = (ast_expression*)aloop;
1922     return true;
1923 }
1924
1925 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1926 {
1927     ast_loop *aloop;
1928     ast_expression *cond, *ontrue;
1929
1930     lex_ctx ctx = parser_ctx(parser);
1931
1932     (void)block; /* not touching */
1933
1934     /* skip the 'do' and get the body */
1935     if (!parser_next(parser)) {
1936         parseerror(parser, "expected loop body");
1937         return false;
1938     }
1939     if (!parse_statement_or_block(parser, &ontrue))
1940         return false;
1941
1942     /* expect the "while" */
1943     if (parser->tok != TOKEN_KEYWORD ||
1944         strcmp(parser_tokval(parser), "while"))
1945     {
1946         parseerror(parser, "expected 'while' and condition");
1947         ast_delete(ontrue);
1948         return false;
1949     }
1950
1951     /* skip the 'while' and check for opening paren */
1952     if (!parser_next(parser) || parser->tok != '(') {
1953         parseerror(parser, "expected 'while' condition in parenthesis");
1954         ast_delete(ontrue);
1955         return false;
1956     }
1957     /* parse into the expression */
1958     if (!parser_next(parser)) {
1959         parseerror(parser, "expected 'while' condition after opening paren");
1960         ast_delete(ontrue);
1961         return false;
1962     }
1963     /* parse the condition */
1964     cond = parse_expression_leave(parser, false);
1965     if (!cond)
1966         return false;
1967     /* closing paren */
1968     if (parser->tok != ')') {
1969         parseerror(parser, "expected closing paren after 'while' condition");
1970         ast_delete(ontrue);
1971         ast_delete(cond);
1972         return false;
1973     }
1974     /* parse on */
1975     if (!parser_next(parser) || parser->tok != ';') {
1976         parseerror(parser, "expected semicolon after condition");
1977         ast_delete(ontrue);
1978         ast_delete(cond);
1979         return false;
1980     }
1981
1982     if (!parser_next(parser)) {
1983         parseerror(parser, "parse error");
1984         ast_delete(ontrue);
1985         ast_delete(cond);
1986         return false;
1987     }
1988
1989     aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1990     *out = (ast_expression*)aloop;
1991     return true;
1992 }
1993
1994 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1995 {
1996     ast_loop       *aloop;
1997     ast_expression *initexpr, *cond, *increment, *ontrue;
1998     ast_value      *typevar;
1999     bool   retval = true;
2000
2001     lex_ctx ctx = parser_ctx(parser);
2002
2003     parser_enterblock(parser);
2004
2005     initexpr  = NULL;
2006     cond      = NULL;
2007     increment = NULL;
2008     ontrue    = NULL;
2009
2010     /* skip the 'while' and check for opening paren */
2011     if (!parser_next(parser) || parser->tok != '(') {
2012         parseerror(parser, "expected 'for' expressions in parenthesis");
2013         goto onerr;
2014     }
2015     /* parse into the expression */
2016     if (!parser_next(parser)) {
2017         parseerror(parser, "expected 'for' initializer after opening paren");
2018         goto onerr;
2019     }
2020
2021     typevar = NULL;
2022     if (parser->tok == TOKEN_IDENT)
2023         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2024
2025     if (typevar || parser->tok == TOKEN_TYPENAME) {
2026         if (opts_standard != COMPILER_GMQCC) {
2027             if (parsewarning(parser, WARN_EXTENSIONS,
2028                              "current standard does not allow variable declarations in for-loop initializers"))
2029                 goto onerr;
2030         }
2031         if (!parse_variable(parser, block, true, CV_VAR, typevar))
2032             goto onerr;
2033     }
2034     else if (parser->tok != ';')
2035     {
2036         initexpr = parse_expression_leave(parser, false);
2037         if (!initexpr)
2038             goto onerr;
2039     }
2040
2041     /* move on to condition */
2042     if (parser->tok != ';') {
2043         parseerror(parser, "expected semicolon after for-loop initializer");
2044         goto onerr;
2045     }
2046     if (!parser_next(parser)) {
2047         parseerror(parser, "expected for-loop condition");
2048         goto onerr;
2049     }
2050
2051     /* parse the condition */
2052     if (parser->tok != ';') {
2053         cond = parse_expression_leave(parser, false);
2054         if (!cond)
2055             goto onerr;
2056     }
2057
2058     /* move on to incrementor */
2059     if (parser->tok != ';') {
2060         parseerror(parser, "expected semicolon after for-loop initializer");
2061         goto onerr;
2062     }
2063     if (!parser_next(parser)) {
2064         parseerror(parser, "expected for-loop condition");
2065         goto onerr;
2066     }
2067
2068     /* parse the incrementor */
2069     if (parser->tok != ')') {
2070         increment = parse_expression_leave(parser, false);
2071         if (!increment)
2072             goto onerr;
2073         if (!ast_side_effects(increment)) {
2074             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2075                 goto onerr;
2076         }
2077     }
2078
2079     /* closing paren */
2080     if (parser->tok != ')') {
2081         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2082         goto onerr;
2083     }
2084     /* parse into the 'then' branch */
2085     if (!parser_next(parser)) {
2086         parseerror(parser, "expected for-loop body");
2087         goto onerr;
2088     }
2089     if (!parse_statement_or_block(parser, &ontrue))
2090         goto onerr;
2091
2092     aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
2093     *out = (ast_expression*)aloop;
2094
2095     if (!parser_leaveblock(parser))
2096         retval = false;
2097     return retval;
2098 onerr:
2099     if (initexpr)  ast_delete(initexpr);
2100     if (cond)      ast_delete(cond);
2101     if (increment) ast_delete(increment);
2102     (void)!parser_leaveblock(parser);
2103     return false;
2104 }
2105
2106 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2107 {
2108     ast_expression *exp = NULL;
2109     ast_return     *ret = NULL;
2110     ast_value      *expected = parser->function->vtype;
2111
2112     lex_ctx ctx = parser_ctx(parser);
2113
2114     (void)block; /* not touching */
2115
2116     if (!parser_next(parser)) {
2117         parseerror(parser, "expected return expression");
2118         return false;
2119     }
2120
2121     if (parser->tok != ';') {
2122         exp = parse_expression(parser, false);
2123         if (!exp)
2124             return false;
2125
2126         if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2127             parseerror(parser, "return with invalid expression");
2128         }
2129
2130         ret = ast_return_new(exp->expression.node.context, exp);
2131         if (!ret) {
2132             ast_delete(exp);
2133             return false;
2134         }
2135     } else {
2136         if (!parser_next(parser))
2137             parseerror(parser, "parse error");
2138         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2139             if (opts_standard != COMPILER_GMQCC)
2140                 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2141             else
2142                 parseerror(parser, "return without value");
2143         }
2144         ret = ast_return_new(ctx, NULL);
2145     }
2146     *out = (ast_expression*)ret;
2147     return true;
2148 }
2149
2150 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2151 {
2152     lex_ctx ctx = parser_ctx(parser);
2153
2154     (void)block; /* not touching */
2155
2156     if (!parser_next(parser) || parser->tok != ';') {
2157         parseerror(parser, "expected semicolon");
2158         return false;
2159     }
2160
2161     if (!parser_next(parser))
2162         parseerror(parser, "parse error");
2163
2164     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2165     return true;
2166 }
2167
2168 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2169 {
2170     ast_expression *operand;
2171     ast_value      *opval;
2172     ast_value      *typevar;
2173     ast_switch     *switchnode;
2174     ast_switch_case swcase;
2175
2176     lex_ctx ctx = parser_ctx(parser);
2177
2178     (void)block; /* not touching */
2179     (void)opval;
2180
2181     /* parse over the opening paren */
2182     if (!parser_next(parser) || parser->tok != '(') {
2183         parseerror(parser, "expected switch operand in parenthesis");
2184         return false;
2185     }
2186
2187     /* parse into the expression */
2188     if (!parser_next(parser)) {
2189         parseerror(parser, "expected switch operand");
2190         return false;
2191     }
2192     /* parse the operand */
2193     operand = parse_expression_leave(parser, false);
2194     if (!operand)
2195         return false;
2196
2197     switchnode = ast_switch_new(ctx, operand);
2198
2199     /* closing paren */
2200     if (parser->tok != ')') {
2201         ast_delete(switchnode);
2202         parseerror(parser, "expected closing paren after 'switch' operand");
2203         return false;
2204     }
2205
2206     /* parse over the opening paren */
2207     if (!parser_next(parser) || parser->tok != '{') {
2208         ast_delete(switchnode);
2209         parseerror(parser, "expected list of cases");
2210         return false;
2211     }
2212
2213     if (!parser_next(parser)) {
2214         ast_delete(switchnode);
2215         parseerror(parser, "expected 'case' or 'default'");
2216         return false;
2217     }
2218
2219     /* new block; allow some variables to be declared here */
2220     parser_enterblock(parser);
2221     while (true) {
2222         typevar = NULL;
2223         if (parser->tok == TOKEN_IDENT)
2224             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2225         if (typevar || parser->tok == TOKEN_TYPENAME) {
2226             if (!parse_variable(parser, block, false, CV_NONE, typevar)) {
2227                 ast_delete(switchnode);
2228                 return false;
2229             }
2230             continue;
2231         }
2232         if (!strcmp(parser_tokval(parser), "var") ||
2233             !strcmp(parser_tokval(parser), "local"))
2234         {
2235             if (!parser_next(parser)) {
2236                 parseerror(parser, "expected variable declaration");
2237                 ast_delete(switchnode);
2238                 return false;
2239             }
2240             if (!parse_variable(parser, block, false, CV_VAR, NULL)) {
2241                 ast_delete(switchnode);
2242                 return false;
2243             }
2244             continue;
2245         }
2246         if (!strcmp(parser_tokval(parser), "const")) {
2247             if (!parser_next(parser)) {
2248                 parseerror(parser, "expected variable declaration");
2249                 ast_delete(switchnode);
2250                 return false;
2251             }
2252             if (!strcmp(parser_tokval(parser), "var")) {
2253                 if (!parser_next(parser)) {
2254                     parseerror(parser, "expected variable declaration");
2255                     ast_delete(switchnode);
2256                     return false;
2257                 }
2258             }
2259             if (!parse_variable(parser, block, false, CV_CONST, NULL)) {
2260                 ast_delete(switchnode);
2261                 return false;
2262             }
2263             continue;
2264         }
2265         break;
2266     }
2267
2268     /* case list! */
2269     while (parser->tok != '}') {
2270         ast_block *caseblock;
2271
2272         if (parser->tok != TOKEN_KEYWORD) {
2273             ast_delete(switchnode);
2274             parseerror(parser, "expected 'case' or 'default'");
2275             return false;
2276         }
2277         if (!strcmp(parser_tokval(parser), "case")) {
2278             if (!parser_next(parser)) {
2279                 ast_delete(switchnode);
2280                 parseerror(parser, "expected expression for case");
2281                 return false;
2282             }
2283             swcase.value = parse_expression_leave(parser, false);
2284             if (!swcase.value) {
2285                 ast_delete(switchnode);
2286                 parseerror(parser, "expected expression for case");
2287                 return false;
2288             }
2289             if (!OPTS_FLAG(RELAXED_SWITCH)) {
2290                 opval = (ast_value*)swcase.value;
2291                 if (!ast_istype(swcase.value, ast_value)) { /* || opval->cvq != CV_CONST) { */
2292                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2293                     ast_unref(operand);
2294                     return false;
2295                 }
2296             }
2297         }
2298         else if (!strcmp(parser_tokval(parser), "default")) {
2299             swcase.value = NULL;
2300             if (!parser_next(parser)) {
2301                 ast_delete(switchnode);
2302                 parseerror(parser, "expected colon");
2303                 return false;
2304             }
2305         }
2306
2307         /* Now the colon and body */
2308         if (parser->tok != ':') {
2309             if (swcase.value) ast_unref(swcase.value);
2310             ast_delete(switchnode);
2311             parseerror(parser, "expected colon");
2312             return false;
2313         }
2314
2315         if (!parser_next(parser)) {
2316             if (swcase.value) ast_unref(swcase.value);
2317             ast_delete(switchnode);
2318             parseerror(parser, "expected statements or case");
2319             return false;
2320         }
2321         caseblock = ast_block_new(parser_ctx(parser));
2322         if (!caseblock) {
2323             if (swcase.value) ast_unref(swcase.value);
2324             ast_delete(switchnode);
2325             return false;
2326         }
2327         swcase.code = (ast_expression*)caseblock;
2328         vec_push(switchnode->cases, swcase);
2329         while (true) {
2330             ast_expression *expr;
2331             if (parser->tok == '}')
2332                 break;
2333             if (parser->tok == TOKEN_KEYWORD) {
2334                 if (!strcmp(parser_tokval(parser), "case") ||
2335                     !strcmp(parser_tokval(parser), "default"))
2336                 {
2337                     break;
2338                 }
2339             }
2340             if (!parse_statement(parser, caseblock, &expr, true)) {
2341                 ast_delete(switchnode);
2342                 return false;
2343             }
2344             if (!expr)
2345                 continue;
2346             ast_block_add_expr(caseblock, expr);
2347         }
2348     }
2349
2350     parser_leaveblock(parser);
2351
2352     /* closing paren */
2353     if (parser->tok != '}') {
2354         ast_delete(switchnode);
2355         parseerror(parser, "expected closing paren of case list");
2356         return false;
2357     }
2358     if (!parser_next(parser)) {
2359         ast_delete(switchnode);
2360         parseerror(parser, "parse error after switch");
2361         return false;
2362     }
2363     *out = (ast_expression*)switchnode;
2364     return true;
2365 }
2366
2367 static bool parse_goto(parser_t *parser, ast_expression **out)
2368 {
2369     size_t    i;
2370     ast_goto *gt;
2371
2372     if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2373         parseerror(parser, "expected label name after `goto`");
2374         return false;
2375     }
2376
2377     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2378
2379     for (i = 0; i < vec_size(parser->labels); ++i) {
2380         if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2381             ast_goto_set_label(gt, parser->labels[i]);
2382             break;
2383         }
2384     }
2385     if (i == vec_size(parser->labels))
2386         vec_push(parser->gotos, gt);
2387
2388     if (!parser_next(parser) || parser->tok != ';') {
2389         parseerror(parser, "semicolon expected after goto label");
2390         return false;
2391     }
2392     if (!parser_next(parser)) {
2393         parseerror(parser, "parse error after goto");
2394         return false;
2395     }
2396
2397     *out = (ast_expression*)gt;
2398     return true;
2399 }
2400
2401 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2402 {
2403     int cvq;
2404     ast_value *typevar = NULL;
2405     *out = NULL;
2406
2407     if (parser->tok == TOKEN_IDENT)
2408         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2409
2410     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2411     {
2412         /* local variable */
2413         if (!block) {
2414             parseerror(parser, "cannot declare a variable from here");
2415             return false;
2416         }
2417         if (opts_standard == COMPILER_QCC) {
2418             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2419                 return false;
2420         }
2421         if (!parse_variable(parser, block, false, CV_NONE, typevar))
2422             return false;
2423         *out = NULL;
2424         return true;
2425     }
2426     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
2427     {
2428         goto ident_var;
2429     }
2430     else if (parser->tok == TOKEN_KEYWORD)
2431     {
2432         if (!strcmp(parser_tokval(parser), "local") ||
2433             !strcmp(parser_tokval(parser), "const") ||
2434             !strcmp(parser_tokval(parser), "var"))
2435         {
2436 ident_var:
2437             if (parser_tokval(parser)[0] == 'c')
2438                 cvq = CV_CONST;
2439             else if (parser_tokval(parser)[0] == 'v')
2440                 cvq = CV_VAR;
2441             else
2442                 cvq = CV_NONE;
2443
2444             if (!block) {
2445                 parseerror(parser, "cannot declare a local variable here");
2446                 return false;
2447             }
2448             if (!parser_next(parser)) {
2449                 parseerror(parser, "expected variable declaration");
2450                 return false;
2451             }
2452             if (!parse_variable(parser, block, true, cvq, NULL))
2453                 return false;
2454             *out = NULL;
2455             return true;
2456         }
2457         else if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2458         {
2459             char ty[1024];
2460             ast_value *tdef;
2461
2462             if (!parser_next(parser)) {
2463                 parseerror(parser, "parse error after __builtin_debug_printtype");
2464                 return false;
2465             }
2466
2467             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2468             {
2469                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2470                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2471                 if (!parser_next(parser)) {
2472                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2473                     return false;
2474                 }
2475             }
2476             else
2477             {
2478                 if (!parse_statement(parser, block, out, allow_cases))
2479                     return false;
2480                 if (!*out)
2481                     con_out("__builtin_debug_printtype: got no output node\n");
2482                 else
2483                 {
2484                     ast_type_to_string(*out, ty, sizeof(ty));
2485                     con_out("__builtin_debug_printtype: `%s`\n", ty);
2486                 }
2487             }
2488             return true;
2489         }
2490         else if (!strcmp(parser_tokval(parser), "return"))
2491         {
2492             return parse_return(parser, block, out);
2493         }
2494         else if (!strcmp(parser_tokval(parser), "if"))
2495         {
2496             return parse_if(parser, block, out);
2497         }
2498         else if (!strcmp(parser_tokval(parser), "while"))
2499         {
2500             return parse_while(parser, block, out);
2501         }
2502         else if (!strcmp(parser_tokval(parser), "do"))
2503         {
2504             return parse_dowhile(parser, block, out);
2505         }
2506         else if (!strcmp(parser_tokval(parser), "for"))
2507         {
2508             if (opts_standard == COMPILER_QCC) {
2509                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2510                     return false;
2511             }
2512             return parse_for(parser, block, out);
2513         }
2514         else if (!strcmp(parser_tokval(parser), "break"))
2515         {
2516             return parse_break_continue(parser, block, out, false);
2517         }
2518         else if (!strcmp(parser_tokval(parser), "continue"))
2519         {
2520             return parse_break_continue(parser, block, out, true);
2521         }
2522         else if (!strcmp(parser_tokval(parser), "switch"))
2523         {
2524             return parse_switch(parser, block, out);
2525         }
2526         else if (!strcmp(parser_tokval(parser), "case") ||
2527                  !strcmp(parser_tokval(parser), "default"))
2528         {
2529             if (!allow_cases) {
2530                 parseerror(parser, "unexpected 'case' label");
2531                 return false;
2532             }
2533             return true;
2534         }
2535         else if (!strcmp(parser_tokval(parser), "goto"))
2536         {
2537             return parse_goto(parser, out);
2538         }
2539         else if (!strcmp(parser_tokval(parser), "typedef"))
2540         {
2541             if (!parser_next(parser)) {
2542                 parseerror(parser, "expected type definition after 'typedef'");
2543                 return false;
2544             }
2545             return parse_typedef(parser);
2546         }
2547         parseerror(parser, "Unexpected keyword");
2548         return false;
2549     }
2550     else if (parser->tok == '{')
2551     {
2552         ast_block *inner;
2553         inner = parse_block(parser);
2554         if (!inner)
2555             return false;
2556         *out = (ast_expression*)inner;
2557         return true;
2558     }
2559     else if (parser->tok == ':')
2560     {
2561         size_t i;
2562         ast_label *label;
2563         if (!parser_next(parser)) {
2564             parseerror(parser, "expected label name");
2565             return false;
2566         }
2567         if (parser->tok != TOKEN_IDENT) {
2568             parseerror(parser, "label must be an identifier");
2569             return false;
2570         }
2571         label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2572         if (!label)
2573             return false;
2574         vec_push(parser->labels, label);
2575         *out = (ast_expression*)label;
2576         if (!parser_next(parser)) {
2577             parseerror(parser, "parse error after label");
2578             return false;
2579         }
2580         for (i = 0; i < vec_size(parser->gotos); ++i) {
2581             if (!strcmp(parser->gotos[i]->name, label->name)) {
2582                 ast_goto_set_label(parser->gotos[i], label);
2583                 vec_remove(parser->gotos, i, 1);
2584                 --i;
2585             }
2586         }
2587         return true;
2588     }
2589     else if (parser->tok == ';')
2590     {
2591         if (!parser_next(parser)) {
2592             parseerror(parser, "parse error after empty statement");
2593             return false;
2594         }
2595         return true;
2596     }
2597     else
2598     {
2599         ast_expression *exp = parse_expression(parser, false);
2600         if (!exp)
2601             return false;
2602         *out = exp;
2603         if (!ast_side_effects(exp)) {
2604             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2605                 return false;
2606         }
2607         return true;
2608     }
2609 }
2610
2611 static bool parse_block_into(parser_t *parser, ast_block *block)
2612 {
2613     bool   retval = true;
2614
2615     parser_enterblock(parser);
2616
2617     if (!parser_next(parser)) { /* skip the '{' */
2618         parseerror(parser, "expected function body");
2619         goto cleanup;
2620     }
2621
2622     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2623     {
2624         ast_expression *expr = NULL;
2625         if (parser->tok == '}')
2626             break;
2627
2628         if (!parse_statement(parser, block, &expr, false)) {
2629             /* parseerror(parser, "parse error"); */
2630             block = NULL;
2631             goto cleanup;
2632         }
2633         if (!expr)
2634             continue;
2635         ast_block_add_expr(block, expr);
2636     }
2637
2638     if (parser->tok != '}') {
2639         block = NULL;
2640     } else {
2641         (void)parser_next(parser);
2642     }
2643
2644 cleanup:
2645     if (!parser_leaveblock(parser))
2646         retval = false;
2647     return retval && !!block;
2648 }
2649
2650 static ast_block* parse_block(parser_t *parser)
2651 {
2652     ast_block *block;
2653     block = ast_block_new(parser_ctx(parser));
2654     if (!block)
2655         return NULL;
2656     if (!parse_block_into(parser, block)) {
2657         ast_block_delete(block);
2658         return NULL;
2659     }
2660     return block;
2661 }
2662
2663 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2664 {
2665     if (parser->tok == '{') {
2666         *out = (ast_expression*)parse_block(parser);
2667         return !!*out;
2668     }
2669     return parse_statement(parser, NULL, out, false);
2670 }
2671
2672 static bool create_vector_members(ast_value *var, ast_member **me)
2673 {
2674     size_t i;
2675     size_t len = strlen(var->name);
2676
2677     for (i = 0; i < 3; ++i) {
2678         char *name = mem_a(len+3);
2679         memcpy(name, var->name, len);
2680         name[len+0] = '_';
2681         name[len+1] = 'x'+i;
2682         name[len+2] = 0;
2683         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2684         mem_d(name);
2685         if (!me[i])
2686             break;
2687     }
2688     if (i == 3)
2689         return true;
2690
2691     /* unroll */
2692     do { ast_member_delete(me[--i]); } while(i);
2693     return false;
2694 }
2695
2696 static bool parse_function_body(parser_t *parser, ast_value *var)
2697 {
2698     ast_block      *block = NULL;
2699     ast_function   *func;
2700     ast_function   *old;
2701     size_t          parami;
2702
2703     ast_expression *framenum  = NULL;
2704     ast_expression *nextthink = NULL;
2705     /* None of the following have to be deleted */
2706     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2707     ast_expression *gbl_time = NULL, *gbl_self = NULL;
2708     bool            has_frame_think;
2709
2710     bool retval = true;
2711
2712     has_frame_think = false;
2713     old = parser->function;
2714
2715     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
2716         parseerror(parser, "gotos/labels leaking");
2717         return false;
2718     }
2719
2720     if (var->expression.variadic) {
2721         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2722                          "variadic function with implementation will not be able to access additional parameters"))
2723         {
2724             return false;
2725         }
2726     }
2727
2728     if (parser->tok == '[') {
2729         /* got a frame definition: [ framenum, nextthink ]
2730          * this translates to:
2731          * self.frame = framenum;
2732          * self.nextthink = time + 0.1;
2733          * self.think = nextthink;
2734          */
2735         nextthink = NULL;
2736
2737         fld_think     = parser_find_field(parser, "think");
2738         fld_nextthink = parser_find_field(parser, "nextthink");
2739         fld_frame     = parser_find_field(parser, "frame");
2740         if (!fld_think || !fld_nextthink || !fld_frame) {
2741             parseerror(parser, "cannot use [frame,think] notation without the required fields");
2742             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2743             return false;
2744         }
2745         gbl_time      = parser_find_global(parser, "time");
2746         gbl_self      = parser_find_global(parser, "self");
2747         if (!gbl_time || !gbl_self) {
2748             parseerror(parser, "cannot use [frame,think] notation without the required globals");
2749             parseerror(parser, "please declare the following globals: `time`, `self`");
2750             return false;
2751         }
2752
2753         if (!parser_next(parser))
2754             return false;
2755
2756         framenum = parse_expression_leave(parser, true);
2757         if (!framenum) {
2758             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2759             return false;
2760         }
2761         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
2762             ast_unref(framenum);
2763             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2764             return false;
2765         }
2766
2767         if (parser->tok != ',') {
2768             ast_unref(framenum);
2769             parseerror(parser, "expected comma after frame number in [frame,think] notation");
2770             parseerror(parser, "Got a %i\n", parser->tok);
2771             return false;
2772         }
2773
2774         if (!parser_next(parser)) {
2775             ast_unref(framenum);
2776             return false;
2777         }
2778
2779         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2780         {
2781             /* qc allows the use of not-yet-declared functions here
2782              * - this automatically creates a prototype */
2783             ast_value      *thinkfunc;
2784             ast_expression *functype = fld_think->expression.next;
2785
2786             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2787             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2788                 ast_unref(framenum);
2789                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2790                 return false;
2791             }
2792
2793             if (!parser_next(parser)) {
2794                 ast_unref(framenum);
2795                 ast_delete(thinkfunc);
2796                 return false;
2797             }
2798
2799             vec_push(parser->globals, (ast_expression*)thinkfunc);
2800             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2801             nextthink = (ast_expression*)thinkfunc;
2802
2803         } else {
2804             nextthink = parse_expression_leave(parser, true);
2805             if (!nextthink) {
2806                 ast_unref(framenum);
2807                 parseerror(parser, "expected a think-function in [frame,think] notation");
2808                 return false;
2809             }
2810         }
2811
2812         if (!ast_istype(nextthink, ast_value)) {
2813             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2814             retval = false;
2815         }
2816
2817         if (retval && parser->tok != ']') {
2818             parseerror(parser, "expected closing `]` for [frame,think] notation");
2819             retval = false;
2820         }
2821
2822         if (retval && !parser_next(parser)) {
2823             retval = false;
2824         }
2825
2826         if (retval && parser->tok != '{') {
2827             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2828             retval = false;
2829         }
2830
2831         if (!retval) {
2832             ast_unref(nextthink);
2833             ast_unref(framenum);
2834             return false;
2835         }
2836
2837         has_frame_think = true;
2838     }
2839
2840     block = ast_block_new(parser_ctx(parser));
2841     if (!block) {
2842         parseerror(parser, "failed to allocate block");
2843         if (has_frame_think) {
2844             ast_unref(nextthink);
2845             ast_unref(framenum);
2846         }
2847         return false;
2848     }
2849
2850     if (has_frame_think) {
2851         lex_ctx ctx;
2852         ast_expression *self_frame;
2853         ast_expression *self_nextthink;
2854         ast_expression *self_think;
2855         ast_expression *time_plus_1;
2856         ast_store *store_frame;
2857         ast_store *store_nextthink;
2858         ast_store *store_think;
2859
2860         ctx = parser_ctx(parser);
2861         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2862         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2863         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2864
2865         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2866                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2867
2868         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2869             if (self_frame)     ast_delete(self_frame);
2870             if (self_nextthink) ast_delete(self_nextthink);
2871             if (self_think)     ast_delete(self_think);
2872             if (time_plus_1)    ast_delete(time_plus_1);
2873             retval = false;
2874         }
2875
2876         if (retval)
2877         {
2878             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2879             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2880             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2881
2882             if (!store_frame) {
2883                 ast_delete(self_frame);
2884                 retval = false;
2885             }
2886             if (!store_nextthink) {
2887                 ast_delete(self_nextthink);
2888                 retval = false;
2889             }
2890             if (!store_think) {
2891                 ast_delete(self_think);
2892                 retval = false;
2893             }
2894             if (!retval) {
2895                 if (store_frame)     ast_delete(store_frame);
2896                 if (store_nextthink) ast_delete(store_nextthink);
2897                 if (store_think)     ast_delete(store_think);
2898                 retval = false;
2899             }
2900             ast_block_add_expr(block, (ast_expression*)store_frame);
2901             ast_block_add_expr(block, (ast_expression*)store_nextthink);
2902             ast_block_add_expr(block, (ast_expression*)store_think);
2903         }
2904
2905         if (!retval) {
2906             parseerror(parser, "failed to generate code for [frame,think]");
2907             ast_unref(nextthink);
2908             ast_unref(framenum);
2909             ast_delete(block);
2910             return false;
2911         }
2912     }
2913
2914     parser_enterblock(parser);
2915
2916     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2917         size_t     e;
2918         ast_value *param = var->expression.params[parami];
2919         ast_member *me[3];
2920
2921         if (param->expression.vtype != TYPE_VECTOR &&
2922             (param->expression.vtype != TYPE_FIELD ||
2923              param->expression.next->expression.vtype != TYPE_VECTOR))
2924         {
2925             continue;
2926         }
2927
2928         if (!create_vector_members(param, me)) {
2929             ast_block_delete(block);
2930             return false;
2931         }
2932
2933         for (e = 0; e < 3; ++e) {
2934             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2935             ast_block_collect(block, (ast_expression*)me[e]);
2936         }
2937     }
2938
2939     func = ast_function_new(ast_ctx(var), var->name, var);
2940     if (!func) {
2941         parseerror(parser, "failed to allocate function for `%s`", var->name);
2942         ast_block_delete(block);
2943         goto enderr;
2944     }
2945     vec_push(parser->functions, func);
2946
2947     parser->function = func;
2948     if (!parse_block_into(parser, block)) {
2949         ast_block_delete(block);
2950         goto enderrfn;
2951     }
2952
2953     vec_push(func->blocks, block);
2954
2955     parser->function = old;
2956     if (!parser_leaveblock(parser))
2957         retval = false;
2958     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2959         parseerror(parser, "internal error: local scopes left");
2960         retval = false;
2961     }
2962
2963     if (parser->tok == ';')
2964         return parser_next(parser);
2965     else if (opts_standard == COMPILER_QCC)
2966         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2967     return retval;
2968
2969 enderrfn:
2970     vec_pop(parser->functions);
2971     ast_function_delete(func);
2972     var->constval.vfunc = NULL;
2973
2974 enderr:
2975     (void)!parser_leaveblock(parser);
2976     parser->function = old;
2977     return false;
2978 }
2979
2980 static ast_expression *array_accessor_split(
2981     parser_t  *parser,
2982     ast_value *array,
2983     ast_value *index,
2984     size_t     middle,
2985     ast_expression *left,
2986     ast_expression *right
2987     )
2988 {
2989     ast_ifthen *ifthen;
2990     ast_binary *cmp;
2991
2992     lex_ctx ctx = ast_ctx(array);
2993
2994     if (!left || !right) {
2995         if (left)  ast_delete(left);
2996         if (right) ast_delete(right);
2997         return NULL;
2998     }
2999
3000     cmp = ast_binary_new(ctx, INSTR_LT,
3001                          (ast_expression*)index,
3002                          (ast_expression*)parser_const_float(parser, middle));
3003     if (!cmp) {
3004         ast_delete(left);
3005         ast_delete(right);
3006         parseerror(parser, "internal error: failed to create comparison for array setter");
3007         return NULL;
3008     }
3009
3010     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3011     if (!ifthen) {
3012         ast_delete(cmp); /* will delete left and right */
3013         parseerror(parser, "internal error: failed to create conditional jump for array setter");
3014         return NULL;
3015     }
3016
3017     return (ast_expression*)ifthen;
3018 }
3019
3020 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3021 {
3022     lex_ctx ctx = ast_ctx(array);
3023
3024     if (from+1 == afterend) {
3025         /* set this value */
3026         ast_block       *block;
3027         ast_return      *ret;
3028         ast_array_index *subscript;
3029         ast_store       *st;
3030         int assignop = type_store_instr[value->expression.vtype];
3031
3032         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3033             assignop = INSTR_STORE_V;
3034
3035         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3036         if (!subscript)
3037             return NULL;
3038
3039         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3040         if (!st) {
3041             ast_delete(subscript);
3042             return NULL;
3043         }
3044
3045         block = ast_block_new(ctx);
3046         if (!block) {
3047             ast_delete(st);
3048             return NULL;
3049         }
3050
3051         ast_block_add_expr(block, (ast_expression*)st);
3052
3053         ret = ast_return_new(ctx, NULL);
3054         if (!ret) {
3055             ast_delete(block);
3056             return NULL;
3057         }
3058
3059         ast_block_add_expr(block, (ast_expression*)ret);
3060
3061         return (ast_expression*)block;
3062     } else {
3063         ast_expression *left, *right;
3064         size_t diff = afterend - from;
3065         size_t middle = from + diff/2;
3066         left  = array_setter_node(parser, array, index, value, from, middle);
3067         right = array_setter_node(parser, array, index, value, middle, afterend);
3068         return array_accessor_split(parser, array, index, middle, left, right);
3069     }
3070 }
3071
3072 static ast_expression *array_field_setter_node(
3073     parser_t  *parser,
3074     ast_value *array,
3075     ast_value *entity,
3076     ast_value *index,
3077     ast_value *value,
3078     size_t     from,
3079     size_t     afterend)
3080 {
3081     lex_ctx ctx = ast_ctx(array);
3082
3083     if (from+1 == afterend) {
3084         /* set this value */
3085         ast_block       *block;
3086         ast_return      *ret;
3087         ast_entfield    *entfield;
3088         ast_array_index *subscript;
3089         ast_store       *st;
3090         int assignop = type_storep_instr[value->expression.vtype];
3091
3092         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3093             assignop = INSTR_STOREP_V;
3094
3095         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3096         if (!subscript)
3097             return NULL;
3098
3099         entfield = ast_entfield_new_force(ctx,
3100                                           (ast_expression*)entity,
3101                                           (ast_expression*)subscript,
3102                                           (ast_expression*)subscript);
3103         if (!entfield) {
3104             ast_delete(subscript);
3105             return NULL;
3106         }
3107
3108         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3109         if (!st) {
3110             ast_delete(entfield);
3111             return NULL;
3112         }
3113
3114         block = ast_block_new(ctx);
3115         if (!block) {
3116             ast_delete(st);
3117             return NULL;
3118         }
3119
3120         ast_block_add_expr(block, (ast_expression*)st);
3121
3122         ret = ast_return_new(ctx, NULL);
3123         if (!ret) {
3124             ast_delete(block);
3125             return NULL;
3126         }
3127
3128         ast_block_add_expr(block, (ast_expression*)ret);
3129
3130         return (ast_expression*)block;
3131     } else {
3132         ast_expression *left, *right;
3133         size_t diff = afterend - from;
3134         size_t middle = from + diff/2;
3135         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
3136         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3137         return array_accessor_split(parser, array, index, middle, left, right);
3138     }
3139 }
3140
3141 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3142 {
3143     lex_ctx ctx = ast_ctx(array);
3144
3145     if (from+1 == afterend) {
3146         ast_return      *ret;
3147         ast_array_index *subscript;
3148
3149         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3150         if (!subscript)
3151             return NULL;
3152
3153         ret = ast_return_new(ctx, (ast_expression*)subscript);
3154         if (!ret) {
3155             ast_delete(subscript);
3156             return NULL;
3157         }
3158
3159         return (ast_expression*)ret;
3160     } else {
3161         ast_expression *left, *right;
3162         size_t diff = afterend - from;
3163         size_t middle = from + diff/2;
3164         left  = array_getter_node(parser, array, index, from, middle);
3165         right = array_getter_node(parser, array, index, middle, afterend);
3166         return array_accessor_split(parser, array, index, middle, left, right);
3167     }
3168 }
3169
3170 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3171 {
3172     ast_function   *func = NULL;
3173     ast_value      *fval = NULL;
3174     ast_block      *body = NULL;
3175
3176     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3177     if (!fval) {
3178         parseerror(parser, "failed to create accessor function value");
3179         return false;
3180     }
3181
3182     func = ast_function_new(ast_ctx(array), funcname, fval);
3183     if (!func) {
3184         ast_delete(fval);
3185         parseerror(parser, "failed to create accessor function node");
3186         return false;
3187     }
3188
3189     body = ast_block_new(ast_ctx(array));
3190     if (!body) {
3191         parseerror(parser, "failed to create block for array accessor");
3192         ast_delete(fval);
3193         ast_delete(func);
3194         return false;
3195     }
3196
3197     vec_push(func->blocks, body);
3198     *out = fval;
3199
3200     vec_push(parser->accessors, fval);
3201
3202     return true;
3203 }
3204
3205 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3206 {
3207     ast_expression *root = NULL;
3208     ast_value      *index = NULL;
3209     ast_value      *value = NULL;
3210     ast_function   *func;
3211     ast_value      *fval;
3212
3213     if (!ast_istype(array->expression.next, ast_value)) {
3214         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3215         return false;
3216     }
3217
3218     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3219         return false;
3220     func = fval->constval.vfunc;
3221     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3222
3223     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3224     value = ast_value_copy((ast_value*)array->expression.next);
3225
3226     if (!index || !value) {
3227         parseerror(parser, "failed to create locals for array accessor");
3228         goto cleanup;
3229     }
3230     (void)!ast_value_set_name(value, "value"); /* not important */
3231     vec_push(fval->expression.params, index);
3232     vec_push(fval->expression.params, value);
3233
3234     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3235     if (!root) {
3236         parseerror(parser, "failed to build accessor search tree");
3237         goto cleanup;
3238     }
3239
3240     ast_block_add_expr(func->blocks[0], root);
3241     array->setter = fval;
3242     return true;
3243 cleanup:
3244     if (index) ast_delete(index);
3245     if (value) ast_delete(value);
3246     if (root)  ast_delete(root);
3247     ast_delete(func);
3248     ast_delete(fval);
3249     return false;
3250 }
3251
3252 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3253 {
3254     ast_expression *root = NULL;
3255     ast_value      *entity = NULL;
3256     ast_value      *index = NULL;
3257     ast_value      *value = NULL;
3258     ast_function   *func;
3259     ast_value      *fval;
3260
3261     if (!ast_istype(array->expression.next, ast_value)) {
3262         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3263         return false;
3264     }
3265
3266     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3267         return false;
3268     func = fval->constval.vfunc;
3269     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3270
3271     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3272     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
3273     value  = ast_value_copy((ast_value*)array->expression.next);
3274     if (!entity || !index || !value) {
3275         parseerror(parser, "failed to create locals for array accessor");
3276         goto cleanup;
3277     }
3278     (void)!ast_value_set_name(value, "value"); /* not important */
3279     vec_push(fval->expression.params, entity);
3280     vec_push(fval->expression.params, index);
3281     vec_push(fval->expression.params, value);
3282
3283     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3284     if (!root) {
3285         parseerror(parser, "failed to build accessor search tree");
3286         goto cleanup;
3287     }
3288
3289     ast_block_add_expr(func->blocks[0], root);
3290     array->setter = fval;
3291     return true;
3292 cleanup:
3293     if (entity) ast_delete(entity);
3294     if (index)  ast_delete(index);
3295     if (value)  ast_delete(value);
3296     if (root)   ast_delete(root);
3297     ast_delete(func);
3298     ast_delete(fval);
3299     return false;
3300 }
3301
3302 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3303 {
3304     ast_expression *root = NULL;
3305     ast_value      *index = NULL;
3306     ast_value      *fval;
3307     ast_function   *func;
3308
3309     /* NOTE: checking array->expression.next rather than elemtype since
3310      * for fields elemtype is a temporary fieldtype.
3311      */
3312     if (!ast_istype(array->expression.next, ast_value)) {
3313         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3314         return false;
3315     }
3316
3317     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3318         return false;
3319     func = fval->constval.vfunc;
3320     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3321
3322     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3323
3324     if (!index) {
3325         parseerror(parser, "failed to create locals for array accessor");
3326         goto cleanup;
3327     }
3328     vec_push(fval->expression.params, index);
3329
3330     root = array_getter_node(parser, array, index, 0, array->expression.count);
3331     if (!root) {
3332         parseerror(parser, "failed to build accessor search tree");
3333         goto cleanup;
3334     }
3335
3336     ast_block_add_expr(func->blocks[0], root);
3337     array->getter = fval;
3338     return true;
3339 cleanup:
3340     if (index) ast_delete(index);
3341     if (root)  ast_delete(root);
3342     ast_delete(func);
3343     ast_delete(fval);
3344     return false;
3345 }
3346
3347 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3348 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3349 {
3350     lex_ctx     ctx;
3351     size_t      i;
3352     ast_value **params;
3353     ast_value  *param;
3354     ast_value  *fval;
3355     bool        first = true;
3356     bool        variadic = false;
3357
3358     ctx = parser_ctx(parser);
3359
3360     /* for the sake of less code we parse-in in this function */
3361     if (!parser_next(parser)) {
3362         parseerror(parser, "expected parameter list");
3363         return NULL;
3364     }
3365
3366     params = NULL;
3367
3368     /* parse variables until we hit a closing paren */
3369     while (parser->tok != ')') {
3370         if (!first) {
3371             /* there must be commas between them */
3372             if (parser->tok != ',') {
3373                 parseerror(parser, "expected comma or end of parameter list");
3374                 goto on_error;
3375             }
3376             if (!parser_next(parser)) {
3377                 parseerror(parser, "expected parameter");
3378                 goto on_error;
3379             }
3380         }
3381         first = false;
3382
3383         if (parser->tok == TOKEN_DOTS) {
3384             /* '...' indicates a varargs function */
3385             variadic = true;
3386             if (!parser_next(parser)) {
3387                 parseerror(parser, "expected parameter");
3388                 return NULL;
3389             }
3390             if (parser->tok != ')') {
3391                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3392                 goto on_error;
3393             }
3394         }
3395         else
3396         {
3397             /* for anything else just parse a typename */
3398             param = parse_typename(parser, NULL, NULL);
3399             if (!param)
3400                 goto on_error;
3401             vec_push(params, param);
3402             if (param->expression.vtype >= TYPE_VARIANT) {
3403                 char typename[1024];
3404                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3405                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3406                 goto on_error;
3407             }
3408         }
3409     }
3410
3411     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3412         vec_free(params);
3413
3414     /* sanity check */
3415     if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3416         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3417
3418     /* parse-out */
3419     if (!parser_next(parser)) {
3420         parseerror(parser, "parse error after typename");
3421         goto on_error;
3422     }
3423
3424     /* now turn 'var' into a function type */
3425     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3426     fval->expression.next     = (ast_expression*)var;
3427     fval->expression.variadic = variadic;
3428     var = fval;
3429
3430     var->expression.params = params;
3431     params = NULL;
3432
3433     return var;
3434
3435 on_error:
3436     ast_delete(var);
3437     for (i = 0; i < vec_size(params); ++i)
3438         ast_delete(params[i]);
3439     vec_free(params);
3440     return NULL;
3441 }
3442
3443 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3444 {
3445     ast_expression *cexp;
3446     ast_value      *cval, *tmp;
3447     lex_ctx ctx;
3448
3449     ctx = parser_ctx(parser);
3450
3451     if (!parser_next(parser)) {
3452         ast_delete(var);
3453         parseerror(parser, "expected array-size");
3454         return NULL;
3455     }
3456
3457     cexp = parse_expression_leave(parser, true);
3458
3459     if (!cexp || !ast_istype(cexp, ast_value)) {
3460         if (cexp)
3461             ast_unref(cexp);
3462         ast_delete(var);
3463         parseerror(parser, "expected array-size as constant positive integer");
3464         return NULL;
3465     }
3466     cval = (ast_value*)cexp;
3467
3468     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3469     tmp->expression.next = (ast_expression*)var;
3470     var = tmp;
3471
3472     if (cval->expression.vtype == TYPE_INTEGER)
3473         tmp->expression.count = cval->constval.vint;
3474     else if (cval->expression.vtype == TYPE_FLOAT)
3475         tmp->expression.count = cval->constval.vfloat;
3476     else {
3477         ast_unref(cexp);
3478         ast_delete(var);
3479         parseerror(parser, "array-size must be a positive integer constant");
3480         return NULL;
3481     }
3482     ast_unref(cexp);
3483
3484     if (parser->tok != ']') {
3485         ast_delete(var);
3486         parseerror(parser, "expected ']' after array-size");
3487         return NULL;
3488     }
3489     if (!parser_next(parser)) {
3490         ast_delete(var);
3491         parseerror(parser, "error after parsing array size");
3492         return NULL;
3493     }
3494     return var;
3495 }
3496
3497 /* Parse a complete typename.
3498  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3499  * but when parsing variables separated by comma
3500  * 'storebase' should point to where the base-type should be kept.
3501  * The base type makes up every bit of type information which comes *before* the
3502  * variable name.
3503  *
3504  * The following will be parsed in its entirety:
3505  *     void() foo()
3506  * The 'basetype' in this case is 'void()'
3507  * and if there's a comma after it, say:
3508  *     void() foo(), bar
3509  * then the type-information 'void()' can be stored in 'storebase'
3510  */
3511 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3512 {
3513     ast_value *var, *tmp;
3514     lex_ctx    ctx;
3515
3516     const char *name = NULL;
3517     bool        isfield  = false;
3518     bool        wasarray = false;
3519     size_t      morefields = 0;
3520
3521     ctx = parser_ctx(parser);
3522
3523     /* types may start with a dot */
3524     if (parser->tok == '.') {
3525         isfield = true;
3526         /* if we parsed a dot we need a typename now */
3527         if (!parser_next(parser)) {
3528             parseerror(parser, "expected typename for field definition");
3529             return NULL;
3530         }
3531
3532         /* Further dots are handled seperately because they won't be part of the
3533          * basetype
3534          */
3535         while (parser->tok == '.') {
3536             ++morefields;
3537             if (!parser_next(parser)) {
3538                 parseerror(parser, "expected typename for field definition");
3539                 return NULL;
3540             }
3541         }
3542     }
3543     if (parser->tok == TOKEN_IDENT)
3544         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3545     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3546         parseerror(parser, "expected typename");
3547         return NULL;
3548     }
3549
3550     /* generate the basic type value */
3551     if (cached_typedef) {
3552         var = ast_value_copy(cached_typedef);
3553         ast_value_set_name(var, "<type(from_def)>");
3554     } else
3555         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3556
3557     for (; morefields; --morefields) {
3558         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3559         tmp->expression.next = (ast_expression*)var;
3560         var = tmp;
3561     }
3562
3563     /* do not yet turn into a field - remember:
3564      * .void() foo; is a field too
3565      * .void()() foo; is a function
3566      */
3567
3568     /* parse on */
3569     if (!parser_next(parser)) {
3570         ast_delete(var);
3571         parseerror(parser, "parse error after typename");
3572         return NULL;
3573     }
3574
3575     /* an opening paren now starts the parameter-list of a function
3576      * this is where original-QC has parameter lists.
3577      * We allow a single parameter list here.
3578      * Much like fteqcc we don't allow `float()() x`
3579      */
3580     if (parser->tok == '(') {
3581         var = parse_parameter_list(parser, var);
3582         if (!var)
3583             return NULL;
3584     }
3585
3586     /* store the base if requested */
3587     if (storebase) {
3588         *storebase = ast_value_copy(var);
3589         if (isfield) {
3590             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3591             tmp->expression.next = (ast_expression*)*storebase;
3592             *storebase = tmp;
3593         }
3594     }
3595
3596     /* there may be a name now */
3597     if (parser->tok == TOKEN_IDENT) {
3598         name = util_strdup(parser_tokval(parser));
3599         /* parse on */
3600         if (!parser_next(parser)) {
3601             ast_delete(var);
3602             parseerror(parser, "error after variable or field declaration");
3603             return NULL;
3604         }
3605     }
3606
3607     /* now this may be an array */
3608     if (parser->tok == '[') {
3609         wasarray = true;
3610         var = parse_arraysize(parser, var);
3611         if (!var)
3612             return NULL;
3613     }
3614
3615     /* This is the point where we can turn it into a field */
3616     if (isfield) {
3617         /* turn it into a field if desired */
3618         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3619         tmp->expression.next = (ast_expression*)var;
3620         var = tmp;
3621     }
3622
3623     /* now there may be function parens again */
3624     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3625         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3626     if (parser->tok == '(' && wasarray)
3627         parseerror(parser, "arrays as part of a return type is not supported");
3628     while (parser->tok == '(') {
3629         var = parse_parameter_list(parser, var);
3630         if (!var) {
3631             if (name)
3632                 mem_d((void*)name);
3633             ast_delete(var);
3634             return NULL;
3635         }
3636     }
3637
3638     /* finally name it */
3639     if (name) {
3640         if (!ast_value_set_name(var, name)) {
3641             ast_delete(var);
3642             parseerror(parser, "internal error: failed to set name");
3643             return NULL;
3644         }
3645         /* free the name, ast_value_set_name duplicates */
3646         mem_d((void*)name);
3647     }
3648
3649     return var;
3650 }
3651
3652 static bool parse_typedef(parser_t *parser)
3653 {
3654     ast_value      *typevar, *oldtype;
3655     ast_expression *old;
3656
3657     typevar = parse_typename(parser, NULL, NULL);
3658
3659     if (!typevar)
3660         return false;
3661
3662     if ( (old = parser_find_var(parser, typevar->name)) ) {
3663         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3664                    " -> `%s` has been declared here: %s:%i",
3665                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3666         ast_delete(typevar);
3667         return false;
3668     }
3669
3670     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3671         parseerror(parser, "type `%s` has already been declared here: %s:%i",
3672                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3673         ast_delete(typevar);
3674         return false;
3675     }
3676
3677     vec_push(parser->_typedefs, typevar);
3678     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3679
3680     if (parser->tok != ';') {
3681         parseerror(parser, "expected semicolon after typedef");
3682         return false;
3683     }
3684     if (!parser_next(parser)) {
3685         parseerror(parser, "parse error after typedef");
3686         return false;
3687     }
3688
3689     return true;
3690 }
3691
3692 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef)
3693 {
3694     ast_value *var;
3695     ast_value *proto;
3696     ast_expression *old;
3697     bool       was_end;
3698     size_t     i;
3699
3700     ast_value *basetype = NULL;
3701     bool      retval    = true;
3702     bool      isparam   = false;
3703     bool      isvector  = false;
3704     bool      cleanvar  = true;
3705     bool      wasarray  = false;
3706
3707     ast_member *me[3];
3708
3709     /* get the first complete variable */
3710     var = parse_typename(parser, &basetype, cached_typedef);
3711     if (!var) {
3712         if (basetype)
3713             ast_delete(basetype);
3714         return false;
3715     }
3716
3717     while (true) {
3718         proto = NULL;
3719         wasarray = false;
3720
3721         /* Part 0: finish the type */
3722         if (parser->tok == '(') {
3723             if (opts_standard == COMPILER_QCC)
3724                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3725             var = parse_parameter_list(parser, var);
3726             if (!var) {
3727                 retval = false;
3728                 goto cleanup;
3729             }
3730         }
3731         /* we only allow 1-dimensional arrays */
3732         if (parser->tok == '[') {
3733             wasarray = true;
3734             var = parse_arraysize(parser, var);
3735             if (!var) {
3736                 retval = false;
3737                 goto cleanup;
3738             }
3739         }
3740         if (parser->tok == '(' && wasarray) {
3741             parseerror(parser, "arrays as part of a return type is not supported");
3742             /* we'll still parse the type completely for now */
3743         }
3744         /* for functions returning functions */
3745         while (parser->tok == '(') {
3746             if (opts_standard == COMPILER_QCC)
3747                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3748             var = parse_parameter_list(parser, var);
3749             if (!var) {
3750                 retval = false;
3751                 goto cleanup;
3752             }
3753         }
3754
3755         var->cvq = qualifier;
3756
3757         /* Part 1:
3758          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3759          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3760          * is then filled with the previous definition and the parameter-names replaced.
3761          */
3762         if (!localblock) {
3763             /* Deal with end_sys_ vars */
3764             was_end = false;
3765             if (!strcmp(var->name, "end_sys_globals")) {
3766                 parser->crc_globals = vec_size(parser->globals);
3767                 was_end = true;
3768             }
3769             else if (!strcmp(var->name, "end_sys_fields")) {
3770                 parser->crc_fields = vec_size(parser->fields);
3771                 was_end = true;
3772             }
3773             if (was_end && var->expression.vtype == TYPE_FIELD) {
3774                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3775                                  "global '%s' hint should not be a field",
3776                                  parser_tokval(parser)))
3777                 {
3778                     retval = false;
3779                     goto cleanup;
3780                 }
3781             }
3782
3783             if (!nofields && var->expression.vtype == TYPE_FIELD)
3784             {
3785                 /* deal with field declarations */
3786                 old = parser_find_field(parser, var->name);
3787                 if (old) {
3788                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3789                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3790                     {
3791                         retval = false;
3792                         goto cleanup;
3793                     }
3794                     ast_delete(var);
3795                     var = NULL;
3796                     goto skipvar;
3797                     /*
3798                     parseerror(parser, "field `%s` already declared here: %s:%i",
3799                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3800                     retval = false;
3801                     goto cleanup;
3802                     */
3803                 }
3804                 if (opts_standard == COMPILER_QCC &&
3805                     (old = parser_find_global(parser, var->name)))
3806                 {
3807                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3808                     parseerror(parser, "field `%s` already declared here: %s:%i",
3809                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3810                     retval = false;
3811                     goto cleanup;
3812                 }
3813             }
3814             else
3815             {
3816                 /* deal with other globals */
3817                 old = parser_find_global(parser, var->name);
3818                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3819                 {
3820                     /* This is a function which had a prototype */
3821                     if (!ast_istype(old, ast_value)) {
3822                         parseerror(parser, "internal error: prototype is not an ast_value");
3823                         retval = false;
3824                         goto cleanup;
3825                     }
3826                     proto = (ast_value*)old;
3827                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3828                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3829                                    proto->name,
3830                                    ast_ctx(proto).file, ast_ctx(proto).line);
3831                         retval = false;
3832                         goto cleanup;
3833                     }
3834                     /* we need the new parameter-names */
3835                     for (i = 0; i < vec_size(proto->expression.params); ++i)
3836                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3837                     ast_delete(var);
3838                     var = proto;
3839                 }
3840                 else
3841                 {
3842                     /* other globals */
3843                     if (old) {
3844                         if (opts_standard == COMPILER_GMQCC) {
3845                             parseerror(parser, "global `%s` already declared here: %s:%i",
3846                                        var->name, ast_ctx(old).file, ast_ctx(old).line);
3847                             retval = false;
3848                             goto cleanup;
3849                         } else {
3850                             if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3851                                              "global `%s` already declared here: %s:%i",
3852                                              var->name, ast_ctx(old).file, ast_ctx(old).line))
3853                             {
3854                                 retval = false;
3855                                 goto cleanup;
3856                             }
3857                             proto = (ast_value*)old;
3858                             if (!ast_istype(old, ast_value)) {
3859                                 parseerror(parser, "internal error: not an ast_value");
3860                                 retval = false;
3861                                 proto = NULL;
3862                                 goto cleanup;
3863                             }
3864                             ast_delete(var);
3865                             var = proto;
3866                         }
3867                     }
3868                     if (opts_standard == COMPILER_QCC &&
3869                         (old = parser_find_field(parser, var->name)))
3870                     {
3871                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3872                         parseerror(parser, "global `%s` already declared here: %s:%i",
3873                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3874                         retval = false;
3875                         goto cleanup;
3876                     }
3877                 }
3878             }
3879         }
3880         else /* it's not a global */
3881         {
3882             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3883             if (old && !isparam) {
3884                 parseerror(parser, "local `%s` already declared here: %s:%i",
3885                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3886                 retval = false;
3887                 goto cleanup;
3888             }
3889             old = parser_find_local(parser, var->name, 0, &isparam);
3890             if (old && isparam) {
3891                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3892                                  "local `%s` is shadowing a parameter", var->name))
3893                 {
3894                     parseerror(parser, "local `%s` already declared here: %s:%i",
3895                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3896                     retval = false;
3897                     goto cleanup;
3898                 }
3899                 if (opts_standard != COMPILER_GMQCC) {
3900                     ast_delete(var);
3901                     var = NULL;
3902                     goto skipvar;
3903                 }
3904             }
3905         }
3906
3907         /* Part 2:
3908          * Create the global/local, and deal with vector types.
3909          */
3910         if (!proto) {
3911             if (var->expression.vtype == TYPE_VECTOR)
3912                 isvector = true;
3913             else if (var->expression.vtype == TYPE_FIELD &&
3914                      var->expression.next->expression.vtype == TYPE_VECTOR)
3915                 isvector = true;
3916
3917             if (isvector) {
3918                 if (!create_vector_members(var, me)) {
3919                     retval = false;
3920                     goto cleanup;
3921                 }
3922             }
3923
3924             if (!localblock) {
3925                 /* deal with global variables, fields, functions */
3926                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
3927                     var->isfield = true;
3928                     vec_push(parser->fields, (ast_expression*)var);
3929                     util_htset(parser->htfields, var->name, var);
3930                     if (isvector) {
3931                         for (i = 0; i < 3; ++i) {
3932                             vec_push(parser->fields, (ast_expression*)me[i]);
3933                             util_htset(parser->htfields, me[i]->name, me[i]);
3934                         }
3935                     }
3936                 }
3937                 else {
3938                     vec_push(parser->globals, (ast_expression*)var);
3939                     util_htset(parser->htglobals, var->name, var);
3940                     if (isvector) {
3941                         for (i = 0; i < 3; ++i) {
3942                             vec_push(parser->globals, (ast_expression*)me[i]);
3943                             util_htset(parser->htglobals, me[i]->name, me[i]);
3944                         }
3945                     }
3946                 }
3947             } else {
3948                 vec_push(localblock->locals, var);
3949                 parser_addlocal(parser, var->name, (ast_expression*)var);
3950                 if (isvector) {
3951                     for (i = 0; i < 3; ++i) {
3952                         parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3953                         ast_block_collect(localblock, (ast_expression*)me[i]);
3954                     }
3955                 }
3956             }
3957
3958         }
3959         me[0] = me[1] = me[2] = NULL;
3960         cleanvar = false;
3961         /* Part 2.2
3962          * deal with arrays
3963          */
3964         if (var->expression.vtype == TYPE_ARRAY) {
3965             char name[1024];
3966             snprintf(name, sizeof(name), "%s##SET", var->name);
3967             if (!parser_create_array_setter(parser, var, name))
3968                 goto cleanup;
3969             snprintf(name, sizeof(name), "%s##GET", var->name);
3970             if (!parser_create_array_getter(parser, var, var->expression.next, name))
3971                 goto cleanup;
3972         }
3973         else if (!localblock && !nofields &&
3974                  var->expression.vtype == TYPE_FIELD &&
3975                  var->expression.next->expression.vtype == TYPE_ARRAY)
3976         {
3977             char name[1024];
3978             ast_expression *telem;
3979             ast_value      *tfield;
3980             ast_value      *array = (ast_value*)var->expression.next;
3981
3982             if (!ast_istype(var->expression.next, ast_value)) {
3983                 parseerror(parser, "internal error: field element type must be an ast_value");
3984                 goto cleanup;
3985             }
3986
3987             snprintf(name, sizeof(name), "%s##SETF", var->name);
3988             if (!parser_create_array_field_setter(parser, array, name))
3989                 goto cleanup;
3990
3991             telem = ast_type_copy(ast_ctx(var), array->expression.next);
3992             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3993             tfield->expression.next = telem;
3994             snprintf(name, sizeof(name), "%s##GETFP", var->name);
3995             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3996                 ast_delete(tfield);
3997                 goto cleanup;
3998             }
3999             ast_delete(tfield);
4000         }
4001
4002 skipvar:
4003         if (parser->tok == ';') {
4004             ast_delete(basetype);
4005             if (!parser_next(parser)) {
4006                 parseerror(parser, "error after variable declaration");
4007                 return false;
4008             }
4009             return true;
4010         }
4011
4012         if (parser->tok == ',')
4013             goto another;
4014
4015         /*
4016         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4017         */
4018         if (!var) {
4019             parseerror(parser, "missing comma or semicolon while parsing variables");
4020             break;
4021         }
4022
4023         if (localblock && opts_standard == COMPILER_QCC) {
4024             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4025                              "initializing expression turns variable `%s` into a constant in this standard",
4026                              var->name) )
4027             {
4028                 break;
4029             }
4030         }
4031
4032         if (parser->tok != '{') {
4033             if (parser->tok != '=') {
4034                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4035                 break;
4036             }
4037
4038             if (!parser_next(parser)) {
4039                 parseerror(parser, "error parsing initializer");
4040                 break;
4041             }
4042         }
4043         else if (opts_standard == COMPILER_QCC) {
4044             parseerror(parser, "expected '=' before function body in this standard");
4045         }
4046
4047         if (parser->tok == '#') {
4048             ast_function *func = NULL;
4049
4050             if (localblock) {
4051                 parseerror(parser, "cannot declare builtins within functions");
4052                 break;
4053             }
4054             if (var->expression.vtype != TYPE_FUNCTION) {
4055                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4056                 break;
4057             }
4058             if (!parser_next(parser)) {
4059                 parseerror(parser, "expected builtin number");
4060                 break;
4061             }
4062             if (parser->tok != TOKEN_INTCONST) {
4063                 parseerror(parser, "builtin number must be an integer constant");
4064                 break;
4065             }
4066             if (parser_token(parser)->constval.i < 0) {
4067                 parseerror(parser, "builtin number must be an integer greater than zero");
4068                 break;
4069             }
4070
4071             if (var->hasvalue) {
4072                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4073                                     "builtin `%s` has already been defined\n"
4074                                     " -> previous declaration here: %s:%i",
4075                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4076             }
4077             else
4078             {
4079                 func = ast_function_new(ast_ctx(var), var->name, var);
4080                 if (!func) {
4081                     parseerror(parser, "failed to allocate function for `%s`", var->name);
4082                     break;
4083                 }
4084                 vec_push(parser->functions, func);
4085
4086                 func->builtin = -parser_token(parser)->constval.i-1;
4087             }
4088
4089             if (!parser_next(parser)) {
4090                 parseerror(parser, "expected comma or semicolon");
4091                 if (func)
4092                     ast_function_delete(func);
4093                 var->constval.vfunc = NULL;
4094                 break;
4095             }
4096         }
4097         else if (parser->tok == '{' || parser->tok == '[')
4098         {
4099             size_t i;
4100             if (localblock) {
4101                 parseerror(parser, "cannot declare functions within functions");
4102                 break;
4103             }
4104
4105             if (proto)
4106                 ast_ctx(proto) = parser_ctx(parser);
4107
4108             if (!parse_function_body(parser, var))
4109                 break;
4110             ast_delete(basetype);
4111             for (i = 0; i < vec_size(parser->gotos); ++i)
4112                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4113             vec_free(parser->gotos);
4114             vec_free(parser->labels);
4115             return true;
4116         } else {
4117             ast_expression *cexp;
4118             ast_value      *cval;
4119
4120             cexp = parse_expression_leave(parser, true);
4121             if (!cexp)
4122                 break;
4123
4124             if (!localblock) {
4125                 cval = (ast_value*)cexp;
4126                 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4127                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4128                 else
4129                 {
4130                     if (opts_standard != COMPILER_GMQCC &&
4131                         !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4132                         qualifier != CV_VAR)
4133                     {
4134                         var->cvq = CV_CONST;
4135                     }
4136                     var->hasvalue = true;
4137                     if (cval->expression.vtype == TYPE_STRING)
4138                         var->constval.vstring = parser_strdup(cval->constval.vstring);
4139                     else if (cval->expression.vtype == TYPE_FIELD)
4140                         var->constval.vfield = cval;
4141                     else
4142                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4143                     ast_unref(cval);
4144                 }
4145             } else {
4146                 bool cvq;
4147                 shunt sy = { NULL, NULL };
4148                 cvq = var->cvq;
4149                 var->cvq = CV_NONE;
4150                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4151                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4152                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4153                 if (!parser_sy_pop(parser, &sy))
4154                     ast_unref(cexp);
4155                 else {
4156                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4157                         parseerror(parser, "internal error: leaked operands");
4158                     ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out);
4159                 }
4160                 vec_free(sy.out);
4161                 vec_free(sy.ops);
4162                 var->cvq = cvq;
4163             }
4164         }
4165
4166 another:
4167         if (parser->tok == ',') {
4168             if (!parser_next(parser)) {
4169                 parseerror(parser, "expected another variable");
4170                 break;
4171             }
4172
4173             if (parser->tok != TOKEN_IDENT) {
4174                 parseerror(parser, "expected another variable");
4175                 break;
4176             }
4177             var = ast_value_copy(basetype);
4178             cleanvar = true;
4179             ast_value_set_name(var, parser_tokval(parser));
4180             if (!parser_next(parser)) {
4181                 parseerror(parser, "error parsing variable declaration");
4182                 break;
4183             }
4184             continue;
4185         }
4186
4187         if (parser->tok != ';') {
4188             parseerror(parser, "missing semicolon after variables");
4189             break;
4190         }
4191
4192         if (!parser_next(parser)) {
4193             parseerror(parser, "parse error after variable declaration");
4194             break;
4195         }
4196
4197         ast_delete(basetype);
4198         return true;
4199     }
4200
4201     if (cleanvar && var)
4202         ast_delete(var);
4203     ast_delete(basetype);
4204     return false;
4205
4206 cleanup:
4207     ast_delete(basetype);
4208     if (cleanvar && var)
4209         ast_delete(var);
4210     if (me[0]) ast_member_delete(me[0]);
4211     if (me[1]) ast_member_delete(me[1]);
4212     if (me[2]) ast_member_delete(me[2]);
4213     return retval;
4214 }
4215
4216 static bool parser_global_statement(parser_t *parser)
4217 {
4218     ast_value *istype = NULL;
4219     if (parser->tok == TOKEN_IDENT)
4220         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4221
4222     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4223     {
4224         return parse_variable(parser, NULL, false, CV_NONE, istype);
4225     }
4226     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
4227     {
4228         if (!strcmp(parser_tokval(parser), "var")) {
4229             if (!parser_next(parser)) {
4230                 parseerror(parser, "expected variable declaration after 'var'");
4231                 return false;
4232             }
4233             if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "const")) {
4234                 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `const` after 'var' qualifier");
4235                 if (!parser_next(parser)) {
4236                     parseerror(parser, "expected variable declaration after 'const var'");
4237                     return false;
4238                 }
4239             }
4240             return parse_variable(parser, NULL, true, CV_VAR, NULL);
4241         }
4242     }
4243     else if (parser->tok == TOKEN_KEYWORD)
4244     {
4245         if (!strcmp(parser_tokval(parser), "const")) {
4246             if (!parser_next(parser)) {
4247                 parseerror(parser, "expected variable declaration after 'const'");
4248                 return false;
4249             }
4250             if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var")) {
4251                 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `var` after const qualifier");
4252                 if (!parser_next(parser)) {
4253                     parseerror(parser, "expected variable declaration after 'const var'");
4254                     return false;
4255                 }
4256             }
4257             return parse_variable(parser, NULL, true, CV_CONST, NULL);
4258         }
4259         else if (!strcmp(parser_tokval(parser), "typedef")) {
4260             if (!parser_next(parser)) {
4261                 parseerror(parser, "expected type definition after 'typedef'");
4262                 return false;
4263             }
4264             return parse_typedef(parser);
4265         }
4266         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4267         return false;
4268     }
4269     else if (parser->tok == '$')
4270     {
4271         if (!parser_next(parser)) {
4272             parseerror(parser, "parse error");
4273             return false;
4274         }
4275     }
4276     else
4277     {
4278         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4279         return false;
4280     }
4281     return true;
4282 }
4283
4284 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4285 {
4286     return util_crc16(old, str, strlen(str));
4287 }
4288
4289 static void progdefs_crc_file(const char *str)
4290 {
4291     /* write to progdefs.h here */
4292     (void)str;
4293 }
4294
4295 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4296 {
4297     old = progdefs_crc_sum(old, str);
4298     progdefs_crc_file(str);
4299     return old;
4300 }
4301
4302 static void generate_checksum(parser_t *parser)
4303 {
4304     uint16_t   crc = 0xFFFF;
4305     size_t     i;
4306     ast_value *value;
4307
4308         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4309         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4310         /*
4311         progdefs_crc_file("\tint\tpad;\n");
4312         progdefs_crc_file("\tint\tofs_return[3];\n");
4313         progdefs_crc_file("\tint\tofs_parm0[3];\n");
4314         progdefs_crc_file("\tint\tofs_parm1[3];\n");
4315         progdefs_crc_file("\tint\tofs_parm2[3];\n");
4316         progdefs_crc_file("\tint\tofs_parm3[3];\n");
4317         progdefs_crc_file("\tint\tofs_parm4[3];\n");
4318         progdefs_crc_file("\tint\tofs_parm5[3];\n");
4319         progdefs_crc_file("\tint\tofs_parm6[3];\n");
4320         progdefs_crc_file("\tint\tofs_parm7[3];\n");
4321         */
4322         for (i = 0; i < parser->crc_globals; ++i) {
4323             if (!ast_istype(parser->globals[i], ast_value))
4324                 continue;
4325             value = (ast_value*)(parser->globals[i]);
4326             switch (value->expression.vtype) {
4327                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4328                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4329                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4330                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4331                 default:
4332                     crc = progdefs_crc_both(crc, "\tint\t");
4333                     break;
4334             }
4335             crc = progdefs_crc_both(crc, value->name);
4336             crc = progdefs_crc_both(crc, ";\n");
4337         }
4338         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4339         for (i = 0; i < parser->crc_fields; ++i) {
4340             if (!ast_istype(parser->fields[i], ast_value))
4341                 continue;
4342             value = (ast_value*)(parser->fields[i]);
4343             switch (value->expression.next->expression.vtype) {
4344                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4345                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4346                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4347                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4348                 default:
4349                     crc = progdefs_crc_both(crc, "\tint\t");
4350                     break;
4351             }
4352             crc = progdefs_crc_both(crc, value->name);
4353             crc = progdefs_crc_both(crc, ";\n");
4354         }
4355         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4356
4357         code_crc = crc;
4358 }
4359
4360 static parser_t *parser;
4361
4362 bool parser_init()
4363 {
4364     size_t i;
4365
4366     parser = (parser_t*)mem_a(sizeof(parser_t));
4367     if (!parser)
4368         return false;
4369
4370     memset(parser, 0, sizeof(*parser));
4371
4372     for (i = 0; i < operator_count; ++i) {
4373         if (operators[i].id == opid1('=')) {
4374             parser->assign_op = operators+i;
4375             break;
4376         }
4377     }
4378     if (!parser->assign_op) {
4379         printf("internal error: initializing parser: failed to find assign operator\n");
4380         mem_d(parser);
4381         return false;
4382     }
4383
4384     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
4385     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4386     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4387     vec_push(parser->_blocktypedefs, 0);
4388     return true;
4389 }
4390
4391 bool parser_compile()
4392 {
4393     /* initial lexer/parser state */
4394     parser->lex->flags.noops = true;
4395
4396     if (parser_next(parser))
4397     {
4398         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4399         {
4400             if (!parser_global_statement(parser)) {
4401                 if (parser->tok == TOKEN_EOF)
4402                     parseerror(parser, "unexpected eof");
4403                 else if (!parser->errors)
4404                     parseerror(parser, "there have been errors, bailing out");
4405                 lex_close(parser->lex);
4406                 parser->lex = NULL;
4407                 return false;
4408             }
4409         }
4410     } else {
4411         parseerror(parser, "parse error");
4412         lex_close(parser->lex);
4413         parser->lex = NULL;
4414         return false;
4415     }
4416
4417     lex_close(parser->lex);
4418     parser->lex = NULL;
4419
4420     return !parser->errors;
4421 }
4422
4423 bool parser_compile_file(const char *filename)
4424 {
4425     parser->lex = lex_open(filename);
4426     if (!parser->lex) {
4427         con_err("failed to open file \"%s\"\n", filename);
4428         return false;
4429     }
4430     return parser_compile();
4431 }
4432
4433 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4434 {
4435     parser->lex = lex_open_string(str, len, name);
4436     if (!parser->lex) {
4437         con_err("failed to create lexer for string \"%s\"\n", name);
4438         return false;
4439     }
4440     return parser_compile();
4441 }
4442
4443 bool parser_compile_string(const char *name, const char *str)
4444 {
4445     parser->lex = lex_open_string(str, strlen(str), name);
4446     if (!parser->lex) {
4447         con_err("failed to create lexer for string \"%s\"\n", name);
4448         return false;
4449     }
4450     return parser_compile();
4451 }
4452
4453 void parser_cleanup()
4454 {
4455     size_t i;
4456     for (i = 0; i < vec_size(parser->accessors); ++i) {
4457         ast_delete(parser->accessors[i]->constval.vfunc);
4458         parser->accessors[i]->constval.vfunc = NULL;
4459         ast_delete(parser->accessors[i]);
4460     }
4461     for (i = 0; i < vec_size(parser->functions); ++i) {
4462         ast_delete(parser->functions[i]);
4463     }
4464     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4465         ast_delete(parser->imm_vector[i]);
4466     }
4467     for (i = 0; i < vec_size(parser->imm_string); ++i) {
4468         ast_delete(parser->imm_string[i]);
4469     }
4470     for (i = 0; i < vec_size(parser->imm_float); ++i) {
4471         ast_delete(parser->imm_float[i]);
4472     }
4473     for (i = 0; i < vec_size(parser->fields); ++i) {
4474         ast_delete(parser->fields[i]);
4475     }
4476     for (i = 0; i < vec_size(parser->globals); ++i) {
4477         ast_delete(parser->globals[i]);
4478     }
4479     vec_free(parser->accessors);
4480     vec_free(parser->functions);
4481     vec_free(parser->imm_vector);
4482     vec_free(parser->imm_string);
4483     vec_free(parser->imm_float);
4484     vec_free(parser->globals);
4485     vec_free(parser->fields);
4486
4487     for (i = 0; i < vec_size(parser->variables); ++i)
4488         util_htdel(parser->variables[i]);
4489     vec_free(parser->variables);
4490     vec_free(parser->_blocklocals);
4491     vec_free(parser->_locals);
4492
4493     for (i = 0; i < vec_size(parser->_typedefs); ++i)
4494         ast_delete(parser->_typedefs[i]);
4495     vec_free(parser->_typedefs);
4496     for (i = 0; i < vec_size(parser->typedefs); ++i)
4497         util_htdel(parser->typedefs[i]);
4498     vec_free(parser->typedefs);
4499     vec_free(parser->_blocktypedefs);
4500
4501     vec_free(parser->_block_ctx);
4502
4503     vec_free(parser->labels);
4504     vec_free(parser->gotos);
4505
4506     mem_d(parser);
4507 }
4508
4509 bool parser_finish(const char *output)
4510 {
4511     size_t i;
4512     ir_builder *ir;
4513     bool retval = true;
4514
4515     if (!parser->errors)
4516     {
4517         ir = ir_builder_new("gmqcc_out");
4518         if (!ir) {
4519             con_out("failed to allocate builder\n");
4520             return false;
4521         }
4522
4523         for (i = 0; i < vec_size(parser->fields); ++i) {
4524             ast_value *field;
4525             bool hasvalue;
4526             if (!ast_istype(parser->fields[i], ast_value))
4527                 continue;
4528             field = (ast_value*)parser->fields[i];
4529             hasvalue = field->hasvalue;
4530             field->hasvalue = false;
4531             if (!ast_global_codegen((ast_value*)field, ir, true)) {
4532                 con_out("failed to generate field %s\n", field->name);
4533                 ir_builder_delete(ir);
4534                 return false;
4535             }
4536             if (hasvalue) {
4537                 ir_value *ifld;
4538                 ast_expression *subtype;
4539                 field->hasvalue = true;
4540                 subtype = field->expression.next;
4541                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4542                 if (subtype->expression.vtype == TYPE_FIELD)
4543                     ifld->fieldtype = subtype->expression.next->expression.vtype;
4544                 else if (subtype->expression.vtype == TYPE_FUNCTION)
4545                     ifld->outtype = subtype->expression.next->expression.vtype;
4546                 (void)!ir_value_set_field(field->ir_v, ifld);
4547             }
4548         }
4549         for (i = 0; i < vec_size(parser->globals); ++i) {
4550             ast_value *asvalue;
4551             if (!ast_istype(parser->globals[i], ast_value))
4552                 continue;
4553             asvalue = (ast_value*)(parser->globals[i]);
4554             if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4555                 if (strcmp(asvalue->name, "end_sys_globals") &&
4556                     strcmp(asvalue->name, "end_sys_fields"))
4557                 {
4558                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4559                                                    "unused global: `%s`", asvalue->name);
4560                 }
4561             }
4562             if (!ast_global_codegen(asvalue, ir, false)) {
4563                 con_out("failed to generate global %s\n", asvalue->name);
4564                 ir_builder_delete(ir);
4565                 return false;
4566             }
4567         }
4568         for (i = 0; i < vec_size(parser->imm_float); ++i) {
4569             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4570                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4571                 ir_builder_delete(ir);
4572                 return false;
4573             }
4574         }
4575         for (i = 0; i < vec_size(parser->imm_string); ++i) {
4576             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4577                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4578                 ir_builder_delete(ir);
4579                 return false;
4580             }
4581         }
4582         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4583             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4584                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4585                 ir_builder_delete(ir);
4586                 return false;
4587             }
4588         }
4589         for (i = 0; i < vec_size(parser->globals); ++i) {
4590             ast_value *asvalue;
4591             if (!ast_istype(parser->globals[i], ast_value))
4592                 continue;
4593             asvalue = (ast_value*)(parser->globals[i]);
4594             if (!ast_generate_accessors(asvalue, ir)) {
4595                 ir_builder_delete(ir);
4596                 return false;
4597             }
4598         }
4599         for (i = 0; i < vec_size(parser->fields); ++i) {
4600             ast_value *asvalue;
4601             asvalue = (ast_value*)(parser->fields[i]->expression.next);
4602
4603             if (!ast_istype((ast_expression*)asvalue, ast_value))
4604                 continue;
4605             if (asvalue->expression.vtype != TYPE_ARRAY)
4606                 continue;
4607             if (!ast_generate_accessors(asvalue, ir)) {
4608                 ir_builder_delete(ir);
4609                 return false;
4610             }
4611         }
4612         for (i = 0; i < vec_size(parser->functions); ++i) {
4613             if (!ast_function_codegen(parser->functions[i], ir)) {
4614                 con_out("failed to generate function %s\n", parser->functions[i]->name);
4615                 ir_builder_delete(ir);
4616                 return false;
4617             }
4618         }
4619         if (opts_dump)
4620             ir_builder_dump(ir, con_out);
4621         for (i = 0; i < vec_size(parser->functions); ++i) {
4622             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4623                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4624                 ir_builder_delete(ir);
4625                 return false;
4626             }
4627         }
4628
4629         if (retval) {
4630             if (opts_dumpfin)
4631                 ir_builder_dump(ir, con_out);
4632
4633             generate_checksum(parser);
4634
4635             if (!ir_builder_generate(ir, output)) {
4636                 con_out("*** failed to generate output file\n");
4637                 ir_builder_delete(ir);
4638                 return false;
4639             }
4640         }
4641
4642         ir_builder_delete(ir);
4643         return retval;
4644     }
4645
4646     con_out("*** there were compile errors\n");
4647     return false;
4648 }