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