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