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