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