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