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