]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Store accessors in the ast_value for access from within the ast - generate accessors...
[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
2331     if (!ast_istype(array->expression.next, ast_value)) {
2332         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2333         return false;
2334     }
2335
2336     body = ast_block_new(ast_ctx(array));
2337     if (!body) {
2338         parseerror(parser, "failed to create block for array accessor");
2339         return false;
2340     }
2341
2342     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2343     value = ast_value_copy((ast_value*)array->expression.next);
2344
2345     if (!index || !value) {
2346         ast_delete(body);
2347         if (index) ast_delete(index);
2348         if (value) ast_delete(value);
2349         parseerror(parser, "failed to create locals for array accessor");
2350         return false;
2351     }
2352
2353     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2354     if (!root) {
2355         parseerror(parser, "failed to build accessor search tree");
2356         goto cleanup;
2357     }
2358
2359     if (!ast_block_exprs_add(body, root)) {
2360         parseerror(parser, "failed to build accessor search block");
2361         goto cleanup;
2362     }
2363
2364     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2365     if (!fval) {
2366         parseerror(parser, "failed to create accessor function value");
2367         goto cleanup;
2368     }
2369     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2370
2371     (void)!ast_value_set_name(value, "value"); /* not important */
2372     if (!ast_expression_common_params_add(&fval->expression, index)) {
2373         parseerror(parser, "failed to build array setter");
2374         goto cleanup;
2375     }
2376     if (!ast_expression_common_params_add(&fval->expression, value)) {
2377         ast_delete(index);
2378         parseerror(parser, "failed to build array setter");
2379         goto cleanup2;
2380     }
2381
2382     func = ast_function_new(ast_ctx(array), funcname, fval);
2383     if (!func) {
2384         parseerror(parser, "failed to create accessor function node");
2385         goto cleanup2;
2386     }
2387
2388     if (!ast_function_blocks_add(func, body))
2389         goto cleanup2;
2390
2391     array->setter = fval;
2392
2393     return true;
2394 cleanup:
2395     ast_delete(index);
2396     ast_delete(value);
2397 cleanup2:
2398     ast_delete(body);
2399     if (root) ast_delete(root);
2400     if (func) ast_delete(func);
2401     if (fval) ast_delete(fval);
2402     return false;
2403 }
2404
2405 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const char *funcname)
2406 {
2407     ast_expression *root = NULL;
2408     ast_function   *func = NULL;
2409     ast_value      *fval = NULL;
2410     ast_block      *body;
2411     ast_value      *index;
2412
2413     if (!ast_istype(array->expression.next, ast_value)) {
2414         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2415         return false;
2416     }
2417
2418     body = ast_block_new(ast_ctx(array));
2419     if (!body) {
2420         parseerror(parser, "failed to create block for array accessor");
2421         return false;
2422     }
2423
2424     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2425
2426     if (!index) {
2427         ast_delete(body);
2428         if (index) ast_delete(index);
2429         parseerror(parser, "failed to create locals for array accessor");
2430         return false;
2431     }
2432
2433     root = array_getter_node(parser, array, index, 0, array->expression.count);
2434     if (!root) {
2435         parseerror(parser, "failed to build accessor search tree");
2436         goto cleanup;
2437     }
2438
2439     if (!ast_block_exprs_add(body, root)) {
2440         parseerror(parser, "failed to build accessor search block");
2441         goto cleanup;
2442     }
2443
2444     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2445     if (!fval) {
2446         parseerror(parser, "failed to create accessor function value");
2447         goto cleanup;
2448     }
2449     fval->expression.next = ast_type_copy(ast_ctx(array), array->expression.next);
2450
2451     if (!ast_expression_common_params_add(&fval->expression, index)) {
2452         parseerror(parser, "failed to build array setter");
2453         goto cleanup;
2454     }
2455
2456     func = ast_function_new(ast_ctx(array), funcname, fval);
2457     if (!func) {
2458         parseerror(parser, "failed to create accessor function node");
2459         goto cleanup2;
2460     }
2461
2462     if (!ast_function_blocks_add(func, body))
2463         goto cleanup2;
2464
2465     array->getter = fval;
2466
2467     return true;
2468 cleanup:
2469     ast_delete(index);
2470 cleanup2:
2471     ast_delete(body);
2472     if (root) ast_delete(root);
2473     if (func) ast_delete(func);
2474     if (fval) ast_delete(fval);
2475     return false;
2476 }
2477
2478 typedef struct {
2479     MEM_VECTOR_MAKE(ast_value*, p);
2480 } paramlist_t;
2481 MEM_VEC_FUNCTIONS(paramlist_t, ast_value*, p)
2482
2483 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2484 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2485 {
2486     lex_ctx     ctx;
2487     size_t      i;
2488     paramlist_t params;
2489     ast_value  *param;
2490     ast_value  *fval;
2491     bool        first = true;
2492     bool        variadic = false;
2493
2494     ctx = parser_ctx(parser);
2495
2496     /* for the sake of less code we parse-in in this function */
2497     if (!parser_next(parser)) {
2498         parseerror(parser, "expected parameter list");
2499         return NULL;
2500     }
2501
2502     MEM_VECTOR_INIT(&params, p);
2503
2504     /* parse variables until we hit a closing paren */
2505     while (parser->tok != ')') {
2506         if (!first) {
2507             /* there must be commas between them */
2508             if (parser->tok != ',') {
2509                 parseerror(parser, "expected comma or end of parameter list");
2510                 goto on_error;
2511             }
2512             if (!parser_next(parser)) {
2513                 parseerror(parser, "expected parameter");
2514                 goto on_error;
2515             }
2516         }
2517         first = false;
2518
2519         if (parser->tok == TOKEN_DOTS) {
2520             /* '...' indicates a varargs function */
2521             variadic = true;
2522             if (!parser_next(parser)) {
2523                 parseerror(parser, "expected parameter");
2524                 return NULL;
2525             }
2526             if (parser->tok != ')') {
2527                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2528                 goto on_error;
2529             }
2530         }
2531         else
2532         {
2533             /* for anything else just parse a typename */
2534             param = parse_typename(parser, NULL);
2535             if (!param)
2536                 goto on_error;
2537             if (!paramlist_t_p_add(&params, param)) {
2538                 ast_delete(param);
2539                 goto on_error;
2540             }
2541             if (param->expression.vtype >= TYPE_VARIANT) {
2542                 char typename[1024];
2543                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
2544                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
2545                 goto on_error;
2546             }
2547         }
2548     }
2549
2550     /* sanity check */
2551     if (params.p_count > 8)
2552         parseerror(parser, "more than 8 parameters are currently not supported");
2553
2554     /* parse-out */
2555     if (!parser_next(parser)) {
2556         parseerror(parser, "parse error after typename");
2557         goto on_error;
2558     }
2559
2560     /* now turn 'var' into a function type */
2561     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2562     fval->expression.next     = (ast_expression*)var;
2563     fval->expression.variadic = variadic;
2564     var = fval;
2565
2566     MEM_VECTOR_MOVE(&params, p, &var->expression, params);
2567
2568     return var;
2569
2570 on_error:
2571     ast_delete(var);
2572     for (i = 0; i < params.p_count; ++i)
2573         ast_delete(params.p[i]);
2574     MEM_VECTOR_CLEAR(&params, p);
2575     return NULL;
2576 }
2577
2578 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2579 {
2580     ast_expression *cexp;
2581     ast_value      *cval, *tmp;
2582     lex_ctx ctx;
2583
2584     ctx = parser_ctx(parser);
2585
2586     if (!parser_next(parser)) {
2587         ast_delete(var);
2588         parseerror(parser, "expected array-size");
2589         return NULL;
2590     }
2591
2592     cexp = parse_expression_leave(parser, true);
2593
2594     if (!cexp || !ast_istype(cexp, ast_value)) {
2595         if (cexp)
2596             ast_unref(cexp);
2597         ast_delete(var);
2598         parseerror(parser, "expected array-size as constant positive integer");
2599         return NULL;
2600     }
2601     cval = (ast_value*)cexp;
2602
2603     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2604     tmp->expression.next = (ast_expression*)var;
2605     var = tmp;
2606
2607     if (cval->expression.vtype == TYPE_INTEGER)
2608         tmp->expression.count = cval->constval.vint;
2609     else if (cval->expression.vtype == TYPE_FLOAT)
2610         tmp->expression.count = cval->constval.vfloat;
2611     else {
2612         ast_unref(cexp);
2613         ast_delete(var);
2614         parseerror(parser, "array-size must be a positive integer constant");
2615         return NULL;
2616     }
2617     ast_unref(cexp);
2618
2619     if (parser->tok != ']') {
2620         ast_delete(var);
2621         parseerror(parser, "expected ']' after array-size");
2622         return NULL;
2623     }
2624     if (!parser_next(parser)) {
2625         ast_delete(var);
2626         parseerror(parser, "error after parsing array size");
2627         return NULL;
2628     }
2629     return var;
2630 }
2631
2632 /* Parse a complete typename.
2633  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2634  * but when parsing variables separated by comma
2635  * 'storebase' should point to where the base-type should be kept.
2636  * The base type makes up every bit of type information which comes *before* the
2637  * variable name.
2638  *
2639  * The following will be parsed in its entirety:
2640  *     void() foo()
2641  * The 'basetype' in this case is 'void()'
2642  * and if there's a comma after it, say:
2643  *     void() foo(), bar
2644  * then the type-information 'void()' can be stored in 'storebase'
2645  */
2646 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2647 {
2648     ast_value *var, *tmp;
2649     lex_ctx    ctx;
2650
2651     const char *name = NULL;
2652     bool        isfield  = false;
2653     bool        wasarray = false;
2654
2655     ctx = parser_ctx(parser);
2656
2657     /* types may start with a dot */
2658     if (parser->tok == '.') {
2659         isfield = true;
2660         /* if we parsed a dot we need a typename now */
2661         if (!parser_next(parser)) {
2662             parseerror(parser, "expected typename for field definition");
2663             return NULL;
2664         }
2665         if (parser->tok != TOKEN_TYPENAME) {
2666             parseerror(parser, "expected typename");
2667             return NULL;
2668         }
2669     }
2670
2671     /* generate the basic type value */
2672     var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2673     /* do not yet turn into a field - remember:
2674      * .void() foo; is a field too
2675      * .void()() foo; is a function
2676      */
2677
2678     /* parse on */
2679     if (!parser_next(parser)) {
2680         ast_delete(var);
2681         parseerror(parser, "parse error after typename");
2682         return NULL;
2683     }
2684
2685     /* an opening paren now starts the parameter-list of a function
2686      * this is where original-QC has parameter lists.
2687      * We allow a single parameter list here.
2688      * Much like fteqcc we don't allow `float()() x`
2689      */
2690     if (parser->tok == '(') {
2691         var = parse_parameter_list(parser, var);
2692         if (!var)
2693             return NULL;
2694     }
2695
2696     /* store the base if requested */
2697     if (storebase) {
2698         *storebase = ast_value_copy(var);
2699         if (isfield) {
2700             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2701             tmp->expression.next = (ast_expression*)*storebase;
2702             *storebase = tmp;
2703         }
2704     }
2705
2706     /* there may be a name now */
2707     if (parser->tok == TOKEN_IDENT) {
2708         name = util_strdup(parser_tokval(parser));
2709         /* parse on */
2710         if (!parser_next(parser)) {
2711             ast_delete(var);
2712             parseerror(parser, "error after variable or field declaration");
2713             return NULL;
2714         }
2715     }
2716
2717     /* now this may be an array */
2718     if (parser->tok == '[') {
2719         wasarray = true;
2720         var = parse_arraysize(parser, var);
2721         if (!var)
2722             return NULL;
2723     }
2724
2725     /* This is the point where we can turn it into a field */
2726     if (isfield) {
2727         /* turn it into a field if desired */
2728         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2729         tmp->expression.next = (ast_expression*)var;
2730         var = tmp;
2731     }
2732
2733     /* now there may be function parens again */
2734     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2735         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2736     if (parser->tok == '(' && wasarray)
2737         parseerror(parser, "arrays as part of a return type is not supported");
2738     while (parser->tok == '(') {
2739         var = parse_parameter_list(parser, var);
2740         if (!var) {
2741             if (name)
2742                 mem_d((void*)name);
2743             ast_delete(var);
2744             return NULL;
2745         }
2746     }
2747
2748     /* finally name it */
2749     if (name) {
2750         if (!ast_value_set_name(var, name)) {
2751             ast_delete(var);
2752             parseerror(parser, "internal error: failed to set name");
2753             return NULL;
2754         }
2755         /* free the name, ast_value_set_name duplicates */
2756         mem_d((void*)name);
2757     }
2758
2759     return var;
2760 }
2761
2762 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2763 {
2764     ast_value *var;
2765     ast_value *proto;
2766     ast_expression *old;
2767     bool       was_end;
2768     size_t     i;
2769
2770     ast_value *basetype = NULL;
2771     bool      retval    = true;
2772     bool      isparam   = false;
2773     bool      isvector  = false;
2774     bool      cleanvar  = true;
2775     bool      wasarray  = false;
2776
2777     varentry_t varent, ve[3];
2778
2779     /* get the first complete variable */
2780     var = parse_typename(parser, &basetype);
2781     if (!var) {
2782         if (basetype)
2783             ast_delete(basetype);
2784         return false;
2785     }
2786
2787     memset(&varent, 0, sizeof(varent));
2788     memset(&ve, 0, sizeof(ve));
2789
2790     while (true) {
2791         proto = NULL;
2792         wasarray = false;
2793
2794         /* Part 0: finish the type */
2795         if (parser->tok == '(') {
2796             if (opts_standard == COMPILER_QCC)
2797                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2798             var = parse_parameter_list(parser, var);
2799             if (!var) {
2800                 retval = false;
2801                 goto cleanup;
2802             }
2803         }
2804         /* we only allow 1-dimensional arrays */
2805         if (parser->tok == '[') {
2806             wasarray = true;
2807             var = parse_arraysize(parser, var);
2808             if (!var) {
2809                 retval = false;
2810                 goto cleanup;
2811             }
2812         }
2813         if (parser->tok == '(' && wasarray) {
2814             parseerror(parser, "arrays as part of a return type is not supported");
2815             /* we'll still parse the type completely for now */
2816         }
2817         /* for functions returning functions */
2818         while (parser->tok == '(') {
2819             if (opts_standard == COMPILER_QCC)
2820                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2821             var = parse_parameter_list(parser, var);
2822             if (!var) {
2823                 retval = false;
2824                 goto cleanup;
2825             }
2826         }
2827
2828         /* Part 1:
2829          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2830          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2831          * is then filled with the previous definition and the parameter-names replaced.
2832          */
2833         if (!localblock) {
2834             /* Deal with end_sys_ vars */
2835             was_end = false;
2836             if (!strcmp(var->name, "end_sys_globals")) {
2837                 parser->crc_globals = parser->globals_count;
2838                 was_end = true;
2839             }
2840             else if (!strcmp(var->name, "end_sys_fields")) {
2841                 parser->crc_fields = parser->fields_count;
2842                 was_end = true;
2843             }
2844             if (was_end && var->expression.vtype == TYPE_FIELD) {
2845                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2846                                  "global '%s' hint should not be a field",
2847                                  parser_tokval(parser)))
2848                 {
2849                     retval = false;
2850                     goto cleanup;
2851                 }
2852             }
2853
2854             if (!nofields && var->expression.vtype == TYPE_FIELD)
2855             {
2856                 /* deal with field declarations */
2857                 old = parser_find_field(parser, var->name);
2858                 if (old) {
2859                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2860                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2861                     {
2862                         retval = false;
2863                         goto cleanup;
2864                     }
2865                     ast_delete(var);
2866                     var = NULL;
2867                     goto skipvar;
2868                     /*
2869                     parseerror(parser, "field `%s` already declared here: %s:%i",
2870                                var->name, ast_ctx(old).file, ast_ctx(old).line);
2871                     retval = false;
2872                     goto cleanup;
2873                     */
2874                 }
2875                 if (opts_standard == COMPILER_QCC &&
2876                     (old = parser_find_global(parser, var->name)))
2877                 {
2878                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2879                     parseerror(parser, "field `%s` already declared here: %s:%i",
2880                                var->name, ast_ctx(old).file, ast_ctx(old).line);
2881                     retval = false;
2882                     goto cleanup;
2883                 }
2884             }
2885             else
2886             {
2887                 /* deal with other globals */
2888                 old = parser_find_global(parser, var->name);
2889                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
2890                 {
2891                     /* This is a function which had a prototype */
2892                     if (!ast_istype(old, ast_value)) {
2893                         parseerror(parser, "internal error: prototype is not an ast_value");
2894                         retval = false;
2895                         goto cleanup;
2896                     }
2897                     proto = (ast_value*)old;
2898                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
2899                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
2900                                    proto->name,
2901                                    ast_ctx(proto).file, ast_ctx(proto).line);
2902                         retval = false;
2903                         goto cleanup;
2904                     }
2905                     /* we need the new parameter-names */
2906                     for (i = 0; i < proto->expression.params_count; ++i)
2907                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
2908                     ast_delete(var);
2909                     var = proto;
2910                 }
2911                 else
2912                 {
2913                     /* other globals */
2914                     if (old) {
2915                         parseerror(parser, "global `%s` already declared here: %s:%i",
2916                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
2917                         retval = false;
2918                         goto cleanup;
2919                     }
2920                     if (opts_standard == COMPILER_QCC &&
2921                         (old = parser_find_field(parser, var->name)))
2922                     {
2923                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2924                         parseerror(parser, "global `%s` already declared here: %s:%i",
2925                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
2926                         retval = false;
2927                         goto cleanup;
2928                     }
2929                 }
2930             }
2931         }
2932         else /* it's not a global */
2933         {
2934             old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
2935             if (old && !isparam) {
2936                 parseerror(parser, "local `%s` already declared here: %s:%i",
2937                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2938                 retval = false;
2939                 goto cleanup;
2940             }
2941             old = parser_find_local(parser, var->name, 0, &isparam);
2942             if (old && isparam) {
2943                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
2944                                  "local `%s` is shadowing a parameter", var->name))
2945                 {
2946                     parseerror(parser, "local `%s` already declared here: %s:%i",
2947                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2948                     retval = false;
2949                     goto cleanup;
2950                 }
2951                 if (opts_standard != COMPILER_GMQCC) {
2952                     ast_delete(var);
2953                     var = NULL;
2954                     goto skipvar;
2955                 }
2956             }
2957         }
2958
2959         /* Part 2:
2960          * Create the global/local, and deal with vector types.
2961          */
2962         if (!proto) {
2963             if (var->expression.vtype == TYPE_VECTOR)
2964                 isvector = true;
2965             else if (var->expression.vtype == TYPE_FIELD &&
2966                      var->expression.next->expression.vtype == TYPE_VECTOR)
2967                 isvector = true;
2968
2969             if (isvector) {
2970                 if (!create_vector_members(parser, var, ve)) {
2971                     retval = false;
2972                     goto cleanup;
2973                 }
2974             }
2975
2976             varent.name = util_strdup(var->name);
2977             varent.var  = (ast_expression*)var;
2978
2979             if (!localblock) {
2980                 /* deal with global variables, fields, functions */
2981                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
2982                     if (!(retval = parser_t_fields_add(parser, varent)))
2983                         goto cleanup;
2984                     if (isvector) {
2985                         for (i = 0; i < 3; ++i) {
2986                             if (!(retval = parser_t_fields_add(parser, ve[i])))
2987                                 break;
2988                         }
2989                         if (!retval) {
2990                             parser->fields_count -= i+1;
2991                             goto cleanup;
2992                         }
2993                     }
2994                 }
2995                 else {
2996                     if (!(retval = parser_t_globals_add(parser, varent)))
2997                         goto cleanup;
2998                     if (isvector) {
2999                         for (i = 0; i < 3; ++i) {
3000                             if (!(retval = parser_t_globals_add(parser, ve[i])))
3001                                 break;
3002                         }
3003                         if (!retval) {
3004                             parser->globals_count -= i+1;
3005                             goto cleanup;
3006                         }
3007                     }
3008                 }
3009             } else {
3010                 if (!(retval = parser_t_locals_add(parser, varent)))
3011                     goto cleanup;
3012                 if (!(retval = ast_block_locals_add(localblock, var))) {
3013                     parser->locals_count--;
3014                     goto cleanup;
3015                 }
3016                 if (isvector) {
3017                     for (i = 0; i < 3; ++i) {
3018                         if (!(retval = parser_t_locals_add(parser, ve[i])))
3019                             break;
3020                         if (!(retval = ast_block_collect(localblock, ve[i].var)))
3021                             break;
3022                         ve[i].var = NULL; /* from here it's being collected in the block */
3023                     }
3024                     if (!retval) {
3025                         parser->locals_count -= i+1;
3026                         localblock->locals_count--;
3027                         goto cleanup;
3028                     }
3029                 }
3030             }
3031
3032             varent.name = NULL;
3033             ve[0].name = ve[1].name = ve[2].name = NULL;
3034             ve[0].var  = ve[1].var  = ve[2].var  = NULL;
3035             cleanvar = false;
3036         }
3037         /* Part 2.2
3038          * deal with arrays
3039          */
3040         if (var->expression.vtype == TYPE_ARRAY) {
3041             char          name[1024];
3042             snprintf(name, sizeof(name), "%s::SET", var->name);
3043             if (!parser_create_array_setter(parser, var, name))
3044                 goto cleanup;
3045             snprintf(name, sizeof(name), "%s::GET", var->name);
3046             if (!parser_create_array_getter(parser, var, name))
3047                 goto cleanup;
3048         }
3049
3050 skipvar:
3051         if (parser->tok == ';') {
3052             ast_delete(basetype);
3053             if (!parser_next(parser)) {
3054                 parseerror(parser, "error after variable declaration");
3055                 return false;
3056             }
3057             return true;
3058         }
3059
3060         if (parser->tok == ',')
3061             goto another;
3062
3063         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3064             parseerror(parser, "missing comma or semicolon while parsing variables");
3065             break;
3066         }
3067
3068         if (localblock && opts_standard == COMPILER_QCC) {
3069             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3070                              "initializing expression turns variable `%s` into a constant in this standard",
3071                              var->name) )
3072             {
3073                 break;
3074             }
3075         }
3076
3077         if (parser->tok != '{') {
3078             if (parser->tok != '=') {
3079                 parseerror(parser, "missing semicolon or initializer");
3080                 break;
3081             }
3082
3083             if (!parser_next(parser)) {
3084                 parseerror(parser, "error parsing initializer");
3085                 break;
3086             }
3087         }
3088         else if (opts_standard == COMPILER_QCC) {
3089             parseerror(parser, "expected '=' before function body in this standard");
3090         }
3091
3092         if (parser->tok == '#') {
3093             ast_function *func;
3094
3095             if (localblock) {
3096                 parseerror(parser, "cannot declare builtins within functions");
3097                 break;
3098             }
3099             if (var->expression.vtype != TYPE_FUNCTION) {
3100                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3101                 break;
3102             }
3103             if (!parser_next(parser)) {
3104                 parseerror(parser, "expected builtin number");
3105                 break;
3106             }
3107             if (parser->tok != TOKEN_INTCONST) {
3108                 parseerror(parser, "builtin number must be an integer constant");
3109                 break;
3110             }
3111             if (parser_token(parser)->constval.i <= 0) {
3112                 parseerror(parser, "builtin number must be an integer greater than zero");
3113                 break;
3114             }
3115
3116             func = ast_function_new(ast_ctx(var), var->name, var);
3117             if (!func) {
3118                 parseerror(parser, "failed to allocate function for `%s`", var->name);
3119                 break;
3120             }
3121             if (!parser_t_functions_add(parser, func)) {
3122                 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
3123                 ast_function_delete(func);
3124                 var->constval.vfunc = NULL;
3125                 break;
3126             }
3127
3128             func->builtin = -parser_token(parser)->constval.i;
3129
3130             if (!parser_next(parser)) {
3131                 parseerror(parser, "expected comma or semicolon");
3132                 ast_function_delete(func);
3133                 var->constval.vfunc = NULL;
3134                 break;
3135             }
3136         }
3137         else if (parser->tok == '{' || parser->tok == '[')
3138         {
3139             if (localblock) {
3140                 parseerror(parser, "cannot declare functions within functions");
3141                 break;
3142             }
3143
3144             if (!parse_function_body(parser, var))
3145                 break;
3146             ast_delete(basetype);
3147             return true;
3148         } else {
3149             ast_expression *cexp;
3150             ast_value      *cval;
3151
3152             cexp = parse_expression_leave(parser, true);
3153             if (!cexp)
3154                 break;
3155
3156             if (!localblock) {
3157                 cval = (ast_value*)cexp;
3158                 if (!ast_istype(cval, ast_value) || !cval->isconst)
3159                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3160                 else
3161                 {
3162                     var->isconst = true;
3163                     if (cval->expression.vtype == TYPE_STRING)
3164                         var->constval.vstring = parser_strdup(cval->constval.vstring);
3165                     else
3166                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3167                     ast_unref(cval);
3168                 }
3169             } else {
3170                 shunt sy;
3171                 MEM_VECTOR_INIT(&sy, out);
3172                 MEM_VECTOR_INIT(&sy, ops);
3173                 if (!shunt_out_add(&sy, syexp(ast_ctx(var), (ast_expression*)var)) ||
3174                     !shunt_out_add(&sy, syexp(ast_ctx(cexp), (ast_expression*)cexp)) ||
3175                     !shunt_ops_add(&sy, syop(ast_ctx(var), parser->assign_op)))
3176                 {
3177                     parseerror(parser, "internal error: failed to prepare initializer");
3178                     ast_unref(cexp);
3179                 }
3180                 else if (!parser_sy_pop(parser, &sy))
3181                     ast_unref(cexp);
3182                 else {
3183                     if (sy.out_count != 1 && sy.ops_count != 0)
3184                         parseerror(parser, "internal error: leaked operands");
3185                     else if (!ast_block_exprs_add(localblock, (ast_expression*)sy.out[0].out)) {
3186                         parseerror(parser, "failed to create intializing expression");
3187                         ast_unref(sy.out[0].out);
3188                         ast_unref(cexp);
3189                     }
3190                 }
3191                 MEM_VECTOR_CLEAR(&sy, out);
3192                 MEM_VECTOR_CLEAR(&sy, ops);
3193             }
3194         }
3195
3196 another:
3197         if (parser->tok == ',') {
3198             if (!parser_next(parser)) {
3199                 parseerror(parser, "expected another variable");
3200                 break;
3201             }
3202
3203             if (parser->tok != TOKEN_IDENT) {
3204                 parseerror(parser, "expected another variable");
3205                 break;
3206             }
3207             var = ast_value_copy(basetype);
3208             cleanvar = true;
3209             ast_value_set_name(var, parser_tokval(parser));
3210             if (!parser_next(parser)) {
3211                 parseerror(parser, "error parsing variable declaration");
3212                 break;
3213             }
3214             continue;
3215         }
3216
3217         if (parser->tok != ';') {
3218             parseerror(parser, "missing semicolon after variables");
3219             break;
3220         }
3221
3222         if (!parser_next(parser)) {
3223             parseerror(parser, "parse error after variable declaration");
3224             break;
3225         }
3226
3227         ast_delete(basetype);
3228         return true;
3229     }
3230
3231     if (cleanvar && var)
3232         ast_delete(var);
3233     ast_delete(basetype);
3234     return false;
3235
3236 cleanup:
3237     ast_delete(basetype);
3238     if (cleanvar && var)
3239         ast_delete(var);
3240     if (varent.name) mem_d(varent.name);
3241     if (ve[0].name)  mem_d(ve[0].name);
3242     if (ve[1].name)  mem_d(ve[1].name);
3243     if (ve[2].name)  mem_d(ve[2].name);
3244     if (ve[0].var)   mem_d(ve[0].var);
3245     if (ve[1].var)   mem_d(ve[1].var);
3246     if (ve[2].var)   mem_d(ve[2].var);
3247     return retval;
3248 }
3249
3250 static bool parser_global_statement(parser_t *parser)
3251 {
3252     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3253     {
3254         return parse_variable(parser, NULL, false);
3255     }
3256     else if (parser->tok == TOKEN_KEYWORD)
3257     {
3258         /* handle 'var' and 'const' */
3259         if (!strcmp(parser_tokval(parser), "var")) {
3260             if (!parser_next(parser)) {
3261                 parseerror(parser, "expected variable declaration after 'var'");
3262                 return false;
3263             }
3264             return parse_variable(parser, NULL, true);
3265         }
3266         return false;
3267     }
3268     else if (parser->tok == '$')
3269     {
3270         if (!parser_next(parser)) {
3271             parseerror(parser, "parse error");
3272             return false;
3273         }
3274     }
3275     else
3276     {
3277         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3278         return false;
3279     }
3280     return true;
3281 }
3282
3283 static parser_t *parser;
3284
3285 bool parser_init()
3286 {
3287     size_t i;
3288     parser = (parser_t*)mem_a(sizeof(parser_t));
3289     if (!parser)
3290         return false;
3291
3292     memset(parser, 0, sizeof(*parser));
3293
3294     for (i = 0; i < operator_count; ++i) {
3295         if (operators[i].id == opid1('=')) {
3296             parser->assign_op = operators+i;
3297             break;
3298         }
3299     }
3300     if (!parser->assign_op) {
3301         printf("internal error: initializing parser: failed to find assign operator\n");
3302         mem_d(parser);
3303         return false;
3304     }
3305     return true;
3306 }
3307
3308 bool parser_compile(const char *filename)
3309 {
3310     parser->lex = lex_open(filename);
3311     if (!parser->lex) {
3312         printf("failed to open file \"%s\"\n", filename);
3313         return false;
3314     }
3315
3316     /* initial lexer/parser state */
3317     parser->lex->flags.noops = true;
3318
3319     if (parser_next(parser))
3320     {
3321         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3322         {
3323             if (!parser_global_statement(parser)) {
3324                 if (parser->tok == TOKEN_EOF)
3325                     parseerror(parser, "unexpected eof");
3326                 else if (!parser->errors)
3327                     parseerror(parser, "there have been errors, bailing out");
3328                 lex_close(parser->lex);
3329                 parser->lex = NULL;
3330                 return false;
3331             }
3332         }
3333     } else {
3334         parseerror(parser, "parse error");
3335         lex_close(parser->lex);
3336         parser->lex = NULL;
3337         return false;
3338     }
3339
3340     lex_close(parser->lex);
3341     parser->lex = NULL;
3342
3343     return !parser->errors;
3344 }
3345
3346 void parser_cleanup()
3347 {
3348     size_t i;
3349     for (i = 0; i < parser->functions_count; ++i) {
3350         ast_delete(parser->functions[i]);
3351     }
3352     for (i = 0; i < parser->imm_vector_count; ++i) {
3353         ast_delete(parser->imm_vector[i]);
3354     }
3355     for (i = 0; i < parser->imm_string_count; ++i) {
3356         ast_delete(parser->imm_string[i]);
3357     }
3358     for (i = 0; i < parser->imm_float_count; ++i) {
3359         ast_delete(parser->imm_float[i]);
3360     }
3361     for (i = 0; i < parser->fields_count; ++i) {
3362         ast_delete(parser->fields[i].var);
3363         mem_d(parser->fields[i].name);
3364     }
3365     for (i = 0; i < parser->globals_count; ++i) {
3366         ast_delete(parser->globals[i].var);
3367         mem_d(parser->globals[i].name);
3368     }
3369     MEM_VECTOR_CLEAR(parser, functions);
3370     MEM_VECTOR_CLEAR(parser, imm_vector);
3371     MEM_VECTOR_CLEAR(parser, imm_string);
3372     MEM_VECTOR_CLEAR(parser, imm_float);
3373     MEM_VECTOR_CLEAR(parser, globals);
3374     MEM_VECTOR_CLEAR(parser, fields);
3375     MEM_VECTOR_CLEAR(parser, locals);
3376
3377     mem_d(parser);
3378 }
3379
3380 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3381 {
3382     return util_crc16(old, str, strlen(str));
3383 }
3384
3385 static void progdefs_crc_file(const char *str)
3386 {
3387     /* write to progdefs.h here */
3388 }
3389
3390 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3391 {
3392     old = progdefs_crc_sum(old, str);
3393     progdefs_crc_file(str);
3394     return old;
3395 }
3396
3397 static void generate_checksum(parser_t *parser)
3398 {
3399     uint16_t crc = 0xFFFF;
3400     size_t i;
3401
3402         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3403         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3404         /*
3405         progdefs_crc_file("\tint\tpad;\n");
3406         progdefs_crc_file("\tint\tofs_return[3];\n");
3407         progdefs_crc_file("\tint\tofs_parm0[3];\n");
3408         progdefs_crc_file("\tint\tofs_parm1[3];\n");
3409         progdefs_crc_file("\tint\tofs_parm2[3];\n");
3410         progdefs_crc_file("\tint\tofs_parm3[3];\n");
3411         progdefs_crc_file("\tint\tofs_parm4[3];\n");
3412         progdefs_crc_file("\tint\tofs_parm5[3];\n");
3413         progdefs_crc_file("\tint\tofs_parm6[3];\n");
3414         progdefs_crc_file("\tint\tofs_parm7[3];\n");
3415         */
3416         for (i = 0; i < parser->crc_globals; ++i) {
3417             if (!ast_istype(parser->globals[i].var, ast_value))
3418                 continue;
3419             switch (parser->globals[i].var->expression.vtype) {
3420                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3421                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3422                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3423                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3424                 default:
3425                     crc = progdefs_crc_both(crc, "\tint\t");
3426                     break;
3427             }
3428             crc = progdefs_crc_both(crc, parser->globals[i].name);
3429             crc = progdefs_crc_both(crc, ";\n");
3430         }
3431         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3432         for (i = 0; i < parser->crc_fields; ++i) {
3433             if (!ast_istype(parser->fields[i].var, ast_value))
3434                 continue;
3435             switch (parser->fields[i].var->expression.next->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->fields[i].name);
3445             crc = progdefs_crc_both(crc, ";\n");
3446         }
3447         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3448
3449         code_crc = crc;
3450 }
3451
3452 bool parser_finish(const char *output)
3453 {
3454     size_t i;
3455     ir_builder *ir;
3456     bool retval = true;
3457
3458     if (!parser->errors)
3459     {
3460         ir = ir_builder_new("gmqcc_out");
3461         if (!ir) {
3462             printf("failed to allocate builder\n");
3463             return false;
3464         }
3465
3466         for (i = 0; i < parser->fields_count; ++i) {
3467             ast_value *field;
3468             bool isconst;
3469             if (!ast_istype(parser->fields[i].var, ast_value))
3470                 continue;
3471             field = (ast_value*)parser->fields[i].var;
3472             isconst = field->isconst;
3473             field->isconst = false;
3474             if (!ast_global_codegen((ast_value*)field, ir, true)) {
3475                 printf("failed to generate field %s\n", field->name);
3476                 ir_builder_delete(ir);
3477                 return false;
3478             }
3479             if (isconst) {
3480                 ir_value *ifld;
3481                 ast_expression *subtype;
3482                 field->isconst = true;
3483                 subtype = field->expression.next;
3484                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3485                 if (subtype->expression.vtype == TYPE_FIELD)
3486                     ifld->fieldtype = subtype->expression.next->expression.vtype;
3487                 else if (subtype->expression.vtype == TYPE_FUNCTION)
3488                     ifld->outtype = subtype->expression.next->expression.vtype;
3489                 (void)!ir_value_set_field(field->ir_v, ifld);
3490             }
3491         }
3492         for (i = 0; i < parser->globals_count; ++i) {
3493             ast_value *asvalue;
3494             if (!ast_istype(parser->globals[i].var, ast_value))
3495                 continue;
3496             asvalue = (ast_value*)(parser->globals[i].var);
3497             if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3498                 if (strcmp(asvalue->name, "end_sys_globals") &&
3499                     strcmp(asvalue->name, "end_sys_fields"))
3500                 {
3501                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3502                                                    "unused global: `%s`", asvalue->name);
3503                 }
3504             }
3505             if (!ast_global_codegen(asvalue, ir, false)) {
3506                 printf("failed to generate global %s\n", parser->globals[i].name);
3507                 ir_builder_delete(ir);
3508                 return false;
3509             }
3510         }
3511         for (i = 0; i < parser->imm_float_count; ++i) {
3512             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3513                 printf("failed to generate global %s\n", parser->imm_float[i]->name);
3514                 ir_builder_delete(ir);
3515                 return false;
3516             }
3517         }
3518         for (i = 0; i < parser->imm_string_count; ++i) {
3519             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3520                 printf("failed to generate global %s\n", parser->imm_string[i]->name);
3521                 ir_builder_delete(ir);
3522                 return false;
3523             }
3524         }
3525         for (i = 0; i < parser->imm_vector_count; ++i) {
3526             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3527                 printf("failed to generate global %s\n", parser->imm_vector[i]->name);
3528                 ir_builder_delete(ir);
3529                 return false;
3530             }
3531         }
3532         for (i = 0; i < parser->globals_count; ++i) {
3533             ast_value *asvalue;
3534             if (!ast_istype(parser->globals[i].var, ast_value))
3535                 continue;
3536             asvalue = (ast_value*)(parser->globals[i].var);
3537             if (asvalue->setter) {
3538                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3539                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir))
3540                 {
3541                     printf("failed to generate setter for %s\n", parser->globals[i].name);
3542                     ir_builder_delete(ir);
3543                     return false;
3544                 }
3545             }
3546             if (asvalue->getter) {
3547                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3548                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir))
3549                 {
3550                     printf("failed to generate getter for %s\n", parser->globals[i].name);
3551                     ir_builder_delete(ir);
3552                     return false;
3553                 }
3554             }
3555         }
3556         for (i = 0; i < parser->functions_count; ++i) {
3557             if (!ast_function_codegen(parser->functions[i], ir)) {
3558                 printf("failed to generate function %s\n", parser->functions[i]->name);
3559                 ir_builder_delete(ir);
3560                 return false;
3561             }
3562             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3563                 printf("failed to finalize function %s\n", parser->functions[i]->name);
3564                 ir_builder_delete(ir);
3565                 return false;
3566             }
3567         }
3568
3569         if (retval) {
3570             if (opts_dump)
3571                 ir_builder_dump(ir, printf);
3572
3573             generate_checksum(parser);
3574
3575             if (!ir_builder_generate(ir, output)) {
3576                 printf("*** failed to generate output file\n");
3577                 ir_builder_delete(ir);
3578                 return false;
3579             }
3580         }
3581
3582         ir_builder_delete(ir);
3583         return retval;
3584     }
3585
3586     printf("*** there were compile errors\n");
3587     return false;
3588 }