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