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