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