]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Support non-const initialized locals
[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             if (wantop) {
1153                 DEBUGSHUNTDO(printf("do[op] )\n"));
1154                 --parens;
1155                 if (parens < 0)
1156                     break;
1157                 /* we do expect an operator next */
1158                 /* closing an opening paren */
1159                 if (!parser_close_paren(parser, &sy, false))
1160                     goto onerr;
1161             } else {
1162                 DEBUGSHUNTDO(printf("do[nop] )\n"));
1163                 --parens;
1164                 if (parens < 0)
1165                     break;
1166                 /* allowed for function calls */
1167                 if (!parser_close_paren(parser, &sy, true))
1168                     goto onerr;
1169             }
1170             wantop = true;
1171         }
1172         else if (parser->tok != TOKEN_OPERATOR) {
1173             if (wantop) {
1174                 parseerror(parser, "expected operator or end of statement");
1175                 goto onerr;
1176             }
1177             break;
1178         }
1179         else
1180         {
1181             /* classify the operator */
1182             /* TODO: suffix operators */
1183             const oper_info *op;
1184             const oper_info *olast = NULL;
1185             size_t o;
1186             for (o = 0; o < operator_count; ++o) {
1187                 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1188                     !(operators[o].flags & OP_SUFFIX) && /* remove this */
1189                     !strcmp(parser_tokval(parser), operators[o].op))
1190                 {
1191                     break;
1192                 }
1193             }
1194             if (o == operator_count) {
1195                 /* no operator found... must be the end of the statement */
1196                 break;
1197             }
1198             /* found an operator */
1199             op = &operators[o];
1200
1201             /* when declaring variables, a comma starts a new variable */
1202             if (op->id == opid1(',') && !parens && stopatcomma) {
1203                 /* fixup the token */
1204                 parser->tok = ',';
1205                 break;
1206             }
1207
1208             if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1209                 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1210
1211             while (olast && (
1212                     (op->prec < olast->prec) ||
1213                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1214             {
1215                 if (!parser_sy_pop(parser, &sy))
1216                     goto onerr;
1217                 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1218                     olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1219                 else
1220                     olast = NULL;
1221             }
1222
1223             if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1224                 /* for gmqcc standard: open up the namespace of the previous type */
1225                 ast_expression *prevex = sy.out[sy.out_count-1].out;
1226                 if (!prevex) {
1227                     parseerror(parser, "unexpected member operator");
1228                     goto onerr;
1229                 }
1230                 if (prevex->expression.vtype == TYPE_ENTITY)
1231                     parser->memberof = TYPE_ENTITY;
1232                 else if (prevex->expression.vtype == TYPE_VECTOR)
1233                     parser->memberof = TYPE_VECTOR;
1234                 else {
1235                     parseerror(parser, "type error: type has no members");
1236                     goto onerr;
1237                 }
1238                 gotmemberof = true;
1239             }
1240
1241             if (op->id == opid1('(')) {
1242                 if (wantop) {
1243                     DEBUGSHUNTDO(printf("push [op] (\n"));
1244                     ++parens;
1245                     /* we expected an operator, this is the function-call operator */
1246                     if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), 'f', sy.out_count-1))) {
1247                         parseerror(parser, "out of memory");
1248                         goto onerr;
1249                     }
1250                 } else {
1251                     ++parens;
1252                     if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), 1, 0))) {
1253                         parseerror(parser, "out of memory");
1254                         goto onerr;
1255                     }
1256                     DEBUGSHUNTDO(printf("push [nop] (\n"));
1257                 }
1258                 wantop = false;
1259             } else {
1260                 DEBUGSHUNTDO(printf("push operator %s\n", op->op));
1261                 if (!shunt_ops_add(&sy, syop(parser_ctx(parser), op)))
1262                     goto onerr;
1263                 wantop = false;
1264             }
1265         }
1266         if (!parser_next(parser)) {
1267             goto onerr;
1268         }
1269         if (parser->tok == ';' || parser->tok == ']') {
1270             break;
1271         }
1272     }
1273
1274     while (sy.ops_count) {
1275         if (!parser_sy_pop(parser, &sy))
1276             goto onerr;
1277     }
1278
1279     parser->lex->flags.noops = true;
1280     if (!sy.out_count) {
1281         parseerror(parser, "empty expression");
1282         expr = NULL;
1283     } else
1284         expr = sy.out[0].out;
1285     MEM_VECTOR_CLEAR(&sy, out);
1286     MEM_VECTOR_CLEAR(&sy, ops);
1287     DEBUGSHUNTDO(printf("shunt done\n"));
1288     return expr;
1289
1290 onerr:
1291     parser->lex->flags.noops = true;
1292     MEM_VECTOR_CLEAR(&sy, out);
1293     MEM_VECTOR_CLEAR(&sy, ops);
1294     return NULL;
1295 }
1296
1297 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1298 {
1299     ast_expression *e = parse_expression_leave(parser, stopatcomma);
1300     if (!e)
1301         return NULL;
1302     if (!parser_next(parser)) {
1303         ast_delete(e);
1304         return NULL;
1305     }
1306     return e;
1307 }
1308
1309 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1310 {
1311     ast_ifthen *ifthen;
1312     ast_expression *cond, *ontrue, *onfalse = NULL;
1313
1314     lex_ctx ctx = parser_ctx(parser);
1315
1316     /* skip the 'if' and check for opening paren */
1317     if (!parser_next(parser) || parser->tok != '(') {
1318         parseerror(parser, "expected 'if' condition in parenthesis");
1319         return false;
1320     }
1321     /* parse into the expression */
1322     if (!parser_next(parser)) {
1323         parseerror(parser, "expected 'if' condition after opening paren");
1324         return false;
1325     }
1326     /* parse the condition */
1327     cond = parse_expression_leave(parser, false);
1328     if (!cond)
1329         return false;
1330     /* closing paren */
1331     if (parser->tok != ')') {
1332         parseerror(parser, "expected closing paren after 'if' condition");
1333         ast_delete(cond);
1334         return false;
1335     }
1336     /* parse into the 'then' branch */
1337     if (!parser_next(parser)) {
1338         parseerror(parser, "expected statement for on-true branch of 'if'");
1339         ast_delete(cond);
1340         return false;
1341     }
1342     ontrue = parse_statement_or_block(parser);
1343     if (!ontrue) {
1344         ast_delete(cond);
1345         return false;
1346     }
1347     /* check for an else */
1348     if (!strcmp(parser_tokval(parser), "else")) {
1349         /* parse into the 'else' branch */
1350         if (!parser_next(parser)) {
1351             parseerror(parser, "expected on-false branch after 'else'");
1352             ast_delete(ontrue);
1353             ast_delete(cond);
1354             return false;
1355         }
1356         onfalse = parse_statement_or_block(parser);
1357         if (!onfalse) {
1358             ast_delete(ontrue);
1359             ast_delete(cond);
1360             return false;
1361         }
1362     }
1363
1364     ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1365     *out = (ast_expression*)ifthen;
1366     return true;
1367 }
1368
1369 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1370 {
1371     ast_loop *aloop;
1372     ast_expression *cond, *ontrue;
1373
1374     lex_ctx ctx = parser_ctx(parser);
1375
1376     /* skip the 'while' and check for opening paren */
1377     if (!parser_next(parser) || parser->tok != '(') {
1378         parseerror(parser, "expected 'while' condition in parenthesis");
1379         return false;
1380     }
1381     /* parse into the expression */
1382     if (!parser_next(parser)) {
1383         parseerror(parser, "expected 'while' condition after opening paren");
1384         return false;
1385     }
1386     /* parse the condition */
1387     cond = parse_expression_leave(parser, false);
1388     if (!cond)
1389         return false;
1390     /* closing paren */
1391     if (parser->tok != ')') {
1392         parseerror(parser, "expected closing paren after 'while' condition");
1393         ast_delete(cond);
1394         return false;
1395     }
1396     /* parse into the 'then' branch */
1397     if (!parser_next(parser)) {
1398         parseerror(parser, "expected while-loop body");
1399         ast_delete(cond);
1400         return false;
1401     }
1402     ontrue = parse_statement_or_block(parser);
1403     if (!ontrue) {
1404         ast_delete(cond);
1405         return false;
1406     }
1407
1408     aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1409     *out = (ast_expression*)aloop;
1410     return true;
1411 }
1412
1413 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1414 {
1415     ast_loop *aloop;
1416     ast_expression *cond, *ontrue;
1417
1418     lex_ctx ctx = parser_ctx(parser);
1419
1420     /* skip the 'do' and get the body */
1421     if (!parser_next(parser)) {
1422         parseerror(parser, "expected loop body");
1423         return false;
1424     }
1425     ontrue = parse_statement_or_block(parser);
1426     if (!ontrue)
1427         return false;
1428
1429     /* expect the "while" */
1430     if (parser->tok != TOKEN_KEYWORD ||
1431         strcmp(parser_tokval(parser), "while"))
1432     {
1433         parseerror(parser, "expected 'while' and condition");
1434         ast_delete(ontrue);
1435         return false;
1436     }
1437
1438     /* skip the 'while' and check for opening paren */
1439     if (!parser_next(parser) || parser->tok != '(') {
1440         parseerror(parser, "expected 'while' condition in parenthesis");
1441         ast_delete(ontrue);
1442         return false;
1443     }
1444     /* parse into the expression */
1445     if (!parser_next(parser)) {
1446         parseerror(parser, "expected 'while' condition after opening paren");
1447         ast_delete(ontrue);
1448         return false;
1449     }
1450     /* parse the condition */
1451     cond = parse_expression_leave(parser, false);
1452     if (!cond)
1453         return false;
1454     /* closing paren */
1455     if (parser->tok != ')') {
1456         parseerror(parser, "expected closing paren after 'while' condition");
1457         ast_delete(ontrue);
1458         ast_delete(cond);
1459         return false;
1460     }
1461     /* parse on */
1462     if (!parser_next(parser) || parser->tok != ';') {
1463         parseerror(parser, "expected semicolon after condition");
1464         ast_delete(ontrue);
1465         ast_delete(cond);
1466         return false;
1467     }
1468
1469     if (!parser_next(parser)) {
1470         parseerror(parser, "parse error");
1471         ast_delete(ontrue);
1472         ast_delete(cond);
1473         return false;
1474     }
1475
1476     aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1477     *out = (ast_expression*)aloop;
1478     return true;
1479 }
1480
1481 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1482 {
1483     ast_loop *aloop;
1484     ast_expression *initexpr, *cond, *increment, *ontrue;
1485     size_t oldblocklocal;
1486     bool   retval = true;
1487
1488     lex_ctx ctx = parser_ctx(parser);
1489
1490     oldblocklocal = parser->blocklocal;
1491     parser->blocklocal = parser->locals_count;
1492
1493     initexpr  = NULL;
1494     cond      = NULL;
1495     increment = NULL;
1496     ontrue    = NULL;
1497
1498     /* skip the 'while' and check for opening paren */
1499     if (!parser_next(parser) || parser->tok != '(') {
1500         parseerror(parser, "expected 'for' expressions in parenthesis");
1501         goto onerr;
1502     }
1503     /* parse into the expression */
1504     if (!parser_next(parser)) {
1505         parseerror(parser, "expected 'for' initializer after opening paren");
1506         goto onerr;
1507     }
1508
1509     if (parser->tok == TOKEN_TYPENAME) {
1510         if (opts_standard != COMPILER_GMQCC) {
1511             if (parsewarning(parser, WARN_EXTENSIONS,
1512                              "current standard does not allow variable declarations in for-loop initializers"))
1513                 goto onerr;
1514         }
1515
1516         parseerror(parser, "TODO: assignment of new variables to be non-const");
1517         goto onerr;
1518         if (!parse_variable(parser, block, true))
1519             goto onerr;
1520     }
1521     else if (parser->tok != ';')
1522     {
1523         initexpr = parse_expression_leave(parser, false);
1524         if (!initexpr)
1525             goto onerr;
1526     }
1527
1528     /* move on to condition */
1529     if (parser->tok != ';') {
1530         parseerror(parser, "expected semicolon after for-loop initializer");
1531         goto onerr;
1532     }
1533     if (!parser_next(parser)) {
1534         parseerror(parser, "expected for-loop condition");
1535         goto onerr;
1536     }
1537
1538     /* parse the condition */
1539     if (parser->tok != ';') {
1540         cond = parse_expression_leave(parser, false);
1541         if (!cond)
1542             goto onerr;
1543     }
1544
1545     /* move on to incrementor */
1546     if (parser->tok != ';') {
1547         parseerror(parser, "expected semicolon after for-loop initializer");
1548         goto onerr;
1549     }
1550     if (!parser_next(parser)) {
1551         parseerror(parser, "expected for-loop condition");
1552         goto onerr;
1553     }
1554
1555     /* parse the incrementor */
1556     if (parser->tok != ')') {
1557         increment = parse_expression_leave(parser, false);
1558         if (!increment)
1559             goto onerr;
1560         if (!ast_istype(increment, ast_store) &&
1561             !ast_istype(increment, ast_call) &&
1562             !ast_istype(increment, ast_binstore))
1563         {
1564             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1565                 goto onerr;
1566         }
1567     }
1568
1569     /* closing paren */
1570     if (parser->tok != ')') {
1571         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1572         goto onerr;
1573     }
1574     /* parse into the 'then' branch */
1575     if (!parser_next(parser)) {
1576         parseerror(parser, "expected for-loop body");
1577         goto onerr;
1578     }
1579     ontrue = parse_statement_or_block(parser);
1580     if (!ontrue) {
1581         goto onerr;
1582     }
1583
1584     aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1585     *out = (ast_expression*)aloop;
1586
1587     while (parser->locals_count > parser->blocklocal)
1588         retval = retval && parser_pop_local(parser);
1589     parser->blocklocal = oldblocklocal;
1590     return retval;
1591 onerr:
1592     if (initexpr)  ast_delete(initexpr);
1593     if (cond)      ast_delete(cond);
1594     if (increment) ast_delete(increment);
1595     while (parser->locals_count > parser->blocklocal)
1596         (void)!parser_pop_local(parser);
1597     parser->blocklocal = oldblocklocal;
1598     return false;
1599 }
1600
1601 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out)
1602 {
1603     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1604     {
1605         /* local variable */
1606         if (!block) {
1607             parseerror(parser, "cannot declare a variable from here");
1608             return false;
1609         }
1610         if (opts_standard == COMPILER_QCC) {
1611             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1612                 return false;
1613         }
1614         if (!parse_variable(parser, block, false))
1615             return false;
1616         *out = NULL;
1617         return true;
1618     }
1619     else if (parser->tok == TOKEN_KEYWORD)
1620     {
1621         if (!strcmp(parser_tokval(parser), "local"))
1622         {
1623             if (!block) {
1624                 parseerror(parser, "cannot declare a local variable here");
1625                 return false;
1626             }
1627             if (!parser_next(parser)) {
1628                 parseerror(parser, "expected variable declaration");
1629                 return false;
1630             }
1631             if (!parse_variable(parser, block, true))
1632                 return false;
1633             *out = NULL;
1634             return true;
1635         }
1636         else if (!strcmp(parser_tokval(parser), "return"))
1637         {
1638             ast_expression *exp = NULL;
1639             ast_return     *ret = NULL;
1640             ast_value      *expected = parser->function->vtype;
1641
1642             if (!parser_next(parser)) {
1643                 parseerror(parser, "expected return expression");
1644                 return false;
1645             }
1646
1647             if (parser->tok != ';') {
1648                 exp = parse_expression(parser, false);
1649                 if (!exp)
1650                     return false;
1651
1652                 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1653                     parseerror(parser, "return with invalid expression");
1654                 }
1655
1656                 ret = ast_return_new(exp->expression.node.context, exp);
1657                 if (!ret) {
1658                     ast_delete(exp);
1659                     return false;
1660                 }
1661             } else {
1662                 if (!parser_next(parser))
1663                     parseerror(parser, "parse error");
1664                 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1665                     if (opts_standard != COMPILER_GMQCC)
1666                         (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1667                     else
1668                         parseerror(parser, "return without value");
1669                 }
1670                 ret = ast_return_new(parser_ctx(parser), NULL);
1671             }
1672             *out = (ast_expression*)ret;
1673             return true;
1674         }
1675         else if (!strcmp(parser_tokval(parser), "if"))
1676         {
1677             return parse_if(parser, block, out);
1678         }
1679         else if (!strcmp(parser_tokval(parser), "while"))
1680         {
1681             return parse_while(parser, block, out);
1682         }
1683         else if (!strcmp(parser_tokval(parser), "do"))
1684         {
1685             return parse_dowhile(parser, block, out);
1686         }
1687         else if (!strcmp(parser_tokval(parser), "for"))
1688         {
1689             if (opts_standard == COMPILER_QCC) {
1690                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1691                     return false;
1692             }
1693             return parse_for(parser, block, out);
1694         }
1695         parseerror(parser, "Unexpected keyword");
1696         return false;
1697     }
1698     else if (parser->tok == '{')
1699     {
1700         ast_block *inner;
1701         inner = parse_block(parser, false);
1702         if (!inner)
1703             return false;
1704         *out = (ast_expression*)inner;
1705         return true;
1706     }
1707     else
1708     {
1709         ast_expression *exp = parse_expression(parser, false);
1710         if (!exp)
1711             return false;
1712         *out = exp;
1713         if (!ast_istype(exp, ast_store) &&
1714             !ast_istype(exp, ast_call) &&
1715             !ast_istype(exp, ast_binstore))
1716         {
1717             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1718                 return false;
1719         }
1720         return true;
1721     }
1722 }
1723
1724 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
1725 {
1726     varentry_t *ve;
1727     parser->locals_count--;
1728
1729     ve = &parser->locals[parser->locals_count];
1730     if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
1731         if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
1732             return false;
1733     }
1734     mem_d(parser->locals[parser->locals_count].name);
1735     return true;
1736 }
1737
1738 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
1739 {
1740     size_t oldblocklocal;
1741     bool   retval = true;
1742
1743     oldblocklocal = parser->blocklocal;
1744     parser->blocklocal = parser->locals_count;
1745
1746     if (!parser_next(parser)) { /* skip the '{' */
1747         parseerror(parser, "expected function body");
1748         goto cleanup;
1749     }
1750
1751     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
1752     {
1753         ast_expression *expr;
1754         if (parser->tok == '}')
1755             break;
1756
1757         if (!parse_statement(parser, block, &expr)) {
1758             /* parseerror(parser, "parse error"); */
1759             block = NULL;
1760             goto cleanup;
1761         }
1762         if (!expr)
1763             continue;
1764         if (!ast_block_exprs_add(block, expr)) {
1765             ast_delete(expr);
1766             block = NULL;
1767             goto cleanup;
1768         }
1769     }
1770
1771     if (parser->tok != '}') {
1772         block = NULL;
1773     } else {
1774         if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
1775         {
1776             if (!block->exprs_count ||
1777                 !ast_istype(block->exprs[block->exprs_count-1], ast_return))
1778             {
1779                 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
1780                     block = NULL;
1781                     goto cleanup;
1782                 }
1783             }
1784         }
1785         (void)parser_next(parser);
1786     }
1787
1788 cleanup:
1789     while (parser->locals_count > parser->blocklocal)
1790         retval = retval && parser_pop_local(parser);
1791     parser->blocklocal = oldblocklocal;
1792     return !!block;
1793 }
1794
1795 static ast_block* parse_block(parser_t *parser, bool warnreturn)
1796 {
1797     ast_block *block;
1798     block = ast_block_new(parser_ctx(parser));
1799     if (!block)
1800         return NULL;
1801     if (!parse_block_into(parser, block, warnreturn)) {
1802         ast_block_delete(block);
1803         return NULL;
1804     }
1805     return block;
1806 }
1807
1808 static ast_expression* parse_statement_or_block(parser_t *parser)
1809 {
1810     ast_expression *expr = NULL;
1811     if (parser->tok == '{')
1812         return (ast_expression*)parse_block(parser, false);
1813     if (!parse_statement(parser, NULL, &expr))
1814         return NULL;
1815     return expr;
1816 }
1817
1818 /* loop method */
1819 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
1820 {
1821     size_t i;
1822     size_t len = strlen(var->name);
1823
1824     for (i = 0; i < 3; ++i) {
1825         ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
1826         if (!ve[i].var)
1827             break;
1828
1829         ve[i].name = (char*)mem_a(len+3);
1830         if (!ve[i].name) {
1831             ast_delete(ve[i].var);
1832             break;
1833         }
1834
1835         memcpy(ve[i].name, var->name, len);
1836         ve[i].name[len]   = '_';
1837         ve[i].name[len+1] = 'x'+i;
1838         ve[i].name[len+2] = 0;
1839     }
1840     if (i == 3)
1841         return true;
1842
1843     /* unroll */
1844     do {
1845         --i;
1846         mem_d(ve[i].name);
1847         ast_delete(ve[i].var);
1848         ve[i].name = NULL;
1849         ve[i].var  = NULL;
1850     } while (i);
1851     return false;
1852 }
1853
1854 static bool parse_function_body(parser_t *parser, ast_value *var)
1855 {
1856     ast_block      *block = NULL;
1857     ast_function   *func;
1858     ast_function   *old;
1859     size_t          parami;
1860
1861     ast_expression *framenum  = NULL;
1862     ast_expression *nextthink = NULL;
1863     /* None of the following have to be deleted */
1864     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
1865     ast_expression *gbl_time = NULL, *gbl_self = NULL;
1866     bool            has_frame_think;
1867
1868     bool retval = true;
1869
1870     has_frame_think = false;
1871     old = parser->function;
1872
1873     if (var->expression.variadic) {
1874         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
1875                          "variadic function with implementation will not be able to access additional parameters"))
1876         {
1877             return false;
1878         }
1879     }
1880
1881     if (parser->tok == '[') {
1882         /* got a frame definition: [ framenum, nextthink ]
1883          * this translates to:
1884          * self.frame = framenum;
1885          * self.nextthink = time + 0.1;
1886          * self.think = nextthink;
1887          */
1888         nextthink = NULL;
1889
1890         fld_think     = parser_find_field(parser, "think");
1891         fld_nextthink = parser_find_field(parser, "nextthink");
1892         fld_frame     = parser_find_field(parser, "frame");
1893         if (!fld_think || !fld_nextthink || !fld_frame) {
1894             parseerror(parser, "cannot use [frame,think] notation without the required fields");
1895             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
1896             return false;
1897         }
1898         gbl_time      = parser_find_global(parser, "time");
1899         gbl_self      = parser_find_global(parser, "self");
1900         if (!gbl_time || !gbl_self) {
1901             parseerror(parser, "cannot use [frame,think] notation without the required globals");
1902             parseerror(parser, "please declare the following globals: `time`, `self`");
1903             return false;
1904         }
1905
1906         if (!parser_next(parser))
1907             return false;
1908
1909         framenum = parse_expression_leave(parser, true);
1910         if (!framenum) {
1911             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
1912             return false;
1913         }
1914         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
1915             ast_unref(framenum);
1916             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
1917             return false;
1918         }
1919
1920         if (parser->tok != ',') {
1921             ast_unref(framenum);
1922             parseerror(parser, "expected comma after frame number in [frame,think] notation");
1923             parseerror(parser, "Got a %i\n", parser->tok);
1924             return false;
1925         }
1926
1927         if (!parser_next(parser)) {
1928             ast_unref(framenum);
1929             return false;
1930         }
1931
1932         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
1933         {
1934             /* qc allows the use of not-yet-declared functions here
1935              * - this automatically creates a prototype */
1936             varentry_t      varent;
1937             ast_value      *thinkfunc;
1938             ast_expression *functype = fld_think->expression.next;
1939
1940             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
1941             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
1942                 ast_unref(framenum);
1943                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
1944                 return false;
1945             }
1946
1947             if (!parser_next(parser)) {
1948                 ast_unref(framenum);
1949                 ast_delete(thinkfunc);
1950                 return false;
1951             }
1952
1953             varent.var = (ast_expression*)thinkfunc;
1954             varent.name = util_strdup(thinkfunc->name);
1955             if (!parser_t_globals_add(parser, varent)) {
1956                 ast_unref(framenum);
1957                 ast_delete(thinkfunc);
1958                 return false;
1959             }
1960             nextthink = (ast_expression*)thinkfunc;
1961
1962         } else {
1963             nextthink = parse_expression_leave(parser, true);
1964             if (!nextthink) {
1965                 ast_unref(framenum);
1966                 parseerror(parser, "expected a think-function in [frame,think] notation");
1967                 return false;
1968             }
1969         }
1970
1971         if (!ast_istype(nextthink, ast_value)) {
1972             parseerror(parser, "think-function in [frame,think] notation must be a constant");
1973             retval = false;
1974         }
1975
1976         if (retval && parser->tok != ']') {
1977             parseerror(parser, "expected closing `]` for [frame,think] notation");
1978             retval = false;
1979         }
1980
1981         if (retval && !parser_next(parser)) {
1982             retval = false;
1983         }
1984
1985         if (retval && parser->tok != '{') {
1986             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
1987             retval = false;
1988         }
1989
1990         if (!retval) {
1991             ast_unref(nextthink);
1992             ast_unref(framenum);
1993             return false;
1994         }
1995
1996         has_frame_think = true;
1997     }
1998
1999     block = ast_block_new(parser_ctx(parser));
2000     if (!block) {
2001         parseerror(parser, "failed to allocate block");
2002         if (has_frame_think) {
2003             ast_unref(nextthink);
2004             ast_unref(framenum);
2005         }
2006         return false;
2007     }
2008
2009     if (has_frame_think) {
2010         lex_ctx ctx;
2011         ast_expression *self_frame;
2012         ast_expression *self_nextthink;
2013         ast_expression *self_think;
2014         ast_expression *time_plus_1;
2015         ast_store *store_frame;
2016         ast_store *store_nextthink;
2017         ast_store *store_think;
2018
2019         ctx = parser_ctx(parser);
2020         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2021         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2022         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2023
2024         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2025                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2026
2027         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2028             if (self_frame)     ast_delete(self_frame);
2029             if (self_nextthink) ast_delete(self_nextthink);
2030             if (self_think)     ast_delete(self_think);
2031             if (time_plus_1)    ast_delete(time_plus_1);
2032             retval = false;
2033         }
2034
2035         if (retval)
2036         {
2037             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2038             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2039             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2040
2041             if (!store_frame) {
2042                 ast_delete(self_frame);
2043                 retval = false;
2044             }
2045             if (!store_nextthink) {
2046                 ast_delete(self_nextthink);
2047                 retval = false;
2048             }
2049             if (!store_think) {
2050                 ast_delete(self_think);
2051                 retval = false;
2052             }
2053             if (!retval) {
2054                 if (store_frame)     ast_delete(store_frame);
2055                 if (store_nextthink) ast_delete(store_nextthink);
2056                 if (store_think)     ast_delete(store_think);
2057                 retval = false;
2058             }
2059             if (retval && !ast_block_exprs_add(block, (ast_expression*)store_frame)) {
2060                 ast_delete(store_frame);
2061                 ast_delete(store_nextthink);
2062                 ast_delete(store_think);
2063                 retval = false;
2064             }
2065
2066             if (retval && !ast_block_exprs_add(block, (ast_expression*)store_nextthink)) {
2067                 ast_delete(store_nextthink);
2068                 ast_delete(store_think);
2069                 retval = false;
2070             }
2071
2072             if (retval && !ast_block_exprs_add(block, (ast_expression*)store_think) )
2073             {
2074                 ast_delete(store_think);
2075                 retval = false;
2076             }
2077         }
2078
2079         if (!retval) {
2080             parseerror(parser, "failed to generate code for [frame,think]");
2081             ast_unref(nextthink);
2082             ast_unref(framenum);
2083             ast_delete(block);
2084             return false;
2085         }
2086     }
2087
2088     for (parami = 0; parami < var->expression.params_count; ++parami) {
2089         size_t     e;
2090         varentry_t ve[3];
2091         ast_value *param = var->expression.params[parami];
2092
2093         if (param->expression.vtype != TYPE_VECTOR &&
2094             (param->expression.vtype != TYPE_FIELD ||
2095              param->expression.next->expression.vtype != TYPE_VECTOR))
2096         {
2097             continue;
2098         }
2099
2100         if (!create_vector_members(parser, param, ve)) {
2101             ast_block_delete(block);
2102             return false;
2103         }
2104
2105         for (e = 0; e < 3; ++e) {
2106             if (!parser_t_locals_add(parser, ve[e]))
2107                 break;
2108             if (!ast_block_collect(block, ve[e].var)) {
2109                 parser->locals_count--;
2110                 break;
2111             }
2112             ve[e].var = NULL; /* collected */
2113         }
2114         if (e != 3) {
2115             parser->locals -= e;
2116             do {
2117                 mem_d(ve[e].name);
2118                 --e;
2119             } while (e);
2120             ast_block_delete(block);
2121             return false;
2122         }
2123     }
2124
2125     func = ast_function_new(ast_ctx(var), var->name, var);
2126     if (!func) {
2127         parseerror(parser, "failed to allocate function for `%s`", var->name);
2128         ast_block_delete(block);
2129         goto enderr;
2130     }
2131     if (!parser_t_functions_add(parser, func)) {
2132         parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2133         ast_block_delete(block);
2134         goto enderrfn;
2135     }
2136
2137     parser->function = func;
2138     if (!parse_block_into(parser, block, true)) {
2139         ast_block_delete(block);
2140         goto enderrfn2;
2141     }
2142
2143     if (!ast_function_blocks_add(func, block)) {
2144         ast_block_delete(block);
2145         goto enderrfn2;
2146     }
2147
2148     parser->function = old;
2149     while (parser->locals_count)
2150         retval = retval && parser_pop_local(parser);
2151
2152     if (parser->tok == ';')
2153         return parser_next(parser);
2154     else if (opts_standard == COMPILER_QCC)
2155         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2156     return retval;
2157
2158 enderrfn2:
2159     parser->functions_count--;
2160 enderrfn:
2161     ast_function_delete(func);
2162     var->constval.vfunc = NULL;
2163
2164 enderr:
2165     while (parser->locals_count) {
2166         parser->locals_count--;
2167         mem_d(parser->locals[parser->locals_count].name);
2168     }
2169     parser->function = old;
2170     return false;
2171 }
2172
2173 typedef struct {
2174     MEM_VECTOR_MAKE(ast_value*, p);
2175 } paramlist_t;
2176 MEM_VEC_FUNCTIONS(paramlist_t, ast_value*, p)
2177
2178 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2179 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2180 {
2181     lex_ctx     ctx;
2182     size_t      i;
2183     paramlist_t params;
2184     ast_value  *param;
2185     ast_value  *fval;
2186     bool        first = true;
2187     bool        variadic = false;
2188
2189     ctx = parser_ctx(parser);
2190
2191     /* for the sake of less code we parse-in in this function */
2192     if (!parser_next(parser)) {
2193         parseerror(parser, "expected parameter list");
2194         return NULL;
2195     }
2196
2197     MEM_VECTOR_INIT(&params, p);
2198
2199     /* parse variables until we hit a closing paren */
2200     while (parser->tok != ')') {
2201         if (!first) {
2202             /* there must be commas between them */
2203             if (parser->tok != ',') {
2204                 parseerror(parser, "expected comma or end of parameter list");
2205                 goto on_error;
2206             }
2207             if (!parser_next(parser)) {
2208                 parseerror(parser, "expected parameter");
2209                 goto on_error;
2210             }
2211         }
2212         first = false;
2213
2214         if (parser->tok == TOKEN_DOTS) {
2215             /* '...' indicates a varargs function */
2216             variadic = true;
2217             if (!parser_next(parser)) {
2218                 parseerror(parser, "expected parameter");
2219                 return NULL;
2220             }
2221             if (parser->tok != ')') {
2222                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2223                 goto on_error;
2224             }
2225         }
2226         else
2227         {
2228             /* for anything else just parse a typename */
2229             param = parse_typename(parser, NULL);
2230             if (!param)
2231                 goto on_error;
2232             if (!paramlist_t_p_add(&params, param))
2233                 goto on_error;
2234         }
2235     }
2236
2237     /* sanity check */
2238     if (params.p_count > 8)
2239         parseerror(parser, "more than 8 parameters are currently not supported");
2240
2241     /* parse-out */
2242     if (!parser_next(parser)) {
2243         parseerror(parser, "parse error after typename");
2244         goto on_error;
2245     }
2246
2247     /* now turn 'var' into a function type */
2248     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2249     fval->expression.next     = (ast_expression*)var;
2250     fval->expression.variadic = variadic;
2251     var = fval;
2252
2253     MEM_VECTOR_MOVE(&params, p, &var->expression, params);
2254
2255     return var;
2256
2257 on_error:
2258     ast_delete(var);
2259     for (i = 0; i < params.p_count; ++i)
2260         ast_delete(params.p[i]);
2261     MEM_VECTOR_CLEAR(&params, p);
2262     return NULL;
2263 }
2264
2265 /* Parse a complete typename.
2266  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2267  * but when parsing variables separated by comma
2268  * 'storebase' should point to where the base-type should be kept.
2269  * The base type makes up every bit of type information which comes *before* the
2270  * variable name.
2271  *
2272  * The following will be parsed in its entirety:
2273  *     void() foo()
2274  * The 'basetype' in this case is 'void()'
2275  * and if there's a comma after it, say:
2276  *     void() foo(), bar
2277  * then the type-information 'void()' can be stored in 'storebase'
2278  */
2279 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2280 {
2281     ast_value *var, *tmp;
2282     lex_ctx    ctx;
2283
2284     const char *name = NULL;
2285     bool        isfield = false;
2286
2287     ctx = parser_ctx(parser);
2288
2289     /* types may start with a dot */
2290     if (parser->tok == '.') {
2291         isfield = true;
2292         /* if we parsed a dot we need a typename now */
2293         if (!parser_next(parser)) {
2294             parseerror(parser, "expected typename for field definition");
2295             return NULL;
2296         }
2297         if (parser->tok != TOKEN_TYPENAME) {
2298             parseerror(parser, "expected typename");
2299             return NULL;
2300         }
2301     }
2302
2303     /* generate the basic type value */
2304     var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2305     /* do not yet turn into a field - remember:
2306      * .void() foo; is a field too
2307      * .void()() foo; is a function
2308      */
2309
2310     /* parse on */
2311     if (!parser_next(parser)) {
2312         ast_delete(var);
2313         parseerror(parser, "parse error after typename");
2314         return NULL;
2315     }
2316
2317     /* an opening paren now starts the parameter-list of a function */
2318     if (parser->tok == '(') {
2319         var = parse_parameter_list(parser, var);
2320         if (!var)
2321             return NULL;
2322     }
2323     /* This is the point where we can turn it into a field */
2324     if (isfield) {
2325         /* turn it into a field if desired */
2326         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2327         tmp->expression.next = (ast_expression*)var;
2328         var = tmp;
2329     }
2330
2331     while (parser->tok == '(') {
2332         var = parse_parameter_list(parser, var);
2333         if (!var)
2334             return NULL;
2335     }
2336
2337     /* store the base if requested */
2338     if (storebase) {
2339         *storebase = ast_value_copy(var);
2340     }
2341
2342     /* there may be a name now */
2343     if (parser->tok == TOKEN_IDENT) {
2344         name = util_strdup(parser_tokval(parser));
2345         /* parse on */
2346         if (!parser_next(parser)) {
2347             parseerror(parser, "error after variable or field declaration");
2348             return NULL;
2349         }
2350     }
2351
2352     /* now there may be function parens again */
2353     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2354         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2355     while (parser->tok == '(') {
2356         var = parse_parameter_list(parser, var);
2357         if (!var) {
2358             if (name)
2359                 mem_d((void*)name);
2360             return NULL;
2361         }
2362     }
2363
2364     /* finally name it */
2365     if (name) {
2366         if (!ast_value_set_name(var, name)) {
2367             ast_delete(var);
2368             parseerror(parser, "internal error: failed to set name");
2369             return NULL;
2370         }
2371         /* free the name, ast_value_set_name duplicates */
2372         mem_d((void*)name);
2373     }
2374
2375     return var;
2376 }
2377
2378 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2379 {
2380     ast_value *var;
2381     ast_value *proto;
2382     ast_expression *old;
2383     bool       was_end;
2384     size_t     i;
2385
2386     ast_value *basetype = NULL;
2387     bool      retval    = true;
2388     bool      isparam   = false;
2389     bool      isvector  = false;
2390     bool      cleanvar  = true;
2391
2392     varentry_t varent, ve[3];
2393
2394     /* get the first complete variable */
2395     var = parse_typename(parser, &basetype);
2396     if (!var) {
2397         if (basetype)
2398             ast_delete(basetype);
2399         return false;
2400     }
2401
2402     memset(&varent, 0, sizeof(varent));
2403     memset(&ve, 0, sizeof(ve));
2404
2405     while (true) {
2406         proto = NULL;
2407
2408         /* Part 0: finish the type */
2409         while (parser->tok == '(') {
2410             if (opts_standard == COMPILER_QCC)
2411                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2412             var = parse_parameter_list(parser, var);
2413             if (!var) {
2414                 retval = false;
2415                 goto cleanup;
2416             }
2417         }
2418
2419         /* Part 1:
2420          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2421          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2422          * is then filled with the previous definition and the parameter-names replaced.
2423          */
2424         if (!localblock) {
2425             /* Deal with end_sys_ vars */
2426             was_end = false;
2427             if (!strcmp(var->name, "end_sys_globals")) {
2428                 parser->crc_globals = parser->globals_count;
2429                 was_end = true;
2430             }
2431             else if (!strcmp(var->name, "end_sys_fields")) {
2432                 parser->crc_fields = parser->fields_count;
2433                 was_end = true;
2434             }
2435             if (was_end && var->expression.vtype == TYPE_FIELD) {
2436                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2437                                  "global '%s' hint should not be a field",
2438                                  parser_tokval(parser)))
2439                 {
2440                     retval = false;
2441                     goto cleanup;
2442                 }
2443             }
2444
2445             if (!nofields && var->expression.vtype == TYPE_FIELD)
2446             {
2447                 /* deal with field declarations */
2448                 old = parser_find_field(parser, var->name);
2449                 if (old) {
2450                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2451                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2452                     {
2453                         retval = false;
2454                         goto cleanup;
2455                     }
2456                     ast_delete(var);
2457                     var = NULL;
2458                     goto skipvar;
2459                     /*
2460                     parseerror(parser, "field `%s` already declared here: %s:%i",
2461                                var->name, ast_ctx(old).file, ast_ctx(old).line);
2462                     retval = false;
2463                     goto cleanup;
2464                     */
2465                 }
2466                 if (opts_standard == COMPILER_QCC &&
2467                     (old = parser_find_global(parser, var->name)))
2468                 {
2469                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2470                     parseerror(parser, "field `%s` already declared here: %s:%i",
2471                                var->name, ast_ctx(old).file, ast_ctx(old).line);
2472                     retval = false;
2473                     goto cleanup;
2474                 }
2475             }
2476             else
2477             {
2478                 /* deal with other globals */
2479                 old = parser_find_global(parser, var->name);
2480                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
2481                 {
2482                     /* This is a function which had a prototype */
2483                     if (!ast_istype(old, ast_value)) {
2484                         parseerror(parser, "internal error: prototype is not an ast_value");
2485                         retval = false;
2486                         goto cleanup;
2487                     }
2488                     proto = (ast_value*)old;
2489                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
2490                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
2491                                    proto->name,
2492                                    ast_ctx(proto).file, ast_ctx(proto).line);
2493                         retval = false;
2494                         goto cleanup;
2495                     }
2496                     /* we need the new parameter-names */
2497                     for (i = 0; i < proto->expression.params_count; ++i)
2498                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
2499                     ast_delete(var);
2500                     var = proto;
2501                 }
2502                 else
2503                 {
2504                     /* other globals */
2505                     if (old) {
2506                         parseerror(parser, "global `%s` already declared here: %s:%i",
2507                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
2508                         retval = false;
2509                         goto cleanup;
2510                     }
2511                     if (opts_standard == COMPILER_QCC &&
2512                         (old = parser_find_field(parser, var->name)))
2513                     {
2514                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2515                         parseerror(parser, "global `%s` already declared here: %s:%i",
2516                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
2517                         retval = false;
2518                         goto cleanup;
2519                     }
2520                 }
2521             }
2522         }
2523         else /* it's not a global */
2524         {
2525             old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
2526             if (old && !isparam) {
2527                 parseerror(parser, "local `%s` already declared here: %s:%i",
2528                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2529                 retval = false;
2530                 goto cleanup;
2531             }
2532             old = parser_find_local(parser, var->name, 0, &isparam);
2533             if (old && isparam) {
2534                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
2535                                  "local `%s` is shadowing a parameter", var->name))
2536                 {
2537                     parseerror(parser, "local `%s` already declared here: %s:%i",
2538                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2539                     retval = false;
2540                     goto cleanup;
2541                 }
2542                 if (opts_standard != COMPILER_GMQCC) {
2543                     ast_delete(var);
2544                     var = NULL;
2545                     goto skipvar;
2546                 }
2547             }
2548         }
2549
2550         /* Part 2:
2551          * Create the global/local, and deal with vector types.
2552          */
2553         if (!proto) {
2554             if (var->expression.vtype == TYPE_VECTOR)
2555                 isvector = true;
2556             else if (var->expression.vtype == TYPE_FIELD &&
2557                      var->expression.next->expression.vtype == TYPE_VECTOR)
2558                 isvector = true;
2559
2560             if (isvector) {
2561                 if (!create_vector_members(parser, var, ve)) {
2562                     retval = false;
2563                     goto cleanup;
2564                 }
2565             }
2566
2567             varent.name = util_strdup(var->name);
2568             varent.var  = (ast_expression*)var;
2569
2570             if (!localblock) {
2571                 /* deal with global variables, fields, functions */
2572                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
2573                     if (!(retval = parser_t_fields_add(parser, varent)))
2574                         goto cleanup;
2575                     if (isvector) {
2576                         for (i = 0; i < 3; ++i) {
2577                             if (!(retval = parser_t_fields_add(parser, ve[i])))
2578                                 break;
2579                         }
2580                         if (!retval) {
2581                             parser->fields_count -= i+1;
2582                             goto cleanup;
2583                         }
2584                     }
2585                 }
2586                 else {
2587                     if (!(retval = parser_t_globals_add(parser, varent)))
2588                         goto cleanup;
2589                     if (isvector) {
2590                         for (i = 0; i < 3; ++i) {
2591                             if (!(retval = parser_t_globals_add(parser, ve[i])))
2592                                 break;
2593                         }
2594                         if (!retval) {
2595                             parser->globals_count -= i+1;
2596                             goto cleanup;
2597                         }
2598                     }
2599                 }
2600             } else {
2601                 if (!(retval = parser_t_locals_add(parser, varent)))
2602                     goto cleanup;
2603                 if (!(retval = ast_block_locals_add(localblock, var))) {
2604                     parser->locals_count--;
2605                     goto cleanup;
2606                 }
2607                 if (isvector) {
2608                     for (i = 0; i < 3; ++i) {
2609                         if (!(retval = parser_t_locals_add(parser, ve[i])))
2610                             break;
2611                         if (!(retval = ast_block_collect(localblock, ve[i].var)))
2612                             break;
2613                         ve[i].var = NULL; /* from here it's being collected in the block */
2614                     }
2615                     if (!retval) {
2616                         parser->locals_count -= i+1;
2617                         localblock->locals_count--;
2618                         goto cleanup;
2619                     }
2620                 }
2621             }
2622
2623             varent.name = NULL;
2624             ve[0].name = ve[1].name = ve[2].name = NULL;
2625             ve[0].var  = ve[1].var  = ve[2].var  = NULL;
2626             cleanvar = false;
2627         }
2628
2629 skipvar:
2630         if (parser->tok == ';') {
2631             ast_delete(basetype);
2632             if (!parser_next(parser)) {
2633                 parseerror(parser, "error after variable declaration");
2634                 return false;
2635             }
2636             return true;
2637         }
2638
2639         if (parser->tok == ',')
2640             goto another;
2641
2642         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
2643             parseerror(parser, "missing comma or semicolon while parsing variables");
2644             break;
2645         }
2646
2647         if (localblock && opts_standard == COMPILER_QCC) {
2648             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
2649                              "initializing expression turns variable `%s` into a constant in this standard",
2650                              var->name) )
2651             {
2652                 break;
2653             }
2654         }
2655
2656         if (parser->tok != '{') {
2657             if (parser->tok != '=') {
2658                 parseerror(parser, "missing semicolon or initializer");
2659                 break;
2660             }
2661
2662             if (!parser_next(parser)) {
2663                 parseerror(parser, "error parsing initializer");
2664                 break;
2665             }
2666         }
2667         else if (opts_standard == COMPILER_QCC) {
2668             parseerror(parser, "expected '=' before function body in this standard");
2669         }
2670
2671         if (parser->tok == '#') {
2672             ast_function *func;
2673
2674             if (localblock) {
2675                 parseerror(parser, "cannot declare builtins within functions");
2676                 break;
2677             }
2678             if (var->expression.vtype != TYPE_FUNCTION) {
2679                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
2680                 break;
2681             }
2682             if (!parser_next(parser)) {
2683                 parseerror(parser, "expected builtin number");
2684                 break;
2685             }
2686             if (parser->tok != TOKEN_INTCONST) {
2687                 parseerror(parser, "builtin number must be an integer constant");
2688                 break;
2689             }
2690             if (parser_token(parser)->constval.i <= 0) {
2691                 parseerror(parser, "builtin number must be an integer greater than zero");
2692                 break;
2693             }
2694
2695             func = ast_function_new(ast_ctx(var), var->name, var);
2696             if (!func) {
2697                 parseerror(parser, "failed to allocate function for `%s`", var->name);
2698                 break;
2699             }
2700             if (!parser_t_functions_add(parser, func)) {
2701                 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2702                 ast_function_delete(func);
2703                 var->constval.vfunc = NULL;
2704                 break;
2705             }
2706
2707             func->builtin = -parser_token(parser)->constval.i;
2708
2709             if (!parser_next(parser)) {
2710                 parseerror(parser, "expected comma or semicolon");
2711                 ast_function_delete(func);
2712                 var->constval.vfunc = NULL;
2713                 break;
2714             }
2715         }
2716         else if (parser->tok == '{' || parser->tok == '[')
2717         {
2718             if (localblock) {
2719                 parseerror(parser, "cannot declare functions within functions");
2720                 break;
2721             }
2722
2723             if (!parse_function_body(parser, var))
2724                 break;
2725             ast_delete(basetype);
2726             return true;
2727         } else {
2728             ast_expression *cexp;
2729             ast_value      *cval;
2730
2731             cexp = parse_expression_leave(parser, true);
2732             if (!cexp)
2733                 break;
2734
2735             if (!localblock) {
2736                 cval = (ast_value*)cexp;
2737                 if (!ast_istype(cval, ast_value) || !cval->isconst)
2738                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
2739                 else
2740                 {
2741                     var->isconst = true;
2742                     if (cval->expression.vtype == TYPE_STRING)
2743                         var->constval.vstring = parser_strdup(cval->constval.vstring);
2744                     else
2745                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
2746                     ast_unref(cval);
2747                 }
2748             } else {
2749                 shunt sy;
2750                 MEM_VECTOR_INIT(&sy, out);
2751                 MEM_VECTOR_INIT(&sy, ops);
2752                 if (!shunt_out_add(&sy, syexp(ast_ctx(var), (ast_expression*)var)) ||
2753                     !shunt_out_add(&sy, syexp(ast_ctx(cexp), (ast_expression*)cexp)) ||
2754                     !shunt_ops_add(&sy, syop(ast_ctx(var), parser->assign_op)))
2755                 {
2756                     parseerror(parser, "internal error: failed to prepare initializer");
2757                     ast_unref(cexp);
2758                 }
2759                 else if (!parser_sy_pop(parser, &sy))
2760                     ast_unref(cexp);
2761                 else {
2762                     if (sy.out_count != 1 && sy.ops_count != 0)
2763                         parseerror(parser, "internal error: leaked operands");
2764                     else if (!ast_block_exprs_add(localblock, (ast_expression*)sy.out[0].out)) {
2765                         parseerror(parser, "failed to create intializing expression");
2766                         ast_unref(sy.out[0].out);
2767                         ast_unref(cexp);
2768                     }
2769                 }
2770                 MEM_VECTOR_CLEAR(&sy, out);
2771                 MEM_VECTOR_CLEAR(&sy, ops);
2772             }
2773         }
2774
2775 another:
2776         if (parser->tok == ',') {
2777             if (!parser_next(parser)) {
2778                 parseerror(parser, "expected another variable");
2779                 break;
2780             }
2781
2782             if (parser->tok != TOKEN_IDENT) {
2783                 parseerror(parser, "expected another variable");
2784                 break;
2785             }
2786             var = ast_value_copy(basetype);
2787             cleanvar = true;
2788             ast_value_set_name(var, parser_tokval(parser));
2789             if (!parser_next(parser)) {
2790                 parseerror(parser, "error parsing variable declaration");
2791                 break;
2792             }
2793             continue;
2794         }
2795
2796         if (parser->tok != ';') {
2797             parseerror(parser, "missing semicolon after variables");
2798             break;
2799         }
2800
2801         if (!parser_next(parser)) {
2802             parseerror(parser, "parse error after variable declaration");
2803             break;
2804         }
2805
2806         ast_delete(basetype);
2807         return true;
2808     }
2809
2810     if (cleanvar && var)
2811         ast_delete(var);
2812     ast_delete(basetype);
2813     return false;
2814
2815 cleanup:
2816     ast_delete(basetype);
2817     if (cleanvar && var)
2818         ast_delete(var);
2819     if (varent.name) mem_d(varent.name);
2820     if (ve[0].name)  mem_d(ve[0].name);
2821     if (ve[1].name)  mem_d(ve[1].name);
2822     if (ve[2].name)  mem_d(ve[2].name);
2823     if (ve[0].var)   mem_d(ve[0].var);
2824     if (ve[1].var)   mem_d(ve[1].var);
2825     if (ve[2].var)   mem_d(ve[2].var);
2826     return retval;
2827 }
2828
2829 static bool parser_global_statement(parser_t *parser)
2830 {
2831     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2832     {
2833         return parse_variable(parser, NULL, false);
2834     }
2835     else if (parser->tok == TOKEN_KEYWORD)
2836     {
2837         /* handle 'var' and 'const' */
2838         if (!strcmp(parser_tokval(parser), "var")) {
2839             if (!parser_next(parser)) {
2840                 parseerror(parser, "expected variable declaration after 'var'");
2841                 return false;
2842             }
2843             return parse_variable(parser, NULL, true);
2844         }
2845         return false;
2846     }
2847     else if (parser->tok == '$')
2848     {
2849         if (!parser_next(parser)) {
2850             parseerror(parser, "parse error");
2851             return false;
2852         }
2853     }
2854     else
2855     {
2856         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
2857         return false;
2858     }
2859     return true;
2860 }
2861
2862 static parser_t *parser;
2863
2864 bool parser_init()
2865 {
2866     size_t i;
2867     parser = (parser_t*)mem_a(sizeof(parser_t));
2868     if (!parser)
2869         return false;
2870
2871     memset(parser, 0, sizeof(*parser));
2872
2873     for (i = 0; i < operator_count; ++i) {
2874         if (operators[i].id == opid1('=')) {
2875             parser->assign_op = operators+i;
2876             break;
2877         }
2878     }
2879     if (!parser->assign_op) {
2880         printf("internal error: initializing parser: failed to find assign operator\n");
2881         mem_d(parser);
2882         return false;
2883     }
2884     return true;
2885 }
2886
2887 bool parser_compile(const char *filename)
2888 {
2889     parser->lex = lex_open(filename);
2890     if (!parser->lex) {
2891         printf("failed to open file \"%s\"\n", filename);
2892         return false;
2893     }
2894
2895     /* initial lexer/parser state */
2896     parser->lex->flags.noops = true;
2897
2898     if (parser_next(parser))
2899     {
2900         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2901         {
2902             if (!parser_global_statement(parser)) {
2903                 if (parser->tok == TOKEN_EOF)
2904                     parseerror(parser, "unexpected eof");
2905                 else if (!parser->errors)
2906                     parseerror(parser, "there have been errors, bailing out");
2907                 lex_close(parser->lex);
2908                 parser->lex = NULL;
2909                 return false;
2910             }
2911         }
2912     } else {
2913         parseerror(parser, "parse error");
2914         lex_close(parser->lex);
2915         parser->lex = NULL;
2916         return false;
2917     }
2918
2919     lex_close(parser->lex);
2920     parser->lex = NULL;
2921
2922     return !parser->errors;
2923 }
2924
2925 void parser_cleanup()
2926 {
2927     size_t i;
2928     for (i = 0; i < parser->functions_count; ++i) {
2929         ast_delete(parser->functions[i]);
2930     }
2931     for (i = 0; i < parser->imm_vector_count; ++i) {
2932         ast_delete(parser->imm_vector[i]);
2933     }
2934     for (i = 0; i < parser->imm_string_count; ++i) {
2935         ast_delete(parser->imm_string[i]);
2936     }
2937     for (i = 0; i < parser->imm_float_count; ++i) {
2938         ast_delete(parser->imm_float[i]);
2939     }
2940     for (i = 0; i < parser->fields_count; ++i) {
2941         ast_delete(parser->fields[i].var);
2942         mem_d(parser->fields[i].name);
2943     }
2944     for (i = 0; i < parser->globals_count; ++i) {
2945         ast_delete(parser->globals[i].var);
2946         mem_d(parser->globals[i].name);
2947     }
2948     MEM_VECTOR_CLEAR(parser, functions);
2949     MEM_VECTOR_CLEAR(parser, imm_vector);
2950     MEM_VECTOR_CLEAR(parser, imm_string);
2951     MEM_VECTOR_CLEAR(parser, imm_float);
2952     MEM_VECTOR_CLEAR(parser, globals);
2953     MEM_VECTOR_CLEAR(parser, fields);
2954     MEM_VECTOR_CLEAR(parser, locals);
2955
2956     mem_d(parser);
2957 }
2958
2959 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
2960 {
2961     return util_crc16(old, str, strlen(str));
2962 }
2963
2964 static void progdefs_crc_file(const char *str)
2965 {
2966     /* write to progdefs.h here */
2967 }
2968
2969 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
2970 {
2971     old = progdefs_crc_sum(old, str);
2972     progdefs_crc_file(str);
2973     return old;
2974 }
2975
2976 static void generate_checksum(parser_t *parser)
2977 {
2978     uint16_t crc = 0xFFFF;
2979     size_t i;
2980
2981         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
2982         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
2983         /*
2984         progdefs_crc_file("\tint\tpad;\n");
2985         progdefs_crc_file("\tint\tofs_return[3];\n");
2986         progdefs_crc_file("\tint\tofs_parm0[3];\n");
2987         progdefs_crc_file("\tint\tofs_parm1[3];\n");
2988         progdefs_crc_file("\tint\tofs_parm2[3];\n");
2989         progdefs_crc_file("\tint\tofs_parm3[3];\n");
2990         progdefs_crc_file("\tint\tofs_parm4[3];\n");
2991         progdefs_crc_file("\tint\tofs_parm5[3];\n");
2992         progdefs_crc_file("\tint\tofs_parm6[3];\n");
2993         progdefs_crc_file("\tint\tofs_parm7[3];\n");
2994         */
2995         for (i = 0; i < parser->crc_globals; ++i) {
2996             if (!ast_istype(parser->globals[i].var, ast_value))
2997                 continue;
2998             switch (parser->globals[i].var->expression.vtype) {
2999                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3000                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3001                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3002                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3003                 default:
3004                     crc = progdefs_crc_both(crc, "\tint\t");
3005                     break;
3006             }
3007             crc = progdefs_crc_both(crc, parser->globals[i].name);
3008             crc = progdefs_crc_both(crc, ";\n");
3009         }
3010         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3011         for (i = 0; i < parser->crc_fields; ++i) {
3012             if (!ast_istype(parser->fields[i].var, ast_value))
3013                 continue;
3014             switch (parser->fields[i].var->expression.next->expression.vtype) {
3015                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3016                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3017                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3018                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3019                 default:
3020                     crc = progdefs_crc_both(crc, "\tint\t");
3021                     break;
3022             }
3023             crc = progdefs_crc_both(crc, parser->fields[i].name);
3024             crc = progdefs_crc_both(crc, ";\n");
3025         }
3026         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3027
3028         code_crc = crc;
3029 }
3030
3031 bool parser_finish(const char *output)
3032 {
3033     size_t i;
3034     ir_builder *ir;
3035     bool retval = true;
3036
3037     if (!parser->errors)
3038     {
3039         ir = ir_builder_new("gmqcc_out");
3040         if (!ir) {
3041             printf("failed to allocate builder\n");
3042             return false;
3043         }
3044
3045         for (i = 0; i < parser->fields_count; ++i) {
3046             ast_value *field;
3047             bool isconst;
3048             if (!ast_istype(parser->fields[i].var, ast_value))
3049                 continue;
3050             field = (ast_value*)parser->fields[i].var;
3051             isconst = field->isconst;
3052             field->isconst = false;
3053             if (!ast_global_codegen((ast_value*)field, ir, true)) {
3054                 printf("failed to generate field %s\n", field->name);
3055                 ir_builder_delete(ir);
3056                 return false;
3057             }
3058             if (isconst) {
3059                 ir_value *ifld;
3060                 ast_expression *subtype;
3061                 field->isconst = true;
3062                 subtype = field->expression.next;
3063                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3064                 if (subtype->expression.vtype == TYPE_FIELD)
3065                     ifld->fieldtype = subtype->expression.next->expression.vtype;
3066                 else if (subtype->expression.vtype == TYPE_FUNCTION)
3067                     ifld->outtype = subtype->expression.next->expression.vtype;
3068                 (void)!ir_value_set_field(field->ir_v, ifld);
3069             }
3070         }
3071         for (i = 0; i < parser->globals_count; ++i) {
3072             ast_value *asvalue;
3073             if (!ast_istype(parser->globals[i].var, ast_value))
3074                 continue;
3075             asvalue = (ast_value*)(parser->globals[i].var);
3076             if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3077                 if (strcmp(asvalue->name, "end_sys_globals") &&
3078                     strcmp(asvalue->name, "end_sys_fields"))
3079                 {
3080                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3081                                                    "unused global: `%s`", asvalue->name);
3082                 }
3083             }
3084             if (!ast_global_codegen(asvalue, ir, false)) {
3085                 printf("failed to generate global %s\n", parser->globals[i].name);
3086                 ir_builder_delete(ir);
3087                 return false;
3088             }
3089         }
3090         for (i = 0; i < parser->imm_float_count; ++i) {
3091             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3092                 printf("failed to generate global %s\n", parser->imm_float[i]->name);
3093                 ir_builder_delete(ir);
3094                 return false;
3095             }
3096         }
3097         for (i = 0; i < parser->imm_string_count; ++i) {
3098             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3099                 printf("failed to generate global %s\n", parser->imm_string[i]->name);
3100                 ir_builder_delete(ir);
3101                 return false;
3102             }
3103         }
3104         for (i = 0; i < parser->imm_vector_count; ++i) {
3105             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3106                 printf("failed to generate global %s\n", parser->imm_vector[i]->name);
3107                 ir_builder_delete(ir);
3108                 return false;
3109             }
3110         }
3111         for (i = 0; i < parser->functions_count; ++i) {
3112             if (!ast_function_codegen(parser->functions[i], ir)) {
3113                 printf("failed to generate function %s\n", parser->functions[i]->name);
3114                 ir_builder_delete(ir);
3115                 return false;
3116             }
3117             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3118                 printf("failed to finalize function %s\n", parser->functions[i]->name);
3119                 ir_builder_delete(ir);
3120                 return false;
3121             }
3122         }
3123
3124         if (retval) {
3125             if (opts_dump)
3126                 ir_builder_dump(ir, printf);
3127
3128             generate_checksum(parser);
3129
3130             if (!ir_builder_generate(ir, output)) {
3131                 printf("*** failed to generate output file\n");
3132                 ir_builder_delete(ir);
3133                 return false;
3134             }
3135         }
3136
3137         ir_builder_delete(ir);
3138         return retval;
3139     }
3140
3141     printf("*** there were compile errors\n");
3142     return false;
3143 }