]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
array index opening-paren can now return TOKEN_OPERATOR, partially handled in SYA
[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 (sy->ops[sy->ops_count-1].paren == SY_PAREN_INDEX) {
1003             sy->ops_count--;
1004             return true;
1005         }
1006         if (!parser_sy_pop(parser, sy))
1007             return false;
1008     }
1009     return true;
1010 }
1011
1012 static void parser_reclassify_token(parser_t *parser)
1013 {
1014     size_t i;
1015     for (i = 0; i < operator_count; ++i) {
1016         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1017             parser->tok = TOKEN_OPERATOR;
1018             return;
1019         }
1020     }
1021 }
1022
1023 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1024 {
1025     ast_expression *expr = NULL;
1026     shunt sy;
1027     bool wantop = false;
1028     bool gotmemberof = false;
1029
1030     /* count the parens because an if starts with one, so the
1031      * end of a condition is an unmatched closing paren
1032      */
1033     int parens = 0;
1034
1035     MEM_VECTOR_INIT(&sy, out);
1036     MEM_VECTOR_INIT(&sy, ops);
1037
1038     parser->lex->flags.noops = false;
1039
1040     parser_reclassify_token(parser);
1041
1042     while (true)
1043     {
1044         if (gotmemberof)
1045             gotmemberof = false;
1046         else
1047             parser->memberof = 0;
1048
1049         if (parser->tok == TOKEN_IDENT)
1050         {
1051             ast_expression *var;
1052             if (wantop) {
1053                 parseerror(parser, "expected operator or end of statement");
1054                 goto onerr;
1055             }
1056             wantop = true;
1057             /* variable */
1058             if (opts_standard == COMPILER_GMQCC)
1059             {
1060                 if (parser->memberof == TYPE_ENTITY) {
1061                     /* still get vars first since there could be a fieldpointer */
1062                     var = parser_find_var(parser, parser_tokval(parser));
1063                     if (!var)
1064                         var = parser_find_field(parser, parser_tokval(parser));
1065                 }
1066                 else if (parser->memberof == TYPE_VECTOR)
1067                 {
1068                     parseerror(parser, "TODO: implement effective vector member access");
1069                     goto onerr;
1070                 }
1071                 else if (parser->memberof) {
1072                     parseerror(parser, "namespace for member not found");
1073                     goto onerr;
1074                 }
1075                 else
1076                     var = parser_find_var(parser, parser_tokval(parser));
1077             } else {
1078                 var = parser_find_var(parser, parser_tokval(parser));
1079                 if (!var)
1080                     var = parser_find_field(parser, parser_tokval(parser));
1081             }
1082             if (!var) {
1083                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1084                 goto onerr;
1085             }
1086             if (ast_istype(var, ast_value))
1087                 ((ast_value*)var)->uses++;
1088             if (!shunt_out_add(&sy, syexp(parser_ctx(parser), var))) {
1089                 parseerror(parser, "out of memory");
1090                 goto onerr;
1091             }
1092             DEBUGSHUNTDO(printf("push %s\n", parser_tokval(parser)));
1093         }
1094         else if (parser->tok == TOKEN_FLOATCONST) {
1095             ast_value *val;
1096             if (wantop) {
1097                 parseerror(parser, "expected operator or end of statement, got constant");
1098                 goto onerr;
1099             }
1100             wantop = true;
1101             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1102             if (!val)
1103                 return false;
1104             if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1105                 parseerror(parser, "out of memory");
1106                 goto onerr;
1107             }
1108             DEBUGSHUNTDO(printf("push %g\n", parser_token(parser)->constval.f));
1109         }
1110         else if (parser->tok == TOKEN_INTCONST) {
1111             ast_value *val;
1112             if (wantop) {
1113                 parseerror(parser, "expected operator or end of statement, got constant");
1114                 goto onerr;
1115             }
1116             wantop = true;
1117             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1118             if (!val)
1119                 return false;
1120             if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1121                 parseerror(parser, "out of memory");
1122                 goto onerr;
1123             }
1124             DEBUGSHUNTDO(printf("push %i\n", parser_token(parser)->constval.i));
1125         }
1126         else if (parser->tok == TOKEN_STRINGCONST) {
1127             ast_value *val;
1128             if (wantop) {
1129                 parseerror(parser, "expected operator or end of statement, got constant");
1130                 goto onerr;
1131             }
1132             wantop = true;
1133             val = parser_const_string(parser, parser_tokval(parser));
1134             if (!val)
1135                 return false;
1136             if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1137                 parseerror(parser, "out of memory");
1138                 goto onerr;
1139             }
1140             DEBUGSHUNTDO(printf("push string\n"));
1141         }
1142         else if (parser->tok == TOKEN_VECTORCONST) {
1143             ast_value *val;
1144             if (wantop) {
1145                 parseerror(parser, "expected operator or end of statement, got constant");
1146                 goto onerr;
1147             }
1148             wantop = true;
1149             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1150             if (!val)
1151                 return false;
1152             if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1153                 parseerror(parser, "out of memory");
1154                 goto onerr;
1155             }
1156             DEBUGSHUNTDO(printf("push '%g %g %g'\n",
1157                                 parser_token(parser)->constval.v.x,
1158                                 parser_token(parser)->constval.v.y,
1159                                 parser_token(parser)->constval.v.z));
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             parseerror(parser, "internal error: '[' should be classified as operator");
1167             goto onerr;
1168         }
1169         else if (parser->tok == ')') {
1170             if (wantop) {
1171                 DEBUGSHUNTDO(printf("do[op] )\n"));
1172                 --parens;
1173                 if (parens < 0)
1174                     break;
1175                 /* we do expect an operator next */
1176                 /* closing an opening paren */
1177                 if (!parser_close_paren(parser, &sy, false))
1178                     goto onerr;
1179             } else {
1180                 DEBUGSHUNTDO(printf("do[nop] )\n"));
1181                 --parens;
1182                 if (parens < 0)
1183                     break;
1184                 /* allowed for function calls */
1185                 if (!parser_close_paren(parser, &sy, true))
1186                     goto onerr;
1187             }
1188             wantop = true;
1189         }
1190         else if (parser->tok == ']') {
1191             if (!wantop)
1192                 parseerror(parser, "operand expected");
1193             --parens;
1194             if (parens < 0)
1195                 break;
1196             if (!parser_close_paren(parser, &sy, false))
1197                 goto onerr;
1198             wantop = true;
1199         }
1200         else if (parser->tok != TOKEN_OPERATOR) {
1201             if (wantop) {
1202                 parseerror(parser, "expected operator or end of statement");
1203                 goto onerr;
1204             }
1205             break;
1206         }
1207         else
1208         {
1209             /* classify the operator */
1210             /* TODO: suffix operators */
1211             const oper_info *op;
1212             const oper_info *olast = NULL;
1213             size_t o;
1214             for (o = 0; o < operator_count; ++o) {
1215                 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1216                     !(operators[o].flags & OP_SUFFIX) && /* remove this */
1217                     !strcmp(parser_tokval(parser), operators[o].op))
1218                 {
1219                     break;
1220                 }
1221             }
1222             if (o == operator_count) {
1223                 /* no operator found... must be the end of the statement */
1224                 break;
1225             }
1226             /* found an operator */
1227             op = &operators[o];
1228
1229             /* when declaring variables, a comma starts a new variable */
1230             if (op->id == opid1(',') && !parens && stopatcomma) {
1231                 /* fixup the token */
1232                 parser->tok = ',';
1233                 break;
1234             }
1235
1236             if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1237                 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1238
1239             while (olast && (
1240                     (op->prec < olast->prec) ||
1241                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1242             {
1243                 if (!parser_sy_pop(parser, &sy))
1244                     goto onerr;
1245                 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1246                     olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1247                 else
1248                     olast = NULL;
1249             }
1250
1251             if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1252                 /* for gmqcc standard: open up the namespace of the previous type */
1253                 ast_expression *prevex = sy.out[sy.out_count-1].out;
1254                 if (!prevex) {
1255                     parseerror(parser, "unexpected member operator");
1256                     goto onerr;
1257                 }
1258                 if (prevex->expression.vtype == TYPE_ENTITY)
1259                     parser->memberof = TYPE_ENTITY;
1260                 else if (prevex->expression.vtype == TYPE_VECTOR)
1261                     parser->memberof = TYPE_VECTOR;
1262                 else {
1263                     parseerror(parser, "type error: type has no members");
1264                     goto onerr;
1265                 }
1266                 gotmemberof = true;
1267             }
1268
1269             if (op->id == opid1('(')) {
1270                 if (wantop) {
1271                     DEBUGSHUNTDO(printf("push [op] (\n"));
1272                     ++parens;
1273                     /* we expected an operator, this is the function-call operator */
1274                     if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), SY_PAREN_FUNC, sy.out_count-1))) {
1275                         parseerror(parser, "out of memory");
1276                         goto onerr;
1277                     }
1278                 } else {
1279                     ++parens;
1280                     if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0))) {
1281                         parseerror(parser, "out of memory");
1282                         goto onerr;
1283                     }
1284                     DEBUGSHUNTDO(printf("push [nop] (\n"));
1285                 }
1286                 wantop = false;
1287             } else if (op->id == opid1('[')) {
1288                 if (!wantop) {
1289                     parseerror(parser, "unexpected array subscript");
1290                     goto onerr;
1291                 }
1292                 ++parens;
1293                 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0))) {
1294                     parseerror(parser, "out of memory");
1295                     goto onerr;
1296                 }
1297             } else {
1298                 DEBUGSHUNTDO(printf("push operator %s\n", op->op));
1299                 if (!shunt_ops_add(&sy, syop(parser_ctx(parser), op)))
1300                     goto onerr;
1301                 wantop = false;
1302             }
1303         }
1304         if (!parser_next(parser)) {
1305             goto onerr;
1306         }
1307         if (parser->tok == ';' || parser->tok == ']') {
1308             break;
1309         }
1310     }
1311
1312     while (sy.ops_count) {
1313         if (!parser_sy_pop(parser, &sy))
1314             goto onerr;
1315     }
1316
1317     parser->lex->flags.noops = true;
1318     if (!sy.out_count) {
1319         parseerror(parser, "empty expression");
1320         expr = NULL;
1321     } else
1322         expr = sy.out[0].out;
1323     MEM_VECTOR_CLEAR(&sy, out);
1324     MEM_VECTOR_CLEAR(&sy, ops);
1325     DEBUGSHUNTDO(printf("shunt done\n"));
1326     return expr;
1327
1328 onerr:
1329     parser->lex->flags.noops = true;
1330     MEM_VECTOR_CLEAR(&sy, out);
1331     MEM_VECTOR_CLEAR(&sy, ops);
1332     return NULL;
1333 }
1334
1335 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1336 {
1337     ast_expression *e = parse_expression_leave(parser, stopatcomma);
1338     if (!e)
1339         return NULL;
1340     if (!parser_next(parser)) {
1341         ast_delete(e);
1342         return NULL;
1343     }
1344     return e;
1345 }
1346
1347 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1348 {
1349     ast_ifthen *ifthen;
1350     ast_expression *cond, *ontrue, *onfalse = NULL;
1351
1352     lex_ctx ctx = parser_ctx(parser);
1353
1354     /* skip the 'if' and check for opening paren */
1355     if (!parser_next(parser) || parser->tok != '(') {
1356         parseerror(parser, "expected 'if' condition in parenthesis");
1357         return false;
1358     }
1359     /* parse into the expression */
1360     if (!parser_next(parser)) {
1361         parseerror(parser, "expected 'if' condition after opening paren");
1362         return false;
1363     }
1364     /* parse the condition */
1365     cond = parse_expression_leave(parser, false);
1366     if (!cond)
1367         return false;
1368     /* closing paren */
1369     if (parser->tok != ')') {
1370         parseerror(parser, "expected closing paren after 'if' condition");
1371         ast_delete(cond);
1372         return false;
1373     }
1374     /* parse into the 'then' branch */
1375     if (!parser_next(parser)) {
1376         parseerror(parser, "expected statement for on-true branch of 'if'");
1377         ast_delete(cond);
1378         return false;
1379     }
1380     ontrue = parse_statement_or_block(parser);
1381     if (!ontrue) {
1382         ast_delete(cond);
1383         return false;
1384     }
1385     /* check for an else */
1386     if (!strcmp(parser_tokval(parser), "else")) {
1387         /* parse into the 'else' branch */
1388         if (!parser_next(parser)) {
1389             parseerror(parser, "expected on-false branch after 'else'");
1390             ast_delete(ontrue);
1391             ast_delete(cond);
1392             return false;
1393         }
1394         onfalse = parse_statement_or_block(parser);
1395         if (!onfalse) {
1396             ast_delete(ontrue);
1397             ast_delete(cond);
1398             return false;
1399         }
1400     }
1401
1402     ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1403     *out = (ast_expression*)ifthen;
1404     return true;
1405 }
1406
1407 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1408 {
1409     ast_loop *aloop;
1410     ast_expression *cond, *ontrue;
1411
1412     lex_ctx ctx = parser_ctx(parser);
1413
1414     /* skip the 'while' and check for opening paren */
1415     if (!parser_next(parser) || parser->tok != '(') {
1416         parseerror(parser, "expected 'while' condition in parenthesis");
1417         return false;
1418     }
1419     /* parse into the expression */
1420     if (!parser_next(parser)) {
1421         parseerror(parser, "expected 'while' condition after opening paren");
1422         return false;
1423     }
1424     /* parse the condition */
1425     cond = parse_expression_leave(parser, false);
1426     if (!cond)
1427         return false;
1428     /* closing paren */
1429     if (parser->tok != ')') {
1430         parseerror(parser, "expected closing paren after 'while' condition");
1431         ast_delete(cond);
1432         return false;
1433     }
1434     /* parse into the 'then' branch */
1435     if (!parser_next(parser)) {
1436         parseerror(parser, "expected while-loop body");
1437         ast_delete(cond);
1438         return false;
1439     }
1440     ontrue = parse_statement_or_block(parser);
1441     if (!ontrue) {
1442         ast_delete(cond);
1443         return false;
1444     }
1445
1446     aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1447     *out = (ast_expression*)aloop;
1448     return true;
1449 }
1450
1451 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1452 {
1453     ast_loop *aloop;
1454     ast_expression *cond, *ontrue;
1455
1456     lex_ctx ctx = parser_ctx(parser);
1457
1458     /* skip the 'do' and get the body */
1459     if (!parser_next(parser)) {
1460         parseerror(parser, "expected loop body");
1461         return false;
1462     }
1463     ontrue = parse_statement_or_block(parser);
1464     if (!ontrue)
1465         return false;
1466
1467     /* expect the "while" */
1468     if (parser->tok != TOKEN_KEYWORD ||
1469         strcmp(parser_tokval(parser), "while"))
1470     {
1471         parseerror(parser, "expected 'while' and condition");
1472         ast_delete(ontrue);
1473         return false;
1474     }
1475
1476     /* skip the 'while' and check for opening paren */
1477     if (!parser_next(parser) || parser->tok != '(') {
1478         parseerror(parser, "expected 'while' condition in parenthesis");
1479         ast_delete(ontrue);
1480         return false;
1481     }
1482     /* parse into the expression */
1483     if (!parser_next(parser)) {
1484         parseerror(parser, "expected 'while' condition after opening paren");
1485         ast_delete(ontrue);
1486         return false;
1487     }
1488     /* parse the condition */
1489     cond = parse_expression_leave(parser, false);
1490     if (!cond)
1491         return false;
1492     /* closing paren */
1493     if (parser->tok != ')') {
1494         parseerror(parser, "expected closing paren after 'while' condition");
1495         ast_delete(ontrue);
1496         ast_delete(cond);
1497         return false;
1498     }
1499     /* parse on */
1500     if (!parser_next(parser) || parser->tok != ';') {
1501         parseerror(parser, "expected semicolon after condition");
1502         ast_delete(ontrue);
1503         ast_delete(cond);
1504         return false;
1505     }
1506
1507     if (!parser_next(parser)) {
1508         parseerror(parser, "parse error");
1509         ast_delete(ontrue);
1510         ast_delete(cond);
1511         return false;
1512     }
1513
1514     aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1515     *out = (ast_expression*)aloop;
1516     return true;
1517 }
1518
1519 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1520 {
1521     ast_loop *aloop;
1522     ast_expression *initexpr, *cond, *increment, *ontrue;
1523     size_t oldblocklocal;
1524     bool   retval = true;
1525
1526     lex_ctx ctx = parser_ctx(parser);
1527
1528     oldblocklocal = parser->blocklocal;
1529     parser->blocklocal = parser->locals_count;
1530
1531     initexpr  = NULL;
1532     cond      = NULL;
1533     increment = NULL;
1534     ontrue    = NULL;
1535
1536     /* skip the 'while' and check for opening paren */
1537     if (!parser_next(parser) || parser->tok != '(') {
1538         parseerror(parser, "expected 'for' expressions in parenthesis");
1539         goto onerr;
1540     }
1541     /* parse into the expression */
1542     if (!parser_next(parser)) {
1543         parseerror(parser, "expected 'for' initializer after opening paren");
1544         goto onerr;
1545     }
1546
1547     if (parser->tok == TOKEN_TYPENAME) {
1548         if (opts_standard != COMPILER_GMQCC) {
1549             if (parsewarning(parser, WARN_EXTENSIONS,
1550                              "current standard does not allow variable declarations in for-loop initializers"))
1551                 goto onerr;
1552         }
1553
1554         parseerror(parser, "TODO: assignment of new variables to be non-const");
1555         goto onerr;
1556         if (!parse_variable(parser, block, true))
1557             goto onerr;
1558     }
1559     else if (parser->tok != ';')
1560     {
1561         initexpr = parse_expression_leave(parser, false);
1562         if (!initexpr)
1563             goto onerr;
1564     }
1565
1566     /* move on to condition */
1567     if (parser->tok != ';') {
1568         parseerror(parser, "expected semicolon after for-loop initializer");
1569         goto onerr;
1570     }
1571     if (!parser_next(parser)) {
1572         parseerror(parser, "expected for-loop condition");
1573         goto onerr;
1574     }
1575
1576     /* parse the condition */
1577     if (parser->tok != ';') {
1578         cond = parse_expression_leave(parser, false);
1579         if (!cond)
1580             goto onerr;
1581     }
1582
1583     /* move on to incrementor */
1584     if (parser->tok != ';') {
1585         parseerror(parser, "expected semicolon after for-loop initializer");
1586         goto onerr;
1587     }
1588     if (!parser_next(parser)) {
1589         parseerror(parser, "expected for-loop condition");
1590         goto onerr;
1591     }
1592
1593     /* parse the incrementor */
1594     if (parser->tok != ')') {
1595         increment = parse_expression_leave(parser, false);
1596         if (!increment)
1597             goto onerr;
1598         if (!ast_istype(increment, ast_store) &&
1599             !ast_istype(increment, ast_call) &&
1600             !ast_istype(increment, ast_binstore))
1601         {
1602             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1603                 goto onerr;
1604         }
1605     }
1606
1607     /* closing paren */
1608     if (parser->tok != ')') {
1609         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1610         goto onerr;
1611     }
1612     /* parse into the 'then' branch */
1613     if (!parser_next(parser)) {
1614         parseerror(parser, "expected for-loop body");
1615         goto onerr;
1616     }
1617     ontrue = parse_statement_or_block(parser);
1618     if (!ontrue) {
1619         goto onerr;
1620     }
1621
1622     aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1623     *out = (ast_expression*)aloop;
1624
1625     while (parser->locals_count > parser->blocklocal)
1626         retval = retval && parser_pop_local(parser);
1627     parser->blocklocal = oldblocklocal;
1628     return retval;
1629 onerr:
1630     if (initexpr)  ast_delete(initexpr);
1631     if (cond)      ast_delete(cond);
1632     if (increment) ast_delete(increment);
1633     while (parser->locals_count > parser->blocklocal)
1634         (void)!parser_pop_local(parser);
1635     parser->blocklocal = oldblocklocal;
1636     return false;
1637 }
1638
1639 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out)
1640 {
1641     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1642     {
1643         /* local variable */
1644         if (!block) {
1645             parseerror(parser, "cannot declare a variable from here");
1646             return false;
1647         }
1648         if (opts_standard == COMPILER_QCC) {
1649             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1650                 return false;
1651         }
1652         if (!parse_variable(parser, block, false))
1653             return false;
1654         *out = NULL;
1655         return true;
1656     }
1657     else if (parser->tok == TOKEN_KEYWORD)
1658     {
1659         if (!strcmp(parser_tokval(parser), "local"))
1660         {
1661             if (!block) {
1662                 parseerror(parser, "cannot declare a local variable here");
1663                 return false;
1664             }
1665             if (!parser_next(parser)) {
1666                 parseerror(parser, "expected variable declaration");
1667                 return false;
1668             }
1669             if (!parse_variable(parser, block, true))
1670                 return false;
1671             *out = NULL;
1672             return true;
1673         }
1674         else if (!strcmp(parser_tokval(parser), "return"))
1675         {
1676             ast_expression *exp = NULL;
1677             ast_return     *ret = NULL;
1678             ast_value      *expected = parser->function->vtype;
1679
1680             if (!parser_next(parser)) {
1681                 parseerror(parser, "expected return expression");
1682                 return false;
1683             }
1684
1685             if (parser->tok != ';') {
1686                 exp = parse_expression(parser, false);
1687                 if (!exp)
1688                     return false;
1689
1690                 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1691                     parseerror(parser, "return with invalid expression");
1692                 }
1693
1694                 ret = ast_return_new(exp->expression.node.context, exp);
1695                 if (!ret) {
1696                     ast_delete(exp);
1697                     return false;
1698                 }
1699             } else {
1700                 if (!parser_next(parser))
1701                     parseerror(parser, "parse error");
1702                 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1703                     if (opts_standard != COMPILER_GMQCC)
1704                         (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1705                     else
1706                         parseerror(parser, "return without value");
1707                 }
1708                 ret = ast_return_new(parser_ctx(parser), NULL);
1709             }
1710             *out = (ast_expression*)ret;
1711             return true;
1712         }
1713         else if (!strcmp(parser_tokval(parser), "if"))
1714         {
1715             return parse_if(parser, block, out);
1716         }
1717         else if (!strcmp(parser_tokval(parser), "while"))
1718         {
1719             return parse_while(parser, block, out);
1720         }
1721         else if (!strcmp(parser_tokval(parser), "do"))
1722         {
1723             return parse_dowhile(parser, block, out);
1724         }
1725         else if (!strcmp(parser_tokval(parser), "for"))
1726         {
1727             if (opts_standard == COMPILER_QCC) {
1728                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1729                     return false;
1730             }
1731             return parse_for(parser, block, out);
1732         }
1733         parseerror(parser, "Unexpected keyword");
1734         return false;
1735     }
1736     else if (parser->tok == '{')
1737     {
1738         ast_block *inner;
1739         inner = parse_block(parser, false);
1740         if (!inner)
1741             return false;
1742         *out = (ast_expression*)inner;
1743         return true;
1744     }
1745     else
1746     {
1747         ast_expression *exp = parse_expression(parser, false);
1748         if (!exp)
1749             return false;
1750         *out = exp;
1751         if (!ast_istype(exp, ast_store) &&
1752             !ast_istype(exp, ast_call) &&
1753             !ast_istype(exp, ast_binstore))
1754         {
1755             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1756                 return false;
1757         }
1758         return true;
1759     }
1760 }
1761
1762 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
1763 {
1764     varentry_t *ve;
1765     parser->locals_count--;
1766
1767     ve = &parser->locals[parser->locals_count];
1768     if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
1769         if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
1770             return false;
1771     }
1772     mem_d(parser->locals[parser->locals_count].name);
1773     return true;
1774 }
1775
1776 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
1777 {
1778     size_t oldblocklocal;
1779     bool   retval = true;
1780
1781     oldblocklocal = parser->blocklocal;
1782     parser->blocklocal = parser->locals_count;
1783
1784     if (!parser_next(parser)) { /* skip the '{' */
1785         parseerror(parser, "expected function body");
1786         goto cleanup;
1787     }
1788
1789     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
1790     {
1791         ast_expression *expr;
1792         if (parser->tok == '}')
1793             break;
1794
1795         if (!parse_statement(parser, block, &expr)) {
1796             /* parseerror(parser, "parse error"); */
1797             block = NULL;
1798             goto cleanup;
1799         }
1800         if (!expr)
1801             continue;
1802         if (!ast_block_exprs_add(block, expr)) {
1803             ast_delete(expr);
1804             block = NULL;
1805             goto cleanup;
1806         }
1807     }
1808
1809     if (parser->tok != '}') {
1810         block = NULL;
1811     } else {
1812         if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
1813         {
1814             if (!block->exprs_count ||
1815                 !ast_istype(block->exprs[block->exprs_count-1], ast_return))
1816             {
1817                 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
1818                     block = NULL;
1819                     goto cleanup;
1820                 }
1821             }
1822         }
1823         (void)parser_next(parser);
1824     }
1825
1826 cleanup:
1827     while (parser->locals_count > parser->blocklocal)
1828         retval = retval && parser_pop_local(parser);
1829     parser->blocklocal = oldblocklocal;
1830     return !!block;
1831 }
1832
1833 static ast_block* parse_block(parser_t *parser, bool warnreturn)
1834 {
1835     ast_block *block;
1836     block = ast_block_new(parser_ctx(parser));
1837     if (!block)
1838         return NULL;
1839     if (!parse_block_into(parser, block, warnreturn)) {
1840         ast_block_delete(block);
1841         return NULL;
1842     }
1843     return block;
1844 }
1845
1846 static ast_expression* parse_statement_or_block(parser_t *parser)
1847 {
1848     ast_expression *expr = NULL;
1849     if (parser->tok == '{')
1850         return (ast_expression*)parse_block(parser, false);
1851     if (!parse_statement(parser, NULL, &expr))
1852         return NULL;
1853     return expr;
1854 }
1855
1856 /* loop method */
1857 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
1858 {
1859     size_t i;
1860     size_t len = strlen(var->name);
1861
1862     for (i = 0; i < 3; ++i) {
1863         ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
1864         if (!ve[i].var)
1865             break;
1866
1867         ve[i].name = (char*)mem_a(len+3);
1868         if (!ve[i].name) {
1869             ast_delete(ve[i].var);
1870             break;
1871         }
1872
1873         memcpy(ve[i].name, var->name, len);
1874         ve[i].name[len]   = '_';
1875         ve[i].name[len+1] = 'x'+i;
1876         ve[i].name[len+2] = 0;
1877     }
1878     if (i == 3)
1879         return true;
1880
1881     /* unroll */
1882     do {
1883         --i;
1884         mem_d(ve[i].name);
1885         ast_delete(ve[i].var);
1886         ve[i].name = NULL;
1887         ve[i].var  = NULL;
1888     } while (i);
1889     return false;
1890 }
1891
1892 static bool parse_function_body(parser_t *parser, ast_value *var)
1893 {
1894     ast_block      *block = NULL;
1895     ast_function   *func;
1896     ast_function   *old;
1897     size_t          parami;
1898
1899     ast_expression *framenum  = NULL;
1900     ast_expression *nextthink = NULL;
1901     /* None of the following have to be deleted */
1902     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
1903     ast_expression *gbl_time = NULL, *gbl_self = NULL;
1904     bool            has_frame_think;
1905
1906     bool retval = true;
1907
1908     has_frame_think = false;
1909     old = parser->function;
1910
1911     if (var->expression.variadic) {
1912         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
1913                          "variadic function with implementation will not be able to access additional parameters"))
1914         {
1915             return false;
1916         }
1917     }
1918
1919     if (parser->tok == '[') {
1920         /* got a frame definition: [ framenum, nextthink ]
1921          * this translates to:
1922          * self.frame = framenum;
1923          * self.nextthink = time + 0.1;
1924          * self.think = nextthink;
1925          */
1926         nextthink = NULL;
1927
1928         fld_think     = parser_find_field(parser, "think");
1929         fld_nextthink = parser_find_field(parser, "nextthink");
1930         fld_frame     = parser_find_field(parser, "frame");
1931         if (!fld_think || !fld_nextthink || !fld_frame) {
1932             parseerror(parser, "cannot use [frame,think] notation without the required fields");
1933             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
1934             return false;
1935         }
1936         gbl_time      = parser_find_global(parser, "time");
1937         gbl_self      = parser_find_global(parser, "self");
1938         if (!gbl_time || !gbl_self) {
1939             parseerror(parser, "cannot use [frame,think] notation without the required globals");
1940             parseerror(parser, "please declare the following globals: `time`, `self`");
1941             return false;
1942         }
1943
1944         if (!parser_next(parser))
1945             return false;
1946
1947         framenum = parse_expression_leave(parser, true);
1948         if (!framenum) {
1949             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
1950             return false;
1951         }
1952         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
1953             ast_unref(framenum);
1954             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
1955             return false;
1956         }
1957
1958         if (parser->tok != ',') {
1959             ast_unref(framenum);
1960             parseerror(parser, "expected comma after frame number in [frame,think] notation");
1961             parseerror(parser, "Got a %i\n", parser->tok);
1962             return false;
1963         }
1964
1965         if (!parser_next(parser)) {
1966             ast_unref(framenum);
1967             return false;
1968         }
1969
1970         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
1971         {
1972             /* qc allows the use of not-yet-declared functions here
1973              * - this automatically creates a prototype */
1974             varentry_t      varent;
1975             ast_value      *thinkfunc;
1976             ast_expression *functype = fld_think->expression.next;
1977
1978             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
1979             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
1980                 ast_unref(framenum);
1981                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
1982                 return false;
1983             }
1984
1985             if (!parser_next(parser)) {
1986                 ast_unref(framenum);
1987                 ast_delete(thinkfunc);
1988                 return false;
1989             }
1990
1991             varent.var = (ast_expression*)thinkfunc;
1992             varent.name = util_strdup(thinkfunc->name);
1993             if (!parser_t_globals_add(parser, varent)) {
1994                 ast_unref(framenum);
1995                 ast_delete(thinkfunc);
1996                 return false;
1997             }
1998             nextthink = (ast_expression*)thinkfunc;
1999
2000         } else {
2001             nextthink = parse_expression_leave(parser, true);
2002             if (!nextthink) {
2003                 ast_unref(framenum);
2004                 parseerror(parser, "expected a think-function in [frame,think] notation");
2005                 return false;
2006             }
2007         }
2008
2009         if (!ast_istype(nextthink, ast_value)) {
2010             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2011             retval = false;
2012         }
2013
2014         if (retval && parser->tok != ']') {
2015             parseerror(parser, "expected closing `]` for [frame,think] notation");
2016             retval = false;
2017         }
2018
2019         if (retval && !parser_next(parser)) {
2020             retval = false;
2021         }
2022
2023         if (retval && parser->tok != '{') {
2024             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2025             retval = false;
2026         }
2027
2028         if (!retval) {
2029             ast_unref(nextthink);
2030             ast_unref(framenum);
2031             return false;
2032         }
2033
2034         has_frame_think = true;
2035     }
2036
2037     block = ast_block_new(parser_ctx(parser));
2038     if (!block) {
2039         parseerror(parser, "failed to allocate block");
2040         if (has_frame_think) {
2041             ast_unref(nextthink);
2042             ast_unref(framenum);
2043         }
2044         return false;
2045     }
2046
2047     if (has_frame_think) {
2048         lex_ctx ctx;
2049         ast_expression *self_frame;
2050         ast_expression *self_nextthink;
2051         ast_expression *self_think;
2052         ast_expression *time_plus_1;
2053         ast_store *store_frame;
2054         ast_store *store_nextthink;
2055         ast_store *store_think;
2056
2057         ctx = parser_ctx(parser);
2058         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2059         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2060         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2061
2062         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2063                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2064
2065         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2066             if (self_frame)     ast_delete(self_frame);
2067             if (self_nextthink) ast_delete(self_nextthink);
2068             if (self_think)     ast_delete(self_think);
2069             if (time_plus_1)    ast_delete(time_plus_1);
2070             retval = false;
2071         }
2072
2073         if (retval)
2074         {
2075             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2076             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2077             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2078
2079             if (!store_frame) {
2080                 ast_delete(self_frame);
2081                 retval = false;
2082             }
2083             if (!store_nextthink) {
2084                 ast_delete(self_nextthink);
2085                 retval = false;
2086             }
2087             if (!store_think) {
2088                 ast_delete(self_think);
2089                 retval = false;
2090             }
2091             if (!retval) {
2092                 if (store_frame)     ast_delete(store_frame);
2093                 if (store_nextthink) ast_delete(store_nextthink);
2094                 if (store_think)     ast_delete(store_think);
2095                 retval = false;
2096             }
2097             if (retval && !ast_block_exprs_add(block, (ast_expression*)store_frame)) {
2098                 ast_delete(store_frame);
2099                 ast_delete(store_nextthink);
2100                 ast_delete(store_think);
2101                 retval = false;
2102             }
2103
2104             if (retval && !ast_block_exprs_add(block, (ast_expression*)store_nextthink)) {
2105                 ast_delete(store_nextthink);
2106                 ast_delete(store_think);
2107                 retval = false;
2108             }
2109
2110             if (retval && !ast_block_exprs_add(block, (ast_expression*)store_think) )
2111             {
2112                 ast_delete(store_think);
2113                 retval = false;
2114             }
2115         }
2116
2117         if (!retval) {
2118             parseerror(parser, "failed to generate code for [frame,think]");
2119             ast_unref(nextthink);
2120             ast_unref(framenum);
2121             ast_delete(block);
2122             return false;
2123         }
2124     }
2125
2126     for (parami = 0; parami < var->expression.params_count; ++parami) {
2127         size_t     e;
2128         varentry_t ve[3];
2129         ast_value *param = var->expression.params[parami];
2130
2131         if (param->expression.vtype != TYPE_VECTOR &&
2132             (param->expression.vtype != TYPE_FIELD ||
2133              param->expression.next->expression.vtype != TYPE_VECTOR))
2134         {
2135             continue;
2136         }
2137
2138         if (!create_vector_members(parser, param, ve)) {
2139             ast_block_delete(block);
2140             return false;
2141         }
2142
2143         for (e = 0; e < 3; ++e) {
2144             if (!parser_t_locals_add(parser, ve[e]))
2145                 break;
2146             if (!ast_block_collect(block, ve[e].var)) {
2147                 parser->locals_count--;
2148                 break;
2149             }
2150             ve[e].var = NULL; /* collected */
2151         }
2152         if (e != 3) {
2153             parser->locals -= e;
2154             do {
2155                 mem_d(ve[e].name);
2156                 --e;
2157             } while (e);
2158             ast_block_delete(block);
2159             return false;
2160         }
2161     }
2162
2163     func = ast_function_new(ast_ctx(var), var->name, var);
2164     if (!func) {
2165         parseerror(parser, "failed to allocate function for `%s`", var->name);
2166         ast_block_delete(block);
2167         goto enderr;
2168     }
2169     if (!parser_t_functions_add(parser, func)) {
2170         parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2171         ast_block_delete(block);
2172         goto enderrfn;
2173     }
2174
2175     parser->function = func;
2176     if (!parse_block_into(parser, block, true)) {
2177         ast_block_delete(block);
2178         goto enderrfn2;
2179     }
2180
2181     if (!ast_function_blocks_add(func, block)) {
2182         ast_block_delete(block);
2183         goto enderrfn2;
2184     }
2185
2186     parser->function = old;
2187     while (parser->locals_count)
2188         retval = retval && parser_pop_local(parser);
2189
2190     if (parser->tok == ';')
2191         return parser_next(parser);
2192     else if (opts_standard == COMPILER_QCC)
2193         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2194     return retval;
2195
2196 enderrfn2:
2197     parser->functions_count--;
2198 enderrfn:
2199     ast_function_delete(func);
2200     var->constval.vfunc = NULL;
2201
2202 enderr:
2203     while (parser->locals_count) {
2204         parser->locals_count--;
2205         mem_d(parser->locals[parser->locals_count].name);
2206     }
2207     parser->function = old;
2208     return false;
2209 }
2210
2211 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2212 {
2213     lex_ctx ctx = ast_ctx(array);
2214
2215     if (from+1 == afterend) {
2216         // set this value
2217         ast_block       *block;
2218         ast_return      *ret;
2219         ast_array_index *subscript;
2220         int assignop = type_store_instr[value->expression.vtype];
2221
2222         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2223             assignop = INSTR_STORE_V;
2224
2225         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2226         if (!subscript)
2227             return NULL;
2228
2229         ast_store *st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2230         if (!st) {
2231             ast_delete(subscript);
2232             return NULL;
2233         }
2234
2235         block = ast_block_new(ctx);
2236         if (!block) {
2237             ast_delete(st);
2238             return NULL;
2239         }
2240
2241         if (!ast_block_exprs_add(block, (ast_expression*)st)) {
2242             ast_delete(block);
2243             return NULL;
2244         }
2245
2246         ret = ast_return_new(ctx, NULL);
2247         if (!ret) {
2248             ast_delete(block);
2249             return NULL;
2250         }
2251
2252         if (!ast_block_exprs_add(block, (ast_expression*)ret)) {
2253             ast_delete(block);
2254             return NULL;
2255         }
2256
2257         return (ast_expression*)block;
2258     } else {
2259         ast_ifthen *ifthen;
2260         ast_expression *left, *right;
2261         ast_binary *cmp;
2262
2263         size_t diff = afterend - from;
2264         size_t middle = from + diff/2;
2265
2266         left  = array_setter_node(parser, array, index, value, from, middle);
2267         right = array_setter_node(parser, array, index, value, middle, afterend);
2268         if (!left || !right) {
2269             if (left)  ast_delete(left);
2270             if (right) ast_delete(right);
2271             return NULL;
2272         }
2273
2274         cmp = ast_binary_new(ctx, INSTR_LT,
2275                              (ast_expression*)index,
2276                              (ast_expression*)parser_const_float(parser, from + diff/2));
2277         if (!cmp) {
2278             ast_delete(left);
2279             ast_delete(right);
2280             parseerror(parser, "internal error: failed to create comparison for array setter");
2281             return NULL;
2282         }
2283
2284         ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2285         if (!ifthen) {
2286             ast_delete(cmp); /* will delete left and right */
2287             parseerror(parser, "internal error: failed to create conditional jump for array setter");
2288             return NULL;
2289         }
2290
2291         return (ast_expression*)ifthen;
2292     }
2293 }
2294
2295 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2296 {
2297     lex_ctx ctx = ast_ctx(array);
2298
2299     if (from+1 == afterend) {
2300         ast_return      *ret;
2301         ast_array_index *subscript;
2302
2303         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2304         if (!subscript)
2305             return NULL;
2306
2307         ret = ast_return_new(ctx, (ast_expression*)subscript);
2308         if (!ret) {
2309             ast_delete(subscript);
2310             return NULL;
2311         }
2312
2313         return (ast_expression*)ret;
2314     } else {
2315         ast_ifthen *ifthen;
2316         ast_expression *left, *right;
2317         ast_binary *cmp;
2318
2319         size_t diff = afterend - from;
2320         size_t middle = from + diff/2;
2321
2322         left  = array_getter_node(parser, array, index, from, middle);
2323         right = array_getter_node(parser, array, index, middle, afterend);
2324         if (!left || !right) {
2325             if (left)  ast_delete(left);
2326             if (right) ast_delete(right);
2327             return NULL;
2328         }
2329
2330         cmp = ast_binary_new(ctx, INSTR_LT,
2331                              (ast_expression*)index,
2332                              (ast_expression*)parser_const_float(parser, from + diff/2));
2333         if (!cmp) {
2334             ast_delete(left);
2335             ast_delete(right);
2336             parseerror(parser, "internal error: failed to create comparison for array setter");
2337             return NULL;
2338         }
2339
2340         ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2341         if (!ifthen) {
2342             ast_delete(cmp); /* will delete left and right */
2343             parseerror(parser, "internal error: failed to create conditional jump for array setter");
2344             return NULL;
2345         }
2346
2347         return (ast_expression*)ifthen;
2348     }
2349 }
2350
2351 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2352 {
2353     ast_expression *root = NULL;
2354     ast_function   *func = NULL;
2355     ast_value      *fval = NULL;
2356     ast_block      *body;
2357     ast_value      *index, *value;
2358
2359     if (!ast_istype(array->expression.next, ast_value)) {
2360         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2361         return false;
2362     }
2363
2364     body = ast_block_new(ast_ctx(array));
2365     if (!body) {
2366         parseerror(parser, "failed to create block for array accessor");
2367         return false;
2368     }
2369
2370     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2371     value = ast_value_copy((ast_value*)array->expression.next);
2372
2373     if (!index || !value) {
2374         ast_delete(body);
2375         if (index) ast_delete(index);
2376         if (value) ast_delete(value);
2377         parseerror(parser, "failed to create locals for array accessor");
2378         return false;
2379     }
2380
2381     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2382     if (!root) {
2383         parseerror(parser, "failed to build accessor search tree");
2384         goto cleanup;
2385     }
2386
2387     if (!ast_block_exprs_add(body, root)) {
2388         parseerror(parser, "failed to build accessor search block");
2389         goto cleanup;
2390     }
2391
2392     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2393     if (!fval) {
2394         parseerror(parser, "failed to create accessor function value");
2395         goto cleanup;
2396     }
2397     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2398
2399     (void)!ast_value_set_name(value, "value"); /* not important */
2400     if (!ast_expression_common_params_add(&fval->expression, index)) {
2401         parseerror(parser, "failed to build array setter");
2402         goto cleanup;
2403     }
2404     if (!ast_expression_common_params_add(&fval->expression, value)) {
2405         ast_delete(index);
2406         parseerror(parser, "failed to build array setter");
2407         goto cleanup2;
2408     }
2409
2410     func = ast_function_new(ast_ctx(array), funcname, fval);
2411     if (!func) {
2412         parseerror(parser, "failed to create accessor function node");
2413         goto cleanup2;
2414     }
2415
2416     if (!ast_function_blocks_add(func, body))
2417         goto cleanup2;
2418
2419     array->setter = fval;
2420
2421     return true;
2422 cleanup:
2423     ast_delete(index);
2424     ast_delete(value);
2425 cleanup2:
2426     ast_delete(body);
2427     if (root) ast_delete(root);
2428     if (func) ast_delete(func);
2429     if (fval) ast_delete(fval);
2430     return false;
2431 }
2432
2433 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const char *funcname)
2434 {
2435     ast_expression *root = NULL;
2436     ast_function   *func = NULL;
2437     ast_value      *fval = NULL;
2438     ast_block      *body;
2439     ast_value      *index;
2440
2441     if (!ast_istype(array->expression.next, ast_value)) {
2442         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2443         return false;
2444     }
2445
2446     body = ast_block_new(ast_ctx(array));
2447     if (!body) {
2448         parseerror(parser, "failed to create block for array accessor");
2449         return false;
2450     }
2451
2452     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2453
2454     if (!index) {
2455         ast_delete(body);
2456         if (index) ast_delete(index);
2457         parseerror(parser, "failed to create locals for array accessor");
2458         return false;
2459     }
2460
2461     root = array_getter_node(parser, array, index, 0, array->expression.count);
2462     if (!root) {
2463         parseerror(parser, "failed to build accessor search tree");
2464         goto cleanup;
2465     }
2466
2467     if (!ast_block_exprs_add(body, root)) {
2468         parseerror(parser, "failed to build accessor search block");
2469         goto cleanup;
2470     }
2471
2472     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2473     if (!fval) {
2474         parseerror(parser, "failed to create accessor function value");
2475         goto cleanup;
2476     }
2477     fval->expression.next = ast_type_copy(ast_ctx(array), array->expression.next);
2478
2479     if (!ast_expression_common_params_add(&fval->expression, index)) {
2480         parseerror(parser, "failed to build array setter");
2481         goto cleanup;
2482     }
2483
2484     func = ast_function_new(ast_ctx(array), funcname, fval);
2485     if (!func) {
2486         parseerror(parser, "failed to create accessor function node");
2487         goto cleanup2;
2488     }
2489
2490     if (!ast_function_blocks_add(func, body))
2491         goto cleanup2;
2492
2493     array->getter = fval;
2494
2495     return true;
2496 cleanup:
2497     ast_delete(index);
2498 cleanup2:
2499     ast_delete(body);
2500     if (root) ast_delete(root);
2501     if (func) ast_delete(func);
2502     if (fval) ast_delete(fval);
2503     return false;
2504 }
2505
2506 typedef struct {
2507     MEM_VECTOR_MAKE(ast_value*, p);
2508 } paramlist_t;
2509 MEM_VEC_FUNCTIONS(paramlist_t, ast_value*, p)
2510
2511 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2512 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2513 {
2514     lex_ctx     ctx;
2515     size_t      i;
2516     paramlist_t params;
2517     ast_value  *param;
2518     ast_value  *fval;
2519     bool        first = true;
2520     bool        variadic = false;
2521
2522     ctx = parser_ctx(parser);
2523
2524     /* for the sake of less code we parse-in in this function */
2525     if (!parser_next(parser)) {
2526         parseerror(parser, "expected parameter list");
2527         return NULL;
2528     }
2529
2530     MEM_VECTOR_INIT(&params, p);
2531
2532     /* parse variables until we hit a closing paren */
2533     while (parser->tok != ')') {
2534         if (!first) {
2535             /* there must be commas between them */
2536             if (parser->tok != ',') {
2537                 parseerror(parser, "expected comma or end of parameter list");
2538                 goto on_error;
2539             }
2540             if (!parser_next(parser)) {
2541                 parseerror(parser, "expected parameter");
2542                 goto on_error;
2543             }
2544         }
2545         first = false;
2546
2547         if (parser->tok == TOKEN_DOTS) {
2548             /* '...' indicates a varargs function */
2549             variadic = true;
2550             if (!parser_next(parser)) {
2551                 parseerror(parser, "expected parameter");
2552                 return NULL;
2553             }
2554             if (parser->tok != ')') {
2555                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2556                 goto on_error;
2557             }
2558         }
2559         else
2560         {
2561             /* for anything else just parse a typename */
2562             param = parse_typename(parser, NULL);
2563             if (!param)
2564                 goto on_error;
2565             if (!paramlist_t_p_add(&params, param)) {
2566                 ast_delete(param);
2567                 goto on_error;
2568             }
2569             if (param->expression.vtype >= TYPE_VARIANT) {
2570                 char typename[1024];
2571                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
2572                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
2573                 goto on_error;
2574             }
2575         }
2576     }
2577
2578     /* sanity check */
2579     if (params.p_count > 8)
2580         parseerror(parser, "more than 8 parameters are currently not supported");
2581
2582     /* parse-out */
2583     if (!parser_next(parser)) {
2584         parseerror(parser, "parse error after typename");
2585         goto on_error;
2586     }
2587
2588     /* now turn 'var' into a function type */
2589     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2590     fval->expression.next     = (ast_expression*)var;
2591     fval->expression.variadic = variadic;
2592     var = fval;
2593
2594     MEM_VECTOR_MOVE(&params, p, &var->expression, params);
2595
2596     return var;
2597
2598 on_error:
2599     ast_delete(var);
2600     for (i = 0; i < params.p_count; ++i)
2601         ast_delete(params.p[i]);
2602     MEM_VECTOR_CLEAR(&params, p);
2603     return NULL;
2604 }
2605
2606 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2607 {
2608     ast_expression *cexp;
2609     ast_value      *cval, *tmp;
2610     lex_ctx ctx;
2611
2612     ctx = parser_ctx(parser);
2613
2614     if (!parser_next(parser)) {
2615         ast_delete(var);
2616         parseerror(parser, "expected array-size");
2617         return NULL;
2618     }
2619
2620     cexp = parse_expression_leave(parser, true);
2621
2622     if (!cexp || !ast_istype(cexp, ast_value)) {
2623         if (cexp)
2624             ast_unref(cexp);
2625         ast_delete(var);
2626         parseerror(parser, "expected array-size as constant positive integer");
2627         return NULL;
2628     }
2629     cval = (ast_value*)cexp;
2630
2631     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2632     tmp->expression.next = (ast_expression*)var;
2633     var = tmp;
2634
2635     if (cval->expression.vtype == TYPE_INTEGER)
2636         tmp->expression.count = cval->constval.vint;
2637     else if (cval->expression.vtype == TYPE_FLOAT)
2638         tmp->expression.count = cval->constval.vfloat;
2639     else {
2640         ast_unref(cexp);
2641         ast_delete(var);
2642         parseerror(parser, "array-size must be a positive integer constant");
2643         return NULL;
2644     }
2645     ast_unref(cexp);
2646
2647     if (parser->tok != ']') {
2648         ast_delete(var);
2649         parseerror(parser, "expected ']' after array-size");
2650         return NULL;
2651     }
2652     if (!parser_next(parser)) {
2653         ast_delete(var);
2654         parseerror(parser, "error after parsing array size");
2655         return NULL;
2656     }
2657     return var;
2658 }
2659
2660 /* Parse a complete typename.
2661  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2662  * but when parsing variables separated by comma
2663  * 'storebase' should point to where the base-type should be kept.
2664  * The base type makes up every bit of type information which comes *before* the
2665  * variable name.
2666  *
2667  * The following will be parsed in its entirety:
2668  *     void() foo()
2669  * The 'basetype' in this case is 'void()'
2670  * and if there's a comma after it, say:
2671  *     void() foo(), bar
2672  * then the type-information 'void()' can be stored in 'storebase'
2673  */
2674 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2675 {
2676     ast_value *var, *tmp;
2677     lex_ctx    ctx;
2678
2679     const char *name = NULL;
2680     bool        isfield  = false;
2681     bool        wasarray = false;
2682
2683     ctx = parser_ctx(parser);
2684
2685     /* types may start with a dot */
2686     if (parser->tok == '.') {
2687         isfield = true;
2688         /* if we parsed a dot we need a typename now */
2689         if (!parser_next(parser)) {
2690             parseerror(parser, "expected typename for field definition");
2691             return NULL;
2692         }
2693         if (parser->tok != TOKEN_TYPENAME) {
2694             parseerror(parser, "expected typename");
2695             return NULL;
2696         }
2697     }
2698
2699     /* generate the basic type value */
2700     var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2701     /* do not yet turn into a field - remember:
2702      * .void() foo; is a field too
2703      * .void()() foo; is a function
2704      */
2705
2706     /* parse on */
2707     if (!parser_next(parser)) {
2708         ast_delete(var);
2709         parseerror(parser, "parse error after typename");
2710         return NULL;
2711     }
2712
2713     /* an opening paren now starts the parameter-list of a function
2714      * this is where original-QC has parameter lists.
2715      * We allow a single parameter list here.
2716      * Much like fteqcc we don't allow `float()() x`
2717      */
2718     if (parser->tok == '(') {
2719         var = parse_parameter_list(parser, var);
2720         if (!var)
2721             return NULL;
2722     }
2723
2724     /* store the base if requested */
2725     if (storebase) {
2726         *storebase = ast_value_copy(var);
2727         if (isfield) {
2728             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2729             tmp->expression.next = (ast_expression*)*storebase;
2730             *storebase = tmp;
2731         }
2732     }
2733
2734     /* there may be a name now */
2735     if (parser->tok == TOKEN_IDENT) {
2736         name = util_strdup(parser_tokval(parser));
2737         /* parse on */
2738         if (!parser_next(parser)) {
2739             ast_delete(var);
2740             parseerror(parser, "error after variable or field declaration");
2741             return NULL;
2742         }
2743     }
2744
2745     /* now this may be an array */
2746     if (parser->tok == '[') {
2747         wasarray = true;
2748         var = parse_arraysize(parser, var);
2749         if (!var)
2750             return NULL;
2751     }
2752
2753     /* This is the point where we can turn it into a field */
2754     if (isfield) {
2755         /* turn it into a field if desired */
2756         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2757         tmp->expression.next = (ast_expression*)var;
2758         var = tmp;
2759     }
2760
2761     /* now there may be function parens again */
2762     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2763         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2764     if (parser->tok == '(' && wasarray)
2765         parseerror(parser, "arrays as part of a return type is not supported");
2766     while (parser->tok == '(') {
2767         var = parse_parameter_list(parser, var);
2768         if (!var) {
2769             if (name)
2770                 mem_d((void*)name);
2771             ast_delete(var);
2772             return NULL;
2773         }
2774     }
2775
2776     /* finally name it */
2777     if (name) {
2778         if (!ast_value_set_name(var, name)) {
2779             ast_delete(var);
2780             parseerror(parser, "internal error: failed to set name");
2781             return NULL;
2782         }
2783         /* free the name, ast_value_set_name duplicates */
2784         mem_d((void*)name);
2785     }
2786
2787     return var;
2788 }
2789
2790 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2791 {
2792     ast_value *var;
2793     ast_value *proto;
2794     ast_expression *old;
2795     bool       was_end;
2796     size_t     i;
2797
2798     ast_value *basetype = NULL;
2799     bool      retval    = true;
2800     bool      isparam   = false;
2801     bool      isvector  = false;
2802     bool      cleanvar  = true;
2803     bool      wasarray  = false;
2804
2805     varentry_t varent, ve[3];
2806
2807     /* get the first complete variable */
2808     var = parse_typename(parser, &basetype);
2809     if (!var) {
2810         if (basetype)
2811             ast_delete(basetype);
2812         return false;
2813     }
2814
2815     memset(&varent, 0, sizeof(varent));
2816     memset(&ve, 0, sizeof(ve));
2817
2818     while (true) {
2819         proto = NULL;
2820         wasarray = false;
2821
2822         /* Part 0: finish the type */
2823         if (parser->tok == '(') {
2824             if (opts_standard == COMPILER_QCC)
2825                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2826             var = parse_parameter_list(parser, var);
2827             if (!var) {
2828                 retval = false;
2829                 goto cleanup;
2830             }
2831         }
2832         /* we only allow 1-dimensional arrays */
2833         if (parser->tok == '[') {
2834             wasarray = true;
2835             var = parse_arraysize(parser, var);
2836             if (!var) {
2837                 retval = false;
2838                 goto cleanup;
2839             }
2840         }
2841         if (parser->tok == '(' && wasarray) {
2842             parseerror(parser, "arrays as part of a return type is not supported");
2843             /* we'll still parse the type completely for now */
2844         }
2845         /* for functions returning functions */
2846         while (parser->tok == '(') {
2847             if (opts_standard == COMPILER_QCC)
2848                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2849             var = parse_parameter_list(parser, var);
2850             if (!var) {
2851                 retval = false;
2852                 goto cleanup;
2853             }
2854         }
2855
2856         /* Part 1:
2857          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2858          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2859          * is then filled with the previous definition and the parameter-names replaced.
2860          */
2861         if (!localblock) {
2862             /* Deal with end_sys_ vars */
2863             was_end = false;
2864             if (!strcmp(var->name, "end_sys_globals")) {
2865                 parser->crc_globals = parser->globals_count;
2866                 was_end = true;
2867             }
2868             else if (!strcmp(var->name, "end_sys_fields")) {
2869                 parser->crc_fields = parser->fields_count;
2870                 was_end = true;
2871             }
2872             if (was_end && var->expression.vtype == TYPE_FIELD) {
2873                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2874                                  "global '%s' hint should not be a field",
2875                                  parser_tokval(parser)))
2876                 {
2877                     retval = false;
2878                     goto cleanup;
2879                 }
2880             }
2881
2882             if (!nofields && var->expression.vtype == TYPE_FIELD)
2883             {
2884                 /* deal with field declarations */
2885                 old = parser_find_field(parser, var->name);
2886                 if (old) {
2887                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2888                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2889                     {
2890                         retval = false;
2891                         goto cleanup;
2892                     }
2893                     ast_delete(var);
2894                     var = NULL;
2895                     goto skipvar;
2896                     /*
2897                     parseerror(parser, "field `%s` already declared here: %s:%i",
2898                                var->name, ast_ctx(old).file, ast_ctx(old).line);
2899                     retval = false;
2900                     goto cleanup;
2901                     */
2902                 }
2903                 if (opts_standard == COMPILER_QCC &&
2904                     (old = parser_find_global(parser, var->name)))
2905                 {
2906                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2907                     parseerror(parser, "field `%s` already declared here: %s:%i",
2908                                var->name, ast_ctx(old).file, ast_ctx(old).line);
2909                     retval = false;
2910                     goto cleanup;
2911                 }
2912             }
2913             else
2914             {
2915                 /* deal with other globals */
2916                 old = parser_find_global(parser, var->name);
2917                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
2918                 {
2919                     /* This is a function which had a prototype */
2920                     if (!ast_istype(old, ast_value)) {
2921                         parseerror(parser, "internal error: prototype is not an ast_value");
2922                         retval = false;
2923                         goto cleanup;
2924                     }
2925                     proto = (ast_value*)old;
2926                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
2927                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
2928                                    proto->name,
2929                                    ast_ctx(proto).file, ast_ctx(proto).line);
2930                         retval = false;
2931                         goto cleanup;
2932                     }
2933                     /* we need the new parameter-names */
2934                     for (i = 0; i < proto->expression.params_count; ++i)
2935                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
2936                     ast_delete(var);
2937                     var = proto;
2938                 }
2939                 else
2940                 {
2941                     /* other globals */
2942                     if (old) {
2943                         parseerror(parser, "global `%s` already declared here: %s:%i",
2944                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
2945                         retval = false;
2946                         goto cleanup;
2947                     }
2948                     if (opts_standard == COMPILER_QCC &&
2949                         (old = parser_find_field(parser, var->name)))
2950                     {
2951                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2952                         parseerror(parser, "global `%s` already declared here: %s:%i",
2953                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
2954                         retval = false;
2955                         goto cleanup;
2956                     }
2957                 }
2958             }
2959         }
2960         else /* it's not a global */
2961         {
2962             old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
2963             if (old && !isparam) {
2964                 parseerror(parser, "local `%s` already declared here: %s:%i",
2965                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2966                 retval = false;
2967                 goto cleanup;
2968             }
2969             old = parser_find_local(parser, var->name, 0, &isparam);
2970             if (old && isparam) {
2971                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
2972                                  "local `%s` is shadowing a parameter", var->name))
2973                 {
2974                     parseerror(parser, "local `%s` already declared here: %s:%i",
2975                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2976                     retval = false;
2977                     goto cleanup;
2978                 }
2979                 if (opts_standard != COMPILER_GMQCC) {
2980                     ast_delete(var);
2981                     var = NULL;
2982                     goto skipvar;
2983                 }
2984             }
2985         }
2986
2987         /* Part 2:
2988          * Create the global/local, and deal with vector types.
2989          */
2990         if (!proto) {
2991             if (var->expression.vtype == TYPE_VECTOR)
2992                 isvector = true;
2993             else if (var->expression.vtype == TYPE_FIELD &&
2994                      var->expression.next->expression.vtype == TYPE_VECTOR)
2995                 isvector = true;
2996
2997             if (isvector) {
2998                 if (!create_vector_members(parser, var, ve)) {
2999                     retval = false;
3000                     goto cleanup;
3001                 }
3002             }
3003
3004             varent.name = util_strdup(var->name);
3005             varent.var  = (ast_expression*)var;
3006
3007             if (!localblock) {
3008                 /* deal with global variables, fields, functions */
3009                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3010                     if (!(retval = parser_t_fields_add(parser, varent)))
3011                         goto cleanup;
3012                     if (isvector) {
3013                         for (i = 0; i < 3; ++i) {
3014                             if (!(retval = parser_t_fields_add(parser, ve[i])))
3015                                 break;
3016                         }
3017                         if (!retval) {
3018                             parser->fields_count -= i+1;
3019                             goto cleanup;
3020                         }
3021                     }
3022                 }
3023                 else {
3024                     if (!(retval = parser_t_globals_add(parser, varent)))
3025                         goto cleanup;
3026                     if (isvector) {
3027                         for (i = 0; i < 3; ++i) {
3028                             if (!(retval = parser_t_globals_add(parser, ve[i])))
3029                                 break;
3030                         }
3031                         if (!retval) {
3032                             parser->globals_count -= i+1;
3033                             goto cleanup;
3034                         }
3035                     }
3036                 }
3037             } else {
3038                 if (!(retval = parser_t_locals_add(parser, varent)))
3039                     goto cleanup;
3040                 if (!(retval = ast_block_locals_add(localblock, var))) {
3041                     parser->locals_count--;
3042                     goto cleanup;
3043                 }
3044                 if (isvector) {
3045                     for (i = 0; i < 3; ++i) {
3046                         if (!(retval = parser_t_locals_add(parser, ve[i])))
3047                             break;
3048                         if (!(retval = ast_block_collect(localblock, ve[i].var)))
3049                             break;
3050                         ve[i].var = NULL; /* from here it's being collected in the block */
3051                     }
3052                     if (!retval) {
3053                         parser->locals_count -= i+1;
3054                         localblock->locals_count--;
3055                         goto cleanup;
3056                     }
3057                 }
3058             }
3059
3060             varent.name = NULL;
3061             ve[0].name = ve[1].name = ve[2].name = NULL;
3062             ve[0].var  = ve[1].var  = ve[2].var  = NULL;
3063             cleanvar = false;
3064         }
3065         /* Part 2.2
3066          * deal with arrays
3067          */
3068         if (var->expression.vtype == TYPE_ARRAY) {
3069             char          name[1024];
3070             snprintf(name, sizeof(name), "%s::SET", var->name);
3071             if (!parser_create_array_setter(parser, var, name))
3072                 goto cleanup;
3073             snprintf(name, sizeof(name), "%s::GET", var->name);
3074             if (!parser_create_array_getter(parser, var, name))
3075                 goto cleanup;
3076         }
3077
3078 skipvar:
3079         if (parser->tok == ';') {
3080             ast_delete(basetype);
3081             if (!parser_next(parser)) {
3082                 parseerror(parser, "error after variable declaration");
3083                 return false;
3084             }
3085             return true;
3086         }
3087
3088         if (parser->tok == ',')
3089             goto another;
3090
3091         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3092             parseerror(parser, "missing comma or semicolon while parsing variables");
3093             break;
3094         }
3095
3096         if (localblock && opts_standard == COMPILER_QCC) {
3097             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3098                              "initializing expression turns variable `%s` into a constant in this standard",
3099                              var->name) )
3100             {
3101                 break;
3102             }
3103         }
3104
3105         if (parser->tok != '{') {
3106             if (parser->tok != '=') {
3107                 parseerror(parser, "missing semicolon or initializer");
3108                 break;
3109             }
3110
3111             if (!parser_next(parser)) {
3112                 parseerror(parser, "error parsing initializer");
3113                 break;
3114             }
3115         }
3116         else if (opts_standard == COMPILER_QCC) {
3117             parseerror(parser, "expected '=' before function body in this standard");
3118         }
3119
3120         if (parser->tok == '#') {
3121             ast_function *func;
3122
3123             if (localblock) {
3124                 parseerror(parser, "cannot declare builtins within functions");
3125                 break;
3126             }
3127             if (var->expression.vtype != TYPE_FUNCTION) {
3128                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3129                 break;
3130             }
3131             if (!parser_next(parser)) {
3132                 parseerror(parser, "expected builtin number");
3133                 break;
3134             }
3135             if (parser->tok != TOKEN_INTCONST) {
3136                 parseerror(parser, "builtin number must be an integer constant");
3137                 break;
3138             }
3139             if (parser_token(parser)->constval.i <= 0) {
3140                 parseerror(parser, "builtin number must be an integer greater than zero");
3141                 break;
3142             }
3143
3144             func = ast_function_new(ast_ctx(var), var->name, var);
3145             if (!func) {
3146                 parseerror(parser, "failed to allocate function for `%s`", var->name);
3147                 break;
3148             }
3149             if (!parser_t_functions_add(parser, func)) {
3150                 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
3151                 ast_function_delete(func);
3152                 var->constval.vfunc = NULL;
3153                 break;
3154             }
3155
3156             func->builtin = -parser_token(parser)->constval.i;
3157
3158             if (!parser_next(parser)) {
3159                 parseerror(parser, "expected comma or semicolon");
3160                 ast_function_delete(func);
3161                 var->constval.vfunc = NULL;
3162                 break;
3163             }
3164         }
3165         else if (parser->tok == '{' || parser->tok == '[')
3166         {
3167             if (localblock) {
3168                 parseerror(parser, "cannot declare functions within functions");
3169                 break;
3170             }
3171
3172             if (!parse_function_body(parser, var))
3173                 break;
3174             ast_delete(basetype);
3175             return true;
3176         } else {
3177             ast_expression *cexp;
3178             ast_value      *cval;
3179
3180             cexp = parse_expression_leave(parser, true);
3181             if (!cexp)
3182                 break;
3183
3184             if (!localblock) {
3185                 cval = (ast_value*)cexp;
3186                 if (!ast_istype(cval, ast_value) || !cval->isconst)
3187                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3188                 else
3189                 {
3190                     var->isconst = true;
3191                     if (cval->expression.vtype == TYPE_STRING)
3192                         var->constval.vstring = parser_strdup(cval->constval.vstring);
3193                     else
3194                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3195                     ast_unref(cval);
3196                 }
3197             } else {
3198                 shunt sy;
3199                 MEM_VECTOR_INIT(&sy, out);
3200                 MEM_VECTOR_INIT(&sy, ops);
3201                 if (!shunt_out_add(&sy, syexp(ast_ctx(var), (ast_expression*)var)) ||
3202                     !shunt_out_add(&sy, syexp(ast_ctx(cexp), (ast_expression*)cexp)) ||
3203                     !shunt_ops_add(&sy, syop(ast_ctx(var), parser->assign_op)))
3204                 {
3205                     parseerror(parser, "internal error: failed to prepare initializer");
3206                     ast_unref(cexp);
3207                 }
3208                 else if (!parser_sy_pop(parser, &sy))
3209                     ast_unref(cexp);
3210                 else {
3211                     if (sy.out_count != 1 && sy.ops_count != 0)
3212                         parseerror(parser, "internal error: leaked operands");
3213                     else if (!ast_block_exprs_add(localblock, (ast_expression*)sy.out[0].out)) {
3214                         parseerror(parser, "failed to create intializing expression");
3215                         ast_unref(sy.out[0].out);
3216                         ast_unref(cexp);
3217                     }
3218                 }
3219                 MEM_VECTOR_CLEAR(&sy, out);
3220                 MEM_VECTOR_CLEAR(&sy, ops);
3221             }
3222         }
3223
3224 another:
3225         if (parser->tok == ',') {
3226             if (!parser_next(parser)) {
3227                 parseerror(parser, "expected another variable");
3228                 break;
3229             }
3230
3231             if (parser->tok != TOKEN_IDENT) {
3232                 parseerror(parser, "expected another variable");
3233                 break;
3234             }
3235             var = ast_value_copy(basetype);
3236             cleanvar = true;
3237             ast_value_set_name(var, parser_tokval(parser));
3238             if (!parser_next(parser)) {
3239                 parseerror(parser, "error parsing variable declaration");
3240                 break;
3241             }
3242             continue;
3243         }
3244
3245         if (parser->tok != ';') {
3246             parseerror(parser, "missing semicolon after variables");
3247             break;
3248         }
3249
3250         if (!parser_next(parser)) {
3251             parseerror(parser, "parse error after variable declaration");
3252             break;
3253         }
3254
3255         ast_delete(basetype);
3256         return true;
3257     }
3258
3259     if (cleanvar && var)
3260         ast_delete(var);
3261     ast_delete(basetype);
3262     return false;
3263
3264 cleanup:
3265     ast_delete(basetype);
3266     if (cleanvar && var)
3267         ast_delete(var);
3268     if (varent.name) mem_d(varent.name);
3269     if (ve[0].name)  mem_d(ve[0].name);
3270     if (ve[1].name)  mem_d(ve[1].name);
3271     if (ve[2].name)  mem_d(ve[2].name);
3272     if (ve[0].var)   mem_d(ve[0].var);
3273     if (ve[1].var)   mem_d(ve[1].var);
3274     if (ve[2].var)   mem_d(ve[2].var);
3275     return retval;
3276 }
3277
3278 static bool parser_global_statement(parser_t *parser)
3279 {
3280     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3281     {
3282         return parse_variable(parser, NULL, false);
3283     }
3284     else if (parser->tok == TOKEN_KEYWORD)
3285     {
3286         /* handle 'var' and 'const' */
3287         if (!strcmp(parser_tokval(parser), "var")) {
3288             if (!parser_next(parser)) {
3289                 parseerror(parser, "expected variable declaration after 'var'");
3290                 return false;
3291             }
3292             return parse_variable(parser, NULL, true);
3293         }
3294         return false;
3295     }
3296     else if (parser->tok == '$')
3297     {
3298         if (!parser_next(parser)) {
3299             parseerror(parser, "parse error");
3300             return false;
3301         }
3302     }
3303     else
3304     {
3305         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3306         return false;
3307     }
3308     return true;
3309 }
3310
3311 static parser_t *parser;
3312
3313 bool parser_init()
3314 {
3315     size_t i;
3316     parser = (parser_t*)mem_a(sizeof(parser_t));
3317     if (!parser)
3318         return false;
3319
3320     memset(parser, 0, sizeof(*parser));
3321
3322     for (i = 0; i < operator_count; ++i) {
3323         if (operators[i].id == opid1('=')) {
3324             parser->assign_op = operators+i;
3325             break;
3326         }
3327     }
3328     if (!parser->assign_op) {
3329         printf("internal error: initializing parser: failed to find assign operator\n");
3330         mem_d(parser);
3331         return false;
3332     }
3333     return true;
3334 }
3335
3336 bool parser_compile(const char *filename)
3337 {
3338     parser->lex = lex_open(filename);
3339     if (!parser->lex) {
3340         printf("failed to open file \"%s\"\n", filename);
3341         return false;
3342     }
3343
3344     /* initial lexer/parser state */
3345     parser->lex->flags.noops = true;
3346
3347     if (parser_next(parser))
3348     {
3349         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3350         {
3351             if (!parser_global_statement(parser)) {
3352                 if (parser->tok == TOKEN_EOF)
3353                     parseerror(parser, "unexpected eof");
3354                 else if (!parser->errors)
3355                     parseerror(parser, "there have been errors, bailing out");
3356                 lex_close(parser->lex);
3357                 parser->lex = NULL;
3358                 return false;
3359             }
3360         }
3361     } else {
3362         parseerror(parser, "parse error");
3363         lex_close(parser->lex);
3364         parser->lex = NULL;
3365         return false;
3366     }
3367
3368     lex_close(parser->lex);
3369     parser->lex = NULL;
3370
3371     return !parser->errors;
3372 }
3373
3374 void parser_cleanup()
3375 {
3376     size_t i;
3377     for (i = 0; i < parser->functions_count; ++i) {
3378         ast_delete(parser->functions[i]);
3379     }
3380     for (i = 0; i < parser->imm_vector_count; ++i) {
3381         ast_delete(parser->imm_vector[i]);
3382     }
3383     for (i = 0; i < parser->imm_string_count; ++i) {
3384         ast_delete(parser->imm_string[i]);
3385     }
3386     for (i = 0; i < parser->imm_float_count; ++i) {
3387         ast_delete(parser->imm_float[i]);
3388     }
3389     for (i = 0; i < parser->fields_count; ++i) {
3390         ast_delete(parser->fields[i].var);
3391         mem_d(parser->fields[i].name);
3392     }
3393     for (i = 0; i < parser->globals_count; ++i) {
3394         ast_delete(parser->globals[i].var);
3395         mem_d(parser->globals[i].name);
3396     }
3397     MEM_VECTOR_CLEAR(parser, functions);
3398     MEM_VECTOR_CLEAR(parser, imm_vector);
3399     MEM_VECTOR_CLEAR(parser, imm_string);
3400     MEM_VECTOR_CLEAR(parser, imm_float);
3401     MEM_VECTOR_CLEAR(parser, globals);
3402     MEM_VECTOR_CLEAR(parser, fields);
3403     MEM_VECTOR_CLEAR(parser, locals);
3404
3405     mem_d(parser);
3406 }
3407
3408 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3409 {
3410     return util_crc16(old, str, strlen(str));
3411 }
3412
3413 static void progdefs_crc_file(const char *str)
3414 {
3415     /* write to progdefs.h here */
3416 }
3417
3418 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3419 {
3420     old = progdefs_crc_sum(old, str);
3421     progdefs_crc_file(str);
3422     return old;
3423 }
3424
3425 static void generate_checksum(parser_t *parser)
3426 {
3427     uint16_t crc = 0xFFFF;
3428     size_t i;
3429
3430         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3431         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3432         /*
3433         progdefs_crc_file("\tint\tpad;\n");
3434         progdefs_crc_file("\tint\tofs_return[3];\n");
3435         progdefs_crc_file("\tint\tofs_parm0[3];\n");
3436         progdefs_crc_file("\tint\tofs_parm1[3];\n");
3437         progdefs_crc_file("\tint\tofs_parm2[3];\n");
3438         progdefs_crc_file("\tint\tofs_parm3[3];\n");
3439         progdefs_crc_file("\tint\tofs_parm4[3];\n");
3440         progdefs_crc_file("\tint\tofs_parm5[3];\n");
3441         progdefs_crc_file("\tint\tofs_parm6[3];\n");
3442         progdefs_crc_file("\tint\tofs_parm7[3];\n");
3443         */
3444         for (i = 0; i < parser->crc_globals; ++i) {
3445             if (!ast_istype(parser->globals[i].var, ast_value))
3446                 continue;
3447             switch (parser->globals[i].var->expression.vtype) {
3448                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3449                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3450                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3451                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3452                 default:
3453                     crc = progdefs_crc_both(crc, "\tint\t");
3454                     break;
3455             }
3456             crc = progdefs_crc_both(crc, parser->globals[i].name);
3457             crc = progdefs_crc_both(crc, ";\n");
3458         }
3459         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3460         for (i = 0; i < parser->crc_fields; ++i) {
3461             if (!ast_istype(parser->fields[i].var, ast_value))
3462                 continue;
3463             switch (parser->fields[i].var->expression.next->expression.vtype) {
3464                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3465                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3466                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3467                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3468                 default:
3469                     crc = progdefs_crc_both(crc, "\tint\t");
3470                     break;
3471             }
3472             crc = progdefs_crc_both(crc, parser->fields[i].name);
3473             crc = progdefs_crc_both(crc, ";\n");
3474         }
3475         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3476
3477         code_crc = crc;
3478 }
3479
3480 bool parser_finish(const char *output)
3481 {
3482     size_t i;
3483     ir_builder *ir;
3484     bool retval = true;
3485
3486     if (!parser->errors)
3487     {
3488         ir = ir_builder_new("gmqcc_out");
3489         if (!ir) {
3490             printf("failed to allocate builder\n");
3491             return false;
3492         }
3493
3494         for (i = 0; i < parser->fields_count; ++i) {
3495             ast_value *field;
3496             bool isconst;
3497             if (!ast_istype(parser->fields[i].var, ast_value))
3498                 continue;
3499             field = (ast_value*)parser->fields[i].var;
3500             isconst = field->isconst;
3501             field->isconst = false;
3502             if (!ast_global_codegen((ast_value*)field, ir, true)) {
3503                 printf("failed to generate field %s\n", field->name);
3504                 ir_builder_delete(ir);
3505                 return false;
3506             }
3507             if (isconst) {
3508                 ir_value *ifld;
3509                 ast_expression *subtype;
3510                 field->isconst = true;
3511                 subtype = field->expression.next;
3512                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3513                 if (subtype->expression.vtype == TYPE_FIELD)
3514                     ifld->fieldtype = subtype->expression.next->expression.vtype;
3515                 else if (subtype->expression.vtype == TYPE_FUNCTION)
3516                     ifld->outtype = subtype->expression.next->expression.vtype;
3517                 (void)!ir_value_set_field(field->ir_v, ifld);
3518             }
3519         }
3520         for (i = 0; i < parser->globals_count; ++i) {
3521             ast_value *asvalue;
3522             if (!ast_istype(parser->globals[i].var, ast_value))
3523                 continue;
3524             asvalue = (ast_value*)(parser->globals[i].var);
3525             if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3526                 if (strcmp(asvalue->name, "end_sys_globals") &&
3527                     strcmp(asvalue->name, "end_sys_fields"))
3528                 {
3529                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3530                                                    "unused global: `%s`", asvalue->name);
3531                 }
3532             }
3533             if (!ast_global_codegen(asvalue, ir, false)) {
3534                 printf("failed to generate global %s\n", parser->globals[i].name);
3535                 ir_builder_delete(ir);
3536                 return false;
3537             }
3538         }
3539         for (i = 0; i < parser->imm_float_count; ++i) {
3540             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3541                 printf("failed to generate global %s\n", parser->imm_float[i]->name);
3542                 ir_builder_delete(ir);
3543                 return false;
3544             }
3545         }
3546         for (i = 0; i < parser->imm_string_count; ++i) {
3547             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3548                 printf("failed to generate global %s\n", parser->imm_string[i]->name);
3549                 ir_builder_delete(ir);
3550                 return false;
3551             }
3552         }
3553         for (i = 0; i < parser->imm_vector_count; ++i) {
3554             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3555                 printf("failed to generate global %s\n", parser->imm_vector[i]->name);
3556                 ir_builder_delete(ir);
3557                 return false;
3558             }
3559         }
3560         for (i = 0; i < parser->globals_count; ++i) {
3561             ast_value *asvalue;
3562             if (!ast_istype(parser->globals[i].var, ast_value))
3563                 continue;
3564             asvalue = (ast_value*)(parser->globals[i].var);
3565             if (asvalue->setter) {
3566                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3567                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir))
3568                 {
3569                     printf("failed to generate setter for %s\n", parser->globals[i].name);
3570                     ir_builder_delete(ir);
3571                     return false;
3572                 }
3573             }
3574             if (asvalue->getter) {
3575                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3576                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir))
3577                 {
3578                     printf("failed to generate getter for %s\n", parser->globals[i].name);
3579                     ir_builder_delete(ir);
3580                     return false;
3581                 }
3582             }
3583         }
3584         for (i = 0; i < parser->functions_count; ++i) {
3585             if (!ast_function_codegen(parser->functions[i], ir)) {
3586                 printf("failed to generate function %s\n", parser->functions[i]->name);
3587                 ir_builder_delete(ir);
3588                 return false;
3589             }
3590             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3591                 printf("failed to finalize function %s\n", parser->functions[i]->name);
3592                 ir_builder_delete(ir);
3593                 return false;
3594             }
3595         }
3596
3597         if (retval) {
3598             if (opts_dump)
3599                 ir_builder_dump(ir, printf);
3600
3601             generate_checksum(parser);
3602
3603             if (!ir_builder_generate(ir, output)) {
3604                 printf("*** failed to generate output file\n");
3605                 ir_builder_delete(ir);
3606                 return false;
3607             }
3608         }
3609
3610         ir_builder_delete(ir);
3611         return retval;
3612     }
3613
3614     printf("*** there were compile errors\n");
3615     return false;
3616 }