]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
parsing the ternary
[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     int ternaries = 0;
1084
1085     sy.out = NULL;
1086     sy.ops = NULL;
1087
1088     parser->lex->flags.noops = false;
1089
1090     parser_reclassify_token(parser);
1091
1092     while (true)
1093     {
1094         if (gotmemberof)
1095             gotmemberof = false;
1096         else
1097             parser->memberof = 0;
1098
1099         if (parser->tok == TOKEN_IDENT)
1100         {
1101             ast_expression *var;
1102             if (wantop) {
1103                 parseerror(parser, "expected operator or end of statement");
1104                 goto onerr;
1105             }
1106             wantop = true;
1107             /* variable */
1108             if (opts_standard == COMPILER_GMQCC)
1109             {
1110                 if (parser->memberof == TYPE_ENTITY) {
1111                     /* still get vars first since there could be a fieldpointer */
1112                     var = parser_find_var(parser, parser_tokval(parser));
1113                     if (!var)
1114                         var = parser_find_field(parser, parser_tokval(parser));
1115                 }
1116                 else if (parser->memberof == TYPE_VECTOR)
1117                 {
1118                     parseerror(parser, "TODO: implement effective vector member access");
1119                     goto onerr;
1120                 }
1121                 else if (parser->memberof) {
1122                     parseerror(parser, "namespace for member not found");
1123                     goto onerr;
1124                 }
1125                 else
1126                     var = parser_find_var(parser, parser_tokval(parser));
1127             } else {
1128                 var = parser_find_var(parser, parser_tokval(parser));
1129                 if (!var)
1130                     var = parser_find_field(parser, parser_tokval(parser));
1131             }
1132             if (!var) {
1133                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1134                 goto onerr;
1135             }
1136             if (ast_istype(var, ast_value))
1137                 ((ast_value*)var)->uses++;
1138             vec_push(sy.out, syexp(parser_ctx(parser), var));
1139             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1140         }
1141         else if (parser->tok == TOKEN_FLOATCONST) {
1142             ast_value *val;
1143             if (wantop) {
1144                 parseerror(parser, "expected operator or end of statement, got constant");
1145                 goto onerr;
1146             }
1147             wantop = true;
1148             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1149             if (!val)
1150                 return false;
1151             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1152             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1153         }
1154         else if (parser->tok == TOKEN_INTCONST) {
1155             ast_value *val;
1156             if (wantop) {
1157                 parseerror(parser, "expected operator or end of statement, got constant");
1158                 goto onerr;
1159             }
1160             wantop = true;
1161             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1162             if (!val)
1163                 return false;
1164             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1165             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1166         }
1167         else if (parser->tok == TOKEN_STRINGCONST) {
1168             ast_value *val;
1169             if (wantop) {
1170                 parseerror(parser, "expected operator or end of statement, got constant");
1171                 goto onerr;
1172             }
1173             wantop = true;
1174             val = parser_const_string(parser, parser_tokval(parser));
1175             if (!val)
1176                 return false;
1177             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1178             DEBUGSHUNTDO(con_out("push string\n"));
1179         }
1180         else if (parser->tok == TOKEN_VECTORCONST) {
1181             ast_value *val;
1182             if (wantop) {
1183                 parseerror(parser, "expected operator or end of statement, got constant");
1184                 goto onerr;
1185             }
1186             wantop = true;
1187             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1188             if (!val)
1189                 return false;
1190             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1191             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1192                                 parser_token(parser)->constval.v.x,
1193                                 parser_token(parser)->constval.v.y,
1194                                 parser_token(parser)->constval.v.z));
1195         }
1196         else if (parser->tok == '(') {
1197             parseerror(parser, "internal error: '(' should be classified as operator");
1198             goto onerr;
1199         }
1200         else if (parser->tok == '[') {
1201             parseerror(parser, "internal error: '[' should be classified as operator");
1202             goto onerr;
1203         }
1204         else if (parser->tok == ')') {
1205             if (wantop) {
1206                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1207                 --parens;
1208                 if (parens < 0)
1209                     break;
1210                 /* we do expect an operator next */
1211                 /* closing an opening paren */
1212                 if (!parser_close_paren(parser, &sy, false))
1213                     goto onerr;
1214             } else {
1215                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1216                 --parens;
1217                 if (parens < 0)
1218                     break;
1219                 /* allowed for function calls */
1220                 if (!parser_close_paren(parser, &sy, true))
1221                     goto onerr;
1222             }
1223             wantop = true;
1224         }
1225         else if (parser->tok == ']') {
1226             if (!wantop)
1227                 parseerror(parser, "operand expected");
1228             --parens;
1229             if (parens < 0)
1230                 break;
1231             if (!parser_close_paren(parser, &sy, false))
1232                 goto onerr;
1233             wantop = true;
1234         }
1235         else if (parser->tok != TOKEN_OPERATOR) {
1236             if (wantop) {
1237                 parseerror(parser, "expected operator or end of statement");
1238                 goto onerr;
1239             }
1240             break;
1241         }
1242         else
1243         {
1244             /* classify the operator */
1245             /* TODO: suffix operators */
1246             const oper_info *op;
1247             const oper_info *olast = NULL;
1248             size_t o;
1249             for (o = 0; o < operator_count; ++o) {
1250                 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1251                     !(operators[o].flags & OP_SUFFIX) && /* remove this */
1252                     !strcmp(parser_tokval(parser), operators[o].op))
1253                 {
1254                     break;
1255                 }
1256             }
1257             if (o == operator_count) {
1258                 /* no operator found... must be the end of the statement */
1259                 break;
1260             }
1261             /* found an operator */
1262             op = &operators[o];
1263
1264             /* when declaring variables, a comma starts a new variable */
1265             if (op->id == opid1(',') && !parens && stopatcomma) {
1266                 /* fixup the token */
1267                 parser->tok = ',';
1268                 break;
1269             }
1270
1271             /* a colon without a pervious question mark cannot be a ternary */
1272             if (op->id == opid2(':','?')) {
1273                 parser->tok = ':';
1274                 break;
1275             }
1276
1277             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1278                 olast = &operators[vec_last(sy.ops).etype-1];
1279
1280             while (olast && (
1281                     (op->prec < olast->prec) ||
1282                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1283             {
1284                 if (!parser_sy_pop(parser, &sy))
1285                     goto onerr;
1286                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1287                     olast = &operators[vec_last(sy.ops).etype-1];
1288                 else
1289                     olast = NULL;
1290             }
1291
1292             if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1293                 /* for gmqcc standard: open up the namespace of the previous type */
1294                 ast_expression *prevex = vec_last(sy.out).out;
1295                 if (!prevex) {
1296                     parseerror(parser, "unexpected member operator");
1297                     goto onerr;
1298                 }
1299                 if (prevex->expression.vtype == TYPE_ENTITY)
1300                     parser->memberof = TYPE_ENTITY;
1301                 else if (prevex->expression.vtype == TYPE_VECTOR)
1302                     parser->memberof = TYPE_VECTOR;
1303                 else {
1304                     parseerror(parser, "type error: type has no members");
1305                     goto onerr;
1306                 }
1307                 gotmemberof = true;
1308             }
1309
1310             if (op->id == opid1('(')) {
1311                 if (wantop) {
1312                     size_t sycount = vec_size(sy.out);
1313                     DEBUGSHUNTDO(con_out("push [op] (\n"));
1314                     ++parens;
1315                     /* we expected an operator, this is the function-call operator */
1316                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1317                 } else {
1318                     ++parens;
1319                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1320                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
1321                 }
1322                 wantop = false;
1323             } else if (op->id == opid1('[')) {
1324                 if (!wantop) {
1325                     parseerror(parser, "unexpected array subscript");
1326                     goto onerr;
1327                 }
1328                 ++parens;
1329                 /* push both the operator and the paren, this makes life easier */
1330                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1331                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1332                 wantop = false;
1333             } else if (op->id == opid2('?',':')) {
1334                 wantop = false;
1335                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1336                 wantop = false;
1337                 --ternaries;
1338             } else if (op->id == opid2(':','?')) {
1339                 /* we don't push this operator */
1340                 wantop = false;
1341                 ++ternaries;
1342             } else {
1343                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1344                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1345                 wantop = false;
1346             }
1347         }
1348         if (!parser_next(parser)) {
1349             goto onerr;
1350         }
1351         if (parser->tok == ';' ||
1352             (!parens && parser->tok == ']'))
1353         {
1354             break;
1355         }
1356     }
1357
1358     while (vec_size(sy.ops)) {
1359         if (!parser_sy_pop(parser, &sy))
1360             goto onerr;
1361     }
1362
1363     parser->lex->flags.noops = true;
1364     if (!vec_size(sy.out)) {
1365         parseerror(parser, "empty expression");
1366         expr = NULL;
1367     } else
1368         expr = sy.out[0].out;
1369     vec_free(sy.out);
1370     vec_free(sy.ops);
1371     DEBUGSHUNTDO(con_out("shunt done\n"));
1372     return expr;
1373
1374 onerr:
1375     parser->lex->flags.noops = true;
1376     vec_free(sy.out);
1377     vec_free(sy.ops);
1378     return NULL;
1379 }
1380
1381 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1382 {
1383     ast_expression *e = parse_expression_leave(parser, stopatcomma);
1384     if (!e)
1385         return NULL;
1386     if (!parser_next(parser)) {
1387         ast_delete(e);
1388         return NULL;
1389     }
1390     return e;
1391 }
1392
1393 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1394 {
1395     ast_ifthen *ifthen;
1396     ast_expression *cond, *ontrue, *onfalse = NULL;
1397     bool ifnot = false;
1398
1399     lex_ctx ctx = parser_ctx(parser);
1400
1401     /* skip the 'if', parse an optional 'not' and check for an opening paren */
1402     if (!parser_next(parser)) {
1403         parseerror(parser, "expected condition or 'not'");
1404         return false;
1405     }
1406     if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "not")) {
1407         ifnot = true;
1408         if (!parser_next(parser)) {
1409             parseerror(parser, "expected condition in parenthesis");
1410             return false;
1411         }
1412     }
1413     if (parser->tok != '(') {
1414         parseerror(parser, "expected 'if' condition in parenthesis");
1415         return false;
1416     }
1417     /* parse into the expression */
1418     if (!parser_next(parser)) {
1419         parseerror(parser, "expected 'if' condition after opening paren");
1420         return false;
1421     }
1422     /* parse the condition */
1423     cond = parse_expression_leave(parser, false);
1424     if (!cond)
1425         return false;
1426     /* closing paren */
1427     if (parser->tok != ')') {
1428         parseerror(parser, "expected closing paren after 'if' condition");
1429         ast_delete(cond);
1430         return false;
1431     }
1432     /* parse into the 'then' branch */
1433     if (!parser_next(parser)) {
1434         parseerror(parser, "expected statement for on-true branch of 'if'");
1435         ast_delete(cond);
1436         return false;
1437     }
1438     ontrue = parse_statement_or_block(parser);
1439     if (!ontrue) {
1440         ast_delete(cond);
1441         return false;
1442     }
1443     /* check for an else */
1444     if (!strcmp(parser_tokval(parser), "else")) {
1445         /* parse into the 'else' branch */
1446         if (!parser_next(parser)) {
1447             parseerror(parser, "expected on-false branch after 'else'");
1448             ast_delete(ontrue);
1449             ast_delete(cond);
1450             return false;
1451         }
1452         onfalse = parse_statement_or_block(parser);
1453         if (!onfalse) {
1454             ast_delete(ontrue);
1455             ast_delete(cond);
1456             return false;
1457         }
1458     }
1459
1460     if (ifnot)
1461         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1462     else
1463         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1464     *out = (ast_expression*)ifthen;
1465     return true;
1466 }
1467
1468 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1469 {
1470     ast_loop *aloop;
1471     ast_expression *cond, *ontrue;
1472
1473     lex_ctx ctx = parser_ctx(parser);
1474
1475     /* skip the 'while' and check for opening paren */
1476     if (!parser_next(parser) || parser->tok != '(') {
1477         parseerror(parser, "expected 'while' condition in parenthesis");
1478         return false;
1479     }
1480     /* parse into the expression */
1481     if (!parser_next(parser)) {
1482         parseerror(parser, "expected 'while' condition after opening paren");
1483         return false;
1484     }
1485     /* parse the condition */
1486     cond = parse_expression_leave(parser, false);
1487     if (!cond)
1488         return false;
1489     /* closing paren */
1490     if (parser->tok != ')') {
1491         parseerror(parser, "expected closing paren after 'while' condition");
1492         ast_delete(cond);
1493         return false;
1494     }
1495     /* parse into the 'then' branch */
1496     if (!parser_next(parser)) {
1497         parseerror(parser, "expected while-loop body");
1498         ast_delete(cond);
1499         return false;
1500     }
1501     ontrue = parse_statement_or_block(parser);
1502     if (!ontrue) {
1503         ast_delete(cond);
1504         return false;
1505     }
1506
1507     aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1508     *out = (ast_expression*)aloop;
1509     return true;
1510 }
1511
1512 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1513 {
1514     ast_loop *aloop;
1515     ast_expression *cond, *ontrue;
1516
1517     lex_ctx ctx = parser_ctx(parser);
1518
1519     /* skip the 'do' and get the body */
1520     if (!parser_next(parser)) {
1521         parseerror(parser, "expected loop body");
1522         return false;
1523     }
1524     ontrue = parse_statement_or_block(parser);
1525     if (!ontrue)
1526         return false;
1527
1528     /* expect the "while" */
1529     if (parser->tok != TOKEN_KEYWORD ||
1530         strcmp(parser_tokval(parser), "while"))
1531     {
1532         parseerror(parser, "expected 'while' and condition");
1533         ast_delete(ontrue);
1534         return false;
1535     }
1536
1537     /* skip the 'while' and check for opening paren */
1538     if (!parser_next(parser) || parser->tok != '(') {
1539         parseerror(parser, "expected 'while' condition in parenthesis");
1540         ast_delete(ontrue);
1541         return false;
1542     }
1543     /* parse into the expression */
1544     if (!parser_next(parser)) {
1545         parseerror(parser, "expected 'while' condition after opening paren");
1546         ast_delete(ontrue);
1547         return false;
1548     }
1549     /* parse the condition */
1550     cond = parse_expression_leave(parser, false);
1551     if (!cond)
1552         return false;
1553     /* closing paren */
1554     if (parser->tok != ')') {
1555         parseerror(parser, "expected closing paren after 'while' condition");
1556         ast_delete(ontrue);
1557         ast_delete(cond);
1558         return false;
1559     }
1560     /* parse on */
1561     if (!parser_next(parser) || parser->tok != ';') {
1562         parseerror(parser, "expected semicolon after condition");
1563         ast_delete(ontrue);
1564         ast_delete(cond);
1565         return false;
1566     }
1567
1568     if (!parser_next(parser)) {
1569         parseerror(parser, "parse error");
1570         ast_delete(ontrue);
1571         ast_delete(cond);
1572         return false;
1573     }
1574
1575     aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1576     *out = (ast_expression*)aloop;
1577     return true;
1578 }
1579
1580 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1581 {
1582     ast_loop *aloop;
1583     ast_expression *initexpr, *cond, *increment, *ontrue;
1584     size_t oldblocklocal;
1585     bool   retval = true;
1586
1587     lex_ctx ctx = parser_ctx(parser);
1588
1589     oldblocklocal = parser->blocklocal;
1590     parser->blocklocal = vec_size(parser->locals);
1591
1592     initexpr  = NULL;
1593     cond      = NULL;
1594     increment = NULL;
1595     ontrue    = NULL;
1596
1597     /* skip the 'while' and check for opening paren */
1598     if (!parser_next(parser) || parser->tok != '(') {
1599         parseerror(parser, "expected 'for' expressions in parenthesis");
1600         goto onerr;
1601     }
1602     /* parse into the expression */
1603     if (!parser_next(parser)) {
1604         parseerror(parser, "expected 'for' initializer after opening paren");
1605         goto onerr;
1606     }
1607
1608     if (parser->tok == TOKEN_TYPENAME) {
1609         if (opts_standard != COMPILER_GMQCC) {
1610             if (parsewarning(parser, WARN_EXTENSIONS,
1611                              "current standard does not allow variable declarations in for-loop initializers"))
1612                 goto onerr;
1613         }
1614
1615         parseerror(parser, "TODO: assignment of new variables to be non-const");
1616         goto onerr;
1617         if (!parse_variable(parser, block, true))
1618             goto onerr;
1619     }
1620     else if (parser->tok != ';')
1621     {
1622         initexpr = parse_expression_leave(parser, false);
1623         if (!initexpr)
1624             goto onerr;
1625     }
1626
1627     /* move on to condition */
1628     if (parser->tok != ';') {
1629         parseerror(parser, "expected semicolon after for-loop initializer");
1630         goto onerr;
1631     }
1632     if (!parser_next(parser)) {
1633         parseerror(parser, "expected for-loop condition");
1634         goto onerr;
1635     }
1636
1637     /* parse the condition */
1638     if (parser->tok != ';') {
1639         cond = parse_expression_leave(parser, false);
1640         if (!cond)
1641             goto onerr;
1642     }
1643
1644     /* move on to incrementor */
1645     if (parser->tok != ';') {
1646         parseerror(parser, "expected semicolon after for-loop initializer");
1647         goto onerr;
1648     }
1649     if (!parser_next(parser)) {
1650         parseerror(parser, "expected for-loop condition");
1651         goto onerr;
1652     }
1653
1654     /* parse the incrementor */
1655     if (parser->tok != ')') {
1656         increment = parse_expression_leave(parser, false);
1657         if (!increment)
1658             goto onerr;
1659         if (!ast_istype(increment, ast_store) &&
1660             !ast_istype(increment, ast_call) &&
1661             !ast_istype(increment, ast_binstore))
1662         {
1663             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1664                 goto onerr;
1665         }
1666     }
1667
1668     /* closing paren */
1669     if (parser->tok != ')') {
1670         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1671         goto onerr;
1672     }
1673     /* parse into the 'then' branch */
1674     if (!parser_next(parser)) {
1675         parseerror(parser, "expected for-loop body");
1676         goto onerr;
1677     }
1678     ontrue = parse_statement_or_block(parser);
1679     if (!ontrue) {
1680         goto onerr;
1681     }
1682
1683     aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1684     *out = (ast_expression*)aloop;
1685
1686     while (vec_size(parser->locals) > parser->blocklocal)
1687         retval = retval && parser_pop_local(parser);
1688     parser->blocklocal = oldblocklocal;
1689     return retval;
1690 onerr:
1691     if (initexpr)  ast_delete(initexpr);
1692     if (cond)      ast_delete(cond);
1693     if (increment) ast_delete(increment);
1694     while (vec_size(parser->locals) > parser->blocklocal)
1695         (void)!parser_pop_local(parser);
1696     parser->blocklocal = oldblocklocal;
1697     return false;
1698 }
1699
1700 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
1701 {
1702     ast_expression *exp = NULL;
1703     ast_return     *ret = NULL;
1704     ast_value      *expected = parser->function->vtype;
1705
1706     if (!parser_next(parser)) {
1707         parseerror(parser, "expected return expression");
1708         return false;
1709     }
1710
1711     if (parser->tok != ';') {
1712         exp = parse_expression(parser, false);
1713         if (!exp)
1714             return false;
1715
1716         if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1717             parseerror(parser, "return with invalid expression");
1718         }
1719
1720         ret = ast_return_new(exp->expression.node.context, exp);
1721         if (!ret) {
1722             ast_delete(exp);
1723             return false;
1724         }
1725     } else {
1726         if (!parser_next(parser))
1727             parseerror(parser, "parse error");
1728         if (expected->expression.next->expression.vtype != TYPE_VOID) {
1729             if (opts_standard != COMPILER_GMQCC)
1730                 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1731             else
1732                 parseerror(parser, "return without value");
1733         }
1734         ret = ast_return_new(parser_ctx(parser), NULL);
1735     }
1736     *out = (ast_expression*)ret;
1737     return true;
1738 }
1739
1740 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
1741 {
1742     lex_ctx ctx = parser_ctx(parser);
1743
1744     if (!parser_next(parser) || parser->tok != ';') {
1745         parseerror(parser, "expected semicolon");
1746         return false;
1747     }
1748
1749     if (!parser_next(parser))
1750         parseerror(parser, "parse error");
1751
1752     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
1753     return true;
1754 }
1755
1756 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
1757 {
1758     ast_expression *operand;
1759     ast_value      *opval;
1760     ast_switch     *switchnode;
1761     ast_switch_case swcase;
1762
1763     lex_ctx ctx = parser_ctx(parser);
1764
1765     /* parse over the opening paren */
1766     if (!parser_next(parser) || parser->tok != '(') {
1767         parseerror(parser, "expected switch operand in parenthesis");
1768         return false;
1769     }
1770
1771     /* parse into the expression */
1772     if (!parser_next(parser)) {
1773         parseerror(parser, "expected switch operand");
1774         return false;
1775     }
1776     /* parse the operand */
1777     operand = parse_expression_leave(parser, false);
1778     if (!operand)
1779         return false;
1780
1781     if (!OPTS_FLAG(RELAXED_SWITCH)) {
1782         opval = (ast_value*)operand;
1783         if (!ast_istype(operand, ast_value) || !opval->isconst) {
1784             parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
1785             ast_unref(operand);
1786             return false;
1787         }
1788     }
1789
1790     switchnode = ast_switch_new(ctx, operand);
1791
1792     /* closing paren */
1793     if (parser->tok != ')') {
1794         ast_delete(switchnode);
1795         parseerror(parser, "expected closing paren after 'switch' operand");
1796         return false;
1797     }
1798
1799     /* parse over the opening paren */
1800     if (!parser_next(parser) || parser->tok != '{') {
1801         ast_delete(switchnode);
1802         parseerror(parser, "expected list of cases");
1803         return false;
1804     }
1805
1806     if (!parser_next(parser)) {
1807         ast_delete(switchnode);
1808         parseerror(parser, "expected 'case' or 'default'");
1809         return false;
1810     }
1811
1812     /* case list! */
1813     while (parser->tok != '}') {
1814         ast_block *block;
1815
1816         if (parser->tok != TOKEN_KEYWORD) {
1817             ast_delete(switchnode);
1818             parseerror(parser, "expected 'case' or 'default'");
1819             return false;
1820         }
1821         if (!strcmp(parser_tokval(parser), "case")) {
1822             if (!parser_next(parser)) {
1823                 ast_delete(switchnode);
1824                 parseerror(parser, "expected expression for case");
1825                 return false;
1826             }
1827             swcase.value = parse_expression_leave(parser, false);
1828             if (!swcase.value) {
1829                 ast_delete(switchnode);
1830                 parseerror(parser, "expected expression for case");
1831                 return false;
1832             }
1833         }
1834         else if (!strcmp(parser_tokval(parser), "default")) {
1835             swcase.value = NULL;
1836             if (!parser_next(parser)) {
1837                 ast_delete(switchnode);
1838                 parseerror(parser, "expected colon");
1839                 return false;
1840             }
1841         }
1842
1843         /* Now the colon and body */
1844         if (parser->tok != ':') {
1845             if (swcase.value) ast_unref(swcase.value);
1846             ast_delete(switchnode);
1847             parseerror(parser, "expected colon");
1848             return false;
1849         }
1850
1851         if (!parser_next(parser)) {
1852             if (swcase.value) ast_unref(swcase.value);
1853             ast_delete(switchnode);
1854             parseerror(parser, "expected statements or case");
1855             return false;
1856         }
1857         block = ast_block_new(parser_ctx(parser));
1858         if (!block) {
1859             if (swcase.value) ast_unref(swcase.value);
1860             ast_delete(switchnode);
1861             return false;
1862         }
1863         swcase.code = (ast_expression*)block;
1864         vec_push(switchnode->cases, swcase);
1865         while (true) {
1866             ast_expression *expr;
1867             if (parser->tok == '}')
1868                 break;
1869             if (parser->tok == TOKEN_KEYWORD) {
1870                 if (!strcmp(parser_tokval(parser), "case") ||
1871                     !strcmp(parser_tokval(parser), "default"))
1872                 {
1873                     break;
1874                 }
1875             }
1876             if (!parse_statement(parser, block, &expr, true)) {
1877                 ast_delete(switchnode);
1878                 return false;
1879             }
1880             if (!expr)
1881                 continue;
1882             vec_push(block->exprs, expr);
1883         }
1884     }
1885
1886     /* closing paren */
1887     if (parser->tok != '}') {
1888         ast_delete(switchnode);
1889         parseerror(parser, "expected closing paren of case list");
1890         return false;
1891     }
1892     if (!parser_next(parser)) {
1893         ast_delete(switchnode);
1894         parseerror(parser, "parse error after switch");
1895         return false;
1896     }
1897     *out = (ast_expression*)switchnode;
1898     return true;
1899 }
1900
1901 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
1902 {
1903     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1904     {
1905         /* local variable */
1906         if (!block) {
1907             parseerror(parser, "cannot declare a variable from here");
1908             return false;
1909         }
1910         if (opts_standard == COMPILER_QCC) {
1911             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1912                 return false;
1913         }
1914         if (!parse_variable(parser, block, false))
1915             return false;
1916         *out = NULL;
1917         return true;
1918     }
1919     else if (parser->tok == TOKEN_KEYWORD)
1920     {
1921         if (!strcmp(parser_tokval(parser), "local"))
1922         {
1923             if (!block) {
1924                 parseerror(parser, "cannot declare a local variable here");
1925                 return false;
1926             }
1927             if (!parser_next(parser)) {
1928                 parseerror(parser, "expected variable declaration");
1929                 return false;
1930             }
1931             if (!parse_variable(parser, block, true))
1932                 return false;
1933             *out = NULL;
1934             return true;
1935         }
1936         else if (!strcmp(parser_tokval(parser), "return"))
1937         {
1938             return parse_return(parser, block, out);
1939         }
1940         else if (!strcmp(parser_tokval(parser), "if"))
1941         {
1942             return parse_if(parser, block, out);
1943         }
1944         else if (!strcmp(parser_tokval(parser), "while"))
1945         {
1946             return parse_while(parser, block, out);
1947         }
1948         else if (!strcmp(parser_tokval(parser), "do"))
1949         {
1950             return parse_dowhile(parser, block, out);
1951         }
1952         else if (!strcmp(parser_tokval(parser), "for"))
1953         {
1954             if (opts_standard == COMPILER_QCC) {
1955                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1956                     return false;
1957             }
1958             return parse_for(parser, block, out);
1959         }
1960         else if (!strcmp(parser_tokval(parser), "break"))
1961         {
1962             return parse_break_continue(parser, block, out, false);
1963         }
1964         else if (!strcmp(parser_tokval(parser), "continue"))
1965         {
1966             return parse_break_continue(parser, block, out, true);
1967         }
1968         else if (!strcmp(parser_tokval(parser), "switch"))
1969         {
1970             return parse_switch(parser, block, out);
1971         }
1972         else if (!strcmp(parser_tokval(parser), "case") ||
1973                  !strcmp(parser_tokval(parser), "default"))
1974         {
1975             if (!allow_cases) {
1976                 parseerror(parser, "unexpected 'case' label");
1977                 return false;
1978             }
1979             return true;
1980         }
1981         parseerror(parser, "Unexpected keyword");
1982         return false;
1983     }
1984     else if (parser->tok == '{')
1985     {
1986         ast_block *inner;
1987         inner = parse_block(parser, false);
1988         if (!inner)
1989             return false;
1990         *out = (ast_expression*)inner;
1991         return true;
1992     }
1993     else
1994     {
1995         ast_expression *exp = parse_expression(parser, false);
1996         if (!exp)
1997             return false;
1998         *out = exp;
1999         if (!ast_istype(exp, ast_store) &&
2000             !ast_istype(exp, ast_call) &&
2001             !ast_istype(exp, ast_binstore))
2002         {
2003             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2004                 return false;
2005         }
2006         return true;
2007     }
2008 }
2009
2010 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
2011 {
2012     bool rv = true;
2013     varentry_t *ve;
2014
2015     ve = &vec_last(parser->locals);
2016     if (!parser->errors) {
2017         if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
2018             if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
2019                 rv = false;
2020         }
2021     }
2022     mem_d(ve->name);
2023     vec_pop(parser->locals);
2024     return rv;
2025 }
2026
2027 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2028 {
2029     size_t oldblocklocal;
2030     bool   retval = true;
2031
2032     oldblocklocal = parser->blocklocal;
2033     parser->blocklocal = vec_size(parser->locals);
2034
2035     if (!parser_next(parser)) { /* skip the '{' */
2036         parseerror(parser, "expected function body");
2037         goto cleanup;
2038     }
2039
2040     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2041     {
2042         ast_expression *expr;
2043         if (parser->tok == '}')
2044             break;
2045
2046         if (!parse_statement(parser, block, &expr, false)) {
2047             /* parseerror(parser, "parse error"); */
2048             block = NULL;
2049             goto cleanup;
2050         }
2051         if (!expr)
2052             continue;
2053         vec_push(block->exprs, expr);
2054     }
2055
2056     if (parser->tok != '}') {
2057         block = NULL;
2058     } else {
2059         if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2060         {
2061             if (!vec_size(block->exprs) ||
2062                 !ast_istype(vec_last(block->exprs), ast_return))
2063             {
2064                 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2065                     block = NULL;
2066                     goto cleanup;
2067                 }
2068             }
2069         }
2070         (void)parser_next(parser);
2071     }
2072
2073 cleanup:
2074     while (vec_size(parser->locals) > parser->blocklocal)
2075         retval = retval && parser_pop_local(parser);
2076     parser->blocklocal = oldblocklocal;
2077     return !!block;
2078 }
2079
2080 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2081 {
2082     ast_block *block;
2083     block = ast_block_new(parser_ctx(parser));
2084     if (!block)
2085         return NULL;
2086     if (!parse_block_into(parser, block, warnreturn)) {
2087         ast_block_delete(block);
2088         return NULL;
2089     }
2090     return block;
2091 }
2092
2093 static ast_expression* parse_statement_or_block(parser_t *parser)
2094 {
2095     ast_expression *expr = NULL;
2096     if (parser->tok == '{')
2097         return (ast_expression*)parse_block(parser, false);
2098     if (!parse_statement(parser, NULL, &expr, false))
2099         return NULL;
2100     return expr;
2101 }
2102
2103 /* loop method */
2104 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
2105 {
2106     size_t i;
2107     size_t len = strlen(var->name);
2108
2109     for (i = 0; i < 3; ++i) {
2110         ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
2111         if (!ve[i].var)
2112             break;
2113
2114         ve[i].name = (char*)mem_a(len+3);
2115         if (!ve[i].name) {
2116             ast_delete(ve[i].var);
2117             break;
2118         }
2119
2120         memcpy(ve[i].name, var->name, len);
2121         ve[i].name[len]   = '_';
2122         ve[i].name[len+1] = 'x'+i;
2123         ve[i].name[len+2] = 0;
2124     }
2125     if (i == 3)
2126         return true;
2127
2128     /* unroll */
2129     do {
2130         --i;
2131         mem_d(ve[i].name);
2132         ast_delete(ve[i].var);
2133         ve[i].name = NULL;
2134         ve[i].var  = NULL;
2135     } while (i);
2136     return false;
2137 }
2138
2139 static bool parse_function_body(parser_t *parser, ast_value *var)
2140 {
2141     ast_block      *block = NULL;
2142     ast_function   *func;
2143     ast_function   *old;
2144     size_t          parami;
2145
2146     ast_expression *framenum  = NULL;
2147     ast_expression *nextthink = NULL;
2148     /* None of the following have to be deleted */
2149     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2150     ast_expression *gbl_time = NULL, *gbl_self = NULL;
2151     bool            has_frame_think;
2152
2153     bool retval = true;
2154
2155     has_frame_think = false;
2156     old = parser->function;
2157
2158     if (var->expression.variadic) {
2159         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2160                          "variadic function with implementation will not be able to access additional parameters"))
2161         {
2162             return false;
2163         }
2164     }
2165
2166     if (parser->tok == '[') {
2167         /* got a frame definition: [ framenum, nextthink ]
2168          * this translates to:
2169          * self.frame = framenum;
2170          * self.nextthink = time + 0.1;
2171          * self.think = nextthink;
2172          */
2173         nextthink = NULL;
2174
2175         fld_think     = parser_find_field(parser, "think");
2176         fld_nextthink = parser_find_field(parser, "nextthink");
2177         fld_frame     = parser_find_field(parser, "frame");
2178         if (!fld_think || !fld_nextthink || !fld_frame) {
2179             parseerror(parser, "cannot use [frame,think] notation without the required fields");
2180             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2181             return false;
2182         }
2183         gbl_time      = parser_find_global(parser, "time");
2184         gbl_self      = parser_find_global(parser, "self");
2185         if (!gbl_time || !gbl_self) {
2186             parseerror(parser, "cannot use [frame,think] notation without the required globals");
2187             parseerror(parser, "please declare the following globals: `time`, `self`");
2188             return false;
2189         }
2190
2191         if (!parser_next(parser))
2192             return false;
2193
2194         framenum = parse_expression_leave(parser, true);
2195         if (!framenum) {
2196             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2197             return false;
2198         }
2199         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2200             ast_unref(framenum);
2201             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2202             return false;
2203         }
2204
2205         if (parser->tok != ',') {
2206             ast_unref(framenum);
2207             parseerror(parser, "expected comma after frame number in [frame,think] notation");
2208             parseerror(parser, "Got a %i\n", parser->tok);
2209             return false;
2210         }
2211
2212         if (!parser_next(parser)) {
2213             ast_unref(framenum);
2214             return false;
2215         }
2216
2217         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2218         {
2219             /* qc allows the use of not-yet-declared functions here
2220              * - this automatically creates a prototype */
2221             varentry_t      varent;
2222             ast_value      *thinkfunc;
2223             ast_expression *functype = fld_think->expression.next;
2224
2225             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2226             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2227                 ast_unref(framenum);
2228                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2229                 return false;
2230             }
2231
2232             if (!parser_next(parser)) {
2233                 ast_unref(framenum);
2234                 ast_delete(thinkfunc);
2235                 return false;
2236             }
2237
2238             varent.var = (ast_expression*)thinkfunc;
2239             varent.name = util_strdup(thinkfunc->name);
2240             vec_push(parser->globals, varent);
2241             nextthink = (ast_expression*)thinkfunc;
2242
2243         } else {
2244             nextthink = parse_expression_leave(parser, true);
2245             if (!nextthink) {
2246                 ast_unref(framenum);
2247                 parseerror(parser, "expected a think-function in [frame,think] notation");
2248                 return false;
2249             }
2250         }
2251
2252         if (!ast_istype(nextthink, ast_value)) {
2253             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2254             retval = false;
2255         }
2256
2257         if (retval && parser->tok != ']') {
2258             parseerror(parser, "expected closing `]` for [frame,think] notation");
2259             retval = false;
2260         }
2261
2262         if (retval && !parser_next(parser)) {
2263             retval = false;
2264         }
2265
2266         if (retval && parser->tok != '{') {
2267             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2268             retval = false;
2269         }
2270
2271         if (!retval) {
2272             ast_unref(nextthink);
2273             ast_unref(framenum);
2274             return false;
2275         }
2276
2277         has_frame_think = true;
2278     }
2279
2280     block = ast_block_new(parser_ctx(parser));
2281     if (!block) {
2282         parseerror(parser, "failed to allocate block");
2283         if (has_frame_think) {
2284             ast_unref(nextthink);
2285             ast_unref(framenum);
2286         }
2287         return false;
2288     }
2289
2290     if (has_frame_think) {
2291         lex_ctx ctx;
2292         ast_expression *self_frame;
2293         ast_expression *self_nextthink;
2294         ast_expression *self_think;
2295         ast_expression *time_plus_1;
2296         ast_store *store_frame;
2297         ast_store *store_nextthink;
2298         ast_store *store_think;
2299
2300         ctx = parser_ctx(parser);
2301         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2302         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2303         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2304
2305         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2306                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2307
2308         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2309             if (self_frame)     ast_delete(self_frame);
2310             if (self_nextthink) ast_delete(self_nextthink);
2311             if (self_think)     ast_delete(self_think);
2312             if (time_plus_1)    ast_delete(time_plus_1);
2313             retval = false;
2314         }
2315
2316         if (retval)
2317         {
2318             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2319             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2320             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2321
2322             if (!store_frame) {
2323                 ast_delete(self_frame);
2324                 retval = false;
2325             }
2326             if (!store_nextthink) {
2327                 ast_delete(self_nextthink);
2328                 retval = false;
2329             }
2330             if (!store_think) {
2331                 ast_delete(self_think);
2332                 retval = false;
2333             }
2334             if (!retval) {
2335                 if (store_frame)     ast_delete(store_frame);
2336                 if (store_nextthink) ast_delete(store_nextthink);
2337                 if (store_think)     ast_delete(store_think);
2338                 retval = false;
2339             }
2340             vec_push(block->exprs, (ast_expression*)store_frame);
2341             vec_push(block->exprs, (ast_expression*)store_nextthink);
2342             vec_push(block->exprs, (ast_expression*)store_think);
2343         }
2344
2345         if (!retval) {
2346             parseerror(parser, "failed to generate code for [frame,think]");
2347             ast_unref(nextthink);
2348             ast_unref(framenum);
2349             ast_delete(block);
2350             return false;
2351         }
2352     }
2353
2354     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2355         size_t     e;
2356         varentry_t ve[3];
2357         ast_value *param = var->expression.params[parami];
2358
2359         if (param->expression.vtype != TYPE_VECTOR &&
2360             (param->expression.vtype != TYPE_FIELD ||
2361              param->expression.next->expression.vtype != TYPE_VECTOR))
2362         {
2363             continue;
2364         }
2365
2366         if (!create_vector_members(parser, param, ve)) {
2367             ast_block_delete(block);
2368             return false;
2369         }
2370
2371         for (e = 0; e < 3; ++e) {
2372             vec_push(parser->locals, ve[e]);
2373             ast_block_collect(block, ve[e].var);
2374             ve[e].var = NULL; /* collected */
2375         }
2376     }
2377
2378     func = ast_function_new(ast_ctx(var), var->name, var);
2379     if (!func) {
2380         parseerror(parser, "failed to allocate function for `%s`", var->name);
2381         ast_block_delete(block);
2382         goto enderr;
2383     }
2384     vec_push(parser->functions, func);
2385
2386     parser->function = func;
2387     if (!parse_block_into(parser, block, true)) {
2388         ast_block_delete(block);
2389         goto enderrfn;
2390     }
2391
2392     vec_push(func->blocks, block);
2393
2394     parser->function = old;
2395     while (vec_size(parser->locals))
2396         retval = retval && parser_pop_local(parser);
2397
2398     if (parser->tok == ';')
2399         return parser_next(parser);
2400     else if (opts_standard == COMPILER_QCC)
2401         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2402     return retval;
2403
2404 enderrfn:
2405     vec_pop(parser->functions);
2406     ast_function_delete(func);
2407     var->constval.vfunc = NULL;
2408
2409 enderr:
2410     while (vec_size(parser->locals)) {
2411         mem_d(vec_last(parser->locals).name);
2412         vec_pop(parser->locals);
2413     }
2414     parser->function = old;
2415     return false;
2416 }
2417
2418 static ast_expression *array_accessor_split(
2419     parser_t  *parser,
2420     ast_value *array,
2421     ast_value *index,
2422     size_t     middle,
2423     ast_expression *left,
2424     ast_expression *right
2425     )
2426 {
2427     ast_ifthen *ifthen;
2428     ast_binary *cmp;
2429
2430     lex_ctx ctx = ast_ctx(array);
2431
2432     if (!left || !right) {
2433         if (left)  ast_delete(left);
2434         if (right) ast_delete(right);
2435         return NULL;
2436     }
2437
2438     cmp = ast_binary_new(ctx, INSTR_LT,
2439                          (ast_expression*)index,
2440                          (ast_expression*)parser_const_float(parser, middle));
2441     if (!cmp) {
2442         ast_delete(left);
2443         ast_delete(right);
2444         parseerror(parser, "internal error: failed to create comparison for array setter");
2445         return NULL;
2446     }
2447
2448     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2449     if (!ifthen) {
2450         ast_delete(cmp); /* will delete left and right */
2451         parseerror(parser, "internal error: failed to create conditional jump for array setter");
2452         return NULL;
2453     }
2454
2455     return (ast_expression*)ifthen;
2456 }
2457
2458 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2459 {
2460     lex_ctx ctx = ast_ctx(array);
2461
2462     if (from+1 == afterend) {
2463         // set this value
2464         ast_block       *block;
2465         ast_return      *ret;
2466         ast_array_index *subscript;
2467         int assignop = type_store_instr[value->expression.vtype];
2468
2469         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2470             assignop = INSTR_STORE_V;
2471
2472         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2473         if (!subscript)
2474             return NULL;
2475
2476         ast_store *st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2477         if (!st) {
2478             ast_delete(subscript);
2479             return NULL;
2480         }
2481
2482         block = ast_block_new(ctx);
2483         if (!block) {
2484             ast_delete(st);
2485             return NULL;
2486         }
2487
2488         vec_push(block->exprs, (ast_expression*)st);
2489
2490         ret = ast_return_new(ctx, NULL);
2491         if (!ret) {
2492             ast_delete(block);
2493             return NULL;
2494         }
2495
2496         vec_push(block->exprs, (ast_expression*)ret);
2497
2498         return (ast_expression*)block;
2499     } else {
2500         ast_expression *left, *right;
2501         size_t diff = afterend - from;
2502         size_t middle = from + diff/2;
2503         left  = array_setter_node(parser, array, index, value, from, middle);
2504         right = array_setter_node(parser, array, index, value, middle, afterend);
2505         return array_accessor_split(parser, array, index, middle, left, right);
2506     }
2507 }
2508
2509 static ast_expression *array_field_setter_node(
2510     parser_t  *parser,
2511     ast_value *array,
2512     ast_value *entity,
2513     ast_value *index,
2514     ast_value *value,
2515     size_t     from,
2516     size_t     afterend)
2517 {
2518     lex_ctx ctx = ast_ctx(array);
2519
2520     if (from+1 == afterend) {
2521         // set this value
2522         ast_block       *block;
2523         ast_return      *ret;
2524         ast_entfield    *entfield;
2525         ast_array_index *subscript;
2526         int assignop = type_storep_instr[value->expression.vtype];
2527
2528         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2529             assignop = INSTR_STOREP_V;
2530
2531         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2532         if (!subscript)
2533             return NULL;
2534
2535         entfield = ast_entfield_new_force(ctx,
2536                                           (ast_expression*)entity,
2537                                           (ast_expression*)subscript,
2538                                           (ast_expression*)subscript);
2539         if (!entfield) {
2540             ast_delete(subscript);
2541             return NULL;
2542         }
2543
2544         ast_store *st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2545         if (!st) {
2546             ast_delete(entfield);
2547             return NULL;
2548         }
2549
2550         block = ast_block_new(ctx);
2551         if (!block) {
2552             ast_delete(st);
2553             return NULL;
2554         }
2555
2556         vec_push(block->exprs, (ast_expression*)st);
2557
2558         ret = ast_return_new(ctx, NULL);
2559         if (!ret) {
2560             ast_delete(block);
2561             return NULL;
2562         }
2563
2564         vec_push(block->exprs, (ast_expression*)ret);
2565
2566         return (ast_expression*)block;
2567     } else {
2568         ast_expression *left, *right;
2569         size_t diff = afterend - from;
2570         size_t middle = from + diff/2;
2571         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
2572         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2573         return array_accessor_split(parser, array, index, middle, left, right);
2574     }
2575 }
2576
2577 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2578 {
2579     lex_ctx ctx = ast_ctx(array);
2580
2581     if (from+1 == afterend) {
2582         ast_return      *ret;
2583         ast_array_index *subscript;
2584
2585         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2586         if (!subscript)
2587             return NULL;
2588
2589         ret = ast_return_new(ctx, (ast_expression*)subscript);
2590         if (!ret) {
2591             ast_delete(subscript);
2592             return NULL;
2593         }
2594
2595         return (ast_expression*)ret;
2596     } else {
2597         ast_expression *left, *right;
2598         size_t diff = afterend - from;
2599         size_t middle = from + diff/2;
2600         left  = array_getter_node(parser, array, index, from, middle);
2601         right = array_getter_node(parser, array, index, middle, afterend);
2602         return array_accessor_split(parser, array, index, middle, left, right);
2603     }
2604 }
2605
2606 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2607 {
2608     ast_function   *func = NULL;
2609     ast_value      *fval = NULL;
2610     ast_block      *body = NULL;
2611
2612     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2613     if (!fval) {
2614         parseerror(parser, "failed to create accessor function value");
2615         return false;
2616     }
2617
2618     func = ast_function_new(ast_ctx(array), funcname, fval);
2619     if (!func) {
2620         ast_delete(fval);
2621         parseerror(parser, "failed to create accessor function node");
2622         return false;
2623     }
2624
2625     body = ast_block_new(ast_ctx(array));
2626     if (!body) {
2627         parseerror(parser, "failed to create block for array accessor");
2628         ast_delete(fval);
2629         ast_delete(func);
2630         return false;
2631     }
2632
2633     vec_push(func->blocks, body);
2634     *out = fval;
2635
2636     vec_push(parser->accessors, fval);
2637
2638     return true;
2639 }
2640
2641 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2642 {
2643     ast_expression *root = NULL;
2644     ast_value      *index = NULL;
2645     ast_value      *value = NULL;
2646     ast_function   *func;
2647     ast_value      *fval;
2648
2649     if (!ast_istype(array->expression.next, ast_value)) {
2650         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2651         return false;
2652     }
2653
2654     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2655         return false;
2656     func = fval->constval.vfunc;
2657     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2658
2659     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2660     value = ast_value_copy((ast_value*)array->expression.next);
2661
2662     if (!index || !value) {
2663         parseerror(parser, "failed to create locals for array accessor");
2664         goto cleanup;
2665     }
2666     (void)!ast_value_set_name(value, "value"); /* not important */
2667     vec_push(fval->expression.params, index);
2668     vec_push(fval->expression.params, value);
2669
2670     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2671     if (!root) {
2672         parseerror(parser, "failed to build accessor search tree");
2673         goto cleanup;
2674     }
2675
2676     vec_push(func->blocks[0]->exprs, root);
2677     array->setter = fval;
2678     return true;
2679 cleanup:
2680     if (index) ast_delete(index);
2681     if (value) ast_delete(value);
2682     if (root)  ast_delete(root);
2683     ast_delete(func);
2684     ast_delete(fval);
2685     return false;
2686 }
2687
2688 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2689 {
2690     ast_expression *root = NULL;
2691     ast_value      *entity = NULL;
2692     ast_value      *index = NULL;
2693     ast_value      *value = NULL;
2694     ast_function   *func;
2695     ast_value      *fval;
2696
2697     if (!ast_istype(array->expression.next, ast_value)) {
2698         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2699         return false;
2700     }
2701
2702     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2703         return false;
2704     func = fval->constval.vfunc;
2705     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2706
2707     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2708     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
2709     value  = ast_value_copy((ast_value*)array->expression.next);
2710     if (!entity || !index || !value) {
2711         parseerror(parser, "failed to create locals for array accessor");
2712         goto cleanup;
2713     }
2714     (void)!ast_value_set_name(value, "value"); /* not important */
2715     vec_push(fval->expression.params, entity);
2716     vec_push(fval->expression.params, index);
2717     vec_push(fval->expression.params, value);
2718
2719     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
2720     if (!root) {
2721         parseerror(parser, "failed to build accessor search tree");
2722         goto cleanup;
2723     }
2724
2725     vec_push(func->blocks[0]->exprs, root);
2726     array->setter = fval;
2727     return true;
2728 cleanup:
2729     if (entity) ast_delete(entity);
2730     if (index)  ast_delete(index);
2731     if (value)  ast_delete(value);
2732     if (root)   ast_delete(root);
2733     ast_delete(func);
2734     ast_delete(fval);
2735     return false;
2736 }
2737
2738 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
2739 {
2740     ast_expression *root = NULL;
2741     ast_value      *index = NULL;
2742     ast_value      *fval;
2743     ast_function   *func;
2744
2745     /* NOTE: checking array->expression.next rather than elemtype since
2746      * for fields elemtype is a temporary fieldtype.
2747      */
2748     if (!ast_istype(array->expression.next, ast_value)) {
2749         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2750         return false;
2751     }
2752
2753     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2754         return false;
2755     func = fval->constval.vfunc;
2756     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
2757
2758     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2759
2760     if (!index) {
2761         parseerror(parser, "failed to create locals for array accessor");
2762         goto cleanup;
2763     }
2764     vec_push(fval->expression.params, index);
2765
2766     root = array_getter_node(parser, array, index, 0, array->expression.count);
2767     if (!root) {
2768         parseerror(parser, "failed to build accessor search tree");
2769         goto cleanup;
2770     }
2771
2772     vec_push(func->blocks[0]->exprs, root);
2773     array->getter = fval;
2774     return true;
2775 cleanup:
2776     if (index) ast_delete(index);
2777     if (root)  ast_delete(root);
2778     ast_delete(func);
2779     ast_delete(fval);
2780     return false;
2781 }
2782
2783 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2784 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2785 {
2786     lex_ctx     ctx;
2787     size_t      i;
2788     ast_value **params;
2789     ast_value  *param;
2790     ast_value  *fval;
2791     bool        first = true;
2792     bool        variadic = false;
2793
2794     ctx = parser_ctx(parser);
2795
2796     /* for the sake of less code we parse-in in this function */
2797     if (!parser_next(parser)) {
2798         parseerror(parser, "expected parameter list");
2799         return NULL;
2800     }
2801
2802     params = NULL;
2803
2804     /* parse variables until we hit a closing paren */
2805     while (parser->tok != ')') {
2806         if (!first) {
2807             /* there must be commas between them */
2808             if (parser->tok != ',') {
2809                 parseerror(parser, "expected comma or end of parameter list");
2810                 goto on_error;
2811             }
2812             if (!parser_next(parser)) {
2813                 parseerror(parser, "expected parameter");
2814                 goto on_error;
2815             }
2816         }
2817         first = false;
2818
2819         if (parser->tok == TOKEN_DOTS) {
2820             /* '...' indicates a varargs function */
2821             variadic = true;
2822             if (!parser_next(parser)) {
2823                 parseerror(parser, "expected parameter");
2824                 return NULL;
2825             }
2826             if (parser->tok != ')') {
2827                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2828                 goto on_error;
2829             }
2830         }
2831         else
2832         {
2833             /* for anything else just parse a typename */
2834             param = parse_typename(parser, NULL);
2835             if (!param)
2836                 goto on_error;
2837             vec_push(params, param);
2838             if (param->expression.vtype >= TYPE_VARIANT) {
2839                 char typename[1024];
2840                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
2841                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
2842                 goto on_error;
2843             }
2844         }
2845     }
2846
2847     /* sanity check */
2848     if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
2849         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
2850
2851     /* parse-out */
2852     if (!parser_next(parser)) {
2853         parseerror(parser, "parse error after typename");
2854         goto on_error;
2855     }
2856
2857     /* now turn 'var' into a function type */
2858     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2859     fval->expression.next     = (ast_expression*)var;
2860     fval->expression.variadic = variadic;
2861     var = fval;
2862
2863     var->expression.params = params;
2864     params = NULL;
2865
2866     return var;
2867
2868 on_error:
2869     ast_delete(var);
2870     for (i = 0; i < vec_size(params); ++i)
2871         ast_delete(params[i]);
2872     vec_free(params);
2873     return NULL;
2874 }
2875
2876 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2877 {
2878     ast_expression *cexp;
2879     ast_value      *cval, *tmp;
2880     lex_ctx ctx;
2881
2882     ctx = parser_ctx(parser);
2883
2884     if (!parser_next(parser)) {
2885         ast_delete(var);
2886         parseerror(parser, "expected array-size");
2887         return NULL;
2888     }
2889
2890     cexp = parse_expression_leave(parser, true);
2891
2892     if (!cexp || !ast_istype(cexp, ast_value)) {
2893         if (cexp)
2894             ast_unref(cexp);
2895         ast_delete(var);
2896         parseerror(parser, "expected array-size as constant positive integer");
2897         return NULL;
2898     }
2899     cval = (ast_value*)cexp;
2900
2901     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2902     tmp->expression.next = (ast_expression*)var;
2903     var = tmp;
2904
2905     if (cval->expression.vtype == TYPE_INTEGER)
2906         tmp->expression.count = cval->constval.vint;
2907     else if (cval->expression.vtype == TYPE_FLOAT)
2908         tmp->expression.count = cval->constval.vfloat;
2909     else {
2910         ast_unref(cexp);
2911         ast_delete(var);
2912         parseerror(parser, "array-size must be a positive integer constant");
2913         return NULL;
2914     }
2915     ast_unref(cexp);
2916
2917     if (parser->tok != ']') {
2918         ast_delete(var);
2919         parseerror(parser, "expected ']' after array-size");
2920         return NULL;
2921     }
2922     if (!parser_next(parser)) {
2923         ast_delete(var);
2924         parseerror(parser, "error after parsing array size");
2925         return NULL;
2926     }
2927     return var;
2928 }
2929
2930 /* Parse a complete typename.
2931  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2932  * but when parsing variables separated by comma
2933  * 'storebase' should point to where the base-type should be kept.
2934  * The base type makes up every bit of type information which comes *before* the
2935  * variable name.
2936  *
2937  * The following will be parsed in its entirety:
2938  *     void() foo()
2939  * The 'basetype' in this case is 'void()'
2940  * and if there's a comma after it, say:
2941  *     void() foo(), bar
2942  * then the type-information 'void()' can be stored in 'storebase'
2943  */
2944 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2945 {
2946     ast_value *var, *tmp;
2947     lex_ctx    ctx;
2948
2949     const char *name = NULL;
2950     bool        isfield  = false;
2951     bool        wasarray = false;
2952
2953     ctx = parser_ctx(parser);
2954
2955     /* types may start with a dot */
2956     if (parser->tok == '.') {
2957         isfield = true;
2958         /* if we parsed a dot we need a typename now */
2959         if (!parser_next(parser)) {
2960             parseerror(parser, "expected typename for field definition");
2961             return NULL;
2962         }
2963         if (parser->tok != TOKEN_TYPENAME) {
2964             parseerror(parser, "expected typename");
2965             return NULL;
2966         }
2967     }
2968
2969     /* generate the basic type value */
2970     var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2971     /* do not yet turn into a field - remember:
2972      * .void() foo; is a field too
2973      * .void()() foo; is a function
2974      */
2975
2976     /* parse on */
2977     if (!parser_next(parser)) {
2978         ast_delete(var);
2979         parseerror(parser, "parse error after typename");
2980         return NULL;
2981     }
2982
2983     /* an opening paren now starts the parameter-list of a function
2984      * this is where original-QC has parameter lists.
2985      * We allow a single parameter list here.
2986      * Much like fteqcc we don't allow `float()() x`
2987      */
2988     if (parser->tok == '(') {
2989         var = parse_parameter_list(parser, var);
2990         if (!var)
2991             return NULL;
2992     }
2993
2994     /* store the base if requested */
2995     if (storebase) {
2996         *storebase = ast_value_copy(var);
2997         if (isfield) {
2998             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2999             tmp->expression.next = (ast_expression*)*storebase;
3000             *storebase = tmp;
3001         }
3002     }
3003
3004     /* there may be a name now */
3005     if (parser->tok == TOKEN_IDENT) {
3006         name = util_strdup(parser_tokval(parser));
3007         /* parse on */
3008         if (!parser_next(parser)) {
3009             ast_delete(var);
3010             parseerror(parser, "error after variable or field declaration");
3011             return NULL;
3012         }
3013     }
3014
3015     /* now this may be an array */
3016     if (parser->tok == '[') {
3017         wasarray = true;
3018         var = parse_arraysize(parser, var);
3019         if (!var)
3020             return NULL;
3021     }
3022
3023     /* This is the point where we can turn it into a field */
3024     if (isfield) {
3025         /* turn it into a field if desired */
3026         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3027         tmp->expression.next = (ast_expression*)var;
3028         var = tmp;
3029     }
3030
3031     /* now there may be function parens again */
3032     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3033         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3034     if (parser->tok == '(' && wasarray)
3035         parseerror(parser, "arrays as part of a return type is not supported");
3036     while (parser->tok == '(') {
3037         var = parse_parameter_list(parser, var);
3038         if (!var) {
3039             if (name)
3040                 mem_d((void*)name);
3041             ast_delete(var);
3042             return NULL;
3043         }
3044     }
3045
3046     /* finally name it */
3047     if (name) {
3048         if (!ast_value_set_name(var, name)) {
3049             ast_delete(var);
3050             parseerror(parser, "internal error: failed to set name");
3051             return NULL;
3052         }
3053         /* free the name, ast_value_set_name duplicates */
3054         mem_d((void*)name);
3055     }
3056
3057     return var;
3058 }
3059
3060 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
3061 {
3062     ast_value *var;
3063     ast_value *proto;
3064     ast_expression *old;
3065     bool       was_end;
3066     size_t     i;
3067
3068     ast_value *basetype = NULL;
3069     bool      retval    = true;
3070     bool      isparam   = false;
3071     bool      isvector  = false;
3072     bool      cleanvar  = true;
3073     bool      wasarray  = false;
3074
3075     varentry_t varent, ve[3];
3076
3077     /* get the first complete variable */
3078     var = parse_typename(parser, &basetype);
3079     if (!var) {
3080         if (basetype)
3081             ast_delete(basetype);
3082         return false;
3083     }
3084
3085     memset(&varent, 0, sizeof(varent));
3086     memset(&ve, 0, sizeof(ve));
3087
3088     while (true) {
3089         proto = NULL;
3090         wasarray = false;
3091
3092         /* Part 0: finish the type */
3093         if (parser->tok == '(') {
3094             if (opts_standard == COMPILER_QCC)
3095                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3096             var = parse_parameter_list(parser, var);
3097             if (!var) {
3098                 retval = false;
3099                 goto cleanup;
3100             }
3101         }
3102         /* we only allow 1-dimensional arrays */
3103         if (parser->tok == '[') {
3104             wasarray = true;
3105             var = parse_arraysize(parser, var);
3106             if (!var) {
3107                 retval = false;
3108                 goto cleanup;
3109             }
3110         }
3111         if (parser->tok == '(' && wasarray) {
3112             parseerror(parser, "arrays as part of a return type is not supported");
3113             /* we'll still parse the type completely for now */
3114         }
3115         /* for functions returning functions */
3116         while (parser->tok == '(') {
3117             if (opts_standard == COMPILER_QCC)
3118                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3119             var = parse_parameter_list(parser, var);
3120             if (!var) {
3121                 retval = false;
3122                 goto cleanup;
3123             }
3124         }
3125
3126         /* Part 1:
3127          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3128          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3129          * is then filled with the previous definition and the parameter-names replaced.
3130          */
3131         if (!localblock) {
3132             /* Deal with end_sys_ vars */
3133             was_end = false;
3134             if (!strcmp(var->name, "end_sys_globals")) {
3135                 parser->crc_globals = vec_size(parser->globals);
3136                 was_end = true;
3137             }
3138             else if (!strcmp(var->name, "end_sys_fields")) {
3139                 parser->crc_fields = vec_size(parser->fields);
3140                 was_end = true;
3141             }
3142             if (was_end && var->expression.vtype == TYPE_FIELD) {
3143                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3144                                  "global '%s' hint should not be a field",
3145                                  parser_tokval(parser)))
3146                 {
3147                     retval = false;
3148                     goto cleanup;
3149                 }
3150             }
3151
3152             if (!nofields && var->expression.vtype == TYPE_FIELD)
3153             {
3154                 /* deal with field declarations */
3155                 old = parser_find_field(parser, var->name);
3156                 if (old) {
3157                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3158                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3159                     {
3160                         retval = false;
3161                         goto cleanup;
3162                     }
3163                     ast_delete(var);
3164                     var = NULL;
3165                     goto skipvar;
3166                     /*
3167                     parseerror(parser, "field `%s` already declared here: %s:%i",
3168                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3169                     retval = false;
3170                     goto cleanup;
3171                     */
3172                 }
3173                 if (opts_standard == COMPILER_QCC &&
3174                     (old = parser_find_global(parser, var->name)))
3175                 {
3176                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3177                     parseerror(parser, "field `%s` already declared here: %s:%i",
3178                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3179                     retval = false;
3180                     goto cleanup;
3181                 }
3182             }
3183             else
3184             {
3185                 /* deal with other globals */
3186                 old = parser_find_global(parser, var->name);
3187                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3188                 {
3189                     /* This is a function which had a prototype */
3190                     if (!ast_istype(old, ast_value)) {
3191                         parseerror(parser, "internal error: prototype is not an ast_value");
3192                         retval = false;
3193                         goto cleanup;
3194                     }
3195                     proto = (ast_value*)old;
3196                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3197                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3198                                    proto->name,
3199                                    ast_ctx(proto).file, ast_ctx(proto).line);
3200                         retval = false;
3201                         goto cleanup;
3202                     }
3203                     /* we need the new parameter-names */
3204                     for (i = 0; i < vec_size(proto->expression.params); ++i)
3205                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3206                     ast_delete(var);
3207                     var = proto;
3208                 }
3209                 else
3210                 {
3211                     /* other globals */
3212                     if (old) {
3213                         parseerror(parser, "global `%s` already declared here: %s:%i",
3214                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3215                         retval = false;
3216                         goto cleanup;
3217                     }
3218                     if (opts_standard == COMPILER_QCC &&
3219                         (old = parser_find_field(parser, var->name)))
3220                     {
3221                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3222                         parseerror(parser, "global `%s` already declared here: %s:%i",
3223                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3224                         retval = false;
3225                         goto cleanup;
3226                     }
3227                 }
3228             }
3229         }
3230         else /* it's not a global */
3231         {
3232             old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
3233             if (old && !isparam) {
3234                 parseerror(parser, "local `%s` already declared here: %s:%i",
3235                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3236                 retval = false;
3237                 goto cleanup;
3238             }
3239             old = parser_find_local(parser, var->name, 0, &isparam);
3240             if (old && isparam) {
3241                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3242                                  "local `%s` is shadowing a parameter", var->name))
3243                 {
3244                     parseerror(parser, "local `%s` already declared here: %s:%i",
3245                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3246                     retval = false;
3247                     goto cleanup;
3248                 }
3249                 if (opts_standard != COMPILER_GMQCC) {
3250                     ast_delete(var);
3251                     var = NULL;
3252                     goto skipvar;
3253                 }
3254             }
3255         }
3256
3257         /* Part 2:
3258          * Create the global/local, and deal with vector types.
3259          */
3260         if (!proto) {
3261             if (var->expression.vtype == TYPE_VECTOR)
3262                 isvector = true;
3263             else if (var->expression.vtype == TYPE_FIELD &&
3264                      var->expression.next->expression.vtype == TYPE_VECTOR)
3265                 isvector = true;
3266
3267             if (isvector) {
3268                 if (!create_vector_members(parser, var, ve)) {
3269                     retval = false;
3270                     goto cleanup;
3271                 }
3272             }
3273
3274             varent.name = util_strdup(var->name);
3275             varent.var  = (ast_expression*)var;
3276
3277             if (!localblock) {
3278                 /* deal with global variables, fields, functions */
3279                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3280                     vec_push(parser->fields, varent);
3281                     if (isvector) {
3282                         for (i = 0; i < 3; ++i)
3283                             vec_push(parser->fields, ve[i]);
3284                     }
3285                 }
3286                 else {
3287                     vec_push(parser->globals, varent);
3288                     if (isvector) {
3289                         for (i = 0; i < 3; ++i)
3290                             vec_push(parser->globals, ve[i]);
3291                     }
3292                 }
3293             } else {
3294                 vec_push(parser->locals, varent);
3295                 vec_push(localblock->locals, var);
3296                 if (isvector) {
3297                     for (i = 0; i < 3; ++i) {
3298                         vec_push(parser->locals, ve[i]);
3299                         ast_block_collect(localblock, ve[i].var);
3300                         ve[i].var = NULL; /* from here it's being collected in the block */
3301                     }
3302                 }
3303             }
3304
3305             varent.name = NULL;
3306             ve[0].name = ve[1].name = ve[2].name = NULL;
3307             ve[0].var  = ve[1].var  = ve[2].var  = NULL;
3308             cleanvar = false;
3309         }
3310         /* Part 2.2
3311          * deal with arrays
3312          */
3313         if (var->expression.vtype == TYPE_ARRAY) {
3314             char name[1024];
3315             snprintf(name, sizeof(name), "%s##SET", var->name);
3316             if (!parser_create_array_setter(parser, var, name))
3317                 goto cleanup;
3318             snprintf(name, sizeof(name), "%s##GET", var->name);
3319             if (!parser_create_array_getter(parser, var, var->expression.next, name))
3320                 goto cleanup;
3321         }
3322         else if (!localblock && !nofields &&
3323                  var->expression.vtype == TYPE_FIELD &&
3324                  var->expression.next->expression.vtype == TYPE_ARRAY)
3325         {
3326             char name[1024];
3327             ast_expression *telem;
3328             ast_value      *tfield;
3329             ast_value      *array = (ast_value*)var->expression.next;
3330
3331             if (!ast_istype(var->expression.next, ast_value)) {
3332                 parseerror(parser, "internal error: field element type must be an ast_value");
3333                 goto cleanup;
3334             }
3335
3336             snprintf(name, sizeof(name), "%s##SETF", var->name);
3337             if (!parser_create_array_field_setter(parser, array, name))
3338                 goto cleanup;
3339
3340             telem = ast_type_copy(ast_ctx(var), array->expression.next);
3341             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3342             tfield->expression.next = telem;
3343             snprintf(name, sizeof(name), "%s##GETFP", var->name);
3344             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3345                 ast_delete(tfield);
3346                 goto cleanup;
3347             }
3348             ast_delete(tfield);
3349         }
3350
3351 skipvar:
3352         if (parser->tok == ';') {
3353             ast_delete(basetype);
3354             if (!parser_next(parser)) {
3355                 parseerror(parser, "error after variable declaration");
3356                 return false;
3357             }
3358             return true;
3359         }
3360
3361         if (parser->tok == ',')
3362             goto another;
3363
3364         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3365             parseerror(parser, "missing comma or semicolon while parsing variables");
3366             break;
3367         }
3368
3369         if (localblock && opts_standard == COMPILER_QCC) {
3370             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3371                              "initializing expression turns variable `%s` into a constant in this standard",
3372                              var->name) )
3373             {
3374                 break;
3375             }
3376         }
3377
3378         if (parser->tok != '{') {
3379             if (parser->tok != '=') {
3380                 parseerror(parser, "missing semicolon or initializer");
3381                 break;
3382             }
3383
3384             if (!parser_next(parser)) {
3385                 parseerror(parser, "error parsing initializer");
3386                 break;
3387             }
3388         }
3389         else if (opts_standard == COMPILER_QCC) {
3390             parseerror(parser, "expected '=' before function body in this standard");
3391         }
3392
3393         if (parser->tok == '#') {
3394             ast_function *func;
3395
3396             if (localblock) {
3397                 parseerror(parser, "cannot declare builtins within functions");
3398                 break;
3399             }
3400             if (var->expression.vtype != TYPE_FUNCTION) {
3401                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3402                 break;
3403             }
3404             if (!parser_next(parser)) {
3405                 parseerror(parser, "expected builtin number");
3406                 break;
3407             }
3408             if (parser->tok != TOKEN_INTCONST) {
3409                 parseerror(parser, "builtin number must be an integer constant");
3410                 break;
3411             }
3412             if (parser_token(parser)->constval.i <= 0) {
3413                 parseerror(parser, "builtin number must be an integer greater than zero");
3414                 break;
3415             }
3416
3417             func = ast_function_new(ast_ctx(var), var->name, var);
3418             if (!func) {
3419                 parseerror(parser, "failed to allocate function for `%s`", var->name);
3420                 break;
3421             }
3422             vec_push(parser->functions, func);
3423
3424             func->builtin = -parser_token(parser)->constval.i;
3425
3426             if (!parser_next(parser)) {
3427                 parseerror(parser, "expected comma or semicolon");
3428                 ast_function_delete(func);
3429                 var->constval.vfunc = NULL;
3430                 break;
3431             }
3432         }
3433         else if (parser->tok == '{' || parser->tok == '[')
3434         {
3435             if (localblock) {
3436                 parseerror(parser, "cannot declare functions within functions");
3437                 break;
3438             }
3439
3440             if (!parse_function_body(parser, var))
3441                 break;
3442             ast_delete(basetype);
3443             return true;
3444         } else {
3445             ast_expression *cexp;
3446             ast_value      *cval;
3447
3448             cexp = parse_expression_leave(parser, true);
3449             if (!cexp)
3450                 break;
3451
3452             if (!localblock) {
3453                 cval = (ast_value*)cexp;
3454                 if (!ast_istype(cval, ast_value) || !cval->isconst)
3455                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3456                 else
3457                 {
3458                     var->isconst = true;
3459                     if (cval->expression.vtype == TYPE_STRING)
3460                         var->constval.vstring = parser_strdup(cval->constval.vstring);
3461                     else
3462                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3463                     ast_unref(cval);
3464                 }
3465             } else {
3466                 shunt sy = { NULL, NULL };
3467                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3468                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3469                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3470                 if (!parser_sy_pop(parser, &sy))
3471                     ast_unref(cexp);
3472                 else {
3473                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3474                         parseerror(parser, "internal error: leaked operands");
3475                     vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3476                 }
3477                 vec_free(sy.out);
3478                 vec_free(sy.ops);
3479             }
3480         }
3481
3482 another:
3483         if (parser->tok == ',') {
3484             if (!parser_next(parser)) {
3485                 parseerror(parser, "expected another variable");
3486                 break;
3487             }
3488
3489             if (parser->tok != TOKEN_IDENT) {
3490                 parseerror(parser, "expected another variable");
3491                 break;
3492             }
3493             var = ast_value_copy(basetype);
3494             cleanvar = true;
3495             ast_value_set_name(var, parser_tokval(parser));
3496             if (!parser_next(parser)) {
3497                 parseerror(parser, "error parsing variable declaration");
3498                 break;
3499             }
3500             continue;
3501         }
3502
3503         if (parser->tok != ';') {
3504             parseerror(parser, "missing semicolon after variables");
3505             break;
3506         }
3507
3508         if (!parser_next(parser)) {
3509             parseerror(parser, "parse error after variable declaration");
3510             break;
3511         }
3512
3513         ast_delete(basetype);
3514         return true;
3515     }
3516
3517     if (cleanvar && var)
3518         ast_delete(var);
3519     ast_delete(basetype);
3520     return false;
3521
3522 cleanup:
3523     ast_delete(basetype);
3524     if (cleanvar && var)
3525         ast_delete(var);
3526     if (varent.name) mem_d(varent.name);
3527     if (ve[0].name)  mem_d(ve[0].name);
3528     if (ve[1].name)  mem_d(ve[1].name);
3529     if (ve[2].name)  mem_d(ve[2].name);
3530     if (ve[0].var)   mem_d(ve[0].var);
3531     if (ve[1].var)   mem_d(ve[1].var);
3532     if (ve[2].var)   mem_d(ve[2].var);
3533     return retval;
3534 }
3535
3536 static bool parser_global_statement(parser_t *parser)
3537 {
3538     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3539     {
3540         return parse_variable(parser, NULL, false);
3541     }
3542     else if (parser->tok == TOKEN_KEYWORD)
3543     {
3544         /* handle 'var' and 'const' */
3545         if (!strcmp(parser_tokval(parser), "var")) {
3546             if (!parser_next(parser)) {
3547                 parseerror(parser, "expected variable declaration after 'var'");
3548                 return false;
3549             }
3550             return parse_variable(parser, NULL, true);
3551         }
3552         return false;
3553     }
3554     else if (parser->tok == '$')
3555     {
3556         if (!parser_next(parser)) {
3557             parseerror(parser, "parse error");
3558             return false;
3559         }
3560     }
3561     else
3562     {
3563         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3564         return false;
3565     }
3566     return true;
3567 }
3568
3569 static parser_t *parser;
3570
3571 bool parser_init()
3572 {
3573     size_t i;
3574     parser = (parser_t*)mem_a(sizeof(parser_t));
3575     if (!parser)
3576         return false;
3577
3578     memset(parser, 0, sizeof(*parser));
3579
3580     for (i = 0; i < operator_count; ++i) {
3581         if (operators[i].id == opid1('=')) {
3582             parser->assign_op = operators+i;
3583             break;
3584         }
3585     }
3586     if (!parser->assign_op) {
3587         printf("internal error: initializing parser: failed to find assign operator\n");
3588         mem_d(parser);
3589         return false;
3590     }
3591     return true;
3592 }
3593
3594 bool parser_compile()
3595 {
3596     /* initial lexer/parser state */
3597     parser->lex->flags.noops = true;
3598
3599     if (parser_next(parser))
3600     {
3601         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3602         {
3603             if (!parser_global_statement(parser)) {
3604                 if (parser->tok == TOKEN_EOF)
3605                     parseerror(parser, "unexpected eof");
3606                 else if (!parser->errors)
3607                     parseerror(parser, "there have been errors, bailing out");
3608                 lex_close(parser->lex);
3609                 parser->lex = NULL;
3610                 return false;
3611             }
3612         }
3613     } else {
3614         parseerror(parser, "parse error");
3615         lex_close(parser->lex);
3616         parser->lex = NULL;
3617         return false;
3618     }
3619
3620     lex_close(parser->lex);
3621     parser->lex = NULL;
3622
3623     return !parser->errors;
3624 }
3625
3626 bool parser_compile_file(const char *filename)
3627 {
3628     parser->lex = lex_open(filename);
3629     if (!parser->lex) {
3630         con_err("failed to open file \"%s\"\n", filename);
3631         return false;
3632     }
3633     return parser_compile();
3634 }
3635
3636 bool parser_compile_string_len(const char *name, const char *str, size_t len)
3637 {
3638     parser->lex = lex_open_string(str, len, name);
3639     if (!parser->lex) {
3640         con_err("failed to create lexer for string \"%s\"\n", name);
3641         return false;
3642     }
3643     return parser_compile();
3644 }
3645
3646 bool parser_compile_string(const char *name, const char *str)
3647 {
3648     parser->lex = lex_open_string(str, strlen(str), name);
3649     if (!parser->lex) {
3650         con_err("failed to create lexer for string \"%s\"\n", name);
3651         return false;
3652     }
3653     return parser_compile();
3654 }
3655
3656 void parser_cleanup()
3657 {
3658     size_t i;
3659     for (i = 0; i < vec_size(parser->accessors); ++i) {
3660         ast_delete(parser->accessors[i]->constval.vfunc);
3661         parser->accessors[i]->constval.vfunc = NULL;
3662         ast_delete(parser->accessors[i]);
3663     }
3664     for (i = 0; i < vec_size(parser->functions); ++i) {
3665         ast_delete(parser->functions[i]);
3666     }
3667     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3668         ast_delete(parser->imm_vector[i]);
3669     }
3670     for (i = 0; i < vec_size(parser->imm_string); ++i) {
3671         ast_delete(parser->imm_string[i]);
3672     }
3673     for (i = 0; i < vec_size(parser->imm_float); ++i) {
3674         ast_delete(parser->imm_float[i]);
3675     }
3676     for (i = 0; i < vec_size(parser->fields); ++i) {
3677         ast_delete(parser->fields[i].var);
3678         mem_d(parser->fields[i].name);
3679     }
3680     for (i = 0; i < vec_size(parser->globals); ++i) {
3681         ast_delete(parser->globals[i].var);
3682         mem_d(parser->globals[i].name);
3683     }
3684     vec_free(parser->accessors);
3685     vec_free(parser->functions);
3686     vec_free(parser->imm_vector);
3687     vec_free(parser->imm_string);
3688     vec_free(parser->imm_float);
3689     vec_free(parser->globals);
3690     vec_free(parser->fields);
3691     vec_free(parser->locals);
3692
3693     mem_d(parser);
3694 }
3695
3696 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3697 {
3698     return util_crc16(old, str, strlen(str));
3699 }
3700
3701 static void progdefs_crc_file(const char *str)
3702 {
3703     /* write to progdefs.h here */
3704 }
3705
3706 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3707 {
3708     old = progdefs_crc_sum(old, str);
3709     progdefs_crc_file(str);
3710     return old;
3711 }
3712
3713 static void generate_checksum(parser_t *parser)
3714 {
3715     uint16_t crc = 0xFFFF;
3716     size_t i;
3717
3718         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3719         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3720         /*
3721         progdefs_crc_file("\tint\tpad;\n");
3722         progdefs_crc_file("\tint\tofs_return[3];\n");
3723         progdefs_crc_file("\tint\tofs_parm0[3];\n");
3724         progdefs_crc_file("\tint\tofs_parm1[3];\n");
3725         progdefs_crc_file("\tint\tofs_parm2[3];\n");
3726         progdefs_crc_file("\tint\tofs_parm3[3];\n");
3727         progdefs_crc_file("\tint\tofs_parm4[3];\n");
3728         progdefs_crc_file("\tint\tofs_parm5[3];\n");
3729         progdefs_crc_file("\tint\tofs_parm6[3];\n");
3730         progdefs_crc_file("\tint\tofs_parm7[3];\n");
3731         */
3732         for (i = 0; i < parser->crc_globals; ++i) {
3733             if (!ast_istype(parser->globals[i].var, ast_value))
3734                 continue;
3735             switch (parser->globals[i].var->expression.vtype) {
3736                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3737                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3738                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3739                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3740                 default:
3741                     crc = progdefs_crc_both(crc, "\tint\t");
3742                     break;
3743             }
3744             crc = progdefs_crc_both(crc, parser->globals[i].name);
3745             crc = progdefs_crc_both(crc, ";\n");
3746         }
3747         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3748         for (i = 0; i < parser->crc_fields; ++i) {
3749             if (!ast_istype(parser->fields[i].var, ast_value))
3750                 continue;
3751             switch (parser->fields[i].var->expression.next->expression.vtype) {
3752                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3753                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3754                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3755                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3756                 default:
3757                     crc = progdefs_crc_both(crc, "\tint\t");
3758                     break;
3759             }
3760             crc = progdefs_crc_both(crc, parser->fields[i].name);
3761             crc = progdefs_crc_both(crc, ";\n");
3762         }
3763         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3764
3765         code_crc = crc;
3766 }
3767
3768 bool parser_finish(const char *output)
3769 {
3770     size_t i;
3771     ir_builder *ir;
3772     bool retval = true;
3773
3774     if (!parser->errors)
3775     {
3776         ir = ir_builder_new("gmqcc_out");
3777         if (!ir) {
3778             con_out("failed to allocate builder\n");
3779             return false;
3780         }
3781
3782         for (i = 0; i < vec_size(parser->fields); ++i) {
3783             ast_value *field;
3784             bool isconst;
3785             if (!ast_istype(parser->fields[i].var, ast_value))
3786                 continue;
3787             field = (ast_value*)parser->fields[i].var;
3788             isconst = field->isconst;
3789             field->isconst = false;
3790             if (!ast_global_codegen((ast_value*)field, ir, true)) {
3791                 con_out("failed to generate field %s\n", field->name);
3792                 ir_builder_delete(ir);
3793                 return false;
3794             }
3795             if (isconst) {
3796                 ir_value *ifld;
3797                 ast_expression *subtype;
3798                 field->isconst = true;
3799                 subtype = field->expression.next;
3800                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3801                 if (subtype->expression.vtype == TYPE_FIELD)
3802                     ifld->fieldtype = subtype->expression.next->expression.vtype;
3803                 else if (subtype->expression.vtype == TYPE_FUNCTION)
3804                     ifld->outtype = subtype->expression.next->expression.vtype;
3805                 (void)!ir_value_set_field(field->ir_v, ifld);
3806             }
3807         }
3808         for (i = 0; i < vec_size(parser->globals); ++i) {
3809             ast_value *asvalue;
3810             if (!ast_istype(parser->globals[i].var, ast_value))
3811                 continue;
3812             asvalue = (ast_value*)(parser->globals[i].var);
3813             if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3814                 if (strcmp(asvalue->name, "end_sys_globals") &&
3815                     strcmp(asvalue->name, "end_sys_fields"))
3816                 {
3817                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3818                                                    "unused global: `%s`", asvalue->name);
3819                 }
3820             }
3821             if (!ast_global_codegen(asvalue, ir, false)) {
3822                 con_out("failed to generate global %s\n", parser->globals[i].name);
3823                 ir_builder_delete(ir);
3824                 return false;
3825             }
3826         }
3827         for (i = 0; i < vec_size(parser->imm_float); ++i) {
3828             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3829                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
3830                 ir_builder_delete(ir);
3831                 return false;
3832             }
3833         }
3834         for (i = 0; i < vec_size(parser->imm_string); ++i) {
3835             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3836                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
3837                 ir_builder_delete(ir);
3838                 return false;
3839             }
3840         }
3841         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3842             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3843                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
3844                 ir_builder_delete(ir);
3845                 return false;
3846             }
3847         }
3848         for (i = 0; i < vec_size(parser->globals); ++i) {
3849             ast_value *asvalue;
3850             if (!ast_istype(parser->globals[i].var, ast_value))
3851                 continue;
3852             asvalue = (ast_value*)(parser->globals[i].var);
3853             if (asvalue->setter) {
3854                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3855                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
3856                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
3857                 {
3858                     printf("failed to generate setter for %s\n", parser->globals[i].name);
3859                     ir_builder_delete(ir);
3860                     return false;
3861                 }
3862             }
3863             if (asvalue->getter) {
3864                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3865                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
3866                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
3867                 {
3868                     printf("failed to generate getter for %s\n", parser->globals[i].name);
3869                     ir_builder_delete(ir);
3870                     return false;
3871                 }
3872             }
3873         }
3874         for (i = 0; i < vec_size(parser->fields); ++i) {
3875             ast_value *asvalue;
3876             asvalue = (ast_value*)(parser->fields[i].var->expression.next);
3877
3878             if (!ast_istype((ast_expression*)asvalue, ast_value))
3879                 continue;
3880             if (asvalue->expression.vtype != TYPE_ARRAY)
3881                 continue;
3882             if (asvalue->setter) {
3883                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3884                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
3885                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
3886                 {
3887                     printf("failed to generate setter for %s\n", parser->fields[i].name);
3888                     ir_builder_delete(ir);
3889                     return false;
3890                 }
3891             }
3892             if (asvalue->getter) {
3893                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3894                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
3895                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
3896                 {
3897                     printf("failed to generate getter for %s\n", parser->fields[i].name);
3898                     ir_builder_delete(ir);
3899                     return false;
3900                 }
3901             }
3902         }
3903         for (i = 0; i < vec_size(parser->functions); ++i) {
3904             if (!ast_function_codegen(parser->functions[i], ir)) {
3905                 con_out("failed to generate function %s\n", parser->functions[i]->name);
3906                 ir_builder_delete(ir);
3907                 return false;
3908             }
3909             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3910                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
3911                 ir_builder_delete(ir);
3912                 return false;
3913             }
3914         }
3915
3916         if (retval) {
3917             if (opts_dump)
3918                 ir_builder_dump(ir, con_out);
3919
3920             generate_checksum(parser);
3921
3922             if (!ir_builder_generate(ir, output)) {
3923                 con_out("*** failed to generate output file\n");
3924                 ir_builder_delete(ir);
3925                 return false;
3926             }
3927         }
3928
3929         ir_builder_delete(ir);
3930         return retval;
3931     }
3932
3933     con_out("*** there were compile errors\n");
3934     return false;
3935 }