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