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