]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
parse arrays
[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 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2270 {
2271     ast_expression *cexp;
2272     ast_value      *cval, *tmp;
2273     lex_ctx ctx;
2274
2275     ctx = parser_ctx(parser);
2276
2277     if (!parser_next(parser)) {
2278         ast_delete(var);
2279         parseerror(parser, "expected array-size");
2280         return NULL;
2281     }
2282
2283     cexp = parse_expression_leave(parser, true);
2284
2285     if (!cexp || !ast_istype(cexp, ast_value)) {
2286         if (cexp)
2287             ast_delete(cexp);
2288         ast_delete(var);
2289         parseerror(parser, "expected array-size as constant positive integer");
2290         return NULL;
2291     }
2292     cval = (ast_value*)cexp;
2293
2294     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2295     tmp->expression.next = (ast_expression*)var;
2296     var = tmp;
2297
2298     if (cval->expression.vtype == TYPE_INTEGER)
2299         tmp->expression.count = cval->constval.vint;
2300     else if (cval->expression.vtype == TYPE_FLOAT)
2301         tmp->expression.count = cval->constval.vfloat;
2302     else {
2303         ast_delete(cexp);
2304         ast_delete(var);
2305         parseerror(parser, "array-size must be a positive integer constant");
2306         return NULL;
2307     }
2308     ast_delete(cexp);
2309
2310     if (parser->tok != ']') {
2311         ast_delete(var);
2312         parseerror(parser, "expected ']' after array-size");
2313         return NULL;
2314     }
2315     if (!parser_next(parser)) {
2316         ast_delete(var);
2317         parseerror(parser, "error after parsing array size");
2318         return NULL;
2319     }
2320     return var;
2321 }
2322
2323 /* Parse a complete typename.
2324  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2325  * but when parsing variables separated by comma
2326  * 'storebase' should point to where the base-type should be kept.
2327  * The base type makes up every bit of type information which comes *before* the
2328  * variable name.
2329  *
2330  * The following will be parsed in its entirety:
2331  *     void() foo()
2332  * The 'basetype' in this case is 'void()'
2333  * and if there's a comma after it, say:
2334  *     void() foo(), bar
2335  * then the type-information 'void()' can be stored in 'storebase'
2336  */
2337 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2338 {
2339     ast_value *var, *tmp;
2340     lex_ctx    ctx;
2341
2342     const char *name = NULL;
2343     bool        isfield = false;
2344
2345     ctx = parser_ctx(parser);
2346
2347     /* types may start with a dot */
2348     if (parser->tok == '.') {
2349         isfield = true;
2350         /* if we parsed a dot we need a typename now */
2351         if (!parser_next(parser)) {
2352             parseerror(parser, "expected typename for field definition");
2353             return NULL;
2354         }
2355         if (parser->tok != TOKEN_TYPENAME) {
2356             parseerror(parser, "expected typename");
2357             return NULL;
2358         }
2359     }
2360
2361     /* generate the basic type value */
2362     var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2363     /* do not yet turn into a field - remember:
2364      * .void() foo; is a field too
2365      * .void()() foo; is a function
2366      */
2367
2368     /* parse on */
2369     if (!parser_next(parser)) {
2370         ast_delete(var);
2371         parseerror(parser, "parse error after typename");
2372         return NULL;
2373     }
2374
2375     /* an opening paren now starts the parameter-list of a function
2376      * this is where original-QC has parameter lists.
2377      * We allow a single parameter list here.
2378      * Much like fteqcc we don't allow `float()() x`
2379      */
2380     if (parser->tok == '(') {
2381         var = parse_parameter_list(parser, var);
2382         if (!var)
2383             return NULL;
2384     }
2385
2386     /* store the base if requested */
2387     if (storebase) {
2388         *storebase = ast_value_copy(var);
2389         if (isfield) {
2390             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2391             tmp->expression.next = (ast_expression*)*storebase;
2392             *storebase = tmp;
2393         }
2394     }
2395
2396     /* there may be a name now */
2397     if (parser->tok == TOKEN_IDENT) {
2398         name = util_strdup(parser_tokval(parser));
2399         /* parse on */
2400         if (!parser_next(parser)) {
2401             ast_delete(var);
2402             parseerror(parser, "error after variable or field declaration");
2403             return NULL;
2404         }
2405     }
2406
2407     /* now this may be an array */
2408     if (parser->tok == '[') {
2409         var = parse_arraysize(parser, var);
2410         if (!var)
2411             return NULL;
2412     }
2413
2414     /* This is the point where we can turn it into a field */
2415     if (isfield) {
2416         /* turn it into a field if desired */
2417         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2418         tmp->expression.next = (ast_expression*)var;
2419         var = tmp;
2420     }
2421
2422     /* now there may be function parens again */
2423     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2424         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2425     while (parser->tok == '(') {
2426         var = parse_parameter_list(parser, var);
2427         if (!var) {
2428             if (name)
2429                 mem_d((void*)name);
2430             ast_delete(var);
2431             return NULL;
2432         }
2433     }
2434
2435     /* finally name it */
2436     if (name) {
2437         if (!ast_value_set_name(var, name)) {
2438             ast_delete(var);
2439             parseerror(parser, "internal error: failed to set name");
2440             return NULL;
2441         }
2442         /* free the name, ast_value_set_name duplicates */
2443         mem_d((void*)name);
2444     }
2445
2446     return var;
2447 }
2448
2449 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2450 {
2451     ast_value *var;
2452     ast_value *proto;
2453     ast_expression *old;
2454     bool       was_end;
2455     size_t     i;
2456
2457     ast_value *basetype = NULL;
2458     bool      retval    = true;
2459     bool      isparam   = false;
2460     bool      isvector  = false;
2461     bool      cleanvar  = true;
2462     bool      wasarray  = false;
2463
2464     varentry_t varent, ve[3];
2465
2466     /* get the first complete variable */
2467     var = parse_typename(parser, &basetype);
2468     if (!var) {
2469         if (basetype)
2470             ast_delete(basetype);
2471         return false;
2472     }
2473
2474     memset(&varent, 0, sizeof(varent));
2475     memset(&ve, 0, sizeof(ve));
2476
2477     while (true) {
2478         proto = NULL;
2479         wasarray = false;
2480
2481         /* Part 0: finish the type */
2482         if (parser->tok == '(') {
2483             if (opts_standard == COMPILER_QCC)
2484                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2485             var = parse_parameter_list(parser, var);
2486             if (!var) {
2487                 retval = false;
2488                 goto cleanup;
2489             }
2490         }
2491         /* we only allow 1-dimensional arrays */
2492         if (parser->tok == '[') {
2493             wasarray = true;
2494             var = parse_arraysize(parser, var);
2495             if (!var) {
2496                 retval = false;
2497                 goto cleanup;
2498             }
2499         }
2500         if (parser->tok == '(' && wasarray) {
2501             parseerror(parser, "functions cannot return arrays");
2502             /* we'll still parse the type completely for now */
2503         }
2504         /* for functions returning functions */
2505         while (parser->tok == '(') {
2506             if (opts_standard == COMPILER_QCC)
2507                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2508             var = parse_parameter_list(parser, var);
2509             if (!var) {
2510                 retval = false;
2511                 goto cleanup;
2512             }
2513         }
2514
2515         /* Part 1:
2516          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2517          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2518          * is then filled with the previous definition and the parameter-names replaced.
2519          */
2520         if (!localblock) {
2521             /* Deal with end_sys_ vars */
2522             was_end = false;
2523             if (!strcmp(var->name, "end_sys_globals")) {
2524                 parser->crc_globals = parser->globals_count;
2525                 was_end = true;
2526             }
2527             else if (!strcmp(var->name, "end_sys_fields")) {
2528                 parser->crc_fields = parser->fields_count;
2529                 was_end = true;
2530             }
2531             if (was_end && var->expression.vtype == TYPE_FIELD) {
2532                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2533                                  "global '%s' hint should not be a field",
2534                                  parser_tokval(parser)))
2535                 {
2536                     retval = false;
2537                     goto cleanup;
2538                 }
2539             }
2540
2541             if (!nofields && var->expression.vtype == TYPE_FIELD)
2542             {
2543                 /* deal with field declarations */
2544                 old = parser_find_field(parser, var->name);
2545                 if (old) {
2546                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2547                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2548                     {
2549                         retval = false;
2550                         goto cleanup;
2551                     }
2552                     ast_delete(var);
2553                     var = NULL;
2554                     goto skipvar;
2555                     /*
2556                     parseerror(parser, "field `%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                 }
2562                 if (opts_standard == COMPILER_QCC &&
2563                     (old = parser_find_global(parser, var->name)))
2564                 {
2565                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2566                     parseerror(parser, "field `%s` already declared here: %s:%i",
2567                                var->name, ast_ctx(old).file, ast_ctx(old).line);
2568                     retval = false;
2569                     goto cleanup;
2570                 }
2571             }
2572             else
2573             {
2574                 /* deal with other globals */
2575                 old = parser_find_global(parser, var->name);
2576                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
2577                 {
2578                     /* This is a function which had a prototype */
2579                     if (!ast_istype(old, ast_value)) {
2580                         parseerror(parser, "internal error: prototype is not an ast_value");
2581                         retval = false;
2582                         goto cleanup;
2583                     }
2584                     proto = (ast_value*)old;
2585                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
2586                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
2587                                    proto->name,
2588                                    ast_ctx(proto).file, ast_ctx(proto).line);
2589                         retval = false;
2590                         goto cleanup;
2591                     }
2592                     /* we need the new parameter-names */
2593                     for (i = 0; i < proto->expression.params_count; ++i)
2594                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
2595                     ast_delete(var);
2596                     var = proto;
2597                 }
2598                 else
2599                 {
2600                     /* other globals */
2601                     if (old) {
2602                         parseerror(parser, "global `%s` already declared here: %s:%i",
2603                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
2604                         retval = false;
2605                         goto cleanup;
2606                     }
2607                     if (opts_standard == COMPILER_QCC &&
2608                         (old = parser_find_field(parser, var->name)))
2609                     {
2610                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2611                         parseerror(parser, "global `%s` already declared here: %s:%i",
2612                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
2613                         retval = false;
2614                         goto cleanup;
2615                     }
2616                 }
2617             }
2618         }
2619         else /* it's not a global */
2620         {
2621             old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
2622             if (old && !isparam) {
2623                 parseerror(parser, "local `%s` already declared here: %s:%i",
2624                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2625                 retval = false;
2626                 goto cleanup;
2627             }
2628             old = parser_find_local(parser, var->name, 0, &isparam);
2629             if (old && isparam) {
2630                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
2631                                  "local `%s` is shadowing a parameter", var->name))
2632                 {
2633                     parseerror(parser, "local `%s` already declared here: %s:%i",
2634                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2635                     retval = false;
2636                     goto cleanup;
2637                 }
2638                 if (opts_standard != COMPILER_GMQCC) {
2639                     ast_delete(var);
2640                     var = NULL;
2641                     goto skipvar;
2642                 }
2643             }
2644         }
2645
2646         /* Part 2:
2647          * Create the global/local, and deal with vector types.
2648          */
2649         if (!proto) {
2650             if (var->expression.vtype == TYPE_VECTOR)
2651                 isvector = true;
2652             else if (var->expression.vtype == TYPE_FIELD &&
2653                      var->expression.next->expression.vtype == TYPE_VECTOR)
2654                 isvector = true;
2655
2656             if (isvector) {
2657                 if (!create_vector_members(parser, var, ve)) {
2658                     retval = false;
2659                     goto cleanup;
2660                 }
2661             }
2662
2663             varent.name = util_strdup(var->name);
2664             varent.var  = (ast_expression*)var;
2665
2666             if (!localblock) {
2667                 /* deal with global variables, fields, functions */
2668                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
2669                     if (!(retval = parser_t_fields_add(parser, varent)))
2670                         goto cleanup;
2671                     if (isvector) {
2672                         for (i = 0; i < 3; ++i) {
2673                             if (!(retval = parser_t_fields_add(parser, ve[i])))
2674                                 break;
2675                         }
2676                         if (!retval) {
2677                             parser->fields_count -= i+1;
2678                             goto cleanup;
2679                         }
2680                     }
2681                 }
2682                 else {
2683                     if (!(retval = parser_t_globals_add(parser, varent)))
2684                         goto cleanup;
2685                     if (isvector) {
2686                         for (i = 0; i < 3; ++i) {
2687                             if (!(retval = parser_t_globals_add(parser, ve[i])))
2688                                 break;
2689                         }
2690                         if (!retval) {
2691                             parser->globals_count -= i+1;
2692                             goto cleanup;
2693                         }
2694                     }
2695                 }
2696             } else {
2697                 if (!(retval = parser_t_locals_add(parser, varent)))
2698                     goto cleanup;
2699                 if (!(retval = ast_block_locals_add(localblock, var))) {
2700                     parser->locals_count--;
2701                     goto cleanup;
2702                 }
2703                 if (isvector) {
2704                     for (i = 0; i < 3; ++i) {
2705                         if (!(retval = parser_t_locals_add(parser, ve[i])))
2706                             break;
2707                         if (!(retval = ast_block_collect(localblock, ve[i].var)))
2708                             break;
2709                         ve[i].var = NULL; /* from here it's being collected in the block */
2710                     }
2711                     if (!retval) {
2712                         parser->locals_count -= i+1;
2713                         localblock->locals_count--;
2714                         goto cleanup;
2715                     }
2716                 }
2717             }
2718
2719             varent.name = NULL;
2720             ve[0].name = ve[1].name = ve[2].name = NULL;
2721             ve[0].var  = ve[1].var  = ve[2].var  = NULL;
2722             cleanvar = false;
2723         }
2724
2725 skipvar:
2726         if (parser->tok == ';') {
2727             ast_delete(basetype);
2728             if (!parser_next(parser)) {
2729                 parseerror(parser, "error after variable declaration");
2730                 return false;
2731             }
2732             return true;
2733         }
2734
2735         if (parser->tok == ',')
2736             goto another;
2737
2738         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
2739             parseerror(parser, "missing comma or semicolon while parsing variables");
2740             break;
2741         }
2742
2743         if (localblock && opts_standard == COMPILER_QCC) {
2744             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
2745                              "initializing expression turns variable `%s` into a constant in this standard",
2746                              var->name) )
2747             {
2748                 break;
2749             }
2750         }
2751
2752         if (parser->tok != '{') {
2753             if (parser->tok != '=') {
2754                 parseerror(parser, "missing semicolon or initializer");
2755                 break;
2756             }
2757
2758             if (!parser_next(parser)) {
2759                 parseerror(parser, "error parsing initializer");
2760                 break;
2761             }
2762         }
2763         else if (opts_standard == COMPILER_QCC) {
2764             parseerror(parser, "expected '=' before function body in this standard");
2765         }
2766
2767         if (parser->tok == '#') {
2768             ast_function *func;
2769
2770             if (localblock) {
2771                 parseerror(parser, "cannot declare builtins within functions");
2772                 break;
2773             }
2774             if (var->expression.vtype != TYPE_FUNCTION) {
2775                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
2776                 break;
2777             }
2778             if (!parser_next(parser)) {
2779                 parseerror(parser, "expected builtin number");
2780                 break;
2781             }
2782             if (parser->tok != TOKEN_INTCONST) {
2783                 parseerror(parser, "builtin number must be an integer constant");
2784                 break;
2785             }
2786             if (parser_token(parser)->constval.i <= 0) {
2787                 parseerror(parser, "builtin number must be an integer greater than zero");
2788                 break;
2789             }
2790
2791             func = ast_function_new(ast_ctx(var), var->name, var);
2792             if (!func) {
2793                 parseerror(parser, "failed to allocate function for `%s`", var->name);
2794                 break;
2795             }
2796             if (!parser_t_functions_add(parser, func)) {
2797                 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2798                 ast_function_delete(func);
2799                 var->constval.vfunc = NULL;
2800                 break;
2801             }
2802
2803             func->builtin = -parser_token(parser)->constval.i;
2804
2805             if (!parser_next(parser)) {
2806                 parseerror(parser, "expected comma or semicolon");
2807                 ast_function_delete(func);
2808                 var->constval.vfunc = NULL;
2809                 break;
2810             }
2811         }
2812         else if (parser->tok == '{' || parser->tok == '[')
2813         {
2814             if (localblock) {
2815                 parseerror(parser, "cannot declare functions within functions");
2816                 break;
2817             }
2818
2819             if (!parse_function_body(parser, var))
2820                 break;
2821             ast_delete(basetype);
2822             return true;
2823         } else {
2824             ast_expression *cexp;
2825             ast_value      *cval;
2826
2827             cexp = parse_expression_leave(parser, true);
2828             if (!cexp)
2829                 break;
2830
2831             if (!localblock) {
2832                 cval = (ast_value*)cexp;
2833                 if (!ast_istype(cval, ast_value) || !cval->isconst)
2834                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
2835                 else
2836                 {
2837                     var->isconst = true;
2838                     if (cval->expression.vtype == TYPE_STRING)
2839                         var->constval.vstring = parser_strdup(cval->constval.vstring);
2840                     else
2841                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
2842                     ast_unref(cval);
2843                 }
2844             } else {
2845                 shunt sy;
2846                 MEM_VECTOR_INIT(&sy, out);
2847                 MEM_VECTOR_INIT(&sy, ops);
2848                 if (!shunt_out_add(&sy, syexp(ast_ctx(var), (ast_expression*)var)) ||
2849                     !shunt_out_add(&sy, syexp(ast_ctx(cexp), (ast_expression*)cexp)) ||
2850                     !shunt_ops_add(&sy, syop(ast_ctx(var), parser->assign_op)))
2851                 {
2852                     parseerror(parser, "internal error: failed to prepare initializer");
2853                     ast_unref(cexp);
2854                 }
2855                 else if (!parser_sy_pop(parser, &sy))
2856                     ast_unref(cexp);
2857                 else {
2858                     if (sy.out_count != 1 && sy.ops_count != 0)
2859                         parseerror(parser, "internal error: leaked operands");
2860                     else if (!ast_block_exprs_add(localblock, (ast_expression*)sy.out[0].out)) {
2861                         parseerror(parser, "failed to create intializing expression");
2862                         ast_unref(sy.out[0].out);
2863                         ast_unref(cexp);
2864                     }
2865                 }
2866                 MEM_VECTOR_CLEAR(&sy, out);
2867                 MEM_VECTOR_CLEAR(&sy, ops);
2868             }
2869         }
2870
2871 another:
2872         if (parser->tok == ',') {
2873             if (!parser_next(parser)) {
2874                 parseerror(parser, "expected another variable");
2875                 break;
2876             }
2877
2878             if (parser->tok != TOKEN_IDENT) {
2879                 parseerror(parser, "expected another variable");
2880                 break;
2881             }
2882             var = ast_value_copy(basetype);
2883             cleanvar = true;
2884             ast_value_set_name(var, parser_tokval(parser));
2885             if (!parser_next(parser)) {
2886                 parseerror(parser, "error parsing variable declaration");
2887                 break;
2888             }
2889             continue;
2890         }
2891
2892         if (parser->tok != ';') {
2893             parseerror(parser, "missing semicolon after variables");
2894             break;
2895         }
2896
2897         if (!parser_next(parser)) {
2898             parseerror(parser, "parse error after variable declaration");
2899             break;
2900         }
2901
2902         ast_delete(basetype);
2903         return true;
2904     }
2905
2906     if (cleanvar && var)
2907         ast_delete(var);
2908     ast_delete(basetype);
2909     return false;
2910
2911 cleanup:
2912     ast_delete(basetype);
2913     if (cleanvar && var)
2914         ast_delete(var);
2915     if (varent.name) mem_d(varent.name);
2916     if (ve[0].name)  mem_d(ve[0].name);
2917     if (ve[1].name)  mem_d(ve[1].name);
2918     if (ve[2].name)  mem_d(ve[2].name);
2919     if (ve[0].var)   mem_d(ve[0].var);
2920     if (ve[1].var)   mem_d(ve[1].var);
2921     if (ve[2].var)   mem_d(ve[2].var);
2922     return retval;
2923 }
2924
2925 static bool parser_global_statement(parser_t *parser)
2926 {
2927     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2928     {
2929         return parse_variable(parser, NULL, false);
2930     }
2931     else if (parser->tok == TOKEN_KEYWORD)
2932     {
2933         /* handle 'var' and 'const' */
2934         if (!strcmp(parser_tokval(parser), "var")) {
2935             if (!parser_next(parser)) {
2936                 parseerror(parser, "expected variable declaration after 'var'");
2937                 return false;
2938             }
2939             return parse_variable(parser, NULL, true);
2940         }
2941         return false;
2942     }
2943     else if (parser->tok == '$')
2944     {
2945         if (!parser_next(parser)) {
2946             parseerror(parser, "parse error");
2947             return false;
2948         }
2949     }
2950     else
2951     {
2952         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
2953         return false;
2954     }
2955     return true;
2956 }
2957
2958 static parser_t *parser;
2959
2960 bool parser_init()
2961 {
2962     size_t i;
2963     parser = (parser_t*)mem_a(sizeof(parser_t));
2964     if (!parser)
2965         return false;
2966
2967     memset(parser, 0, sizeof(*parser));
2968
2969     for (i = 0; i < operator_count; ++i) {
2970         if (operators[i].id == opid1('=')) {
2971             parser->assign_op = operators+i;
2972             break;
2973         }
2974     }
2975     if (!parser->assign_op) {
2976         printf("internal error: initializing parser: failed to find assign operator\n");
2977         mem_d(parser);
2978         return false;
2979     }
2980     return true;
2981 }
2982
2983 bool parser_compile(const char *filename)
2984 {
2985     parser->lex = lex_open(filename);
2986     if (!parser->lex) {
2987         printf("failed to open file \"%s\"\n", filename);
2988         return false;
2989     }
2990
2991     /* initial lexer/parser state */
2992     parser->lex->flags.noops = true;
2993
2994     if (parser_next(parser))
2995     {
2996         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2997         {
2998             if (!parser_global_statement(parser)) {
2999                 if (parser->tok == TOKEN_EOF)
3000                     parseerror(parser, "unexpected eof");
3001                 else if (!parser->errors)
3002                     parseerror(parser, "there have been errors, bailing out");
3003                 lex_close(parser->lex);
3004                 parser->lex = NULL;
3005                 return false;
3006             }
3007         }
3008     } else {
3009         parseerror(parser, "parse error");
3010         lex_close(parser->lex);
3011         parser->lex = NULL;
3012         return false;
3013     }
3014
3015     lex_close(parser->lex);
3016     parser->lex = NULL;
3017
3018     return !parser->errors;
3019 }
3020
3021 void parser_cleanup()
3022 {
3023     size_t i;
3024     for (i = 0; i < parser->functions_count; ++i) {
3025         ast_delete(parser->functions[i]);
3026     }
3027     for (i = 0; i < parser->imm_vector_count; ++i) {
3028         ast_delete(parser->imm_vector[i]);
3029     }
3030     for (i = 0; i < parser->imm_string_count; ++i) {
3031         ast_delete(parser->imm_string[i]);
3032     }
3033     for (i = 0; i < parser->imm_float_count; ++i) {
3034         ast_delete(parser->imm_float[i]);
3035     }
3036     for (i = 0; i < parser->fields_count; ++i) {
3037         ast_delete(parser->fields[i].var);
3038         mem_d(parser->fields[i].name);
3039     }
3040     for (i = 0; i < parser->globals_count; ++i) {
3041         ast_delete(parser->globals[i].var);
3042         mem_d(parser->globals[i].name);
3043     }
3044     MEM_VECTOR_CLEAR(parser, functions);
3045     MEM_VECTOR_CLEAR(parser, imm_vector);
3046     MEM_VECTOR_CLEAR(parser, imm_string);
3047     MEM_VECTOR_CLEAR(parser, imm_float);
3048     MEM_VECTOR_CLEAR(parser, globals);
3049     MEM_VECTOR_CLEAR(parser, fields);
3050     MEM_VECTOR_CLEAR(parser, locals);
3051
3052     mem_d(parser);
3053 }
3054
3055 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3056 {
3057     return util_crc16(old, str, strlen(str));
3058 }
3059
3060 static void progdefs_crc_file(const char *str)
3061 {
3062     /* write to progdefs.h here */
3063 }
3064
3065 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3066 {
3067     old = progdefs_crc_sum(old, str);
3068     progdefs_crc_file(str);
3069     return old;
3070 }
3071
3072 static void generate_checksum(parser_t *parser)
3073 {
3074     uint16_t crc = 0xFFFF;
3075     size_t i;
3076
3077         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3078         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3079         /*
3080         progdefs_crc_file("\tint\tpad;\n");
3081         progdefs_crc_file("\tint\tofs_return[3];\n");
3082         progdefs_crc_file("\tint\tofs_parm0[3];\n");
3083         progdefs_crc_file("\tint\tofs_parm1[3];\n");
3084         progdefs_crc_file("\tint\tofs_parm2[3];\n");
3085         progdefs_crc_file("\tint\tofs_parm3[3];\n");
3086         progdefs_crc_file("\tint\tofs_parm4[3];\n");
3087         progdefs_crc_file("\tint\tofs_parm5[3];\n");
3088         progdefs_crc_file("\tint\tofs_parm6[3];\n");
3089         progdefs_crc_file("\tint\tofs_parm7[3];\n");
3090         */
3091         for (i = 0; i < parser->crc_globals; ++i) {
3092             if (!ast_istype(parser->globals[i].var, ast_value))
3093                 continue;
3094             switch (parser->globals[i].var->expression.vtype) {
3095                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3096                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3097                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3098                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3099                 default:
3100                     crc = progdefs_crc_both(crc, "\tint\t");
3101                     break;
3102             }
3103             crc = progdefs_crc_both(crc, parser->globals[i].name);
3104             crc = progdefs_crc_both(crc, ";\n");
3105         }
3106         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3107         for (i = 0; i < parser->crc_fields; ++i) {
3108             if (!ast_istype(parser->fields[i].var, ast_value))
3109                 continue;
3110             switch (parser->fields[i].var->expression.next->expression.vtype) {
3111                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3112                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3113                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3114                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3115                 default:
3116                     crc = progdefs_crc_both(crc, "\tint\t");
3117                     break;
3118             }
3119             crc = progdefs_crc_both(crc, parser->fields[i].name);
3120             crc = progdefs_crc_both(crc, ";\n");
3121         }
3122         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3123
3124         code_crc = crc;
3125 }
3126
3127 bool parser_finish(const char *output)
3128 {
3129     size_t i;
3130     ir_builder *ir;
3131     bool retval = true;
3132
3133     if (!parser->errors)
3134     {
3135         ir = ir_builder_new("gmqcc_out");
3136         if (!ir) {
3137             printf("failed to allocate builder\n");
3138             return false;
3139         }
3140
3141         for (i = 0; i < parser->fields_count; ++i) {
3142             ast_value *field;
3143             bool isconst;
3144             if (!ast_istype(parser->fields[i].var, ast_value))
3145                 continue;
3146             field = (ast_value*)parser->fields[i].var;
3147             isconst = field->isconst;
3148             field->isconst = false;
3149             if (!ast_global_codegen((ast_value*)field, ir, true)) {
3150                 printf("failed to generate field %s\n", field->name);
3151                 ir_builder_delete(ir);
3152                 return false;
3153             }
3154             if (isconst) {
3155                 ir_value *ifld;
3156                 ast_expression *subtype;
3157                 field->isconst = true;
3158                 subtype = field->expression.next;
3159                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3160                 if (subtype->expression.vtype == TYPE_FIELD)
3161                     ifld->fieldtype = subtype->expression.next->expression.vtype;
3162                 else if (subtype->expression.vtype == TYPE_FUNCTION)
3163                     ifld->outtype = subtype->expression.next->expression.vtype;
3164                 (void)!ir_value_set_field(field->ir_v, ifld);
3165             }
3166         }
3167         for (i = 0; i < parser->globals_count; ++i) {
3168             ast_value *asvalue;
3169             if (!ast_istype(parser->globals[i].var, ast_value))
3170                 continue;
3171             asvalue = (ast_value*)(parser->globals[i].var);
3172             if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3173                 if (strcmp(asvalue->name, "end_sys_globals") &&
3174                     strcmp(asvalue->name, "end_sys_fields"))
3175                 {
3176                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3177                                                    "unused global: `%s`", asvalue->name);
3178                 }
3179             }
3180             if (!ast_global_codegen(asvalue, ir, false)) {
3181                 printf("failed to generate global %s\n", parser->globals[i].name);
3182                 ir_builder_delete(ir);
3183                 return false;
3184             }
3185         }
3186         for (i = 0; i < parser->imm_float_count; ++i) {
3187             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3188                 printf("failed to generate global %s\n", parser->imm_float[i]->name);
3189                 ir_builder_delete(ir);
3190                 return false;
3191             }
3192         }
3193         for (i = 0; i < parser->imm_string_count; ++i) {
3194             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3195                 printf("failed to generate global %s\n", parser->imm_string[i]->name);
3196                 ir_builder_delete(ir);
3197                 return false;
3198             }
3199         }
3200         for (i = 0; i < parser->imm_vector_count; ++i) {
3201             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3202                 printf("failed to generate global %s\n", parser->imm_vector[i]->name);
3203                 ir_builder_delete(ir);
3204                 return false;
3205             }
3206         }
3207         for (i = 0; i < parser->functions_count; ++i) {
3208             if (!ast_function_codegen(parser->functions[i], ir)) {
3209                 printf("failed to generate function %s\n", parser->functions[i]->name);
3210                 ir_builder_delete(ir);
3211                 return false;
3212             }
3213             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3214                 printf("failed to finalize function %s\n", parser->functions[i]->name);
3215                 ir_builder_delete(ir);
3216                 return false;
3217             }
3218         }
3219
3220         if (retval) {
3221             if (opts_dump)
3222                 ir_builder_dump(ir, printf);
3223
3224             generate_checksum(parser);
3225
3226             if (!ir_builder_generate(ir, output)) {
3227                 printf("*** failed to generate output file\n");
3228                 ir_builder_delete(ir);
3229                 return false;
3230             }
3231         }
3232
3233         ir_builder_delete(ir);
3234         return retval;
3235     }
3236
3237     printf("*** there were compile errors\n");
3238     return false;
3239 }