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