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