]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
6ccd5e2b3b1458e30d532b73c3ba1774b922450b
[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 && !strcmp(parser_tokval(parser), "_")) {
1308             /* a translatable string */
1309             ast_value *val;
1310
1311             if (wantop) {
1312                 parseerror(parser, "expected operator or end of statement, got constant");
1313                 goto onerr;
1314             }
1315
1316             parser->lex->flags.noops = true;
1317             if (!parser_next(parser) || parser->tok != '(') {
1318                 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1319                 goto onerr;
1320             }
1321             parser->lex->flags.noops = false;
1322             if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1323                 parseerror(parser, "expected a constant string in translatable-string extension");
1324                 goto onerr;
1325             }
1326             val = parser_const_string(parser, parser_tokval(parser), true);
1327             wantop = true;
1328             if (!val)
1329                 return false;
1330             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1331             DEBUGSHUNTDO(con_out("push string\n"));
1332
1333             if (!parser_next(parser) || parser->tok != ')') {
1334                 parseerror(parser, "expected closing paren after translatable string");
1335                 goto onerr;
1336             }
1337         }
1338         else if (parser->tok == TOKEN_IDENT)
1339         {
1340             ast_expression *var;
1341             if (wantop) {
1342                 parseerror(parser, "expected operator or end of statement");
1343                 goto onerr;
1344             }
1345             wantop = true;
1346             /* variable */
1347             if (opts_standard == COMPILER_GMQCC)
1348             {
1349                 if (parser->memberof == TYPE_ENTITY) {
1350                     /* still get vars first since there could be a fieldpointer */
1351                     var = parser_find_var(parser, parser_tokval(parser));
1352                     if (!var)
1353                         var = parser_find_field(parser, parser_tokval(parser));
1354                 }
1355                 else if (parser->memberof == TYPE_VECTOR)
1356                 {
1357                     parseerror(parser, "TODO: implement effective vector member access");
1358                     goto onerr;
1359                 }
1360                 else if (parser->memberof) {
1361                     parseerror(parser, "namespace for member not found");
1362                     goto onerr;
1363                 }
1364                 else
1365                     var = parser_find_var(parser, parser_tokval(parser));
1366             } else {
1367                 var = parser_find_var(parser, parser_tokval(parser));
1368                 if (!var)
1369                     var = parser_find_field(parser, parser_tokval(parser));
1370             }
1371             if (!var) {
1372                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1373                 goto onerr;
1374             }
1375             if (ast_istype(var, ast_value))
1376                 ((ast_value*)var)->uses++;
1377             vec_push(sy.out, syexp(parser_ctx(parser), var));
1378             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1379         }
1380         else if (parser->tok == TOKEN_FLOATCONST) {
1381             ast_value *val;
1382             if (wantop) {
1383                 parseerror(parser, "expected operator or end of statement, got constant");
1384                 goto onerr;
1385             }
1386             wantop = true;
1387             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1388             if (!val)
1389                 return false;
1390             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1391             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1392         }
1393         else if (parser->tok == TOKEN_INTCONST) {
1394             ast_value *val;
1395             if (wantop) {
1396                 parseerror(parser, "expected operator or end of statement, got constant");
1397                 goto onerr;
1398             }
1399             wantop = true;
1400             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1401             if (!val)
1402                 return false;
1403             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1404             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1405         }
1406         else if (parser->tok == TOKEN_STRINGCONST) {
1407             ast_value *val;
1408             if (wantop) {
1409                 parseerror(parser, "expected operator or end of statement, got constant");
1410                 goto onerr;
1411             }
1412             wantop = true;
1413             val = parser_const_string(parser, parser_tokval(parser), false);
1414             if (!val)
1415                 return false;
1416             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1417             DEBUGSHUNTDO(con_out("push string\n"));
1418         }
1419         else if (parser->tok == TOKEN_VECTORCONST) {
1420             ast_value *val;
1421             if (wantop) {
1422                 parseerror(parser, "expected operator or end of statement, got constant");
1423                 goto onerr;
1424             }
1425             wantop = true;
1426             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1427             if (!val)
1428                 return false;
1429             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1430             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1431                                 parser_token(parser)->constval.v.x,
1432                                 parser_token(parser)->constval.v.y,
1433                                 parser_token(parser)->constval.v.z));
1434         }
1435         else if (parser->tok == '(') {
1436             parseerror(parser, "internal error: '(' should be classified as operator");
1437             goto onerr;
1438         }
1439         else if (parser->tok == '[') {
1440             parseerror(parser, "internal error: '[' should be classified as operator");
1441             goto onerr;
1442         }
1443         else if (parser->tok == ')') {
1444             if (wantop) {
1445                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1446                 --parens;
1447                 if (parens < 0)
1448                     break;
1449                 /* we do expect an operator next */
1450                 /* closing an opening paren */
1451                 if (!parser_close_paren(parser, &sy, false))
1452                     goto onerr;
1453             } else {
1454                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1455                 --parens;
1456                 if (parens < 0)
1457                     break;
1458                 /* allowed for function calls */
1459                 if (!parser_close_paren(parser, &sy, true))
1460                     goto onerr;
1461             }
1462             wantop = true;
1463         }
1464         else if (parser->tok == ']') {
1465             if (!wantop)
1466                 parseerror(parser, "operand expected");
1467             --parens;
1468             if (parens < 0)
1469                 break;
1470             if (!parser_close_paren(parser, &sy, false))
1471                 goto onerr;
1472             wantop = true;
1473         }
1474         else if (parser->tok != TOKEN_OPERATOR) {
1475             if (wantop) {
1476                 parseerror(parser, "expected operator or end of statement");
1477                 goto onerr;
1478             }
1479             break;
1480         }
1481         else
1482         {
1483             /* classify the operator */
1484             const oper_info *op;
1485             const oper_info *olast = NULL;
1486             size_t o;
1487             for (o = 0; o < operator_count; ++o) {
1488                 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1489                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1490                     !strcmp(parser_tokval(parser), operators[o].op))
1491                 {
1492                     break;
1493                 }
1494             }
1495             if (o == operator_count) {
1496                 /* no operator found... must be the end of the statement */
1497                 break;
1498             }
1499             /* found an operator */
1500             op = &operators[o];
1501
1502             /* when declaring variables, a comma starts a new variable */
1503             if (op->id == opid1(',') && !parens && stopatcomma) {
1504                 /* fixup the token */
1505                 parser->tok = ',';
1506                 break;
1507             }
1508
1509             /* a colon without a pervious question mark cannot be a ternary */
1510             if (!ternaries && op->id == opid2(':','?')) {
1511                 parser->tok = ':';
1512                 break;
1513             }
1514
1515             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1516                 olast = &operators[vec_last(sy.ops).etype-1];
1517
1518             while (olast && (
1519                     (op->prec < olast->prec) ||
1520                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1521             {
1522                 if (!parser_sy_pop(parser, &sy))
1523                     goto onerr;
1524                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1525                     olast = &operators[vec_last(sy.ops).etype-1];
1526                 else
1527                     olast = NULL;
1528             }
1529
1530             if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1531                 /* for gmqcc standard: open up the namespace of the previous type */
1532                 ast_expression *prevex = vec_last(sy.out).out;
1533                 if (!prevex) {
1534                     parseerror(parser, "unexpected member operator");
1535                     goto onerr;
1536                 }
1537                 if (prevex->expression.vtype == TYPE_ENTITY)
1538                     parser->memberof = TYPE_ENTITY;
1539                 else if (prevex->expression.vtype == TYPE_VECTOR)
1540                     parser->memberof = TYPE_VECTOR;
1541                 else {
1542                     parseerror(parser, "type error: type has no members");
1543                     goto onerr;
1544                 }
1545                 gotmemberof = true;
1546             }
1547
1548             if (op->id == opid1('(')) {
1549                 if (wantop) {
1550                     size_t sycount = vec_size(sy.out);
1551                     DEBUGSHUNTDO(con_out("push [op] (\n"));
1552                     ++parens;
1553                     /* we expected an operator, this is the function-call operator */
1554                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1555                 } else {
1556                     ++parens;
1557                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1558                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
1559                 }
1560                 wantop = false;
1561             } else if (op->id == opid1('[')) {
1562                 if (!wantop) {
1563                     parseerror(parser, "unexpected array subscript");
1564                     goto onerr;
1565                 }
1566                 ++parens;
1567                 /* push both the operator and the paren, this makes life easier */
1568                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1569                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1570                 wantop = false;
1571             } else if (op->id == opid2('?',':')) {
1572                 wantop = false;
1573                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1574                 wantop = false;
1575                 --ternaries;
1576             } else if (op->id == opid2(':','?')) {
1577                 /* we don't push this operator */
1578                 wantop = false;
1579                 ++ternaries;
1580             } else {
1581                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1582                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1583                 wantop = !!(op->flags & OP_SUFFIX);
1584             }
1585         }
1586         if (!parser_next(parser)) {
1587             goto onerr;
1588         }
1589         if (parser->tok == ';' ||
1590             (!parens && parser->tok == ']'))
1591         {
1592             break;
1593         }
1594     }
1595
1596     while (vec_size(sy.ops)) {
1597         if (!parser_sy_pop(parser, &sy))
1598             goto onerr;
1599     }
1600
1601     parser->lex->flags.noops = true;
1602     if (!vec_size(sy.out)) {
1603         parseerror(parser, "empty expression");
1604         expr = NULL;
1605     } else
1606         expr = sy.out[0].out;
1607     vec_free(sy.out);
1608     vec_free(sy.ops);
1609     DEBUGSHUNTDO(con_out("shunt done\n"));
1610     return expr;
1611
1612 onerr:
1613     parser->lex->flags.noops = true;
1614     vec_free(sy.out);
1615     vec_free(sy.ops);
1616     return NULL;
1617 }
1618
1619 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1620 {
1621     ast_expression *e = parse_expression_leave(parser, stopatcomma);
1622     if (!e)
1623         return NULL;
1624     if (!parser_next(parser)) {
1625         ast_delete(e);
1626         return NULL;
1627     }
1628     return e;
1629 }
1630
1631 static void parser_enterblock(parser_t *parser)
1632 {
1633     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1634     vec_push(parser->_blocklocals, vec_size(parser->_locals));
1635     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1636     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1637 }
1638
1639 static bool parser_leaveblock(parser_t *parser)
1640 {
1641     bool   rv = true;
1642     size_t locals, typedefs;
1643
1644     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1645         parseerror(parser, "internal error: parser_leaveblock with no block");
1646         return false;
1647     }
1648
1649     util_htdel(vec_last(parser->variables));
1650     vec_pop(parser->variables);
1651     if (!vec_size(parser->_blocklocals)) {
1652         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1653         return false;
1654     }
1655
1656     locals = vec_last(parser->_blocklocals);
1657     vec_pop(parser->_blocklocals);
1658     while (vec_size(parser->_locals) != locals) {
1659         ast_expression *e = vec_last(parser->_locals);
1660         ast_value      *v = (ast_value*)e;
1661         vec_pop(parser->_locals);
1662         if (ast_istype(e, ast_value) && !v->uses) {
1663             if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1664                 rv = false;
1665         }
1666     }
1667
1668     typedefs = vec_last(parser->_blocktypedefs);
1669     while (vec_size(parser->_typedefs) != typedefs) {
1670         ast_delete(vec_last(parser->_typedefs));
1671         vec_pop(parser->_typedefs);
1672     }
1673     util_htdel(vec_last(parser->typedefs));
1674     vec_pop(parser->typedefs);
1675
1676     return rv;
1677 }
1678
1679 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1680 {
1681     vec_push(parser->_locals, e);
1682     util_htset(vec_last(parser->variables), name, (void*)e);
1683 }
1684
1685 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1686 {
1687     ast_ifthen *ifthen;
1688     ast_expression *cond, *ontrue, *onfalse = NULL;
1689     bool ifnot = false;
1690
1691     lex_ctx ctx = parser_ctx(parser);
1692
1693     (void)block; /* not touching */
1694
1695     /* skip the 'if', parse an optional 'not' and check for an opening paren */
1696     if (!parser_next(parser)) {
1697         parseerror(parser, "expected condition or 'not'");
1698         return false;
1699     }
1700     if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "not")) {
1701         ifnot = true;
1702         if (!parser_next(parser)) {
1703             parseerror(parser, "expected condition in parenthesis");
1704             return false;
1705         }
1706     }
1707     if (parser->tok != '(') {
1708         parseerror(parser, "expected 'if' condition in parenthesis");
1709         return false;
1710     }
1711     /* parse into the expression */
1712     if (!parser_next(parser)) {
1713         parseerror(parser, "expected 'if' condition after opening paren");
1714         return false;
1715     }
1716     /* parse the condition */
1717     cond = parse_expression_leave(parser, false);
1718     if (!cond)
1719         return false;
1720     /* closing paren */
1721     if (parser->tok != ')') {
1722         parseerror(parser, "expected closing paren after 'if' condition");
1723         ast_delete(cond);
1724         return false;
1725     }
1726     /* parse into the 'then' branch */
1727     if (!parser_next(parser)) {
1728         parseerror(parser, "expected statement for on-true branch of 'if'");
1729         ast_delete(cond);
1730         return false;
1731     }
1732     ontrue = parse_statement_or_block(parser);
1733     if (!ontrue) {
1734         ast_delete(cond);
1735         return false;
1736     }
1737     /* check for an else */
1738     if (!strcmp(parser_tokval(parser), "else")) {
1739         /* parse into the 'else' branch */
1740         if (!parser_next(parser)) {
1741             parseerror(parser, "expected on-false branch after 'else'");
1742             ast_delete(ontrue);
1743             ast_delete(cond);
1744             return false;
1745         }
1746         onfalse = parse_statement_or_block(parser);
1747         if (!onfalse) {
1748             ast_delete(ontrue);
1749             ast_delete(cond);
1750             return false;
1751         }
1752     }
1753
1754     if (ifnot)
1755         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1756     else
1757         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1758     *out = (ast_expression*)ifthen;
1759     return true;
1760 }
1761
1762 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1763 {
1764     ast_loop *aloop;
1765     ast_expression *cond, *ontrue;
1766
1767     lex_ctx ctx = parser_ctx(parser);
1768
1769     (void)block; /* not touching */
1770
1771     /* skip the 'while' and check for opening paren */
1772     if (!parser_next(parser) || parser->tok != '(') {
1773         parseerror(parser, "expected 'while' condition in parenthesis");
1774         return false;
1775     }
1776     /* parse into the expression */
1777     if (!parser_next(parser)) {
1778         parseerror(parser, "expected 'while' condition after opening paren");
1779         return false;
1780     }
1781     /* parse the condition */
1782     cond = parse_expression_leave(parser, false);
1783     if (!cond)
1784         return false;
1785     /* closing paren */
1786     if (parser->tok != ')') {
1787         parseerror(parser, "expected closing paren after 'while' condition");
1788         ast_delete(cond);
1789         return false;
1790     }
1791     /* parse into the 'then' branch */
1792     if (!parser_next(parser)) {
1793         parseerror(parser, "expected while-loop body");
1794         ast_delete(cond);
1795         return false;
1796     }
1797     ontrue = parse_statement_or_block(parser);
1798     if (!ontrue) {
1799         ast_delete(cond);
1800         return false;
1801     }
1802
1803     aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1804     *out = (ast_expression*)aloop;
1805     return true;
1806 }
1807
1808 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1809 {
1810     ast_loop *aloop;
1811     ast_expression *cond, *ontrue;
1812
1813     lex_ctx ctx = parser_ctx(parser);
1814
1815     (void)block; /* not touching */
1816
1817     /* skip the 'do' and get the body */
1818     if (!parser_next(parser)) {
1819         parseerror(parser, "expected loop body");
1820         return false;
1821     }
1822     ontrue = parse_statement_or_block(parser);
1823     if (!ontrue)
1824         return false;
1825
1826     /* expect the "while" */
1827     if (parser->tok != TOKEN_KEYWORD ||
1828         strcmp(parser_tokval(parser), "while"))
1829     {
1830         parseerror(parser, "expected 'while' and condition");
1831         ast_delete(ontrue);
1832         return false;
1833     }
1834
1835     /* skip the 'while' and check for opening paren */
1836     if (!parser_next(parser) || parser->tok != '(') {
1837         parseerror(parser, "expected 'while' condition in parenthesis");
1838         ast_delete(ontrue);
1839         return false;
1840     }
1841     /* parse into the expression */
1842     if (!parser_next(parser)) {
1843         parseerror(parser, "expected 'while' condition after opening paren");
1844         ast_delete(ontrue);
1845         return false;
1846     }
1847     /* parse the condition */
1848     cond = parse_expression_leave(parser, false);
1849     if (!cond)
1850         return false;
1851     /* closing paren */
1852     if (parser->tok != ')') {
1853         parseerror(parser, "expected closing paren after 'while' condition");
1854         ast_delete(ontrue);
1855         ast_delete(cond);
1856         return false;
1857     }
1858     /* parse on */
1859     if (!parser_next(parser) || parser->tok != ';') {
1860         parseerror(parser, "expected semicolon after condition");
1861         ast_delete(ontrue);
1862         ast_delete(cond);
1863         return false;
1864     }
1865
1866     if (!parser_next(parser)) {
1867         parseerror(parser, "parse error");
1868         ast_delete(ontrue);
1869         ast_delete(cond);
1870         return false;
1871     }
1872
1873     aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1874     *out = (ast_expression*)aloop;
1875     return true;
1876 }
1877
1878 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1879 {
1880     ast_loop       *aloop;
1881     ast_expression *initexpr, *cond, *increment, *ontrue;
1882     ast_value      *typevar;
1883     bool   retval = true;
1884
1885     lex_ctx ctx = parser_ctx(parser);
1886
1887     parser_enterblock(parser);
1888
1889     initexpr  = NULL;
1890     cond      = NULL;
1891     increment = NULL;
1892     ontrue    = NULL;
1893
1894     /* skip the 'while' and check for opening paren */
1895     if (!parser_next(parser) || parser->tok != '(') {
1896         parseerror(parser, "expected 'for' expressions in parenthesis");
1897         goto onerr;
1898     }
1899     /* parse into the expression */
1900     if (!parser_next(parser)) {
1901         parseerror(parser, "expected 'for' initializer after opening paren");
1902         goto onerr;
1903     }
1904
1905     typevar = NULL;
1906     if (parser->tok == TOKEN_IDENT)
1907         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
1908
1909     if (typevar || parser->tok == TOKEN_TYPENAME) {
1910         if (opts_standard != COMPILER_GMQCC) {
1911             if (parsewarning(parser, WARN_EXTENSIONS,
1912                              "current standard does not allow variable declarations in for-loop initializers"))
1913                 goto onerr;
1914         }
1915
1916         parseerror(parser, "TODO: assignment of new variables to be non-const");
1917         goto onerr;
1918         if (!parse_variable(parser, block, true, false, typevar))
1919             goto onerr;
1920     }
1921     else if (parser->tok != ';')
1922     {
1923         initexpr = parse_expression_leave(parser, false);
1924         if (!initexpr)
1925             goto onerr;
1926     }
1927
1928     /* move on to condition */
1929     if (parser->tok != ';') {
1930         parseerror(parser, "expected semicolon after for-loop initializer");
1931         goto onerr;
1932     }
1933     if (!parser_next(parser)) {
1934         parseerror(parser, "expected for-loop condition");
1935         goto onerr;
1936     }
1937
1938     /* parse the condition */
1939     if (parser->tok != ';') {
1940         cond = parse_expression_leave(parser, false);
1941         if (!cond)
1942             goto onerr;
1943     }
1944
1945     /* move on to incrementor */
1946     if (parser->tok != ';') {
1947         parseerror(parser, "expected semicolon after for-loop initializer");
1948         goto onerr;
1949     }
1950     if (!parser_next(parser)) {
1951         parseerror(parser, "expected for-loop condition");
1952         goto onerr;
1953     }
1954
1955     /* parse the incrementor */
1956     if (parser->tok != ')') {
1957         increment = parse_expression_leave(parser, false);
1958         if (!increment)
1959             goto onerr;
1960         if (!ast_istype(increment, ast_store) &&
1961             !ast_istype(increment, ast_call) &&
1962             !ast_istype(increment, ast_binstore))
1963         {
1964             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1965                 goto onerr;
1966         }
1967     }
1968
1969     /* closing paren */
1970     if (parser->tok != ')') {
1971         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1972         goto onerr;
1973     }
1974     /* parse into the 'then' branch */
1975     if (!parser_next(parser)) {
1976         parseerror(parser, "expected for-loop body");
1977         goto onerr;
1978     }
1979     ontrue = parse_statement_or_block(parser);
1980     if (!ontrue) {
1981         goto onerr;
1982     }
1983
1984     aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1985     *out = (ast_expression*)aloop;
1986
1987     if (!parser_leaveblock(parser))
1988         retval = false;
1989     return retval;
1990 onerr:
1991     if (initexpr)  ast_delete(initexpr);
1992     if (cond)      ast_delete(cond);
1993     if (increment) ast_delete(increment);
1994     (void)!parser_leaveblock(parser);
1995     return false;
1996 }
1997
1998 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
1999 {
2000     ast_expression *exp = NULL;
2001     ast_return     *ret = NULL;
2002     ast_value      *expected = parser->function->vtype;
2003
2004     (void)block; /* not touching */
2005
2006     if (!parser_next(parser)) {
2007         parseerror(parser, "expected return expression");
2008         return false;
2009     }
2010
2011     if (parser->tok != ';') {
2012         exp = parse_expression(parser, false);
2013         if (!exp)
2014             return false;
2015
2016         if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2017             parseerror(parser, "return with invalid expression");
2018         }
2019
2020         ret = ast_return_new(exp->expression.node.context, exp);
2021         if (!ret) {
2022             ast_delete(exp);
2023             return false;
2024         }
2025     } else {
2026         if (!parser_next(parser))
2027             parseerror(parser, "parse error");
2028         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2029             if (opts_standard != COMPILER_GMQCC)
2030                 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2031             else
2032                 parseerror(parser, "return without value");
2033         }
2034         ret = ast_return_new(parser_ctx(parser), NULL);
2035     }
2036     *out = (ast_expression*)ret;
2037     return true;
2038 }
2039
2040 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2041 {
2042     lex_ctx ctx = parser_ctx(parser);
2043
2044     (void)block; /* not touching */
2045
2046     if (!parser_next(parser) || parser->tok != ';') {
2047         parseerror(parser, "expected semicolon");
2048         return false;
2049     }
2050
2051     if (!parser_next(parser))
2052         parseerror(parser, "parse error");
2053
2054     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2055     return true;
2056 }
2057
2058 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2059 {
2060     ast_expression *operand;
2061     ast_value      *opval;
2062     ast_switch     *switchnode;
2063     ast_switch_case swcase;
2064
2065     lex_ctx ctx = parser_ctx(parser);
2066
2067     (void)block; /* not touching */
2068
2069     /* parse over the opening paren */
2070     if (!parser_next(parser) || parser->tok != '(') {
2071         parseerror(parser, "expected switch operand in parenthesis");
2072         return false;
2073     }
2074
2075     /* parse into the expression */
2076     if (!parser_next(parser)) {
2077         parseerror(parser, "expected switch operand");
2078         return false;
2079     }
2080     /* parse the operand */
2081     operand = parse_expression_leave(parser, false);
2082     if (!operand)
2083         return false;
2084
2085     if (!OPTS_FLAG(RELAXED_SWITCH)) {
2086         opval = (ast_value*)operand;
2087         if (!ast_istype(operand, ast_value) || !opval->isconst) {
2088             parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2089             ast_unref(operand);
2090             return false;
2091         }
2092     }
2093
2094     switchnode = ast_switch_new(ctx, operand);
2095
2096     /* closing paren */
2097     if (parser->tok != ')') {
2098         ast_delete(switchnode);
2099         parseerror(parser, "expected closing paren after 'switch' operand");
2100         return false;
2101     }
2102
2103     /* parse over the opening paren */
2104     if (!parser_next(parser) || parser->tok != '{') {
2105         ast_delete(switchnode);
2106         parseerror(parser, "expected list of cases");
2107         return false;
2108     }
2109
2110     if (!parser_next(parser)) {
2111         ast_delete(switchnode);
2112         parseerror(parser, "expected 'case' or 'default'");
2113         return false;
2114     }
2115
2116     /* case list! */
2117     while (parser->tok != '}') {
2118         ast_block *caseblock;
2119
2120         if (parser->tok != TOKEN_KEYWORD) {
2121             ast_delete(switchnode);
2122             parseerror(parser, "expected 'case' or 'default'");
2123             return false;
2124         }
2125         if (!strcmp(parser_tokval(parser), "case")) {
2126             if (!parser_next(parser)) {
2127                 ast_delete(switchnode);
2128                 parseerror(parser, "expected expression for case");
2129                 return false;
2130             }
2131             swcase.value = parse_expression_leave(parser, false);
2132             if (!swcase.value) {
2133                 ast_delete(switchnode);
2134                 parseerror(parser, "expected expression for case");
2135                 return false;
2136             }
2137         }
2138         else if (!strcmp(parser_tokval(parser), "default")) {
2139             swcase.value = NULL;
2140             if (!parser_next(parser)) {
2141                 ast_delete(switchnode);
2142                 parseerror(parser, "expected colon");
2143                 return false;
2144             }
2145         }
2146
2147         /* Now the colon and body */
2148         if (parser->tok != ':') {
2149             if (swcase.value) ast_unref(swcase.value);
2150             ast_delete(switchnode);
2151             parseerror(parser, "expected colon");
2152             return false;
2153         }
2154
2155         if (!parser_next(parser)) {
2156             if (swcase.value) ast_unref(swcase.value);
2157             ast_delete(switchnode);
2158             parseerror(parser, "expected statements or case");
2159             return false;
2160         }
2161         caseblock = ast_block_new(parser_ctx(parser));
2162         if (!caseblock) {
2163             if (swcase.value) ast_unref(swcase.value);
2164             ast_delete(switchnode);
2165             return false;
2166         }
2167         swcase.code = (ast_expression*)caseblock;
2168         vec_push(switchnode->cases, swcase);
2169         while (true) {
2170             ast_expression *expr;
2171             if (parser->tok == '}')
2172                 break;
2173             if (parser->tok == TOKEN_KEYWORD) {
2174                 if (!strcmp(parser_tokval(parser), "case") ||
2175                     !strcmp(parser_tokval(parser), "default"))
2176                 {
2177                     break;
2178                 }
2179             }
2180             if (!parse_statement(parser, caseblock, &expr, true)) {
2181                 ast_delete(switchnode);
2182                 return false;
2183             }
2184             if (!expr)
2185                 continue;
2186             vec_push(caseblock->exprs, expr);
2187         }
2188     }
2189
2190     /* closing paren */
2191     if (parser->tok != '}') {
2192         ast_delete(switchnode);
2193         parseerror(parser, "expected closing paren of case list");
2194         return false;
2195     }
2196     if (!parser_next(parser)) {
2197         ast_delete(switchnode);
2198         parseerror(parser, "parse error after switch");
2199         return false;
2200     }
2201     *out = (ast_expression*)switchnode;
2202     return true;
2203 }
2204
2205 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2206 {
2207     ast_value *typevar = NULL;
2208     if (parser->tok == TOKEN_IDENT)
2209         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2210
2211     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2212     {
2213         /* local variable */
2214         if (!block) {
2215             parseerror(parser, "cannot declare a variable from here");
2216             return false;
2217         }
2218         if (opts_standard == COMPILER_QCC) {
2219             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2220                 return false;
2221         }
2222         if (!parse_variable(parser, block, false, false, typevar))
2223             return false;
2224         *out = NULL;
2225         return true;
2226     }
2227     else if (parser->tok == TOKEN_KEYWORD)
2228     {
2229         if (!strcmp(parser_tokval(parser), "local"))
2230         {
2231             if (!block) {
2232                 parseerror(parser, "cannot declare a local variable here");
2233                 return false;
2234             }
2235             if (!parser_next(parser)) {
2236                 parseerror(parser, "expected variable declaration");
2237                 return false;
2238             }
2239             if (!parse_variable(parser, block, true, false, NULL))
2240                 return false;
2241             *out = NULL;
2242             return true;
2243         }
2244         else if (!strcmp(parser_tokval(parser), "return"))
2245         {
2246             return parse_return(parser, block, out);
2247         }
2248         else if (!strcmp(parser_tokval(parser), "if"))
2249         {
2250             return parse_if(parser, block, out);
2251         }
2252         else if (!strcmp(parser_tokval(parser), "while"))
2253         {
2254             return parse_while(parser, block, out);
2255         }
2256         else if (!strcmp(parser_tokval(parser), "do"))
2257         {
2258             return parse_dowhile(parser, block, out);
2259         }
2260         else if (!strcmp(parser_tokval(parser), "for"))
2261         {
2262             if (opts_standard == COMPILER_QCC) {
2263                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2264                     return false;
2265             }
2266             return parse_for(parser, block, out);
2267         }
2268         else if (!strcmp(parser_tokval(parser), "break"))
2269         {
2270             return parse_break_continue(parser, block, out, false);
2271         }
2272         else if (!strcmp(parser_tokval(parser), "continue"))
2273         {
2274             return parse_break_continue(parser, block, out, true);
2275         }
2276         else if (!strcmp(parser_tokval(parser), "switch"))
2277         {
2278             return parse_switch(parser, block, out);
2279         }
2280         else if (!strcmp(parser_tokval(parser), "case") ||
2281                  !strcmp(parser_tokval(parser), "default"))
2282         {
2283             if (!allow_cases) {
2284                 parseerror(parser, "unexpected 'case' label");
2285                 return false;
2286             }
2287             return true;
2288         }
2289         else if (!strcmp(parser_tokval(parser), "typedef"))
2290         {
2291             if (!parser_next(parser)) {
2292                 parseerror(parser, "expected type definition after 'typedef'");
2293                 return false;
2294             }
2295             return parse_typedef(parser);
2296         }
2297         parseerror(parser, "Unexpected keyword");
2298         return false;
2299     }
2300     else if (parser->tok == '{')
2301     {
2302         ast_block *inner;
2303         inner = parse_block(parser, false);
2304         if (!inner)
2305             return false;
2306         *out = (ast_expression*)inner;
2307         return true;
2308     }
2309     else
2310     {
2311         ast_expression *exp = parse_expression(parser, false);
2312         if (!exp)
2313             return false;
2314         *out = exp;
2315         if (!ast_istype(exp, ast_store) &&
2316             !ast_istype(exp, ast_call) &&
2317             !ast_istype(exp, ast_binstore))
2318         {
2319             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2320                 return false;
2321         }
2322         return true;
2323     }
2324 }
2325
2326 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2327 {
2328     bool   retval = true;
2329
2330     parser_enterblock(parser);
2331
2332     if (!parser_next(parser)) { /* skip the '{' */
2333         parseerror(parser, "expected function body");
2334         goto cleanup;
2335     }
2336
2337     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2338     {
2339         ast_expression *expr = NULL;
2340         if (parser->tok == '}')
2341             break;
2342
2343         if (!parse_statement(parser, block, &expr, false)) {
2344             /* parseerror(parser, "parse error"); */
2345             block = NULL;
2346             goto cleanup;
2347         }
2348         if (!expr)
2349             continue;
2350         vec_push(block->exprs, expr);
2351     }
2352
2353     if (parser->tok != '}') {
2354         block = NULL;
2355     } else {
2356         if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2357         {
2358             if (!vec_size(block->exprs) ||
2359                 !ast_istype(vec_last(block->exprs), ast_return))
2360             {
2361                 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2362                     block = NULL;
2363                     goto cleanup;
2364                 }
2365             }
2366         }
2367         (void)parser_next(parser);
2368     }
2369
2370 cleanup:
2371     if (!parser_leaveblock(parser))
2372         retval = false;
2373     return retval && !!block;
2374 }
2375
2376 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2377 {
2378     ast_block *block;
2379     block = ast_block_new(parser_ctx(parser));
2380     if (!block)
2381         return NULL;
2382     if (!parse_block_into(parser, block, warnreturn)) {
2383         ast_block_delete(block);
2384         return NULL;
2385     }
2386     return block;
2387 }
2388
2389 static ast_expression* parse_statement_or_block(parser_t *parser)
2390 {
2391     ast_expression *expr = NULL;
2392     if (parser->tok == '{')
2393         return (ast_expression*)parse_block(parser, false);
2394     if (!parse_statement(parser, NULL, &expr, false))
2395         return NULL;
2396     return expr;
2397 }
2398
2399 static bool create_vector_members(ast_value *var, ast_member **me)
2400 {
2401     size_t i;
2402     size_t len = strlen(var->name);
2403
2404     for (i = 0; i < 3; ++i) {
2405         char *name = mem_a(len+3);
2406         memcpy(name, var->name, len);
2407         name[len+0] = '_';
2408         name[len+1] = 'x'+i;
2409         name[len+2] = 0;
2410         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2411         mem_d(name);
2412         if (!me[i])
2413             break;
2414     }
2415     if (i == 3)
2416         return true;
2417
2418     /* unroll */
2419     do { ast_member_delete(me[--i]); } while(i);
2420     return false;
2421 }
2422
2423 static bool parse_function_body(parser_t *parser, ast_value *var)
2424 {
2425     ast_block      *block = NULL;
2426     ast_function   *func;
2427     ast_function   *old;
2428     size_t          parami;
2429
2430     ast_expression *framenum  = NULL;
2431     ast_expression *nextthink = NULL;
2432     /* None of the following have to be deleted */
2433     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2434     ast_expression *gbl_time = NULL, *gbl_self = NULL;
2435     bool            has_frame_think;
2436
2437     bool retval = true;
2438
2439     has_frame_think = false;
2440     old = parser->function;
2441
2442     if (var->expression.variadic) {
2443         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2444                          "variadic function with implementation will not be able to access additional parameters"))
2445         {
2446             return false;
2447         }
2448     }
2449
2450     if (parser->tok == '[') {
2451         /* got a frame definition: [ framenum, nextthink ]
2452          * this translates to:
2453          * self.frame = framenum;
2454          * self.nextthink = time + 0.1;
2455          * self.think = nextthink;
2456          */
2457         nextthink = NULL;
2458
2459         fld_think     = parser_find_field(parser, "think");
2460         fld_nextthink = parser_find_field(parser, "nextthink");
2461         fld_frame     = parser_find_field(parser, "frame");
2462         if (!fld_think || !fld_nextthink || !fld_frame) {
2463             parseerror(parser, "cannot use [frame,think] notation without the required fields");
2464             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2465             return false;
2466         }
2467         gbl_time      = parser_find_global(parser, "time");
2468         gbl_self      = parser_find_global(parser, "self");
2469         if (!gbl_time || !gbl_self) {
2470             parseerror(parser, "cannot use [frame,think] notation without the required globals");
2471             parseerror(parser, "please declare the following globals: `time`, `self`");
2472             return false;
2473         }
2474
2475         if (!parser_next(parser))
2476             return false;
2477
2478         framenum = parse_expression_leave(parser, true);
2479         if (!framenum) {
2480             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2481             return false;
2482         }
2483         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2484             ast_unref(framenum);
2485             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2486             return false;
2487         }
2488
2489         if (parser->tok != ',') {
2490             ast_unref(framenum);
2491             parseerror(parser, "expected comma after frame number in [frame,think] notation");
2492             parseerror(parser, "Got a %i\n", parser->tok);
2493             return false;
2494         }
2495
2496         if (!parser_next(parser)) {
2497             ast_unref(framenum);
2498             return false;
2499         }
2500
2501         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2502         {
2503             /* qc allows the use of not-yet-declared functions here
2504              * - this automatically creates a prototype */
2505             ast_value      *thinkfunc;
2506             ast_expression *functype = fld_think->expression.next;
2507
2508             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2509             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2510                 ast_unref(framenum);
2511                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2512                 return false;
2513             }
2514
2515             if (!parser_next(parser)) {
2516                 ast_unref(framenum);
2517                 ast_delete(thinkfunc);
2518                 return false;
2519             }
2520
2521             vec_push(parser->globals, (ast_expression*)thinkfunc);
2522             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2523             nextthink = (ast_expression*)thinkfunc;
2524
2525         } else {
2526             nextthink = parse_expression_leave(parser, true);
2527             if (!nextthink) {
2528                 ast_unref(framenum);
2529                 parseerror(parser, "expected a think-function in [frame,think] notation");
2530                 return false;
2531             }
2532         }
2533
2534         if (!ast_istype(nextthink, ast_value)) {
2535             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2536             retval = false;
2537         }
2538
2539         if (retval && parser->tok != ']') {
2540             parseerror(parser, "expected closing `]` for [frame,think] notation");
2541             retval = false;
2542         }
2543
2544         if (retval && !parser_next(parser)) {
2545             retval = false;
2546         }
2547
2548         if (retval && parser->tok != '{') {
2549             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2550             retval = false;
2551         }
2552
2553         if (!retval) {
2554             ast_unref(nextthink);
2555             ast_unref(framenum);
2556             return false;
2557         }
2558
2559         has_frame_think = true;
2560     }
2561
2562     block = ast_block_new(parser_ctx(parser));
2563     if (!block) {
2564         parseerror(parser, "failed to allocate block");
2565         if (has_frame_think) {
2566             ast_unref(nextthink);
2567             ast_unref(framenum);
2568         }
2569         return false;
2570     }
2571
2572     if (has_frame_think) {
2573         lex_ctx ctx;
2574         ast_expression *self_frame;
2575         ast_expression *self_nextthink;
2576         ast_expression *self_think;
2577         ast_expression *time_plus_1;
2578         ast_store *store_frame;
2579         ast_store *store_nextthink;
2580         ast_store *store_think;
2581
2582         ctx = parser_ctx(parser);
2583         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2584         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2585         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2586
2587         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2588                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2589
2590         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2591             if (self_frame)     ast_delete(self_frame);
2592             if (self_nextthink) ast_delete(self_nextthink);
2593             if (self_think)     ast_delete(self_think);
2594             if (time_plus_1)    ast_delete(time_plus_1);
2595             retval = false;
2596         }
2597
2598         if (retval)
2599         {
2600             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2601             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2602             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2603
2604             if (!store_frame) {
2605                 ast_delete(self_frame);
2606                 retval = false;
2607             }
2608             if (!store_nextthink) {
2609                 ast_delete(self_nextthink);
2610                 retval = false;
2611             }
2612             if (!store_think) {
2613                 ast_delete(self_think);
2614                 retval = false;
2615             }
2616             if (!retval) {
2617                 if (store_frame)     ast_delete(store_frame);
2618                 if (store_nextthink) ast_delete(store_nextthink);
2619                 if (store_think)     ast_delete(store_think);
2620                 retval = false;
2621             }
2622             vec_push(block->exprs, (ast_expression*)store_frame);
2623             vec_push(block->exprs, (ast_expression*)store_nextthink);
2624             vec_push(block->exprs, (ast_expression*)store_think);
2625         }
2626
2627         if (!retval) {
2628             parseerror(parser, "failed to generate code for [frame,think]");
2629             ast_unref(nextthink);
2630             ast_unref(framenum);
2631             ast_delete(block);
2632             return false;
2633         }
2634     }
2635
2636     parser_enterblock(parser);
2637
2638     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2639         size_t     e;
2640         ast_value *param = var->expression.params[parami];
2641         ast_member *me[3];
2642
2643         if (param->expression.vtype != TYPE_VECTOR &&
2644             (param->expression.vtype != TYPE_FIELD ||
2645              param->expression.next->expression.vtype != TYPE_VECTOR))
2646         {
2647             continue;
2648         }
2649
2650         if (!create_vector_members(param, me)) {
2651             ast_block_delete(block);
2652             return false;
2653         }
2654
2655         for (e = 0; e < 3; ++e) {
2656             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2657             ast_block_collect(block, (ast_expression*)me[e]);
2658         }
2659     }
2660
2661     func = ast_function_new(ast_ctx(var), var->name, var);
2662     if (!func) {
2663         parseerror(parser, "failed to allocate function for `%s`", var->name);
2664         ast_block_delete(block);
2665         goto enderr;
2666     }
2667     vec_push(parser->functions, func);
2668
2669     parser->function = func;
2670     if (!parse_block_into(parser, block, true)) {
2671         ast_block_delete(block);
2672         goto enderrfn;
2673     }
2674
2675     vec_push(func->blocks, block);
2676
2677     parser->function = old;
2678     if (!parser_leaveblock(parser))
2679         retval = false;
2680     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2681         parseerror(parser, "internal error: local scopes left");
2682         retval = false;
2683     }
2684
2685     if (parser->tok == ';')
2686         return parser_next(parser);
2687     else if (opts_standard == COMPILER_QCC)
2688         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2689     return retval;
2690
2691 enderrfn:
2692     vec_pop(parser->functions);
2693     ast_function_delete(func);
2694     var->constval.vfunc = NULL;
2695
2696 enderr:
2697     (void)!parser_leaveblock(parser);
2698     parser->function = old;
2699     return false;
2700 }
2701
2702 static ast_expression *array_accessor_split(
2703     parser_t  *parser,
2704     ast_value *array,
2705     ast_value *index,
2706     size_t     middle,
2707     ast_expression *left,
2708     ast_expression *right
2709     )
2710 {
2711     ast_ifthen *ifthen;
2712     ast_binary *cmp;
2713
2714     lex_ctx ctx = ast_ctx(array);
2715
2716     if (!left || !right) {
2717         if (left)  ast_delete(left);
2718         if (right) ast_delete(right);
2719         return NULL;
2720     }
2721
2722     cmp = ast_binary_new(ctx, INSTR_LT,
2723                          (ast_expression*)index,
2724                          (ast_expression*)parser_const_float(parser, middle));
2725     if (!cmp) {
2726         ast_delete(left);
2727         ast_delete(right);
2728         parseerror(parser, "internal error: failed to create comparison for array setter");
2729         return NULL;
2730     }
2731
2732     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2733     if (!ifthen) {
2734         ast_delete(cmp); /* will delete left and right */
2735         parseerror(parser, "internal error: failed to create conditional jump for array setter");
2736         return NULL;
2737     }
2738
2739     return (ast_expression*)ifthen;
2740 }
2741
2742 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2743 {
2744     lex_ctx ctx = ast_ctx(array);
2745
2746     if (from+1 == afterend) {
2747         /* set this value */
2748         ast_block       *block;
2749         ast_return      *ret;
2750         ast_array_index *subscript;
2751         ast_store       *st;
2752         int assignop = type_store_instr[value->expression.vtype];
2753
2754         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2755             assignop = INSTR_STORE_V;
2756
2757         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2758         if (!subscript)
2759             return NULL;
2760
2761         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2762         if (!st) {
2763             ast_delete(subscript);
2764             return NULL;
2765         }
2766
2767         block = ast_block_new(ctx);
2768         if (!block) {
2769             ast_delete(st);
2770             return NULL;
2771         }
2772
2773         vec_push(block->exprs, (ast_expression*)st);
2774
2775         ret = ast_return_new(ctx, NULL);
2776         if (!ret) {
2777             ast_delete(block);
2778             return NULL;
2779         }
2780
2781         vec_push(block->exprs, (ast_expression*)ret);
2782
2783         return (ast_expression*)block;
2784     } else {
2785         ast_expression *left, *right;
2786         size_t diff = afterend - from;
2787         size_t middle = from + diff/2;
2788         left  = array_setter_node(parser, array, index, value, from, middle);
2789         right = array_setter_node(parser, array, index, value, middle, afterend);
2790         return array_accessor_split(parser, array, index, middle, left, right);
2791     }
2792 }
2793
2794 static ast_expression *array_field_setter_node(
2795     parser_t  *parser,
2796     ast_value *array,
2797     ast_value *entity,
2798     ast_value *index,
2799     ast_value *value,
2800     size_t     from,
2801     size_t     afterend)
2802 {
2803     lex_ctx ctx = ast_ctx(array);
2804
2805     if (from+1 == afterend) {
2806         /* set this value */
2807         ast_block       *block;
2808         ast_return      *ret;
2809         ast_entfield    *entfield;
2810         ast_array_index *subscript;
2811         ast_store       *st;
2812         int assignop = type_storep_instr[value->expression.vtype];
2813
2814         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2815             assignop = INSTR_STOREP_V;
2816
2817         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2818         if (!subscript)
2819             return NULL;
2820
2821         entfield = ast_entfield_new_force(ctx,
2822                                           (ast_expression*)entity,
2823                                           (ast_expression*)subscript,
2824                                           (ast_expression*)subscript);
2825         if (!entfield) {
2826             ast_delete(subscript);
2827             return NULL;
2828         }
2829
2830         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2831         if (!st) {
2832             ast_delete(entfield);
2833             return NULL;
2834         }
2835
2836         block = ast_block_new(ctx);
2837         if (!block) {
2838             ast_delete(st);
2839             return NULL;
2840         }
2841
2842         vec_push(block->exprs, (ast_expression*)st);
2843
2844         ret = ast_return_new(ctx, NULL);
2845         if (!ret) {
2846             ast_delete(block);
2847             return NULL;
2848         }
2849
2850         vec_push(block->exprs, (ast_expression*)ret);
2851
2852         return (ast_expression*)block;
2853     } else {
2854         ast_expression *left, *right;
2855         size_t diff = afterend - from;
2856         size_t middle = from + diff/2;
2857         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
2858         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2859         return array_accessor_split(parser, array, index, middle, left, right);
2860     }
2861 }
2862
2863 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2864 {
2865     lex_ctx ctx = ast_ctx(array);
2866
2867     if (from+1 == afterend) {
2868         ast_return      *ret;
2869         ast_array_index *subscript;
2870
2871         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2872         if (!subscript)
2873             return NULL;
2874
2875         ret = ast_return_new(ctx, (ast_expression*)subscript);
2876         if (!ret) {
2877             ast_delete(subscript);
2878             return NULL;
2879         }
2880
2881         return (ast_expression*)ret;
2882     } else {
2883         ast_expression *left, *right;
2884         size_t diff = afterend - from;
2885         size_t middle = from + diff/2;
2886         left  = array_getter_node(parser, array, index, from, middle);
2887         right = array_getter_node(parser, array, index, middle, afterend);
2888         return array_accessor_split(parser, array, index, middle, left, right);
2889     }
2890 }
2891
2892 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2893 {
2894     ast_function   *func = NULL;
2895     ast_value      *fval = NULL;
2896     ast_block      *body = NULL;
2897
2898     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2899     if (!fval) {
2900         parseerror(parser, "failed to create accessor function value");
2901         return false;
2902     }
2903
2904     func = ast_function_new(ast_ctx(array), funcname, fval);
2905     if (!func) {
2906         ast_delete(fval);
2907         parseerror(parser, "failed to create accessor function node");
2908         return false;
2909     }
2910
2911     body = ast_block_new(ast_ctx(array));
2912     if (!body) {
2913         parseerror(parser, "failed to create block for array accessor");
2914         ast_delete(fval);
2915         ast_delete(func);
2916         return false;
2917     }
2918
2919     vec_push(func->blocks, body);
2920     *out = fval;
2921
2922     vec_push(parser->accessors, fval);
2923
2924     return true;
2925 }
2926
2927 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2928 {
2929     ast_expression *root = NULL;
2930     ast_value      *index = NULL;
2931     ast_value      *value = NULL;
2932     ast_function   *func;
2933     ast_value      *fval;
2934
2935     if (!ast_istype(array->expression.next, ast_value)) {
2936         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2937         return false;
2938     }
2939
2940     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2941         return false;
2942     func = fval->constval.vfunc;
2943     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2944
2945     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2946     value = ast_value_copy((ast_value*)array->expression.next);
2947
2948     if (!index || !value) {
2949         parseerror(parser, "failed to create locals for array accessor");
2950         goto cleanup;
2951     }
2952     (void)!ast_value_set_name(value, "value"); /* not important */
2953     vec_push(fval->expression.params, index);
2954     vec_push(fval->expression.params, value);
2955
2956     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2957     if (!root) {
2958         parseerror(parser, "failed to build accessor search tree");
2959         goto cleanup;
2960     }
2961
2962     vec_push(func->blocks[0]->exprs, root);
2963     array->setter = fval;
2964     return true;
2965 cleanup:
2966     if (index) ast_delete(index);
2967     if (value) ast_delete(value);
2968     if (root)  ast_delete(root);
2969     ast_delete(func);
2970     ast_delete(fval);
2971     return false;
2972 }
2973
2974 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2975 {
2976     ast_expression *root = NULL;
2977     ast_value      *entity = NULL;
2978     ast_value      *index = NULL;
2979     ast_value      *value = NULL;
2980     ast_function   *func;
2981     ast_value      *fval;
2982
2983     if (!ast_istype(array->expression.next, ast_value)) {
2984         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2985         return false;
2986     }
2987
2988     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2989         return false;
2990     func = fval->constval.vfunc;
2991     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2992
2993     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2994     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
2995     value  = ast_value_copy((ast_value*)array->expression.next);
2996     if (!entity || !index || !value) {
2997         parseerror(parser, "failed to create locals for array accessor");
2998         goto cleanup;
2999     }
3000     (void)!ast_value_set_name(value, "value"); /* not important */
3001     vec_push(fval->expression.params, entity);
3002     vec_push(fval->expression.params, index);
3003     vec_push(fval->expression.params, value);
3004
3005     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3006     if (!root) {
3007         parseerror(parser, "failed to build accessor search tree");
3008         goto cleanup;
3009     }
3010
3011     vec_push(func->blocks[0]->exprs, root);
3012     array->setter = fval;
3013     return true;
3014 cleanup:
3015     if (entity) ast_delete(entity);
3016     if (index)  ast_delete(index);
3017     if (value)  ast_delete(value);
3018     if (root)   ast_delete(root);
3019     ast_delete(func);
3020     ast_delete(fval);
3021     return false;
3022 }
3023
3024 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3025 {
3026     ast_expression *root = NULL;
3027     ast_value      *index = NULL;
3028     ast_value      *fval;
3029     ast_function   *func;
3030
3031     /* NOTE: checking array->expression.next rather than elemtype since
3032      * for fields elemtype is a temporary fieldtype.
3033      */
3034     if (!ast_istype(array->expression.next, ast_value)) {
3035         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3036         return false;
3037     }
3038
3039     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3040         return false;
3041     func = fval->constval.vfunc;
3042     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3043
3044     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3045
3046     if (!index) {
3047         parseerror(parser, "failed to create locals for array accessor");
3048         goto cleanup;
3049     }
3050     vec_push(fval->expression.params, index);
3051
3052     root = array_getter_node(parser, array, index, 0, array->expression.count);
3053     if (!root) {
3054         parseerror(parser, "failed to build accessor search tree");
3055         goto cleanup;
3056     }
3057
3058     vec_push(func->blocks[0]->exprs, root);
3059     array->getter = fval;
3060     return true;
3061 cleanup:
3062     if (index) ast_delete(index);
3063     if (root)  ast_delete(root);
3064     ast_delete(func);
3065     ast_delete(fval);
3066     return false;
3067 }
3068
3069 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3070 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3071 {
3072     lex_ctx     ctx;
3073     size_t      i;
3074     ast_value **params;
3075     ast_value  *param;
3076     ast_value  *fval;
3077     bool        first = true;
3078     bool        variadic = false;
3079
3080     ctx = parser_ctx(parser);
3081
3082     /* for the sake of less code we parse-in in this function */
3083     if (!parser_next(parser)) {
3084         parseerror(parser, "expected parameter list");
3085         return NULL;
3086     }
3087
3088     params = NULL;
3089
3090     /* parse variables until we hit a closing paren */
3091     while (parser->tok != ')') {
3092         if (!first) {
3093             /* there must be commas between them */
3094             if (parser->tok != ',') {
3095                 parseerror(parser, "expected comma or end of parameter list");
3096                 goto on_error;
3097             }
3098             if (!parser_next(parser)) {
3099                 parseerror(parser, "expected parameter");
3100                 goto on_error;
3101             }
3102         }
3103         first = false;
3104
3105         if (parser->tok == TOKEN_DOTS) {
3106             /* '...' indicates a varargs function */
3107             variadic = true;
3108             if (!parser_next(parser)) {
3109                 parseerror(parser, "expected parameter");
3110                 return NULL;
3111             }
3112             if (parser->tok != ')') {
3113                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3114                 goto on_error;
3115             }
3116         }
3117         else
3118         {
3119             /* for anything else just parse a typename */
3120             param = parse_typename(parser, NULL, NULL);
3121             if (!param)
3122                 goto on_error;
3123             vec_push(params, param);
3124             if (param->expression.vtype >= TYPE_VARIANT) {
3125                 char typename[1024];
3126                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3127                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3128                 goto on_error;
3129             }
3130         }
3131     }
3132
3133     /* sanity check */
3134     if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3135         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3136
3137     /* parse-out */
3138     if (!parser_next(parser)) {
3139         parseerror(parser, "parse error after typename");
3140         goto on_error;
3141     }
3142
3143     /* now turn 'var' into a function type */
3144     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3145     fval->expression.next     = (ast_expression*)var;
3146     fval->expression.variadic = variadic;
3147     var = fval;
3148
3149     var->expression.params = params;
3150     params = NULL;
3151
3152     return var;
3153
3154 on_error:
3155     ast_delete(var);
3156     for (i = 0; i < vec_size(params); ++i)
3157         ast_delete(params[i]);
3158     vec_free(params);
3159     return NULL;
3160 }
3161
3162 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3163 {
3164     ast_expression *cexp;
3165     ast_value      *cval, *tmp;
3166     lex_ctx ctx;
3167
3168     ctx = parser_ctx(parser);
3169
3170     if (!parser_next(parser)) {
3171         ast_delete(var);
3172         parseerror(parser, "expected array-size");
3173         return NULL;
3174     }
3175
3176     cexp = parse_expression_leave(parser, true);
3177
3178     if (!cexp || !ast_istype(cexp, ast_value)) {
3179         if (cexp)
3180             ast_unref(cexp);
3181         ast_delete(var);
3182         parseerror(parser, "expected array-size as constant positive integer");
3183         return NULL;
3184     }
3185     cval = (ast_value*)cexp;
3186
3187     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3188     tmp->expression.next = (ast_expression*)var;
3189     var = tmp;
3190
3191     if (cval->expression.vtype == TYPE_INTEGER)
3192         tmp->expression.count = cval->constval.vint;
3193     else if (cval->expression.vtype == TYPE_FLOAT)
3194         tmp->expression.count = cval->constval.vfloat;
3195     else {
3196         ast_unref(cexp);
3197         ast_delete(var);
3198         parseerror(parser, "array-size must be a positive integer constant");
3199         return NULL;
3200     }
3201     ast_unref(cexp);
3202
3203     if (parser->tok != ']') {
3204         ast_delete(var);
3205         parseerror(parser, "expected ']' after array-size");
3206         return NULL;
3207     }
3208     if (!parser_next(parser)) {
3209         ast_delete(var);
3210         parseerror(parser, "error after parsing array size");
3211         return NULL;
3212     }
3213     return var;
3214 }
3215
3216 /* Parse a complete typename.
3217  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3218  * but when parsing variables separated by comma
3219  * 'storebase' should point to where the base-type should be kept.
3220  * The base type makes up every bit of type information which comes *before* the
3221  * variable name.
3222  *
3223  * The following will be parsed in its entirety:
3224  *     void() foo()
3225  * The 'basetype' in this case is 'void()'
3226  * and if there's a comma after it, say:
3227  *     void() foo(), bar
3228  * then the type-information 'void()' can be stored in 'storebase'
3229  */
3230 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3231 {
3232     ast_value *var, *tmp;
3233     lex_ctx    ctx;
3234
3235     const char *name = NULL;
3236     bool        isfield  = false;
3237     bool        wasarray = false;
3238     size_t      morefields = 0;
3239
3240     ctx = parser_ctx(parser);
3241
3242     /* types may start with a dot */
3243     if (parser->tok == '.') {
3244         isfield = true;
3245         /* if we parsed a dot we need a typename now */
3246         if (!parser_next(parser)) {
3247             parseerror(parser, "expected typename for field definition");
3248             return NULL;
3249         }
3250
3251         /* Further dots are handled seperately because they won't be part of the
3252          * basetype
3253          */
3254         while (parser->tok == '.') {
3255             ++morefields;
3256             if (!parser_next(parser)) {
3257                 parseerror(parser, "expected typename for field definition");
3258                 return NULL;
3259             }
3260         }
3261
3262         if (parser->tok == TOKEN_IDENT)
3263             cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3264         if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3265             parseerror(parser, "expected typename");
3266             return NULL;
3267         }
3268     }
3269
3270     /* generate the basic type value */
3271     if (cached_typedef) {
3272         var = ast_value_copy(cached_typedef);
3273         ast_value_set_name(var, "<type(from_def)>");
3274     } else
3275         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3276
3277     for (; morefields; --morefields) {
3278         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3279         tmp->expression.next = (ast_expression*)var;
3280         var = tmp;
3281     }
3282
3283     /* do not yet turn into a field - remember:
3284      * .void() foo; is a field too
3285      * .void()() foo; is a function
3286      */
3287
3288     /* parse on */
3289     if (!parser_next(parser)) {
3290         ast_delete(var);
3291         parseerror(parser, "parse error after typename");
3292         return NULL;
3293     }
3294
3295     /* an opening paren now starts the parameter-list of a function
3296      * this is where original-QC has parameter lists.
3297      * We allow a single parameter list here.
3298      * Much like fteqcc we don't allow `float()() x`
3299      */
3300     if (parser->tok == '(') {
3301         var = parse_parameter_list(parser, var);
3302         if (!var)
3303             return NULL;
3304     }
3305
3306     /* store the base if requested */
3307     if (storebase) {
3308         *storebase = ast_value_copy(var);
3309         if (isfield) {
3310             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3311             tmp->expression.next = (ast_expression*)*storebase;
3312             *storebase = tmp;
3313         }
3314     }
3315
3316     /* there may be a name now */
3317     if (parser->tok == TOKEN_IDENT) {
3318         name = util_strdup(parser_tokval(parser));
3319         /* parse on */
3320         if (!parser_next(parser)) {
3321             ast_delete(var);
3322             parseerror(parser, "error after variable or field declaration");
3323             return NULL;
3324         }
3325     }
3326
3327     /* now this may be an array */
3328     if (parser->tok == '[') {
3329         wasarray = true;
3330         var = parse_arraysize(parser, var);
3331         if (!var)
3332             return NULL;
3333     }
3334
3335     /* This is the point where we can turn it into a field */
3336     if (isfield) {
3337         /* turn it into a field if desired */
3338         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3339         tmp->expression.next = (ast_expression*)var;
3340         var = tmp;
3341     }
3342
3343     /* now there may be function parens again */
3344     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3345         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3346     if (parser->tok == '(' && wasarray)
3347         parseerror(parser, "arrays as part of a return type is not supported");
3348     while (parser->tok == '(') {
3349         var = parse_parameter_list(parser, var);
3350         if (!var) {
3351             if (name)
3352                 mem_d((void*)name);
3353             ast_delete(var);
3354             return NULL;
3355         }
3356     }
3357
3358     /* finally name it */
3359     if (name) {
3360         if (!ast_value_set_name(var, name)) {
3361             ast_delete(var);
3362             parseerror(parser, "internal error: failed to set name");
3363             return NULL;
3364         }
3365         /* free the name, ast_value_set_name duplicates */
3366         mem_d((void*)name);
3367     }
3368
3369     return var;
3370 }
3371
3372 static bool parse_typedef(parser_t *parser)
3373 {
3374     ast_value      *typevar, *oldtype;
3375     ast_expression *old;
3376
3377     typevar = parse_typename(parser, NULL, NULL);
3378
3379     if (!typevar)
3380         return false;
3381
3382     if ( (old = parser_find_var(parser, typevar->name)) ) {
3383         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3384                    " -> `%s` has been declared here: %s:%i",
3385                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3386         ast_delete(typevar);
3387         return false;
3388     }
3389
3390     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3391         parseerror(parser, "type `%s` has already been declared here: %s:%i",
3392                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3393         ast_delete(typevar);
3394         return false;
3395     }
3396
3397     vec_push(parser->_typedefs, typevar);
3398     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3399
3400     if (parser->tok != ';') {
3401         parseerror(parser, "expected semicolon after typedef");
3402         return false;
3403     }
3404     if (!parser_next(parser)) {
3405         parseerror(parser, "parse error after typedef");
3406         return false;
3407     }
3408
3409     return true;
3410 }
3411
3412 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const, ast_value *cached_typedef)
3413 {
3414     ast_value *var;
3415     ast_value *proto;
3416     ast_expression *old;
3417     bool       was_end;
3418     size_t     i;
3419
3420     ast_value *basetype = NULL;
3421     bool      retval    = true;
3422     bool      isparam   = false;
3423     bool      isvector  = false;
3424     bool      cleanvar  = true;
3425     bool      wasarray  = false;
3426
3427     ast_member *me[3];
3428
3429     /* get the first complete variable */
3430     var = parse_typename(parser, &basetype, cached_typedef);
3431     if (!var) {
3432         if (basetype)
3433             ast_delete(basetype);
3434         return false;
3435     }
3436
3437     while (true) {
3438         proto = NULL;
3439         wasarray = false;
3440
3441         /* Part 0: finish the type */
3442         if (parser->tok == '(') {
3443             if (opts_standard == COMPILER_QCC)
3444                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3445             var = parse_parameter_list(parser, var);
3446             if (!var) {
3447                 retval = false;
3448                 goto cleanup;
3449             }
3450         }
3451         /* we only allow 1-dimensional arrays */
3452         if (parser->tok == '[') {
3453             wasarray = true;
3454             var = parse_arraysize(parser, var);
3455             if (!var) {
3456                 retval = false;
3457                 goto cleanup;
3458             }
3459         }
3460         if (parser->tok == '(' && wasarray) {
3461             parseerror(parser, "arrays as part of a return type is not supported");
3462             /* we'll still parse the type completely for now */
3463         }
3464         /* for functions returning functions */
3465         while (parser->tok == '(') {
3466             if (opts_standard == COMPILER_QCC)
3467                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3468             var = parse_parameter_list(parser, var);
3469             if (!var) {
3470                 retval = false;
3471                 goto cleanup;
3472             }
3473         }
3474
3475         /* Part 1:
3476          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3477          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3478          * is then filled with the previous definition and the parameter-names replaced.
3479          */
3480         if (!localblock) {
3481             /* Deal with end_sys_ vars */
3482             was_end = false;
3483             if (!strcmp(var->name, "end_sys_globals")) {
3484                 parser->crc_globals = vec_size(parser->globals);
3485                 was_end = true;
3486             }
3487             else if (!strcmp(var->name, "end_sys_fields")) {
3488                 parser->crc_fields = vec_size(parser->fields);
3489                 was_end = true;
3490             }
3491             if (was_end && var->expression.vtype == TYPE_FIELD) {
3492                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3493                                  "global '%s' hint should not be a field",
3494                                  parser_tokval(parser)))
3495                 {
3496                     retval = false;
3497                     goto cleanup;
3498                 }
3499             }
3500
3501             if (!nofields && var->expression.vtype == TYPE_FIELD)
3502             {
3503                 /* deal with field declarations */
3504                 old = parser_find_field(parser, var->name);
3505                 if (old) {
3506                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3507                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3508                     {
3509                         retval = false;
3510                         goto cleanup;
3511                     }
3512                     ast_delete(var);
3513                     var = NULL;
3514                     goto skipvar;
3515                     /*
3516                     parseerror(parser, "field `%s` already declared here: %s:%i",
3517                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3518                     retval = false;
3519                     goto cleanup;
3520                     */
3521                 }
3522                 if (opts_standard == COMPILER_QCC &&
3523                     (old = parser_find_global(parser, var->name)))
3524                 {
3525                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3526                     parseerror(parser, "field `%s` already declared here: %s:%i",
3527                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3528                     retval = false;
3529                     goto cleanup;
3530                 }
3531             }
3532             else
3533             {
3534                 /* deal with other globals */
3535                 old = parser_find_global(parser, var->name);
3536                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3537                 {
3538                     /* This is a function which had a prototype */
3539                     if (!ast_istype(old, ast_value)) {
3540                         parseerror(parser, "internal error: prototype is not an ast_value");
3541                         retval = false;
3542                         goto cleanup;
3543                     }
3544                     proto = (ast_value*)old;
3545                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3546                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3547                                    proto->name,
3548                                    ast_ctx(proto).file, ast_ctx(proto).line);
3549                         retval = false;
3550                         goto cleanup;
3551                     }
3552                     /* we need the new parameter-names */
3553                     for (i = 0; i < vec_size(proto->expression.params); ++i)
3554                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3555                     ast_delete(var);
3556                     var = proto;
3557                 }
3558                 else
3559                 {
3560                     /* other globals */
3561                     if (old) {
3562                         if (opts_standard == COMPILER_GMQCC) {
3563                             parseerror(parser, "global `%s` already declared here: %s:%i",
3564                                        var->name, ast_ctx(old).file, ast_ctx(old).line);
3565                             retval = false;
3566                             goto cleanup;
3567                         } else {
3568                             if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3569                                              "global `%s` already declared here: %s:%i",
3570                                              var->name, ast_ctx(old).file, ast_ctx(old).line))
3571                             {
3572                                 retval = false;
3573                                 goto cleanup;
3574                             }
3575                         }
3576                     }
3577                     if (opts_standard == COMPILER_QCC &&
3578                         (old = parser_find_field(parser, var->name)))
3579                     {
3580                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3581                         parseerror(parser, "global `%s` already declared here: %s:%i",
3582                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3583                         retval = false;
3584                         goto cleanup;
3585                     }
3586                 }
3587             }
3588         }
3589         else /* it's not a global */
3590         {
3591             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3592             if (old && !isparam) {
3593                 parseerror(parser, "local `%s` already declared here: %s:%i",
3594                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3595                 retval = false;
3596                 goto cleanup;
3597             }
3598             old = parser_find_local(parser, var->name, 0, &isparam);
3599             if (old && isparam) {
3600                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3601                                  "local `%s` is shadowing a parameter", var->name))
3602                 {
3603                     parseerror(parser, "local `%s` already declared here: %s:%i",
3604                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3605                     retval = false;
3606                     goto cleanup;
3607                 }
3608                 if (opts_standard != COMPILER_GMQCC) {
3609                     ast_delete(var);
3610                     var = NULL;
3611                     goto skipvar;
3612                 }
3613             }
3614         }
3615
3616         if (is_const)
3617             var->isconst = true;
3618
3619         /* Part 2:
3620          * Create the global/local, and deal with vector types.
3621          */
3622         if (!proto) {
3623             if (var->expression.vtype == TYPE_VECTOR)
3624                 isvector = true;
3625             else if (var->expression.vtype == TYPE_FIELD &&
3626                      var->expression.next->expression.vtype == TYPE_VECTOR)
3627                 isvector = true;
3628
3629             if (isvector) {
3630                 if (!create_vector_members(var, me)) {
3631                     retval = false;
3632                     goto cleanup;
3633                 }
3634             }
3635
3636             if (!localblock) {
3637                 /* deal with global variables, fields, functions */
3638                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3639                     vec_push(parser->fields, (ast_expression*)var);
3640                     util_htset(parser->htfields, var->name, var);
3641                     if (isvector) {
3642                         for (i = 0; i < 3; ++i) {
3643                             vec_push(parser->fields, (ast_expression*)me[i]);
3644                             util_htset(parser->htfields, me[i]->name, me[i]);
3645                         }
3646                     }
3647                 }
3648                 else {
3649                     vec_push(parser->globals, (ast_expression*)var);
3650                     util_htset(parser->htglobals, var->name, var);
3651                     if (isvector) {
3652                         for (i = 0; i < 3; ++i) {
3653                             vec_push(parser->globals, (ast_expression*)me[i]);
3654                             util_htset(parser->htglobals, me[i]->name, me[i]);
3655                         }
3656                     }
3657                 }
3658             } else {
3659                 vec_push(localblock->locals, var);
3660                 parser_addlocal(parser, var->name, (ast_expression*)var);
3661                 if (isvector) {
3662                     for (i = 0; i < 3; ++i) {
3663                         parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3664                         ast_block_collect(localblock, (ast_expression*)me[i]);
3665                     }
3666                 }
3667             }
3668
3669         }
3670         me[0] = me[1] = me[2] = NULL;
3671         cleanvar = false;
3672         /* Part 2.2
3673          * deal with arrays
3674          */
3675         if (var->expression.vtype == TYPE_ARRAY) {
3676             char name[1024];
3677             snprintf(name, sizeof(name), "%s##SET", var->name);
3678             if (!parser_create_array_setter(parser, var, name))
3679                 goto cleanup;
3680             snprintf(name, sizeof(name), "%s##GET", var->name);
3681             if (!parser_create_array_getter(parser, var, var->expression.next, name))
3682                 goto cleanup;
3683         }
3684         else if (!localblock && !nofields &&
3685                  var->expression.vtype == TYPE_FIELD &&
3686                  var->expression.next->expression.vtype == TYPE_ARRAY)
3687         {
3688             char name[1024];
3689             ast_expression *telem;
3690             ast_value      *tfield;
3691             ast_value      *array = (ast_value*)var->expression.next;
3692
3693             if (!ast_istype(var->expression.next, ast_value)) {
3694                 parseerror(parser, "internal error: field element type must be an ast_value");
3695                 goto cleanup;
3696             }
3697
3698             snprintf(name, sizeof(name), "%s##SETF", var->name);
3699             if (!parser_create_array_field_setter(parser, array, name))
3700                 goto cleanup;
3701
3702             telem = ast_type_copy(ast_ctx(var), array->expression.next);
3703             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3704             tfield->expression.next = telem;
3705             snprintf(name, sizeof(name), "%s##GETFP", var->name);
3706             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3707                 ast_delete(tfield);
3708                 goto cleanup;
3709             }
3710             ast_delete(tfield);
3711         }
3712
3713 skipvar:
3714         if (parser->tok == ';') {
3715             ast_delete(basetype);
3716             if (!parser_next(parser)) {
3717                 parseerror(parser, "error after variable declaration");
3718                 return false;
3719             }
3720             return true;
3721         }
3722
3723         if (parser->tok == ',')
3724             goto another;
3725
3726         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3727             parseerror(parser, "missing comma or semicolon while parsing variables");
3728             break;
3729         }
3730
3731         if (localblock && opts_standard == COMPILER_QCC) {
3732             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3733                              "initializing expression turns variable `%s` into a constant in this standard",
3734                              var->name) )
3735             {
3736                 break;
3737             }
3738         }
3739
3740         if (parser->tok != '{') {
3741             if (parser->tok != '=') {
3742                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
3743                 break;
3744             }
3745
3746             if (!parser_next(parser)) {
3747                 parseerror(parser, "error parsing initializer");
3748                 break;
3749             }
3750         }
3751         else if (opts_standard == COMPILER_QCC) {
3752             parseerror(parser, "expected '=' before function body in this standard");
3753         }
3754
3755         if (parser->tok == '#') {
3756             ast_function *func = NULL;
3757
3758             if (localblock) {
3759                 parseerror(parser, "cannot declare builtins within functions");
3760                 break;
3761             }
3762             if (var->expression.vtype != TYPE_FUNCTION) {
3763                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3764                 break;
3765             }
3766             if (!parser_next(parser)) {
3767                 parseerror(parser, "expected builtin number");
3768                 break;
3769             }
3770             if (parser->tok != TOKEN_INTCONST) {
3771                 parseerror(parser, "builtin number must be an integer constant");
3772                 break;
3773             }
3774             if (parser_token(parser)->constval.i <= 0) {
3775                 parseerror(parser, "builtin number must be an integer greater than zero");
3776                 break;
3777             }
3778
3779             if (var->isconst) {
3780                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
3781                                     "builtin `%s` has already been defined\n"
3782                                     " -> previous declaration here: %s:%i",
3783                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
3784             }
3785             else
3786             {
3787                 func = ast_function_new(ast_ctx(var), var->name, var);
3788                 if (!func) {
3789                     parseerror(parser, "failed to allocate function for `%s`", var->name);
3790                     break;
3791                 }
3792                 vec_push(parser->functions, func);
3793
3794                 func->builtin = -parser_token(parser)->constval.i;
3795             }
3796
3797             if (!parser_next(parser)) {
3798                 parseerror(parser, "expected comma or semicolon");
3799                 if (func)
3800                     ast_function_delete(func);
3801                 var->constval.vfunc = NULL;
3802                 break;
3803             }
3804         }
3805         else if (parser->tok == '{' || parser->tok == '[')
3806         {
3807             if (localblock) {
3808                 parseerror(parser, "cannot declare functions within functions");
3809                 break;
3810             }
3811
3812             if (!parse_function_body(parser, var))
3813                 break;
3814             ast_delete(basetype);
3815             return true;
3816         } else {
3817             ast_expression *cexp;
3818             ast_value      *cval;
3819
3820             cexp = parse_expression_leave(parser, true);
3821             if (!cexp)
3822                 break;
3823
3824             if (!localblock) {
3825                 cval = (ast_value*)cexp;
3826                 if (!ast_istype(cval, ast_value) || !cval->isconst)
3827                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3828                 else
3829                 {
3830                     var->isconst = true;
3831                     if (cval->expression.vtype == TYPE_STRING)
3832                         var->constval.vstring = parser_strdup(cval->constval.vstring);
3833                     else
3834                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3835                     ast_unref(cval);
3836                 }
3837             } else {
3838                 shunt sy = { NULL, NULL };
3839                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3840                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3841                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3842                 if (!parser_sy_pop(parser, &sy))
3843                     ast_unref(cexp);
3844                 else {
3845                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3846                         parseerror(parser, "internal error: leaked operands");
3847                     vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3848                 }
3849                 vec_free(sy.out);
3850                 vec_free(sy.ops);
3851             }
3852         }
3853
3854 another:
3855         if (parser->tok == ',') {
3856             if (!parser_next(parser)) {
3857                 parseerror(parser, "expected another variable");
3858                 break;
3859             }
3860
3861             if (parser->tok != TOKEN_IDENT) {
3862                 parseerror(parser, "expected another variable");
3863                 break;
3864             }
3865             var = ast_value_copy(basetype);
3866             cleanvar = true;
3867             ast_value_set_name(var, parser_tokval(parser));
3868             if (!parser_next(parser)) {
3869                 parseerror(parser, "error parsing variable declaration");
3870                 break;
3871             }
3872             continue;
3873         }
3874
3875         if (parser->tok != ';') {
3876             parseerror(parser, "missing semicolon after variables");
3877             break;
3878         }
3879
3880         if (!parser_next(parser)) {
3881             parseerror(parser, "parse error after variable declaration");
3882             break;
3883         }
3884
3885         ast_delete(basetype);
3886         return true;
3887     }
3888
3889     if (cleanvar && var)
3890         ast_delete(var);
3891     ast_delete(basetype);
3892     return false;
3893
3894 cleanup:
3895     ast_delete(basetype);
3896     if (cleanvar && var)
3897         ast_delete(var);
3898     if (me[0]) ast_member_delete(me[0]);
3899     if (me[1]) ast_member_delete(me[1]);
3900     if (me[2]) ast_member_delete(me[2]);
3901     return retval;
3902 }
3903
3904 static bool parser_global_statement(parser_t *parser)
3905 {
3906     ast_value *istype = NULL;
3907     if (parser->tok == TOKEN_IDENT)
3908         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
3909
3910     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3911     {
3912         return parse_variable(parser, NULL, false, false, istype);
3913     }
3914     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
3915     {
3916         if (!strcmp(parser_tokval(parser), "var")) {
3917             if (!parser_next(parser)) {
3918                 parseerror(parser, "expected variable declaration after 'var'");
3919                 return false;
3920             }
3921             return parse_variable(parser, NULL, true, false, NULL);
3922         }
3923     }
3924     else if (parser->tok == TOKEN_KEYWORD)
3925     {
3926         if (!strcmp(parser_tokval(parser), "const")) {
3927             if (!parser_next(parser)) {
3928                 parseerror(parser, "expected variable declaration after 'const'");
3929                 return false;
3930             }
3931             if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var")) {
3932                 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `var` after const qualifier");
3933                 if (!parser_next(parser)) {
3934                     parseerror(parser, "expected variable declaration after 'const var'");
3935                     return false;
3936                 }
3937             }
3938             return parse_variable(parser, NULL, true, true, NULL);
3939         }
3940         else if (!strcmp(parser_tokval(parser), "typedef")) {
3941             if (!parser_next(parser)) {
3942                 parseerror(parser, "expected type definition after 'typedef'");
3943                 return false;
3944             }
3945             return parse_typedef(parser);
3946         }
3947         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
3948         return false;
3949     }
3950     else if (parser->tok == '$')
3951     {
3952         if (!parser_next(parser)) {
3953             parseerror(parser, "parse error");
3954             return false;
3955         }
3956     }
3957     else
3958     {
3959         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3960         return false;
3961     }
3962     return true;
3963 }
3964
3965 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3966 {
3967     return util_crc16(old, str, strlen(str));
3968 }
3969
3970 static void progdefs_crc_file(const char *str)
3971 {
3972     /* write to progdefs.h here */
3973     (void)str;
3974 }
3975
3976 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3977 {
3978     old = progdefs_crc_sum(old, str);
3979     progdefs_crc_file(str);
3980     return old;
3981 }
3982
3983 static void generate_checksum(parser_t *parser)
3984 {
3985     uint16_t   crc = 0xFFFF;
3986     size_t     i;
3987     ast_value *value;
3988
3989         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3990         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3991         /*
3992         progdefs_crc_file("\tint\tpad;\n");
3993         progdefs_crc_file("\tint\tofs_return[3];\n");
3994         progdefs_crc_file("\tint\tofs_parm0[3];\n");
3995         progdefs_crc_file("\tint\tofs_parm1[3];\n");
3996         progdefs_crc_file("\tint\tofs_parm2[3];\n");
3997         progdefs_crc_file("\tint\tofs_parm3[3];\n");
3998         progdefs_crc_file("\tint\tofs_parm4[3];\n");
3999         progdefs_crc_file("\tint\tofs_parm5[3];\n");
4000         progdefs_crc_file("\tint\tofs_parm6[3];\n");
4001         progdefs_crc_file("\tint\tofs_parm7[3];\n");
4002         */
4003         for (i = 0; i < parser->crc_globals; ++i) {
4004             if (!ast_istype(parser->globals[i], ast_value))
4005                 continue;
4006             value = (ast_value*)(parser->globals[i]);
4007             switch (value->expression.vtype) {
4008                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4009                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4010                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4011                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4012                 default:
4013                     crc = progdefs_crc_both(crc, "\tint\t");
4014                     break;
4015             }
4016             crc = progdefs_crc_both(crc, value->name);
4017             crc = progdefs_crc_both(crc, ";\n");
4018         }
4019         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4020         for (i = 0; i < parser->crc_fields; ++i) {
4021             if (!ast_istype(parser->fields[i], ast_value))
4022                 continue;
4023             value = (ast_value*)(parser->fields[i]);
4024             switch (value->expression.next->expression.vtype) {
4025                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4026                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4027                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4028                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4029                 default:
4030                     crc = progdefs_crc_both(crc, "\tint\t");
4031                     break;
4032             }
4033             crc = progdefs_crc_both(crc, value->name);
4034             crc = progdefs_crc_both(crc, ";\n");
4035         }
4036         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4037
4038         code_crc = crc;
4039 }
4040
4041 static parser_t *parser;
4042
4043 bool parser_init()
4044 {
4045     size_t i;
4046
4047     parser = (parser_t*)mem_a(sizeof(parser_t));
4048     if (!parser)
4049         return false;
4050
4051     memset(parser, 0, sizeof(*parser));
4052
4053     for (i = 0; i < operator_count; ++i) {
4054         if (operators[i].id == opid1('=')) {
4055             parser->assign_op = operators+i;
4056             break;
4057         }
4058     }
4059     if (!parser->assign_op) {
4060         printf("internal error: initializing parser: failed to find assign operator\n");
4061         mem_d(parser);
4062         return false;
4063     }
4064
4065     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
4066     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4067     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4068     vec_push(parser->_blocktypedefs, 0);
4069     return true;
4070 }
4071
4072 bool parser_compile()
4073 {
4074     /* initial lexer/parser state */
4075     parser->lex->flags.noops = true;
4076
4077     if (parser_next(parser))
4078     {
4079         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4080         {
4081             if (!parser_global_statement(parser)) {
4082                 if (parser->tok == TOKEN_EOF)
4083                     parseerror(parser, "unexpected eof");
4084                 else if (!parser->errors)
4085                     parseerror(parser, "there have been errors, bailing out");
4086                 lex_close(parser->lex);
4087                 parser->lex = NULL;
4088                 return false;
4089             }
4090         }
4091     } else {
4092         parseerror(parser, "parse error");
4093         lex_close(parser->lex);
4094         parser->lex = NULL;
4095         return false;
4096     }
4097
4098     lex_close(parser->lex);
4099     parser->lex = NULL;
4100
4101     return !parser->errors;
4102 }
4103
4104 bool parser_compile_file(const char *filename)
4105 {
4106     parser->lex = lex_open(filename);
4107     if (!parser->lex) {
4108         con_err("failed to open file \"%s\"\n", filename);
4109         return false;
4110     }
4111     return parser_compile();
4112 }
4113
4114 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4115 {
4116     parser->lex = lex_open_string(str, len, name);
4117     if (!parser->lex) {
4118         con_err("failed to create lexer for string \"%s\"\n", name);
4119         return false;
4120     }
4121     return parser_compile();
4122 }
4123
4124 bool parser_compile_string(const char *name, const char *str)
4125 {
4126     parser->lex = lex_open_string(str, strlen(str), name);
4127     if (!parser->lex) {
4128         con_err("failed to create lexer for string \"%s\"\n", name);
4129         return false;
4130     }
4131     return parser_compile();
4132 }
4133
4134 void parser_cleanup()
4135 {
4136     size_t i;
4137     for (i = 0; i < vec_size(parser->accessors); ++i) {
4138         ast_delete(parser->accessors[i]->constval.vfunc);
4139         parser->accessors[i]->constval.vfunc = NULL;
4140         ast_delete(parser->accessors[i]);
4141     }
4142     for (i = 0; i < vec_size(parser->functions); ++i) {
4143         ast_delete(parser->functions[i]);
4144     }
4145     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4146         ast_delete(parser->imm_vector[i]);
4147     }
4148     for (i = 0; i < vec_size(parser->imm_string); ++i) {
4149         ast_delete(parser->imm_string[i]);
4150     }
4151     for (i = 0; i < vec_size(parser->imm_float); ++i) {
4152         ast_delete(parser->imm_float[i]);
4153     }
4154     for (i = 0; i < vec_size(parser->fields); ++i) {
4155         ast_delete(parser->fields[i]);
4156     }
4157     for (i = 0; i < vec_size(parser->globals); ++i) {
4158         ast_delete(parser->globals[i]);
4159     }
4160     vec_free(parser->accessors);
4161     vec_free(parser->functions);
4162     vec_free(parser->imm_vector);
4163     vec_free(parser->imm_string);
4164     vec_free(parser->imm_float);
4165     vec_free(parser->globals);
4166     vec_free(parser->fields);
4167
4168     for (i = 0; i < vec_size(parser->variables); ++i)
4169         util_htdel(parser->variables[i]);
4170     vec_free(parser->variables);
4171     vec_free(parser->_blocklocals);
4172     vec_free(parser->_locals);
4173
4174     for (i = 0; i < vec_size(parser->_typedefs); ++i)
4175         ast_delete(parser->_typedefs[i]);
4176     vec_free(parser->_typedefs);
4177     for (i = 0; i < vec_size(parser->typedefs); ++i)
4178         util_htdel(parser->typedefs[i]);
4179     vec_free(parser->typedefs);
4180     vec_free(parser->_blocktypedefs);
4181
4182     mem_d(parser);
4183 }
4184
4185 bool parser_finish(const char *output)
4186 {
4187     size_t i;
4188     ir_builder *ir;
4189     bool retval = true;
4190
4191     if (!parser->errors)
4192     {
4193         ir = ir_builder_new("gmqcc_out");
4194         if (!ir) {
4195             con_out("failed to allocate builder\n");
4196             return false;
4197         }
4198
4199         for (i = 0; i < vec_size(parser->fields); ++i) {
4200             ast_value *field;
4201             bool isconst;
4202             if (!ast_istype(parser->fields[i], ast_value))
4203                 continue;
4204             field = (ast_value*)parser->fields[i];
4205             isconst = field->isconst;
4206             field->isconst = false;
4207             if (!ast_global_codegen((ast_value*)field, ir, true)) {
4208                 con_out("failed to generate field %s\n", field->name);
4209                 ir_builder_delete(ir);
4210                 return false;
4211             }
4212             if (isconst) {
4213                 ir_value *ifld;
4214                 ast_expression *subtype;
4215                 field->isconst = true;
4216                 subtype = field->expression.next;
4217                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4218                 if (subtype->expression.vtype == TYPE_FIELD)
4219                     ifld->fieldtype = subtype->expression.next->expression.vtype;
4220                 else if (subtype->expression.vtype == TYPE_FUNCTION)
4221                     ifld->outtype = subtype->expression.next->expression.vtype;
4222                 (void)!ir_value_set_field(field->ir_v, ifld);
4223             }
4224         }
4225         for (i = 0; i < vec_size(parser->globals); ++i) {
4226             ast_value *asvalue;
4227             if (!ast_istype(parser->globals[i], ast_value))
4228                 continue;
4229             asvalue = (ast_value*)(parser->globals[i]);
4230             if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
4231                 if (strcmp(asvalue->name, "end_sys_globals") &&
4232                     strcmp(asvalue->name, "end_sys_fields"))
4233                 {
4234                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4235                                                    "unused global: `%s`", asvalue->name);
4236                 }
4237             }
4238             if (!ast_global_codegen(asvalue, ir, false)) {
4239                 con_out("failed to generate global %s\n", asvalue->name);
4240                 ir_builder_delete(ir);
4241                 return false;
4242             }
4243         }
4244         for (i = 0; i < vec_size(parser->imm_float); ++i) {
4245             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4246                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4247                 ir_builder_delete(ir);
4248                 return false;
4249             }
4250         }
4251         for (i = 0; i < vec_size(parser->imm_string); ++i) {
4252             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4253                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4254                 ir_builder_delete(ir);
4255                 return false;
4256             }
4257         }
4258         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4259             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4260                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4261                 ir_builder_delete(ir);
4262                 return false;
4263             }
4264         }
4265         for (i = 0; i < vec_size(parser->globals); ++i) {
4266             ast_value *asvalue;
4267             if (!ast_istype(parser->globals[i], ast_value))
4268                 continue;
4269             asvalue = (ast_value*)(parser->globals[i]);
4270             if (asvalue->setter) {
4271                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4272                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4273                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4274                 {
4275                     printf("failed to generate setter for %s\n", asvalue->name);
4276                     ir_builder_delete(ir);
4277                     return false;
4278                 }
4279             }
4280             if (asvalue->getter) {
4281                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4282                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4283                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4284                 {
4285                     printf("failed to generate getter for %s\n", asvalue->name);
4286                     ir_builder_delete(ir);
4287                     return false;
4288                 }
4289             }
4290         }
4291         for (i = 0; i < vec_size(parser->fields); ++i) {
4292             ast_value *asvalue;
4293             asvalue = (ast_value*)(parser->fields[i]->expression.next);
4294
4295             if (!ast_istype((ast_expression*)asvalue, ast_value))
4296                 continue;
4297             if (asvalue->expression.vtype != TYPE_ARRAY)
4298                 continue;
4299             if (asvalue->setter) {
4300                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4301                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4302                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4303                 {
4304                     printf("failed to generate setter for %s\n", asvalue->name);
4305                     ir_builder_delete(ir);
4306                     return false;
4307                 }
4308             }
4309             if (asvalue->getter) {
4310                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4311                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4312                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4313                 {
4314                     printf("failed to generate getter for %s\n", asvalue->name);
4315                     ir_builder_delete(ir);
4316                     return false;
4317                 }
4318             }
4319         }
4320         for (i = 0; i < vec_size(parser->functions); ++i) {
4321             if (!ast_function_codegen(parser->functions[i], ir)) {
4322                 con_out("failed to generate function %s\n", parser->functions[i]->name);
4323                 ir_builder_delete(ir);
4324                 return false;
4325             }
4326         }
4327         if (opts_dump)
4328             ir_builder_dump(ir, con_out);
4329         for (i = 0; i < vec_size(parser->functions); ++i) {
4330             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4331                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4332                 ir_builder_delete(ir);
4333                 return false;
4334             }
4335         }
4336
4337         if (retval) {
4338             if (opts_dumpfin)
4339                 ir_builder_dump(ir, con_out);
4340
4341             generate_checksum(parser);
4342
4343             if (!ir_builder_generate(ir, output)) {
4344                 con_out("*** failed to generate output file\n");
4345                 ir_builder_delete(ir);
4346                 return false;
4347             }
4348         }
4349
4350         ir_builder_delete(ir);
4351         return retval;
4352     }
4353
4354     con_out("*** there were compile errors\n");
4355     return false;
4356 }