]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
ast_block_add_expr now lets the block fully adopt the type of the added expression
[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 (!ast_compare_type(field->expression.next, exprs[1])) {
930                     ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
931                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
932                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
933                         field->expression.next->expression.vtype == TYPE_FUNCTION &&
934                         exprs[1]->expression.vtype == TYPE_FUNCTION)
935                     {
936                         if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
937                                          "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
938                         {
939                             parser->errors++;
940                         }
941                     }
942                     else
943                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
944                 }
945             }
946             else
947             {
948                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
949                     exprs[0]->expression.vtype == TYPE_FIELD &&
950                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
951                 {
952                     assignop = type_store_instr[TYPE_VECTOR];
953                 }
954                 else {
955                     assignop = type_store_instr[exprs[0]->expression.vtype];
956                 }
957
958                 if (assignop == AINSTR_END) {
959                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
960                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
961                     parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
962                 }
963                 else if (!ast_compare_type(exprs[0], exprs[1])) {
964                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
965                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
966                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
967                         exprs[0]->expression.vtype == TYPE_FUNCTION &&
968                         exprs[1]->expression.vtype == TYPE_FUNCTION)
969                     {
970                         if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
971                                          "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
972                         {
973                             parser->errors++;
974                         }
975                     }
976                     else
977                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
978                 }
979             }
980             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
981                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
982             }
983             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
984             break;
985         case opid3('+','+','P'):
986         case opid3('-','-','P'):
987             /* prefix ++ */
988             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
989                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
990                 parseerror(parser, "invalid type for prefix increment: %s", ty1);
991                 return false;
992             }
993             if (op->id == opid3('+','+','P'))
994                 addop = INSTR_ADD_F;
995             else
996                 addop = INSTR_SUB_F;
997             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
998                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
999             }
1000             if (ast_istype(exprs[0], ast_entfield)) {
1001                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1002                                                         exprs[0],
1003                                                         (ast_expression*)parser_const_float_1(parser));
1004             } else {
1005                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1006                                                         exprs[0],
1007                                                         (ast_expression*)parser_const_float_1(parser));
1008             }
1009             break;
1010         case opid3('S','+','+'):
1011         case opid3('S','-','-'):
1012             /* prefix ++ */
1013             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1014                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1015                 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1016                 return false;
1017             }
1018             if (op->id == opid3('S','+','+')) {
1019                 addop = INSTR_ADD_F;
1020                 subop = INSTR_SUB_F;
1021             } else {
1022                 addop = INSTR_SUB_F;
1023                 subop = INSTR_ADD_F;
1024             }
1025             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1026                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1027             }
1028             if (ast_istype(exprs[0], ast_entfield)) {
1029                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1030                                                         exprs[0],
1031                                                         (ast_expression*)parser_const_float_1(parser));
1032             } else {
1033                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1034                                                         exprs[0],
1035                                                         (ast_expression*)parser_const_float_1(parser));
1036             }
1037             if (!out)
1038                 return false;
1039             out = (ast_expression*)ast_binary_new(ctx, subop,
1040                                                   out,
1041                                                   (ast_expression*)parser_const_float_1(parser));
1042             break;
1043         case opid2('+','='):
1044         case opid2('-','='):
1045             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1046                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1047             {
1048                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1049                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1050                 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1051                            ty1, ty2);
1052                 return false;
1053             }
1054             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1055                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1056             }
1057             if (ast_istype(exprs[0], ast_entfield))
1058                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1059             else
1060                 assignop = type_store_instr[exprs[0]->expression.vtype];
1061             switch (exprs[0]->expression.vtype) {
1062                 case TYPE_FLOAT:
1063                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1064                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1065                                                             exprs[0], exprs[1]);
1066                     break;
1067                 case TYPE_VECTOR:
1068                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1069                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1070                                                             exprs[0], exprs[1]);
1071                     break;
1072                 default:
1073                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1074                                type_name[exprs[0]->expression.vtype],
1075                                type_name[exprs[1]->expression.vtype]);
1076                     return false;
1077             };
1078             break;
1079         case opid2('*','='):
1080         case opid2('/','='):
1081             if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1082                 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1083                   exprs[0]->expression.vtype == TYPE_VECTOR))
1084             {
1085                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1086                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1087                 parseerror(parser, "invalid types used in expression: %s and %s",
1088                            ty1, ty2);
1089                 return false;
1090             }
1091             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1092                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1093             }
1094             if (ast_istype(exprs[0], ast_entfield))
1095                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1096             else
1097                 assignop = type_store_instr[exprs[0]->expression.vtype];
1098             switch (exprs[0]->expression.vtype) {
1099                 case TYPE_FLOAT:
1100                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1101                                                             (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1102                                                             exprs[0], exprs[1]);
1103                     break;
1104                 case TYPE_VECTOR:
1105                     if (op->id == opid2('*','=')) {
1106                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1107                                                                 exprs[0], exprs[1]);
1108                     } else {
1109                         /* there's no DIV_VF */
1110                         out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1111                                                               (ast_expression*)parser_const_float_1(parser),
1112                                                               exprs[1]);
1113                         if (!out)
1114                             return false;
1115                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1116                                                                 exprs[0], out);
1117                     }
1118                     break;
1119                 default:
1120                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1121                                type_name[exprs[0]->expression.vtype],
1122                                type_name[exprs[1]->expression.vtype]);
1123                     return false;
1124             };
1125             break;
1126         case opid2('&','='):
1127         case opid2('|','='):
1128             if (NotSameType(TYPE_FLOAT)) {
1129                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1130                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1131                 parseerror(parser, "invalid types used in expression: %s and %s",
1132                            ty1, ty2);
1133                 return false;
1134             }
1135             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1136                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1137             }
1138             if (ast_istype(exprs[0], ast_entfield))
1139                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1140             else
1141                 assignop = type_store_instr[exprs[0]->expression.vtype];
1142             out = (ast_expression*)ast_binstore_new(ctx, assignop,
1143                                                     (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1144                                                     exprs[0], exprs[1]);
1145             break;
1146         case opid3('&','~','='):
1147             /* This is like: a &= ~(b);
1148              * But QC has no bitwise-not, so we implement it as
1149              * a -= a & (b);
1150              */
1151             if (NotSameType(TYPE_FLOAT)) {
1152                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1153                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1154                 parseerror(parser, "invalid types used in expression: %s and %s",
1155                            ty1, ty2);
1156                 return false;
1157             }
1158             if (ast_istype(exprs[0], ast_entfield))
1159                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1160             else
1161                 assignop = type_store_instr[exprs[0]->expression.vtype];
1162             out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1163             if (!out)
1164                 return false;
1165             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1166                 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1167             }
1168             asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1169             asbinstore->keep_dest = true;
1170             out = (ast_expression*)asbinstore;
1171             break;
1172     }
1173 #undef NotSameType
1174
1175     if (!out) {
1176         parseerror(parser, "failed to apply operand %s", op->op);
1177         return false;
1178     }
1179
1180     DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1181     vec_push(sy->out, syexp(ctx, out));
1182     return true;
1183 }
1184
1185 static bool parser_close_call(parser_t *parser, shunt *sy)
1186 {
1187     /* was a function call */
1188     ast_expression *fun;
1189     ast_call       *call;
1190
1191     size_t          fid;
1192     size_t          paramcount;
1193
1194     vec_shrinkby(sy->ops, 1);
1195     fid = sy->ops[vec_size(sy->ops)].off;
1196
1197     /* out[fid] is the function
1198      * everything above is parameters...
1199      * 0 params = nothing
1200      * 1 params = ast_expression
1201      * more = ast_block
1202      */
1203
1204     if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1205         parseerror(parser, "internal error: function call needs function and parameter list...");
1206         return false;
1207     }
1208
1209     fun = sy->out[fid].out;
1210
1211     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1212     if (!call) {
1213         parseerror(parser, "out of memory");
1214         return false;
1215     }
1216
1217     if (fid+1 == vec_size(sy->out)) {
1218         /* no arguments */
1219         paramcount = 0;
1220     } else if (fid+2 == vec_size(sy->out)) {
1221         ast_block *params;
1222         vec_shrinkby(sy->out, 1);
1223         params = sy->out[vec_size(sy->out)].block;
1224         if (!params) {
1225             /* 1 param */
1226             paramcount = 1;
1227             vec_push(call->params, sy->out[vec_size(sy->out)].out);
1228         } else {
1229             paramcount = vec_size(params->exprs);
1230             call->params = params->exprs;
1231             params->exprs = NULL;
1232             ast_delete(params);
1233         }
1234         if (!ast_call_check_types(call))
1235             parser->errors++;
1236     } else {
1237         parseerror(parser, "invalid function call");
1238         return false;
1239     }
1240
1241     /* overwrite fid, the function, with a call */
1242     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1243
1244     if (fun->expression.vtype != TYPE_FUNCTION) {
1245         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1246         return false;
1247     }
1248
1249     if (!fun->expression.next) {
1250         parseerror(parser, "could not determine function return type");
1251         return false;
1252     } else {
1253         if (vec_size(fun->expression.params) != paramcount &&
1254             !(fun->expression.variadic &&
1255               vec_size(fun->expression.params) < paramcount))
1256         {
1257             ast_value *fval;
1258             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1259
1260             fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1261             if (opts_standard == COMPILER_GMQCC)
1262             {
1263                 if (fval)
1264                     parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1265                                " -> `%s` has been declared here: %s:%i",
1266                                fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1267                                fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1268                 else
1269                     parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1270                                " -> `%s` has been declared here: %s:%i",
1271                                fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1272                                fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1273                 return false;
1274             }
1275             else
1276             {
1277                 if (fval)
1278                     return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1279                                          "too %s parameters for call to %s: expected %i, got %i\n"
1280                                          " -> `%s` has been declared here: %s:%i",
1281                                          fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1282                                          fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1283                 else
1284                     return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1285                                          "too %s parameters for function call: expected %i, got %i\n"
1286                                          " -> `%s` has been declared here: %s:%i",
1287                                          fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1288                                          fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1289             }
1290         }
1291     }
1292
1293     return true;
1294 }
1295
1296 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1297 {
1298     if (!vec_size(sy->ops)) {
1299         parseerror(parser, "unmatched closing paren");
1300         return false;
1301     }
1302     /* this would for bit a + (x) because there are no operators inside (x)
1303     if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1304         parseerror(parser, "empty parenthesis expression");
1305         return false;
1306     }
1307     */
1308     while (vec_size(sy->ops)) {
1309         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1310             if (!parser_close_call(parser, sy))
1311                 return false;
1312             break;
1313         }
1314         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1315             vec_shrinkby(sy->ops, 1);
1316             return !functions_only;
1317         }
1318         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1319             if (functions_only)
1320                 return false;
1321             /* pop off the parenthesis */
1322             vec_shrinkby(sy->ops, 1);
1323             /* then apply the index operator */
1324             if (!parser_sy_apply_operator(parser, sy))
1325                 return false;
1326             return true;
1327         }
1328         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1329             if (functions_only)
1330                 return false;
1331             if (vec_last(parser->pot) != POT_TERNARY1) {
1332                 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1333                 return false;
1334             }
1335             vec_last(parser->pot) = POT_TERNARY2;
1336             /* pop off the parenthesis */
1337             vec_shrinkby(sy->ops, 1);
1338             return true;
1339         }
1340         if (!parser_sy_apply_operator(parser, sy))
1341             return false;
1342     }
1343     return true;
1344 }
1345
1346 static void parser_reclassify_token(parser_t *parser)
1347 {
1348     size_t i;
1349     for (i = 0; i < operator_count; ++i) {
1350         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1351             parser->tok = TOKEN_OPERATOR;
1352             return;
1353         }
1354     }
1355 }
1356
1357 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1358 {
1359     ast_expression *expr = NULL;
1360     shunt sy;
1361     bool wantop = false;
1362     bool gotmemberof = false;
1363
1364     /* count the parens because an if starts with one, so the
1365      * end of a condition is an unmatched closing paren
1366      */
1367     int parens = 0;
1368     int ternaries = 0;
1369
1370     sy.out = NULL;
1371     sy.ops = NULL;
1372
1373     parser->lex->flags.noops = false;
1374
1375     parser_reclassify_token(parser);
1376
1377     while (true)
1378     {
1379         if (gotmemberof)
1380             gotmemberof = false;
1381         else
1382             parser->memberof = 0;
1383
1384         if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1385             parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1386         {
1387             /* a translatable string */
1388             ast_value *val;
1389
1390             if (wantop) {
1391                 parseerror(parser, "expected operator or end of statement, got constant");
1392                 goto onerr;
1393             }
1394
1395             parser->lex->flags.noops = true;
1396             if (!parser_next(parser) || parser->tok != '(') {
1397                 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1398                 goto onerr;
1399             }
1400             parser->lex->flags.noops = false;
1401             if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1402                 parseerror(parser, "expected a constant string in translatable-string extension");
1403                 goto onerr;
1404             }
1405             val = parser_const_string(parser, parser_tokval(parser), true);
1406             wantop = true;
1407             if (!val)
1408                 return false;
1409             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1410             DEBUGSHUNTDO(con_out("push string\n"));
1411
1412             if (!parser_next(parser) || parser->tok != ')') {
1413                 parseerror(parser, "expected closing paren after translatable string");
1414                 goto onerr;
1415             }
1416         }
1417         else if (parser->tok == TOKEN_IDENT)
1418         {
1419             ast_expression *var;
1420             if (wantop) {
1421                 parseerror(parser, "expected operator or end of statement");
1422                 goto onerr;
1423             }
1424             wantop = true;
1425             /* variable */
1426             if (opts_standard == COMPILER_GMQCC)
1427             {
1428                 if (parser->memberof == TYPE_ENTITY) {
1429                     /* still get vars first since there could be a fieldpointer */
1430                     var = parser_find_var(parser, parser_tokval(parser));
1431                     if (!var)
1432                         var = parser_find_field(parser, parser_tokval(parser));
1433                 }
1434                 else if (parser->memberof == TYPE_VECTOR)
1435                 {
1436                     parseerror(parser, "TODO: implement effective vector member access");
1437                     goto onerr;
1438                 }
1439                 else if (parser->memberof) {
1440                     parseerror(parser, "namespace for member not found");
1441                     goto onerr;
1442                 }
1443                 else
1444                     var = parser_find_var(parser, parser_tokval(parser));
1445             } else {
1446                 var = parser_find_var(parser, parser_tokval(parser));
1447                 if (!var)
1448                     var = parser_find_field(parser, parser_tokval(parser));
1449             }
1450             if (!var) {
1451                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1452                 goto onerr;
1453             }
1454             if (ast_istype(var, ast_value)) {
1455                 ((ast_value*)var)->uses++;
1456             }
1457             else if (ast_istype(var, ast_member)) {
1458                 ast_member *mem = (ast_member*)var;
1459                 if (ast_istype(mem->owner, ast_value))
1460                     ((ast_value*)(mem->owner))->uses++;
1461             }
1462             vec_push(sy.out, syexp(parser_ctx(parser), var));
1463             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1464         }
1465         else if (parser->tok == TOKEN_FLOATCONST) {
1466             ast_value *val;
1467             if (wantop) {
1468                 parseerror(parser, "expected operator or end of statement, got constant");
1469                 goto onerr;
1470             }
1471             wantop = true;
1472             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1473             if (!val)
1474                 return false;
1475             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1476             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1477         }
1478         else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1479             ast_value *val;
1480             if (wantop) {
1481                 parseerror(parser, "expected operator or end of statement, got constant");
1482                 goto onerr;
1483             }
1484             wantop = true;
1485             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1486             if (!val)
1487                 return false;
1488             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1489             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1490         }
1491         else if (parser->tok == TOKEN_STRINGCONST) {
1492             ast_value *val;
1493             if (wantop) {
1494                 parseerror(parser, "expected operator or end of statement, got constant");
1495                 goto onerr;
1496             }
1497             wantop = true;
1498             val = parser_const_string(parser, parser_tokval(parser), false);
1499             if (!val)
1500                 return false;
1501             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1502             DEBUGSHUNTDO(con_out("push string\n"));
1503         }
1504         else if (parser->tok == TOKEN_VECTORCONST) {
1505             ast_value *val;
1506             if (wantop) {
1507                 parseerror(parser, "expected operator or end of statement, got constant");
1508                 goto onerr;
1509             }
1510             wantop = true;
1511             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1512             if (!val)
1513                 return false;
1514             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1515             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1516                                 parser_token(parser)->constval.v.x,
1517                                 parser_token(parser)->constval.v.y,
1518                                 parser_token(parser)->constval.v.z));
1519         }
1520         else if (parser->tok == '(') {
1521             parseerror(parser, "internal error: '(' should be classified as operator");
1522             goto onerr;
1523         }
1524         else if (parser->tok == '[') {
1525             parseerror(parser, "internal error: '[' should be classified as operator");
1526             goto onerr;
1527         }
1528         else if (parser->tok == ')') {
1529             if (wantop) {
1530                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1531                 --parens;
1532                 if (parens < 0)
1533                     break;
1534                 /* we do expect an operator next */
1535                 /* closing an opening paren */
1536                 if (!parser_close_paren(parser, &sy, false))
1537                     goto onerr;
1538                 if (vec_last(parser->pot) != POT_PAREN) {
1539                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1540                     goto onerr;
1541                 }
1542                 vec_pop(parser->pot);
1543             } else {
1544                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1545                 --parens;
1546                 if (parens < 0)
1547                     break;
1548                 /* allowed for function calls */
1549                 if (!parser_close_paren(parser, &sy, true))
1550                     goto onerr;
1551                 if (vec_last(parser->pot) != POT_PAREN) {
1552                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1553                     goto onerr;
1554                 }
1555                 vec_pop(parser->pot);
1556             }
1557             wantop = true;
1558         }
1559         else if (parser->tok == ']') {
1560             if (!wantop)
1561                 parseerror(parser, "operand expected");
1562             --parens;
1563             if (parens < 0)
1564                 break;
1565             if (!parser_close_paren(parser, &sy, false))
1566                 goto onerr;
1567             if (vec_last(parser->pot) != POT_PAREN) {
1568                 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1569                 goto onerr;
1570             }
1571             vec_pop(parser->pot);
1572             wantop = true;
1573         }
1574         else if (parser->tok != TOKEN_OPERATOR) {
1575             if (wantop) {
1576                 parseerror(parser, "expected operator or end of statement");
1577                 goto onerr;
1578             }
1579             break;
1580         }
1581         else
1582         {
1583             /* classify the operator */
1584             const oper_info *op;
1585             const oper_info *olast = NULL;
1586             size_t o;
1587             for (o = 0; o < operator_count; ++o) {
1588                 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1589                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1590                     !strcmp(parser_tokval(parser), operators[o].op))
1591                 {
1592                     break;
1593                 }
1594             }
1595             if (o == operator_count) {
1596                 /* no operator found... must be the end of the statement */
1597                 break;
1598             }
1599             /* found an operator */
1600             op = &operators[o];
1601
1602             /* when declaring variables, a comma starts a new variable */
1603             if (op->id == opid1(',') && !parens && stopatcomma) {
1604                 /* fixup the token */
1605                 parser->tok = ',';
1606                 break;
1607             }
1608
1609             /* a colon without a pervious question mark cannot be a ternary */
1610             if (!ternaries && op->id == opid2(':','?')) {
1611                 parser->tok = ':';
1612                 break;
1613             }
1614
1615             if (op->id == opid1(',')) {
1616                 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1617                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1618                 }
1619             }
1620
1621             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1622                 olast = &operators[vec_last(sy.ops).etype-1];
1623
1624             while (olast && (
1625                     (op->prec < olast->prec) ||
1626                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1627             {
1628                 if (!parser_sy_apply_operator(parser, &sy))
1629                     goto onerr;
1630                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1631                     olast = &operators[vec_last(sy.ops).etype-1];
1632                 else
1633                     olast = NULL;
1634             }
1635
1636             if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1637                 /* for gmqcc standard: open up the namespace of the previous type */
1638                 ast_expression *prevex = vec_last(sy.out).out;
1639                 if (!prevex) {
1640                     parseerror(parser, "unexpected member operator");
1641                     goto onerr;
1642                 }
1643                 if (prevex->expression.vtype == TYPE_ENTITY)
1644                     parser->memberof = TYPE_ENTITY;
1645                 else if (prevex->expression.vtype == TYPE_VECTOR)
1646                     parser->memberof = TYPE_VECTOR;
1647                 else {
1648                     parseerror(parser, "type error: type has no members");
1649                     goto onerr;
1650                 }
1651                 gotmemberof = true;
1652             }
1653
1654             if (op->id == opid1('(')) {
1655                 if (wantop) {
1656                     size_t sycount = vec_size(sy.out);
1657                     DEBUGSHUNTDO(con_out("push [op] (\n"));
1658                     ++parens; vec_push(parser->pot, POT_PAREN);
1659                     /* we expected an operator, this is the function-call operator */
1660                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1661                 } else {
1662                     ++parens; vec_push(parser->pot, POT_PAREN);
1663                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1664                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
1665                 }
1666                 wantop = false;
1667             } else if (op->id == opid1('[')) {
1668                 if (!wantop) {
1669                     parseerror(parser, "unexpected array subscript");
1670                     goto onerr;
1671                 }
1672                 ++parens; vec_push(parser->pot, POT_PAREN);
1673                 /* push both the operator and the paren, this makes life easier */
1674                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1675                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1676                 wantop = false;
1677             } else if (op->id == opid2('?',':')) {
1678                 wantop = false;
1679                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1680                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1681                 wantop = false;
1682                 ++ternaries;
1683                 vec_push(parser->pot, POT_TERNARY1);
1684             } else if (op->id == opid2(':','?')) {
1685                 if (!vec_size(parser->pot)) {
1686                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1687                     goto onerr;
1688                 }
1689                 if (vec_last(parser->pot) != POT_TERNARY1) {
1690                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1691                     goto onerr;
1692                 }
1693                 if (!parser_close_paren(parser, &sy, false))
1694                     goto onerr;
1695                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1696                 wantop = false;
1697                 --ternaries;
1698             } else {
1699                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1700                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1701                 wantop = !!(op->flags & OP_SUFFIX);
1702             }
1703         }
1704         if (!parser_next(parser)) {
1705             goto onerr;
1706         }
1707         if (parser->tok == ';' ||
1708             (!parens && parser->tok == ']'))
1709         {
1710             break;
1711         }
1712     }
1713
1714     while (vec_size(sy.ops)) {
1715         if (!parser_sy_apply_operator(parser, &sy))
1716             goto onerr;
1717     }
1718
1719     parser->lex->flags.noops = true;
1720     if (!vec_size(sy.out)) {
1721         parseerror(parser, "empty expression");
1722         expr = NULL;
1723     } else
1724         expr = sy.out[0].out;
1725     vec_free(sy.out);
1726     vec_free(sy.ops);
1727     DEBUGSHUNTDO(con_out("shunt done\n"));
1728     if (vec_size(parser->pot)) {
1729         parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1730         return NULL;
1731     }
1732     vec_free(parser->pot);
1733     return expr;
1734
1735 onerr:
1736     parser->lex->flags.noops = true;
1737     vec_free(sy.out);
1738     vec_free(sy.ops);
1739     return NULL;
1740 }
1741
1742 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1743 {
1744     ast_expression *e = parse_expression_leave(parser, stopatcomma);
1745     if (!e)
1746         return NULL;
1747     if (!parser_next(parser)) {
1748         ast_delete(e);
1749         return NULL;
1750     }
1751     return e;
1752 }
1753
1754 static void parser_enterblock(parser_t *parser)
1755 {
1756     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1757     vec_push(parser->_blocklocals, vec_size(parser->_locals));
1758     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1759     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1760     vec_push(parser->_block_ctx, parser_ctx(parser));
1761 }
1762
1763 static bool parser_leaveblock(parser_t *parser)
1764 {
1765     bool   rv = true;
1766     size_t locals, typedefs;
1767
1768     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1769         parseerror(parser, "internal error: parser_leaveblock with no block");
1770         return false;
1771     }
1772
1773     util_htdel(vec_last(parser->variables));
1774     vec_pop(parser->variables);
1775     if (!vec_size(parser->_blocklocals)) {
1776         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1777         return false;
1778     }
1779
1780     locals = vec_last(parser->_blocklocals);
1781     vec_pop(parser->_blocklocals);
1782     while (vec_size(parser->_locals) != locals) {
1783         ast_expression *e = vec_last(parser->_locals);
1784         ast_value      *v = (ast_value*)e;
1785         vec_pop(parser->_locals);
1786         if (ast_istype(e, ast_value) && !v->uses) {
1787             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1788                 parser->errors++;
1789                 rv = false;
1790             }
1791         }
1792     }
1793
1794     typedefs = vec_last(parser->_blocktypedefs);
1795     while (vec_size(parser->_typedefs) != typedefs) {
1796         ast_delete(vec_last(parser->_typedefs));
1797         vec_pop(parser->_typedefs);
1798     }
1799     util_htdel(vec_last(parser->typedefs));
1800     vec_pop(parser->typedefs);
1801
1802     vec_pop(parser->_block_ctx);
1803     return rv;
1804 }
1805
1806 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1807 {
1808     vec_push(parser->_locals, e);
1809     util_htset(vec_last(parser->variables), name, (void*)e);
1810 }
1811
1812 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1813 {
1814     ast_ifthen *ifthen;
1815     ast_expression *cond, *ontrue, *onfalse = NULL;
1816     bool ifnot = false;
1817
1818     lex_ctx ctx = parser_ctx(parser);
1819
1820     (void)block; /* not touching */
1821
1822     /* skip the 'if', parse an optional 'not' and check for an opening paren */
1823     if (!parser_next(parser)) {
1824         parseerror(parser, "expected condition or 'not'");
1825         return false;
1826     }
1827     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1828         ifnot = true;
1829         if (!parser_next(parser)) {
1830             parseerror(parser, "expected condition in parenthesis");
1831             return false;
1832         }
1833     }
1834     if (parser->tok != '(') {
1835         parseerror(parser, "expected 'if' condition in parenthesis");
1836         return false;
1837     }
1838     /* parse into the expression */
1839     if (!parser_next(parser)) {
1840         parseerror(parser, "expected 'if' condition after opening paren");
1841         return false;
1842     }
1843     /* parse the condition */
1844     cond = parse_expression_leave(parser, false);
1845     if (!cond)
1846         return false;
1847     /* closing paren */
1848     if (parser->tok != ')') {
1849         parseerror(parser, "expected closing paren after 'if' condition");
1850         ast_delete(cond);
1851         return false;
1852     }
1853     /* parse into the 'then' branch */
1854     if (!parser_next(parser)) {
1855         parseerror(parser, "expected statement for on-true branch of 'if'");
1856         ast_delete(cond);
1857         return false;
1858     }
1859     if (!parse_statement_or_block(parser, &ontrue)) {
1860         ast_delete(cond);
1861         return false;
1862     }
1863     /* check for an else */
1864     if (!strcmp(parser_tokval(parser), "else")) {
1865         /* parse into the 'else' branch */
1866         if (!parser_next(parser)) {
1867             parseerror(parser, "expected on-false branch after 'else'");
1868             ast_delete(ontrue);
1869             ast_delete(cond);
1870             return false;
1871         }
1872         if (!parse_statement_or_block(parser, &onfalse)) {
1873             ast_delete(ontrue);
1874             ast_delete(cond);
1875             return false;
1876         }
1877     }
1878
1879     if (ifnot)
1880         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1881     else
1882         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1883     *out = (ast_expression*)ifthen;
1884     return true;
1885 }
1886
1887 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1888 {
1889     ast_loop *aloop;
1890     ast_expression *cond, *ontrue;
1891
1892     lex_ctx ctx = parser_ctx(parser);
1893
1894     (void)block; /* not touching */
1895
1896     /* skip the 'while' and check for opening paren */
1897     if (!parser_next(parser) || parser->tok != '(') {
1898         parseerror(parser, "expected 'while' condition in parenthesis");
1899         return false;
1900     }
1901     /* parse into the expression */
1902     if (!parser_next(parser)) {
1903         parseerror(parser, "expected 'while' condition after opening paren");
1904         return false;
1905     }
1906     /* parse the condition */
1907     cond = parse_expression_leave(parser, false);
1908     if (!cond)
1909         return false;
1910     /* closing paren */
1911     if (parser->tok != ')') {
1912         parseerror(parser, "expected closing paren after 'while' condition");
1913         ast_delete(cond);
1914         return false;
1915     }
1916     /* parse into the 'then' branch */
1917     if (!parser_next(parser)) {
1918         parseerror(parser, "expected while-loop body");
1919         ast_delete(cond);
1920         return false;
1921     }
1922     if (!parse_statement_or_block(parser, &ontrue)) {
1923         ast_delete(cond);
1924         return false;
1925     }
1926
1927     aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1928     *out = (ast_expression*)aloop;
1929     return true;
1930 }
1931
1932 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1933 {
1934     ast_loop *aloop;
1935     ast_expression *cond, *ontrue;
1936
1937     lex_ctx ctx = parser_ctx(parser);
1938
1939     (void)block; /* not touching */
1940
1941     /* skip the 'do' and get the body */
1942     if (!parser_next(parser)) {
1943         parseerror(parser, "expected loop body");
1944         return false;
1945     }
1946     if (!parse_statement_or_block(parser, &ontrue))
1947         return false;
1948
1949     /* expect the "while" */
1950     if (parser->tok != TOKEN_KEYWORD ||
1951         strcmp(parser_tokval(parser), "while"))
1952     {
1953         parseerror(parser, "expected 'while' and condition");
1954         ast_delete(ontrue);
1955         return false;
1956     }
1957
1958     /* skip the 'while' and check for opening paren */
1959     if (!parser_next(parser) || parser->tok != '(') {
1960         parseerror(parser, "expected 'while' condition in parenthesis");
1961         ast_delete(ontrue);
1962         return false;
1963     }
1964     /* parse into the expression */
1965     if (!parser_next(parser)) {
1966         parseerror(parser, "expected 'while' condition after opening paren");
1967         ast_delete(ontrue);
1968         return false;
1969     }
1970     /* parse the condition */
1971     cond = parse_expression_leave(parser, false);
1972     if (!cond)
1973         return false;
1974     /* closing paren */
1975     if (parser->tok != ')') {
1976         parseerror(parser, "expected closing paren after 'while' condition");
1977         ast_delete(ontrue);
1978         ast_delete(cond);
1979         return false;
1980     }
1981     /* parse on */
1982     if (!parser_next(parser) || parser->tok != ';') {
1983         parseerror(parser, "expected semicolon after condition");
1984         ast_delete(ontrue);
1985         ast_delete(cond);
1986         return false;
1987     }
1988
1989     if (!parser_next(parser)) {
1990         parseerror(parser, "parse error");
1991         ast_delete(ontrue);
1992         ast_delete(cond);
1993         return false;
1994     }
1995
1996     aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1997     *out = (ast_expression*)aloop;
1998     return true;
1999 }
2000
2001 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2002 {
2003     ast_loop       *aloop;
2004     ast_expression *initexpr, *cond, *increment, *ontrue;
2005     ast_value      *typevar;
2006     bool   retval = true;
2007
2008     lex_ctx ctx = parser_ctx(parser);
2009
2010     parser_enterblock(parser);
2011
2012     initexpr  = NULL;
2013     cond      = NULL;
2014     increment = NULL;
2015     ontrue    = NULL;
2016
2017     /* skip the 'while' and check for opening paren */
2018     if (!parser_next(parser) || parser->tok != '(') {
2019         parseerror(parser, "expected 'for' expressions in parenthesis");
2020         goto onerr;
2021     }
2022     /* parse into the expression */
2023     if (!parser_next(parser)) {
2024         parseerror(parser, "expected 'for' initializer after opening paren");
2025         goto onerr;
2026     }
2027
2028     typevar = NULL;
2029     if (parser->tok == TOKEN_IDENT)
2030         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2031
2032     if (typevar || parser->tok == TOKEN_TYPENAME) {
2033         if (opts_standard != COMPILER_GMQCC) {
2034             if (parsewarning(parser, WARN_EXTENSIONS,
2035                              "current standard does not allow variable declarations in for-loop initializers"))
2036                 goto onerr;
2037         }
2038         if (!parse_variable(parser, block, true, CV_VAR, typevar, false))
2039             goto onerr;
2040     }
2041     else if (parser->tok != ';')
2042     {
2043         initexpr = parse_expression_leave(parser, false);
2044         if (!initexpr)
2045             goto onerr;
2046     }
2047
2048     /* move on to condition */
2049     if (parser->tok != ';') {
2050         parseerror(parser, "expected semicolon after for-loop initializer");
2051         goto onerr;
2052     }
2053     if (!parser_next(parser)) {
2054         parseerror(parser, "expected for-loop condition");
2055         goto onerr;
2056     }
2057
2058     /* parse the condition */
2059     if (parser->tok != ';') {
2060         cond = parse_expression_leave(parser, false);
2061         if (!cond)
2062             goto onerr;
2063     }
2064
2065     /* move on to incrementor */
2066     if (parser->tok != ';') {
2067         parseerror(parser, "expected semicolon after for-loop initializer");
2068         goto onerr;
2069     }
2070     if (!parser_next(parser)) {
2071         parseerror(parser, "expected for-loop condition");
2072         goto onerr;
2073     }
2074
2075     /* parse the incrementor */
2076     if (parser->tok != ')') {
2077         increment = parse_expression_leave(parser, false);
2078         if (!increment)
2079             goto onerr;
2080         if (!ast_side_effects(increment)) {
2081             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2082                 goto onerr;
2083         }
2084     }
2085
2086     /* closing paren */
2087     if (parser->tok != ')') {
2088         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2089         goto onerr;
2090     }
2091     /* parse into the 'then' branch */
2092     if (!parser_next(parser)) {
2093         parseerror(parser, "expected for-loop body");
2094         goto onerr;
2095     }
2096     if (!parse_statement_or_block(parser, &ontrue))
2097         goto onerr;
2098
2099     aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
2100     *out = (ast_expression*)aloop;
2101
2102     if (!parser_leaveblock(parser))
2103         retval = false;
2104     return retval;
2105 onerr:
2106     if (initexpr)  ast_delete(initexpr);
2107     if (cond)      ast_delete(cond);
2108     if (increment) ast_delete(increment);
2109     (void)!parser_leaveblock(parser);
2110     return false;
2111 }
2112
2113 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2114 {
2115     ast_expression *exp = NULL;
2116     ast_return     *ret = NULL;
2117     ast_value      *expected = parser->function->vtype;
2118
2119     lex_ctx ctx = parser_ctx(parser);
2120
2121     (void)block; /* not touching */
2122
2123     if (!parser_next(parser)) {
2124         parseerror(parser, "expected return expression");
2125         return false;
2126     }
2127
2128     if (parser->tok != ';') {
2129         exp = parse_expression(parser, false);
2130         if (!exp)
2131             return false;
2132
2133         if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2134             parseerror(parser, "return with invalid expression");
2135         }
2136
2137         ret = ast_return_new(exp->expression.node.context, exp);
2138         if (!ret) {
2139             ast_delete(exp);
2140             return false;
2141         }
2142     } else {
2143         if (!parser_next(parser))
2144             parseerror(parser, "parse error");
2145         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2146             if (opts_standard != COMPILER_GMQCC)
2147                 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2148             else
2149                 parseerror(parser, "return without value");
2150         }
2151         ret = ast_return_new(ctx, NULL);
2152     }
2153     *out = (ast_expression*)ret;
2154     return true;
2155 }
2156
2157 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2158 {
2159     lex_ctx ctx = parser_ctx(parser);
2160
2161     (void)block; /* not touching */
2162
2163     if (!parser_next(parser) || parser->tok != ';') {
2164         parseerror(parser, "expected semicolon");
2165         return false;
2166     }
2167
2168     if (!parser_next(parser))
2169         parseerror(parser, "parse error");
2170
2171     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2172     return true;
2173 }
2174
2175 /* returns true when it was a variable qualifier, false otherwise!
2176  * on error, cvq is set to CV_WRONG
2177  */
2178 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref)
2179 {
2180     bool had_const = false;
2181     bool had_var   = false;
2182     bool had_noref = false;
2183
2184     for (;;) {
2185         if (!strcmp(parser_tokval(parser), "const"))
2186             had_const = true;
2187         else if (!strcmp(parser_tokval(parser), "var"))
2188             had_var = true;
2189         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2190             had_var = true;
2191         else if (!strcmp(parser_tokval(parser), "noref"))
2192             had_noref = true;
2193         else if (!had_const && !had_var && !had_noref) {
2194             return false;
2195         }
2196         else
2197             break;
2198         if (!parser_next(parser))
2199             goto onerr;
2200     }
2201     if (had_const)
2202         *cvq = CV_CONST;
2203     else if (had_var)
2204         *cvq = CV_VAR;
2205     else
2206         *cvq = CV_NONE;
2207     *noref = had_noref;
2208     return true;
2209 onerr:
2210     parseerror(parser, "parse error after variable qualifier");
2211     *cvq = CV_WRONG;
2212     return true;
2213 }
2214
2215 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2216 {
2217     ast_expression *operand;
2218     ast_value      *opval;
2219     ast_value      *typevar;
2220     ast_switch     *switchnode;
2221     ast_switch_case swcase;
2222
2223     int  cvq;
2224     bool noref;
2225
2226     lex_ctx ctx = parser_ctx(parser);
2227
2228     (void)block; /* not touching */
2229     (void)opval;
2230
2231     /* parse over the opening paren */
2232     if (!parser_next(parser) || parser->tok != '(') {
2233         parseerror(parser, "expected switch operand in parenthesis");
2234         return false;
2235     }
2236
2237     /* parse into the expression */
2238     if (!parser_next(parser)) {
2239         parseerror(parser, "expected switch operand");
2240         return false;
2241     }
2242     /* parse the operand */
2243     operand = parse_expression_leave(parser, false);
2244     if (!operand)
2245         return false;
2246
2247     switchnode = ast_switch_new(ctx, operand);
2248
2249     /* closing paren */
2250     if (parser->tok != ')') {
2251         ast_delete(switchnode);
2252         parseerror(parser, "expected closing paren after 'switch' operand");
2253         return false;
2254     }
2255
2256     /* parse over the opening paren */
2257     if (!parser_next(parser) || parser->tok != '{') {
2258         ast_delete(switchnode);
2259         parseerror(parser, "expected list of cases");
2260         return false;
2261     }
2262
2263     if (!parser_next(parser)) {
2264         ast_delete(switchnode);
2265         parseerror(parser, "expected 'case' or 'default'");
2266         return false;
2267     }
2268
2269     /* new block; allow some variables to be declared here */
2270     parser_enterblock(parser);
2271     while (true) {
2272         typevar = NULL;
2273         if (parser->tok == TOKEN_IDENT)
2274             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2275         if (typevar || parser->tok == TOKEN_TYPENAME) {
2276             if (!parse_variable(parser, block, false, CV_NONE, typevar, false)) {
2277                 ast_delete(switchnode);
2278                 return false;
2279             }
2280             continue;
2281         }
2282         if (parse_var_qualifiers(parser, true, &cvq, &noref))
2283         {
2284             if (cvq == CV_WRONG) {
2285                 ast_delete(switchnode);
2286                 return false;
2287             }
2288             if (!parse_variable(parser, block, false, cvq, NULL, noref)) {
2289                 ast_delete(switchnode);
2290                 return false;
2291             }
2292             continue;
2293         }
2294         break;
2295     }
2296
2297     /* case list! */
2298     while (parser->tok != '}') {
2299         ast_block *caseblock;
2300
2301         if (parser->tok != TOKEN_KEYWORD) {
2302             ast_delete(switchnode);
2303             parseerror(parser, "expected 'case' or 'default'");
2304             return false;
2305         }
2306         if (!strcmp(parser_tokval(parser), "case")) {
2307             if (!parser_next(parser)) {
2308                 ast_delete(switchnode);
2309                 parseerror(parser, "expected expression for case");
2310                 return false;
2311             }
2312             swcase.value = parse_expression_leave(parser, false);
2313             if (!swcase.value) {
2314                 ast_delete(switchnode);
2315                 parseerror(parser, "expected expression for case");
2316                 return false;
2317             }
2318             if (!OPTS_FLAG(RELAXED_SWITCH)) {
2319                 opval = (ast_value*)swcase.value;
2320                 if (!ast_istype(swcase.value, ast_value)) { /* || opval->cvq != CV_CONST) { */
2321                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2322                     ast_unref(operand);
2323                     return false;
2324                 }
2325             }
2326         }
2327         else if (!strcmp(parser_tokval(parser), "default")) {
2328             swcase.value = NULL;
2329             if (!parser_next(parser)) {
2330                 ast_delete(switchnode);
2331                 parseerror(parser, "expected colon");
2332                 return false;
2333             }
2334         }
2335
2336         /* Now the colon and body */
2337         if (parser->tok != ':') {
2338             if (swcase.value) ast_unref(swcase.value);
2339             ast_delete(switchnode);
2340             parseerror(parser, "expected colon");
2341             return false;
2342         }
2343
2344         if (!parser_next(parser)) {
2345             if (swcase.value) ast_unref(swcase.value);
2346             ast_delete(switchnode);
2347             parseerror(parser, "expected statements or case");
2348             return false;
2349         }
2350         caseblock = ast_block_new(parser_ctx(parser));
2351         if (!caseblock) {
2352             if (swcase.value) ast_unref(swcase.value);
2353             ast_delete(switchnode);
2354             return false;
2355         }
2356         swcase.code = (ast_expression*)caseblock;
2357         vec_push(switchnode->cases, swcase);
2358         while (true) {
2359             ast_expression *expr;
2360             if (parser->tok == '}')
2361                 break;
2362             if (parser->tok == TOKEN_KEYWORD) {
2363                 if (!strcmp(parser_tokval(parser), "case") ||
2364                     !strcmp(parser_tokval(parser), "default"))
2365                 {
2366                     break;
2367                 }
2368             }
2369             if (!parse_statement(parser, caseblock, &expr, true)) {
2370                 ast_delete(switchnode);
2371                 return false;
2372             }
2373             if (!expr)
2374                 continue;
2375             if (!ast_block_add_expr(caseblock, expr)) {
2376                 ast_delete(switchnode);
2377                 return false;
2378             }
2379         }
2380     }
2381
2382     parser_leaveblock(parser);
2383
2384     /* closing paren */
2385     if (parser->tok != '}') {
2386         ast_delete(switchnode);
2387         parseerror(parser, "expected closing paren of case list");
2388         return false;
2389     }
2390     if (!parser_next(parser)) {
2391         ast_delete(switchnode);
2392         parseerror(parser, "parse error after switch");
2393         return false;
2394     }
2395     *out = (ast_expression*)switchnode;
2396     return true;
2397 }
2398
2399 static bool parse_goto(parser_t *parser, ast_expression **out)
2400 {
2401     size_t    i;
2402     ast_goto *gt;
2403
2404     if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2405         parseerror(parser, "expected label name after `goto`");
2406         return false;
2407     }
2408
2409     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2410
2411     for (i = 0; i < vec_size(parser->labels); ++i) {
2412         if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2413             ast_goto_set_label(gt, parser->labels[i]);
2414             break;
2415         }
2416     }
2417     if (i == vec_size(parser->labels))
2418         vec_push(parser->gotos, gt);
2419
2420     if (!parser_next(parser) || parser->tok != ';') {
2421         parseerror(parser, "semicolon expected after goto label");
2422         return false;
2423     }
2424     if (!parser_next(parser)) {
2425         parseerror(parser, "parse error after goto");
2426         return false;
2427     }
2428
2429     *out = (ast_expression*)gt;
2430     return true;
2431 }
2432
2433 static bool parse_skipwhite(parser_t *parser)
2434 {
2435     do {
2436         if (!parser_next(parser))
2437             return false;
2438     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2439     return parser->tok < TOKEN_ERROR;
2440 }
2441
2442 static bool parse_eol(parser_t *parser)
2443 {
2444     if (!parse_skipwhite(parser))
2445         return false;
2446     return parser->tok == TOKEN_EOL;
2447 }
2448
2449 static bool parse_pragma_do(parser_t *parser)
2450 {
2451     if (!parser_next(parser) ||
2452         parser->tok != TOKEN_IDENT ||
2453         strcmp(parser_tokval(parser), "pragma"))
2454     {
2455         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2456         return false;
2457     }
2458     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2459         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2460         return false;
2461     }
2462
2463     if (!strcmp(parser_tokval(parser), "noref")) {
2464         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2465             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2466             return false;
2467         }
2468         parser->noref = !!parser_token(parser)->constval.i;
2469         if (!parse_eol(parser)) {
2470             parseerror(parser, "parse error after `noref` pragma");
2471             return false;
2472         }
2473     }
2474     else
2475     {
2476         parseerror(parser, "unrecognized hash-keyword: `%s`", parser_tokval(parser));
2477         return false;
2478     }
2479
2480     return true;
2481 }
2482
2483 static bool parse_pragma(parser_t *parser)
2484 {
2485     bool rv;
2486     parser->lex->flags.preprocessing = true;
2487     parser->lex->flags.mergelines = true;
2488     rv = parse_pragma_do(parser);
2489     if (parser->tok != TOKEN_EOL) {
2490         parseerror(parser, "junk after pragma");
2491         rv = false;
2492     }
2493     parser->lex->flags.preprocessing = false;
2494     parser->lex->flags.mergelines = false;
2495     if (!parser_next(parser)) {
2496         parseerror(parser, "parse error after pragma");
2497         rv = false;
2498     }
2499     return rv;
2500 }
2501
2502 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2503 {
2504     bool       noref;
2505     int        cvq = CV_NONE;
2506     ast_value *typevar = NULL;
2507
2508     *out = NULL;
2509
2510     if (parser->tok == TOKEN_IDENT)
2511         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2512
2513     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2514     {
2515         /* local variable */
2516         if (!block) {
2517             parseerror(parser, "cannot declare a variable from here");
2518             return false;
2519         }
2520         if (opts_standard == COMPILER_QCC) {
2521             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2522                 return false;
2523         }
2524         if (!parse_variable(parser, block, false, CV_NONE, typevar, false))
2525             return false;
2526         return true;
2527     }
2528     else if (parse_var_qualifiers(parser, !!block, &cvq, &noref))
2529     {
2530         if (cvq == CV_WRONG)
2531             return false;
2532         return parse_variable(parser, block, true, cvq, NULL, noref);
2533     }
2534     else if (parser->tok == TOKEN_KEYWORD)
2535     {
2536         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2537         {
2538             char ty[1024];
2539             ast_value *tdef;
2540
2541             if (!parser_next(parser)) {
2542                 parseerror(parser, "parse error after __builtin_debug_printtype");
2543                 return false;
2544             }
2545
2546             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2547             {
2548                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2549                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2550                 if (!parser_next(parser)) {
2551                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2552                     return false;
2553                 }
2554             }
2555             else
2556             {
2557                 if (!parse_statement(parser, block, out, allow_cases))
2558                     return false;
2559                 if (!*out)
2560                     con_out("__builtin_debug_printtype: got no output node\n");
2561                 else
2562                 {
2563                     ast_type_to_string(*out, ty, sizeof(ty));
2564                     con_out("__builtin_debug_printtype: `%s`\n", ty);
2565                 }
2566             }
2567             return true;
2568         }
2569         else if (!strcmp(parser_tokval(parser), "return"))
2570         {
2571             return parse_return(parser, block, out);
2572         }
2573         else if (!strcmp(parser_tokval(parser), "if"))
2574         {
2575             return parse_if(parser, block, out);
2576         }
2577         else if (!strcmp(parser_tokval(parser), "while"))
2578         {
2579             return parse_while(parser, block, out);
2580         }
2581         else if (!strcmp(parser_tokval(parser), "do"))
2582         {
2583             return parse_dowhile(parser, block, out);
2584         }
2585         else if (!strcmp(parser_tokval(parser), "for"))
2586         {
2587             if (opts_standard == COMPILER_QCC) {
2588                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2589                     return false;
2590             }
2591             return parse_for(parser, block, out);
2592         }
2593         else if (!strcmp(parser_tokval(parser), "break"))
2594         {
2595             return parse_break_continue(parser, block, out, false);
2596         }
2597         else if (!strcmp(parser_tokval(parser), "continue"))
2598         {
2599             return parse_break_continue(parser, block, out, true);
2600         }
2601         else if (!strcmp(parser_tokval(parser), "switch"))
2602         {
2603             return parse_switch(parser, block, out);
2604         }
2605         else if (!strcmp(parser_tokval(parser), "case") ||
2606                  !strcmp(parser_tokval(parser), "default"))
2607         {
2608             if (!allow_cases) {
2609                 parseerror(parser, "unexpected 'case' label");
2610                 return false;
2611             }
2612             return true;
2613         }
2614         else if (!strcmp(parser_tokval(parser), "goto"))
2615         {
2616             return parse_goto(parser, out);
2617         }
2618         else if (!strcmp(parser_tokval(parser), "typedef"))
2619         {
2620             if (!parser_next(parser)) {
2621                 parseerror(parser, "expected type definition after 'typedef'");
2622                 return false;
2623             }
2624             return parse_typedef(parser);
2625         }
2626         parseerror(parser, "Unexpected keyword");
2627         return false;
2628     }
2629     else if (parser->tok == '{')
2630     {
2631         ast_block *inner;
2632         inner = parse_block(parser);
2633         if (!inner)
2634             return false;
2635         *out = (ast_expression*)inner;
2636         return true;
2637     }
2638     else if (parser->tok == ':')
2639     {
2640         size_t i;
2641         ast_label *label;
2642         if (!parser_next(parser)) {
2643             parseerror(parser, "expected label name");
2644             return false;
2645         }
2646         if (parser->tok != TOKEN_IDENT) {
2647             parseerror(parser, "label must be an identifier");
2648             return false;
2649         }
2650         label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2651         if (!label)
2652             return false;
2653         vec_push(parser->labels, label);
2654         *out = (ast_expression*)label;
2655         if (!parser_next(parser)) {
2656             parseerror(parser, "parse error after label");
2657             return false;
2658         }
2659         for (i = 0; i < vec_size(parser->gotos); ++i) {
2660             if (!strcmp(parser->gotos[i]->name, label->name)) {
2661                 ast_goto_set_label(parser->gotos[i], label);
2662                 vec_remove(parser->gotos, i, 1);
2663                 --i;
2664             }
2665         }
2666         return true;
2667     }
2668     else if (parser->tok == ';')
2669     {
2670         if (!parser_next(parser)) {
2671             parseerror(parser, "parse error after empty statement");
2672             return false;
2673         }
2674         return true;
2675     }
2676     else
2677     {
2678         ast_expression *exp = parse_expression(parser, false);
2679         if (!exp)
2680             return false;
2681         *out = exp;
2682         if (!ast_side_effects(exp)) {
2683             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2684                 return false;
2685         }
2686         return true;
2687     }
2688 }
2689
2690 static bool parse_block_into(parser_t *parser, ast_block *block)
2691 {
2692     bool   retval = true;
2693
2694     parser_enterblock(parser);
2695
2696     if (!parser_next(parser)) { /* skip the '{' */
2697         parseerror(parser, "expected function body");
2698         goto cleanup;
2699     }
2700
2701     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2702     {
2703         ast_expression *expr = NULL;
2704         if (parser->tok == '}')
2705             break;
2706
2707         if (!parse_statement(parser, block, &expr, false)) {
2708             /* parseerror(parser, "parse error"); */
2709             block = NULL;
2710             goto cleanup;
2711         }
2712         if (!expr)
2713             continue;
2714         if (!ast_block_add_expr(block, expr)) {
2715             ast_delete(block);
2716             block = NULL;
2717             goto cleanup;
2718         }
2719     }
2720
2721     if (parser->tok != '}') {
2722         block = NULL;
2723     } else {
2724         (void)parser_next(parser);
2725     }
2726
2727 cleanup:
2728     if (!parser_leaveblock(parser))
2729         retval = false;
2730     return retval && !!block;
2731 }
2732
2733 static ast_block* parse_block(parser_t *parser)
2734 {
2735     ast_block *block;
2736     block = ast_block_new(parser_ctx(parser));
2737     if (!block)
2738         return NULL;
2739     if (!parse_block_into(parser, block)) {
2740         ast_block_delete(block);
2741         return NULL;
2742     }
2743     return block;
2744 }
2745
2746 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2747 {
2748     if (parser->tok == '{') {
2749         *out = (ast_expression*)parse_block(parser);
2750         return !!*out;
2751     }
2752     return parse_statement(parser, NULL, out, false);
2753 }
2754
2755 static bool create_vector_members(ast_value *var, ast_member **me)
2756 {
2757     size_t i;
2758     size_t len = strlen(var->name);
2759
2760     for (i = 0; i < 3; ++i) {
2761         char *name = mem_a(len+3);
2762         memcpy(name, var->name, len);
2763         name[len+0] = '_';
2764         name[len+1] = 'x'+i;
2765         name[len+2] = 0;
2766         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2767         mem_d(name);
2768         if (!me[i])
2769             break;
2770     }
2771     if (i == 3)
2772         return true;
2773
2774     /* unroll */
2775     do { ast_member_delete(me[--i]); } while(i);
2776     return false;
2777 }
2778
2779 static bool parse_function_body(parser_t *parser, ast_value *var)
2780 {
2781     ast_block      *block = NULL;
2782     ast_function   *func;
2783     ast_function   *old;
2784     size_t          parami;
2785
2786     ast_expression *framenum  = NULL;
2787     ast_expression *nextthink = NULL;
2788     /* None of the following have to be deleted */
2789     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2790     ast_expression *gbl_time = NULL, *gbl_self = NULL;
2791     bool            has_frame_think;
2792
2793     bool retval = true;
2794
2795     has_frame_think = false;
2796     old = parser->function;
2797
2798     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
2799         parseerror(parser, "gotos/labels leaking");
2800         return false;
2801     }
2802
2803     if (var->expression.variadic) {
2804         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2805                          "variadic function with implementation will not be able to access additional parameters"))
2806         {
2807             return false;
2808         }
2809     }
2810
2811     if (parser->tok == '[') {
2812         /* got a frame definition: [ framenum, nextthink ]
2813          * this translates to:
2814          * self.frame = framenum;
2815          * self.nextthink = time + 0.1;
2816          * self.think = nextthink;
2817          */
2818         nextthink = NULL;
2819
2820         fld_think     = parser_find_field(parser, "think");
2821         fld_nextthink = parser_find_field(parser, "nextthink");
2822         fld_frame     = parser_find_field(parser, "frame");
2823         if (!fld_think || !fld_nextthink || !fld_frame) {
2824             parseerror(parser, "cannot use [frame,think] notation without the required fields");
2825             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2826             return false;
2827         }
2828         gbl_time      = parser_find_global(parser, "time");
2829         gbl_self      = parser_find_global(parser, "self");
2830         if (!gbl_time || !gbl_self) {
2831             parseerror(parser, "cannot use [frame,think] notation without the required globals");
2832             parseerror(parser, "please declare the following globals: `time`, `self`");
2833             return false;
2834         }
2835
2836         if (!parser_next(parser))
2837             return false;
2838
2839         framenum = parse_expression_leave(parser, true);
2840         if (!framenum) {
2841             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2842             return false;
2843         }
2844         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
2845             ast_unref(framenum);
2846             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2847             return false;
2848         }
2849
2850         if (parser->tok != ',') {
2851             ast_unref(framenum);
2852             parseerror(parser, "expected comma after frame number in [frame,think] notation");
2853             parseerror(parser, "Got a %i\n", parser->tok);
2854             return false;
2855         }
2856
2857         if (!parser_next(parser)) {
2858             ast_unref(framenum);
2859             return false;
2860         }
2861
2862         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2863         {
2864             /* qc allows the use of not-yet-declared functions here
2865              * - this automatically creates a prototype */
2866             ast_value      *thinkfunc;
2867             ast_expression *functype = fld_think->expression.next;
2868
2869             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2870             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2871                 ast_unref(framenum);
2872                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2873                 return false;
2874             }
2875
2876             if (!parser_next(parser)) {
2877                 ast_unref(framenum);
2878                 ast_delete(thinkfunc);
2879                 return false;
2880             }
2881
2882             vec_push(parser->globals, (ast_expression*)thinkfunc);
2883             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2884             nextthink = (ast_expression*)thinkfunc;
2885
2886         } else {
2887             nextthink = parse_expression_leave(parser, true);
2888             if (!nextthink) {
2889                 ast_unref(framenum);
2890                 parseerror(parser, "expected a think-function in [frame,think] notation");
2891                 return false;
2892             }
2893         }
2894
2895         if (!ast_istype(nextthink, ast_value)) {
2896             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2897             retval = false;
2898         }
2899
2900         if (retval && parser->tok != ']') {
2901             parseerror(parser, "expected closing `]` for [frame,think] notation");
2902             retval = false;
2903         }
2904
2905         if (retval && !parser_next(parser)) {
2906             retval = false;
2907         }
2908
2909         if (retval && parser->tok != '{') {
2910             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2911             retval = false;
2912         }
2913
2914         if (!retval) {
2915             ast_unref(nextthink);
2916             ast_unref(framenum);
2917             return false;
2918         }
2919
2920         has_frame_think = true;
2921     }
2922
2923     block = ast_block_new(parser_ctx(parser));
2924     if (!block) {
2925         parseerror(parser, "failed to allocate block");
2926         if (has_frame_think) {
2927             ast_unref(nextthink);
2928             ast_unref(framenum);
2929         }
2930         return false;
2931     }
2932
2933     if (has_frame_think) {
2934         lex_ctx ctx;
2935         ast_expression *self_frame;
2936         ast_expression *self_nextthink;
2937         ast_expression *self_think;
2938         ast_expression *time_plus_1;
2939         ast_store *store_frame;
2940         ast_store *store_nextthink;
2941         ast_store *store_think;
2942
2943         ctx = parser_ctx(parser);
2944         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2945         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2946         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2947
2948         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2949                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2950
2951         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2952             if (self_frame)     ast_delete(self_frame);
2953             if (self_nextthink) ast_delete(self_nextthink);
2954             if (self_think)     ast_delete(self_think);
2955             if (time_plus_1)    ast_delete(time_plus_1);
2956             retval = false;
2957         }
2958
2959         if (retval)
2960         {
2961             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2962             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2963             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2964
2965             if (!store_frame) {
2966                 ast_delete(self_frame);
2967                 retval = false;
2968             }
2969             if (!store_nextthink) {
2970                 ast_delete(self_nextthink);
2971                 retval = false;
2972             }
2973             if (!store_think) {
2974                 ast_delete(self_think);
2975                 retval = false;
2976             }
2977             if (!retval) {
2978                 if (store_frame)     ast_delete(store_frame);
2979                 if (store_nextthink) ast_delete(store_nextthink);
2980                 if (store_think)     ast_delete(store_think);
2981                 retval = false;
2982             }
2983             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
2984                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
2985                 !ast_block_add_expr(block, (ast_expression*)store_think))
2986             {
2987                 retval = false;
2988             }
2989         }
2990
2991         if (!retval) {
2992             parseerror(parser, "failed to generate code for [frame,think]");
2993             ast_unref(nextthink);
2994             ast_unref(framenum);
2995             ast_delete(block);
2996             return false;
2997         }
2998     }
2999
3000     parser_enterblock(parser);
3001
3002     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3003         size_t     e;
3004         ast_value *param = var->expression.params[parami];
3005         ast_member *me[3];
3006
3007         if (param->expression.vtype != TYPE_VECTOR &&
3008             (param->expression.vtype != TYPE_FIELD ||
3009              param->expression.next->expression.vtype != TYPE_VECTOR))
3010         {
3011             continue;
3012         }
3013
3014         if (!create_vector_members(param, me)) {
3015             ast_block_delete(block);
3016             return false;
3017         }
3018
3019         for (e = 0; e < 3; ++e) {
3020             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3021             ast_block_collect(block, (ast_expression*)me[e]);
3022         }
3023     }
3024
3025     func = ast_function_new(ast_ctx(var), var->name, var);
3026     if (!func) {
3027         parseerror(parser, "failed to allocate function for `%s`", var->name);
3028         ast_block_delete(block);
3029         goto enderr;
3030     }
3031     vec_push(parser->functions, func);
3032
3033     parser->function = func;
3034     if (!parse_block_into(parser, block)) {
3035         ast_block_delete(block);
3036         goto enderrfn;
3037     }
3038
3039     vec_push(func->blocks, block);
3040
3041     parser->function = old;
3042     if (!parser_leaveblock(parser))
3043         retval = false;
3044     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3045         parseerror(parser, "internal error: local scopes left");
3046         retval = false;
3047     }
3048
3049     if (parser->tok == ';')
3050         return parser_next(parser);
3051     else if (opts_standard == COMPILER_QCC)
3052         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3053     return retval;
3054
3055 enderrfn:
3056     vec_pop(parser->functions);
3057     ast_function_delete(func);
3058     var->constval.vfunc = NULL;
3059
3060 enderr:
3061     (void)!parser_leaveblock(parser);
3062     parser->function = old;
3063     return false;
3064 }
3065
3066 static ast_expression *array_accessor_split(
3067     parser_t  *parser,
3068     ast_value *array,
3069     ast_value *index,
3070     size_t     middle,
3071     ast_expression *left,
3072     ast_expression *right
3073     )
3074 {
3075     ast_ifthen *ifthen;
3076     ast_binary *cmp;
3077
3078     lex_ctx ctx = ast_ctx(array);
3079
3080     if (!left || !right) {
3081         if (left)  ast_delete(left);
3082         if (right) ast_delete(right);
3083         return NULL;
3084     }
3085
3086     cmp = ast_binary_new(ctx, INSTR_LT,
3087                          (ast_expression*)index,
3088                          (ast_expression*)parser_const_float(parser, middle));
3089     if (!cmp) {
3090         ast_delete(left);
3091         ast_delete(right);
3092         parseerror(parser, "internal error: failed to create comparison for array setter");
3093         return NULL;
3094     }
3095
3096     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3097     if (!ifthen) {
3098         ast_delete(cmp); /* will delete left and right */
3099         parseerror(parser, "internal error: failed to create conditional jump for array setter");
3100         return NULL;
3101     }
3102
3103     return (ast_expression*)ifthen;
3104 }
3105
3106 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3107 {
3108     lex_ctx ctx = ast_ctx(array);
3109
3110     if (from+1 == afterend) {
3111         /* set this value */
3112         ast_block       *block;
3113         ast_return      *ret;
3114         ast_array_index *subscript;
3115         ast_store       *st;
3116         int assignop = type_store_instr[value->expression.vtype];
3117
3118         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3119             assignop = INSTR_STORE_V;
3120
3121         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3122         if (!subscript)
3123             return NULL;
3124
3125         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3126         if (!st) {
3127             ast_delete(subscript);
3128             return NULL;
3129         }
3130
3131         block = ast_block_new(ctx);
3132         if (!block) {
3133             ast_delete(st);
3134             return NULL;
3135         }
3136
3137         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3138             ast_delete(block);
3139             return NULL;
3140         }
3141
3142         ret = ast_return_new(ctx, NULL);
3143         if (!ret) {
3144             ast_delete(block);
3145             return NULL;
3146         }
3147
3148         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3149             ast_delete(block);
3150             return NULL;
3151         }
3152
3153         return (ast_expression*)block;
3154     } else {
3155         ast_expression *left, *right;
3156         size_t diff = afterend - from;
3157         size_t middle = from + diff/2;
3158         left  = array_setter_node(parser, array, index, value, from, middle);
3159         right = array_setter_node(parser, array, index, value, middle, afterend);
3160         return array_accessor_split(parser, array, index, middle, left, right);
3161     }
3162 }
3163
3164 static ast_expression *array_field_setter_node(
3165     parser_t  *parser,
3166     ast_value *array,
3167     ast_value *entity,
3168     ast_value *index,
3169     ast_value *value,
3170     size_t     from,
3171     size_t     afterend)
3172 {
3173     lex_ctx ctx = ast_ctx(array);
3174
3175     if (from+1 == afterend) {
3176         /* set this value */
3177         ast_block       *block;
3178         ast_return      *ret;
3179         ast_entfield    *entfield;
3180         ast_array_index *subscript;
3181         ast_store       *st;
3182         int assignop = type_storep_instr[value->expression.vtype];
3183
3184         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3185             assignop = INSTR_STOREP_V;
3186
3187         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3188         if (!subscript)
3189             return NULL;
3190
3191         entfield = ast_entfield_new_force(ctx,
3192                                           (ast_expression*)entity,
3193                                           (ast_expression*)subscript,
3194                                           (ast_expression*)subscript);
3195         if (!entfield) {
3196             ast_delete(subscript);
3197             return NULL;
3198         }
3199
3200         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3201         if (!st) {
3202             ast_delete(entfield);
3203             return NULL;
3204         }
3205
3206         block = ast_block_new(ctx);
3207         if (!block) {
3208             ast_delete(st);
3209             return NULL;
3210         }
3211
3212         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3213             ast_delete(block);
3214             return NULL;
3215         }
3216
3217         ret = ast_return_new(ctx, NULL);
3218         if (!ret) {
3219             ast_delete(block);
3220             return NULL;
3221         }
3222
3223         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3224             ast_delete(block);
3225             return NULL;
3226         }
3227
3228         return (ast_expression*)block;
3229     } else {
3230         ast_expression *left, *right;
3231         size_t diff = afterend - from;
3232         size_t middle = from + diff/2;
3233         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
3234         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3235         return array_accessor_split(parser, array, index, middle, left, right);
3236     }
3237 }
3238
3239 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3240 {
3241     lex_ctx ctx = ast_ctx(array);
3242
3243     if (from+1 == afterend) {
3244         ast_return      *ret;
3245         ast_array_index *subscript;
3246
3247         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3248         if (!subscript)
3249             return NULL;
3250
3251         ret = ast_return_new(ctx, (ast_expression*)subscript);
3252         if (!ret) {
3253             ast_delete(subscript);
3254             return NULL;
3255         }
3256
3257         return (ast_expression*)ret;
3258     } else {
3259         ast_expression *left, *right;
3260         size_t diff = afterend - from;
3261         size_t middle = from + diff/2;
3262         left  = array_getter_node(parser, array, index, from, middle);
3263         right = array_getter_node(parser, array, index, middle, afterend);
3264         return array_accessor_split(parser, array, index, middle, left, right);
3265     }
3266 }
3267
3268 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3269 {
3270     ast_function   *func = NULL;
3271     ast_value      *fval = NULL;
3272     ast_block      *body = NULL;
3273
3274     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3275     if (!fval) {
3276         parseerror(parser, "failed to create accessor function value");
3277         return false;
3278     }
3279
3280     func = ast_function_new(ast_ctx(array), funcname, fval);
3281     if (!func) {
3282         ast_delete(fval);
3283         parseerror(parser, "failed to create accessor function node");
3284         return false;
3285     }
3286
3287     body = ast_block_new(ast_ctx(array));
3288     if (!body) {
3289         parseerror(parser, "failed to create block for array accessor");
3290         ast_delete(fval);
3291         ast_delete(func);
3292         return false;
3293     }
3294
3295     vec_push(func->blocks, body);
3296     *out = fval;
3297
3298     vec_push(parser->accessors, fval);
3299
3300     return true;
3301 }
3302
3303 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3304 {
3305     ast_expression *root = NULL;
3306     ast_value      *index = NULL;
3307     ast_value      *value = NULL;
3308     ast_function   *func;
3309     ast_value      *fval;
3310
3311     if (!ast_istype(array->expression.next, ast_value)) {
3312         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3313         return false;
3314     }
3315
3316     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3317         return false;
3318     func = fval->constval.vfunc;
3319     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3320
3321     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3322     value = ast_value_copy((ast_value*)array->expression.next);
3323
3324     if (!index || !value) {
3325         parseerror(parser, "failed to create locals for array accessor");
3326         goto cleanup;
3327     }
3328     (void)!ast_value_set_name(value, "value"); /* not important */
3329     vec_push(fval->expression.params, index);
3330     vec_push(fval->expression.params, value);
3331
3332     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3333     if (!root) {
3334         parseerror(parser, "failed to build accessor search tree");
3335         goto cleanup;
3336     }
3337
3338     array->setter = fval;
3339     return ast_block_add_expr(func->blocks[0], root);
3340 cleanup:
3341     if (index) ast_delete(index);
3342     if (value) ast_delete(value);
3343     if (root)  ast_delete(root);
3344     ast_delete(func);
3345     ast_delete(fval);
3346     return false;
3347 }
3348
3349 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3350 {
3351     ast_expression *root = NULL;
3352     ast_value      *entity = NULL;
3353     ast_value      *index = NULL;
3354     ast_value      *value = NULL;
3355     ast_function   *func;
3356     ast_value      *fval;
3357
3358     if (!ast_istype(array->expression.next, ast_value)) {
3359         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3360         return false;
3361     }
3362
3363     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3364         return false;
3365     func = fval->constval.vfunc;
3366     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3367
3368     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3369     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
3370     value  = ast_value_copy((ast_value*)array->expression.next);
3371     if (!entity || !index || !value) {
3372         parseerror(parser, "failed to create locals for array accessor");
3373         goto cleanup;
3374     }
3375     (void)!ast_value_set_name(value, "value"); /* not important */
3376     vec_push(fval->expression.params, entity);
3377     vec_push(fval->expression.params, index);
3378     vec_push(fval->expression.params, value);
3379
3380     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3381     if (!root) {
3382         parseerror(parser, "failed to build accessor search tree");
3383         goto cleanup;
3384     }
3385
3386     array->setter = fval;
3387     return ast_block_add_expr(func->blocks[0], root);
3388 cleanup:
3389     if (entity) ast_delete(entity);
3390     if (index)  ast_delete(index);
3391     if (value)  ast_delete(value);
3392     if (root)   ast_delete(root);
3393     ast_delete(func);
3394     ast_delete(fval);
3395     return false;
3396 }
3397
3398 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3399 {
3400     ast_expression *root = NULL;
3401     ast_value      *index = NULL;
3402     ast_value      *fval;
3403     ast_function   *func;
3404
3405     /* NOTE: checking array->expression.next rather than elemtype since
3406      * for fields elemtype is a temporary fieldtype.
3407      */
3408     if (!ast_istype(array->expression.next, ast_value)) {
3409         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3410         return false;
3411     }
3412
3413     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3414         return false;
3415     func = fval->constval.vfunc;
3416     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3417
3418     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3419
3420     if (!index) {
3421         parseerror(parser, "failed to create locals for array accessor");
3422         goto cleanup;
3423     }
3424     vec_push(fval->expression.params, index);
3425
3426     root = array_getter_node(parser, array, index, 0, array->expression.count);
3427     if (!root) {
3428         parseerror(parser, "failed to build accessor search tree");
3429         goto cleanup;
3430     }
3431
3432     array->getter = fval;
3433     return ast_block_add_expr(func->blocks[0], root);
3434 cleanup:
3435     if (index) ast_delete(index);
3436     if (root)  ast_delete(root);
3437     ast_delete(func);
3438     ast_delete(fval);
3439     return false;
3440 }
3441
3442 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3443 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3444 {
3445     lex_ctx     ctx;
3446     size_t      i;
3447     ast_value **params;
3448     ast_value  *param;
3449     ast_value  *fval;
3450     bool        first = true;
3451     bool        variadic = false;
3452
3453     ctx = parser_ctx(parser);
3454
3455     /* for the sake of less code we parse-in in this function */
3456     if (!parser_next(parser)) {
3457         parseerror(parser, "expected parameter list");
3458         return NULL;
3459     }
3460
3461     params = NULL;
3462
3463     /* parse variables until we hit a closing paren */
3464     while (parser->tok != ')') {
3465         if (!first) {
3466             /* there must be commas between them */
3467             if (parser->tok != ',') {
3468                 parseerror(parser, "expected comma or end of parameter list");
3469                 goto on_error;
3470             }
3471             if (!parser_next(parser)) {
3472                 parseerror(parser, "expected parameter");
3473                 goto on_error;
3474             }
3475         }
3476         first = false;
3477
3478         if (parser->tok == TOKEN_DOTS) {
3479             /* '...' indicates a varargs function */
3480             variadic = true;
3481             if (!parser_next(parser)) {
3482                 parseerror(parser, "expected parameter");
3483                 return NULL;
3484             }
3485             if (parser->tok != ')') {
3486                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3487                 goto on_error;
3488             }
3489         }
3490         else
3491         {
3492             /* for anything else just parse a typename */
3493             param = parse_typename(parser, NULL, NULL);
3494             if (!param)
3495                 goto on_error;
3496             vec_push(params, param);
3497             if (param->expression.vtype >= TYPE_VARIANT) {
3498                 char typename[1024];
3499                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3500                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3501                 goto on_error;
3502             }
3503         }
3504     }
3505
3506     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3507         vec_free(params);
3508
3509     /* sanity check */
3510     if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3511         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3512
3513     /* parse-out */
3514     if (!parser_next(parser)) {
3515         parseerror(parser, "parse error after typename");
3516         goto on_error;
3517     }
3518
3519     /* now turn 'var' into a function type */
3520     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3521     fval->expression.next     = (ast_expression*)var;
3522     fval->expression.variadic = variadic;
3523     var = fval;
3524
3525     var->expression.params = params;
3526     params = NULL;
3527
3528     return var;
3529
3530 on_error:
3531     ast_delete(var);
3532     for (i = 0; i < vec_size(params); ++i)
3533         ast_delete(params[i]);
3534     vec_free(params);
3535     return NULL;
3536 }
3537
3538 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3539 {
3540     ast_expression *cexp;
3541     ast_value      *cval, *tmp;
3542     lex_ctx ctx;
3543
3544     ctx = parser_ctx(parser);
3545
3546     if (!parser_next(parser)) {
3547         ast_delete(var);
3548         parseerror(parser, "expected array-size");
3549         return NULL;
3550     }
3551
3552     cexp = parse_expression_leave(parser, true);
3553
3554     if (!cexp || !ast_istype(cexp, ast_value)) {
3555         if (cexp)
3556             ast_unref(cexp);
3557         ast_delete(var);
3558         parseerror(parser, "expected array-size as constant positive integer");
3559         return NULL;
3560     }
3561     cval = (ast_value*)cexp;
3562
3563     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3564     tmp->expression.next = (ast_expression*)var;
3565     var = tmp;
3566
3567     if (cval->expression.vtype == TYPE_INTEGER)
3568         tmp->expression.count = cval->constval.vint;
3569     else if (cval->expression.vtype == TYPE_FLOAT)
3570         tmp->expression.count = cval->constval.vfloat;
3571     else {
3572         ast_unref(cexp);
3573         ast_delete(var);
3574         parseerror(parser, "array-size must be a positive integer constant");
3575         return NULL;
3576     }
3577     ast_unref(cexp);
3578
3579     if (parser->tok != ']') {
3580         ast_delete(var);
3581         parseerror(parser, "expected ']' after array-size");
3582         return NULL;
3583     }
3584     if (!parser_next(parser)) {
3585         ast_delete(var);
3586         parseerror(parser, "error after parsing array size");
3587         return NULL;
3588     }
3589     return var;
3590 }
3591
3592 /* Parse a complete typename.
3593  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3594  * but when parsing variables separated by comma
3595  * 'storebase' should point to where the base-type should be kept.
3596  * The base type makes up every bit of type information which comes *before* the
3597  * variable name.
3598  *
3599  * The following will be parsed in its entirety:
3600  *     void() foo()
3601  * The 'basetype' in this case is 'void()'
3602  * and if there's a comma after it, say:
3603  *     void() foo(), bar
3604  * then the type-information 'void()' can be stored in 'storebase'
3605  */
3606 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3607 {
3608     ast_value *var, *tmp;
3609     lex_ctx    ctx;
3610
3611     const char *name = NULL;
3612     bool        isfield  = false;
3613     bool        wasarray = false;
3614     size_t      morefields = 0;
3615
3616     ctx = parser_ctx(parser);
3617
3618     /* types may start with a dot */
3619     if (parser->tok == '.') {
3620         isfield = true;
3621         /* if we parsed a dot we need a typename now */
3622         if (!parser_next(parser)) {
3623             parseerror(parser, "expected typename for field definition");
3624             return NULL;
3625         }
3626
3627         /* Further dots are handled seperately because they won't be part of the
3628          * basetype
3629          */
3630         while (parser->tok == '.') {
3631             ++morefields;
3632             if (!parser_next(parser)) {
3633                 parseerror(parser, "expected typename for field definition");
3634                 return NULL;
3635             }
3636         }
3637     }
3638     if (parser->tok == TOKEN_IDENT)
3639         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3640     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3641         parseerror(parser, "expected typename");
3642         return NULL;
3643     }
3644
3645     /* generate the basic type value */
3646     if (cached_typedef) {
3647         var = ast_value_copy(cached_typedef);
3648         ast_value_set_name(var, "<type(from_def)>");
3649     } else
3650         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3651
3652     for (; morefields; --morefields) {
3653         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3654         tmp->expression.next = (ast_expression*)var;
3655         var = tmp;
3656     }
3657
3658     /* do not yet turn into a field - remember:
3659      * .void() foo; is a field too
3660      * .void()() foo; is a function
3661      */
3662
3663     /* parse on */
3664     if (!parser_next(parser)) {
3665         ast_delete(var);
3666         parseerror(parser, "parse error after typename");
3667         return NULL;
3668     }
3669
3670     /* an opening paren now starts the parameter-list of a function
3671      * this is where original-QC has parameter lists.
3672      * We allow a single parameter list here.
3673      * Much like fteqcc we don't allow `float()() x`
3674      */
3675     if (parser->tok == '(') {
3676         var = parse_parameter_list(parser, var);
3677         if (!var)
3678             return NULL;
3679     }
3680
3681     /* store the base if requested */
3682     if (storebase) {
3683         *storebase = ast_value_copy(var);
3684         if (isfield) {
3685             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3686             tmp->expression.next = (ast_expression*)*storebase;
3687             *storebase = tmp;
3688         }
3689     }
3690
3691     /* there may be a name now */
3692     if (parser->tok == TOKEN_IDENT) {
3693         name = util_strdup(parser_tokval(parser));
3694         /* parse on */
3695         if (!parser_next(parser)) {
3696             ast_delete(var);
3697             parseerror(parser, "error after variable or field declaration");
3698             return NULL;
3699         }
3700     }
3701
3702     /* now this may be an array */
3703     if (parser->tok == '[') {
3704         wasarray = true;
3705         var = parse_arraysize(parser, var);
3706         if (!var)
3707             return NULL;
3708     }
3709
3710     /* This is the point where we can turn it into a field */
3711     if (isfield) {
3712         /* turn it into a field if desired */
3713         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3714         tmp->expression.next = (ast_expression*)var;
3715         var = tmp;
3716     }
3717
3718     /* now there may be function parens again */
3719     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3720         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3721     if (parser->tok == '(' && wasarray)
3722         parseerror(parser, "arrays as part of a return type is not supported");
3723     while (parser->tok == '(') {
3724         var = parse_parameter_list(parser, var);
3725         if (!var) {
3726             if (name)
3727                 mem_d((void*)name);
3728             ast_delete(var);
3729             return NULL;
3730         }
3731     }
3732
3733     /* finally name it */
3734     if (name) {
3735         if (!ast_value_set_name(var, name)) {
3736             ast_delete(var);
3737             parseerror(parser, "internal error: failed to set name");
3738             return NULL;
3739         }
3740         /* free the name, ast_value_set_name duplicates */
3741         mem_d((void*)name);
3742     }
3743
3744     return var;
3745 }
3746
3747 static bool parse_typedef(parser_t *parser)
3748 {
3749     ast_value      *typevar, *oldtype;
3750     ast_expression *old;
3751
3752     typevar = parse_typename(parser, NULL, NULL);
3753
3754     if (!typevar)
3755         return false;
3756
3757     if ( (old = parser_find_var(parser, typevar->name)) ) {
3758         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3759                    " -> `%s` has been declared here: %s:%i",
3760                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3761         ast_delete(typevar);
3762         return false;
3763     }
3764
3765     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3766         parseerror(parser, "type `%s` has already been declared here: %s:%i",
3767                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3768         ast_delete(typevar);
3769         return false;
3770     }
3771
3772     vec_push(parser->_typedefs, typevar);
3773     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3774
3775     if (parser->tok != ';') {
3776         parseerror(parser, "expected semicolon after typedef");
3777         return false;
3778     }
3779     if (!parser_next(parser)) {
3780         parseerror(parser, "parse error after typedef");
3781         return false;
3782     }
3783
3784     return true;
3785 }
3786
3787 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref)
3788 {
3789     ast_value *var;
3790     ast_value *proto;
3791     ast_expression *old;
3792     bool       was_end;
3793     size_t     i;
3794
3795     ast_value *basetype = NULL;
3796     bool      retval    = true;
3797     bool      isparam   = false;
3798     bool      isvector  = false;
3799     bool      cleanvar  = true;
3800     bool      wasarray  = false;
3801
3802     ast_member *me[3];
3803
3804     /* get the first complete variable */
3805     var = parse_typename(parser, &basetype, cached_typedef);
3806     if (!var) {
3807         if (basetype)
3808             ast_delete(basetype);
3809         return false;
3810     }
3811
3812     while (true) {
3813         proto = NULL;
3814         wasarray = false;
3815
3816         /* Part 0: finish the type */
3817         if (parser->tok == '(') {
3818             if (opts_standard == COMPILER_QCC)
3819                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3820             var = parse_parameter_list(parser, var);
3821             if (!var) {
3822                 retval = false;
3823                 goto cleanup;
3824             }
3825         }
3826         /* we only allow 1-dimensional arrays */
3827         if (parser->tok == '[') {
3828             wasarray = true;
3829             var = parse_arraysize(parser, var);
3830             if (!var) {
3831                 retval = false;
3832                 goto cleanup;
3833             }
3834         }
3835         if (parser->tok == '(' && wasarray) {
3836             parseerror(parser, "arrays as part of a return type is not supported");
3837             /* we'll still parse the type completely for now */
3838         }
3839         /* for functions returning functions */
3840         while (parser->tok == '(') {
3841             if (opts_standard == COMPILER_QCC)
3842                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3843             var = parse_parameter_list(parser, var);
3844             if (!var) {
3845                 retval = false;
3846                 goto cleanup;
3847             }
3848         }
3849
3850         var->cvq = qualifier;
3851         /* in a noref section we simply bump the usecount */
3852         if (noref || parser->noref)
3853             var->uses++;
3854
3855         /* Part 1:
3856          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3857          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3858          * is then filled with the previous definition and the parameter-names replaced.
3859          */
3860         if (!localblock) {
3861             /* Deal with end_sys_ vars */
3862             was_end = false;
3863             if (!strcmp(var->name, "end_sys_globals")) {
3864                 var->uses++;
3865                 parser->crc_globals = vec_size(parser->globals);
3866                 was_end = true;
3867             }
3868             else if (!strcmp(var->name, "end_sys_fields")) {
3869                 var->uses++;
3870                 parser->crc_fields = vec_size(parser->fields);
3871                 was_end = true;
3872             }
3873             if (was_end && var->expression.vtype == TYPE_FIELD) {
3874                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3875                                  "global '%s' hint should not be a field",
3876                                  parser_tokval(parser)))
3877                 {
3878                     retval = false;
3879                     goto cleanup;
3880                 }
3881             }
3882
3883             if (!nofields && var->expression.vtype == TYPE_FIELD)
3884             {
3885                 /* deal with field declarations */
3886                 old = parser_find_field(parser, var->name);
3887                 if (old) {
3888                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3889                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3890                     {
3891                         retval = false;
3892                         goto cleanup;
3893                     }
3894                     ast_delete(var);
3895                     var = NULL;
3896                     goto skipvar;
3897                     /*
3898                     parseerror(parser, "field `%s` already declared here: %s:%i",
3899                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3900                     retval = false;
3901                     goto cleanup;
3902                     */
3903                 }
3904                 if (opts_standard == COMPILER_QCC &&
3905                     (old = parser_find_global(parser, var->name)))
3906                 {
3907                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3908                     parseerror(parser, "field `%s` already declared here: %s:%i",
3909                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3910                     retval = false;
3911                     goto cleanup;
3912                 }
3913             }
3914             else
3915             {
3916                 /* deal with other globals */
3917                 old = parser_find_global(parser, var->name);
3918                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3919                 {
3920                     /* This is a function which had a prototype */
3921                     if (!ast_istype(old, ast_value)) {
3922                         parseerror(parser, "internal error: prototype is not an ast_value");
3923                         retval = false;
3924                         goto cleanup;
3925                     }
3926                     proto = (ast_value*)old;
3927                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3928                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3929                                    proto->name,
3930                                    ast_ctx(proto).file, ast_ctx(proto).line);
3931                         retval = false;
3932                         goto cleanup;
3933                     }
3934                     /* we need the new parameter-names */
3935                     for (i = 0; i < vec_size(proto->expression.params); ++i)
3936                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3937                     ast_delete(var);
3938                     var = proto;
3939                 }
3940                 else
3941                 {
3942                     /* other globals */
3943                     if (old) {
3944                         if (opts_standard == COMPILER_GMQCC) {
3945                             parseerror(parser, "global `%s` already declared here: %s:%i",
3946                                        var->name, ast_ctx(old).file, ast_ctx(old).line);
3947                             retval = false;
3948                             goto cleanup;
3949                         } else {
3950                             if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3951                                              "global `%s` already declared here: %s:%i",
3952                                              var->name, ast_ctx(old).file, ast_ctx(old).line))
3953                             {
3954                                 retval = false;
3955                                 goto cleanup;
3956                             }
3957                             proto = (ast_value*)old;
3958                             if (!ast_istype(old, ast_value)) {
3959                                 parseerror(parser, "internal error: not an ast_value");
3960                                 retval = false;
3961                                 proto = NULL;
3962                                 goto cleanup;
3963                             }
3964                             ast_delete(var);
3965                             var = proto;
3966                         }
3967                     }
3968                     if (opts_standard == COMPILER_QCC &&
3969                         (old = parser_find_field(parser, var->name)))
3970                     {
3971                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3972                         parseerror(parser, "global `%s` already declared here: %s:%i",
3973                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3974                         retval = false;
3975                         goto cleanup;
3976                     }
3977                 }
3978             }
3979         }
3980         else /* it's not a global */
3981         {
3982             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3983             if (old && !isparam) {
3984                 parseerror(parser, "local `%s` already declared here: %s:%i",
3985                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3986                 retval = false;
3987                 goto cleanup;
3988             }
3989             old = parser_find_local(parser, var->name, 0, &isparam);
3990             if (old && isparam) {
3991                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3992                                  "local `%s` is shadowing a parameter", var->name))
3993                 {
3994                     parseerror(parser, "local `%s` already declared here: %s:%i",
3995                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3996                     retval = false;
3997                     goto cleanup;
3998                 }
3999                 if (opts_standard != COMPILER_GMQCC) {
4000                     ast_delete(var);
4001                     var = NULL;
4002                     goto skipvar;
4003                 }
4004             }
4005         }
4006
4007         /* Part 2:
4008          * Create the global/local, and deal with vector types.
4009          */
4010         if (!proto) {
4011             if (var->expression.vtype == TYPE_VECTOR)
4012                 isvector = true;
4013             else if (var->expression.vtype == TYPE_FIELD &&
4014                      var->expression.next->expression.vtype == TYPE_VECTOR)
4015                 isvector = true;
4016
4017             if (isvector) {
4018                 if (!create_vector_members(var, me)) {
4019                     retval = false;
4020                     goto cleanup;
4021                 }
4022             }
4023
4024             if (!localblock) {
4025                 /* deal with global variables, fields, functions */
4026                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4027                     var->isfield = true;
4028                     vec_push(parser->fields, (ast_expression*)var);
4029                     util_htset(parser->htfields, var->name, var);
4030                     if (isvector) {
4031                         for (i = 0; i < 3; ++i) {
4032                             vec_push(parser->fields, (ast_expression*)me[i]);
4033                             util_htset(parser->htfields, me[i]->name, me[i]);
4034                         }
4035                     }
4036                 }
4037                 else {
4038                     vec_push(parser->globals, (ast_expression*)var);
4039                     util_htset(parser->htglobals, var->name, var);
4040                     if (isvector) {
4041                         for (i = 0; i < 3; ++i) {
4042                             vec_push(parser->globals, (ast_expression*)me[i]);
4043                             util_htset(parser->htglobals, me[i]->name, me[i]);
4044                         }
4045                     }
4046                 }
4047             } else {
4048                 vec_push(localblock->locals, var);
4049                 parser_addlocal(parser, var->name, (ast_expression*)var);
4050                 if (isvector) {
4051                     for (i = 0; i < 3; ++i) {
4052                         parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4053                         ast_block_collect(localblock, (ast_expression*)me[i]);
4054                     }
4055                 }
4056             }
4057
4058         }
4059         me[0] = me[1] = me[2] = NULL;
4060         cleanvar = false;
4061         /* Part 2.2
4062          * deal with arrays
4063          */
4064         if (var->expression.vtype == TYPE_ARRAY) {
4065             char name[1024];
4066             snprintf(name, sizeof(name), "%s##SET", var->name);
4067             if (!parser_create_array_setter(parser, var, name))
4068                 goto cleanup;
4069             snprintf(name, sizeof(name), "%s##GET", var->name);
4070             if (!parser_create_array_getter(parser, var, var->expression.next, name))
4071                 goto cleanup;
4072         }
4073         else if (!localblock && !nofields &&
4074                  var->expression.vtype == TYPE_FIELD &&
4075                  var->expression.next->expression.vtype == TYPE_ARRAY)
4076         {
4077             char name[1024];
4078             ast_expression *telem;
4079             ast_value      *tfield;
4080             ast_value      *array = (ast_value*)var->expression.next;
4081
4082             if (!ast_istype(var->expression.next, ast_value)) {
4083                 parseerror(parser, "internal error: field element type must be an ast_value");
4084                 goto cleanup;
4085             }
4086
4087             snprintf(name, sizeof(name), "%s##SETF", var->name);
4088             if (!parser_create_array_field_setter(parser, array, name))
4089                 goto cleanup;
4090
4091             telem = ast_type_copy(ast_ctx(var), array->expression.next);
4092             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4093             tfield->expression.next = telem;
4094             snprintf(name, sizeof(name), "%s##GETFP", var->name);
4095             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4096                 ast_delete(tfield);
4097                 goto cleanup;
4098             }
4099             ast_delete(tfield);
4100         }
4101
4102 skipvar:
4103         if (parser->tok == ';') {
4104             ast_delete(basetype);
4105             if (!parser_next(parser)) {
4106                 parseerror(parser, "error after variable declaration");
4107                 return false;
4108             }
4109             return true;
4110         }
4111
4112         if (parser->tok == ',')
4113             goto another;
4114
4115         /*
4116         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4117         */
4118         if (!var) {
4119             parseerror(parser, "missing comma or semicolon while parsing variables");
4120             break;
4121         }
4122
4123         if (localblock && opts_standard == COMPILER_QCC) {
4124             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4125                              "initializing expression turns variable `%s` into a constant in this standard",
4126                              var->name) )
4127             {
4128                 break;
4129             }
4130         }
4131
4132         if (parser->tok != '{') {
4133             if (parser->tok != '=') {
4134                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4135                 break;
4136             }
4137
4138             if (!parser_next(parser)) {
4139                 parseerror(parser, "error parsing initializer");
4140                 break;
4141             }
4142         }
4143         else if (opts_standard == COMPILER_QCC) {
4144             parseerror(parser, "expected '=' before function body in this standard");
4145         }
4146
4147         if (parser->tok == '#') {
4148             ast_function *func = NULL;
4149
4150             if (localblock) {
4151                 parseerror(parser, "cannot declare builtins within functions");
4152                 break;
4153             }
4154             if (var->expression.vtype != TYPE_FUNCTION) {
4155                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4156                 break;
4157             }
4158             if (!parser_next(parser)) {
4159                 parseerror(parser, "expected builtin number");
4160                 break;
4161             }
4162             if (parser->tok != TOKEN_INTCONST) {
4163                 parseerror(parser, "builtin number must be an integer constant");
4164                 break;
4165             }
4166             if (parser_token(parser)->constval.i < 0) {
4167                 parseerror(parser, "builtin number must be an integer greater than zero");
4168                 break;
4169             }
4170
4171             if (var->hasvalue) {
4172                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4173                                     "builtin `%s` has already been defined\n"
4174                                     " -> previous declaration here: %s:%i",
4175                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4176             }
4177             else
4178             {
4179                 func = ast_function_new(ast_ctx(var), var->name, var);
4180                 if (!func) {
4181                     parseerror(parser, "failed to allocate function for `%s`", var->name);
4182                     break;
4183                 }
4184                 vec_push(parser->functions, func);
4185
4186                 func->builtin = -parser_token(parser)->constval.i-1;
4187             }
4188
4189             if (!parser_next(parser)) {
4190                 parseerror(parser, "expected comma or semicolon");
4191                 if (func)
4192                     ast_function_delete(func);
4193                 var->constval.vfunc = NULL;
4194                 break;
4195             }
4196         }
4197         else if (parser->tok == '{' || parser->tok == '[')
4198         {
4199             size_t i;
4200             if (localblock) {
4201                 parseerror(parser, "cannot declare functions within functions");
4202                 break;
4203             }
4204
4205             if (proto)
4206                 ast_ctx(proto) = parser_ctx(parser);
4207
4208             if (!parse_function_body(parser, var))
4209                 break;
4210             ast_delete(basetype);
4211             for (i = 0; i < vec_size(parser->gotos); ++i)
4212                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4213             vec_free(parser->gotos);
4214             vec_free(parser->labels);
4215             return true;
4216         } else {
4217             ast_expression *cexp;
4218             ast_value      *cval;
4219
4220             cexp = parse_expression_leave(parser, true);
4221             if (!cexp)
4222                 break;
4223
4224             if (!localblock) {
4225                 cval = (ast_value*)cexp;
4226                 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4227                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4228                 else
4229                 {
4230                     if (opts_standard != COMPILER_GMQCC &&
4231                         !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4232                         qualifier != CV_VAR)
4233                     {
4234                         var->cvq = CV_CONST;
4235                     }
4236                     var->hasvalue = true;
4237                     if (cval->expression.vtype == TYPE_STRING)
4238                         var->constval.vstring = parser_strdup(cval->constval.vstring);
4239                     else if (cval->expression.vtype == TYPE_FIELD)
4240                         var->constval.vfield = cval;
4241                     else
4242                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4243                     ast_unref(cval);
4244                 }
4245             } else {
4246                 bool cvq;
4247                 shunt sy = { NULL, NULL };
4248                 cvq = var->cvq;
4249                 var->cvq = CV_NONE;
4250                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4251                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4252                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4253                 if (!parser_sy_apply_operator(parser, &sy))
4254                     ast_unref(cexp);
4255                 else {
4256                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4257                         parseerror(parser, "internal error: leaked operands");
4258                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4259                         break;
4260                 }
4261                 vec_free(sy.out);
4262                 vec_free(sy.ops);
4263                 var->cvq = cvq;
4264             }
4265         }
4266
4267 another:
4268         if (parser->tok == ',') {
4269             if (!parser_next(parser)) {
4270                 parseerror(parser, "expected another variable");
4271                 break;
4272             }
4273
4274             if (parser->tok != TOKEN_IDENT) {
4275                 parseerror(parser, "expected another variable");
4276                 break;
4277             }
4278             var = ast_value_copy(basetype);
4279             cleanvar = true;
4280             ast_value_set_name(var, parser_tokval(parser));
4281             if (!parser_next(parser)) {
4282                 parseerror(parser, "error parsing variable declaration");
4283                 break;
4284             }
4285             continue;
4286         }
4287
4288         if (parser->tok != ';') {
4289             parseerror(parser, "missing semicolon after variables");
4290             break;
4291         }
4292
4293         if (!parser_next(parser)) {
4294             parseerror(parser, "parse error after variable declaration");
4295             break;
4296         }
4297
4298         ast_delete(basetype);
4299         return true;
4300     }
4301
4302     if (cleanvar && var)
4303         ast_delete(var);
4304     ast_delete(basetype);
4305     return false;
4306
4307 cleanup:
4308     ast_delete(basetype);
4309     if (cleanvar && var)
4310         ast_delete(var);
4311     if (me[0]) ast_member_delete(me[0]);
4312     if (me[1]) ast_member_delete(me[1]);
4313     if (me[2]) ast_member_delete(me[2]);
4314     return retval;
4315 }
4316
4317 static bool parser_global_statement(parser_t *parser)
4318 {
4319     int        cvq = CV_WRONG;
4320     bool       noref = false;
4321     ast_value *istype = NULL;
4322
4323     if (parser->tok == TOKEN_IDENT)
4324         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4325
4326     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4327     {
4328         return parse_variable(parser, NULL, false, CV_NONE, istype, false);
4329     }
4330     else if (parse_var_qualifiers(parser, false, &cvq, &noref))
4331     {
4332         if (cvq == CV_WRONG)
4333             return false;
4334         return parse_variable(parser, NULL, true, cvq, NULL, noref);
4335     }
4336     else if (parser->tok == TOKEN_KEYWORD)
4337     {
4338         if (!strcmp(parser_tokval(parser), "typedef")) {
4339             if (!parser_next(parser)) {
4340                 parseerror(parser, "expected type definition after 'typedef'");
4341                 return false;
4342             }
4343             return parse_typedef(parser);
4344         }
4345         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4346         return false;
4347     }
4348     else if (parser->tok == '#')
4349     {
4350         return parse_pragma(parser);
4351     }
4352     else if (parser->tok == '$')
4353     {
4354         if (!parser_next(parser)) {
4355             parseerror(parser, "parse error");
4356             return false;
4357         }
4358     }
4359     else
4360     {
4361         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4362         return false;
4363     }
4364     return true;
4365 }
4366
4367 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4368 {
4369     return util_crc16(old, str, strlen(str));
4370 }
4371
4372 static void progdefs_crc_file(const char *str)
4373 {
4374     /* write to progdefs.h here */
4375     (void)str;
4376 }
4377
4378 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4379 {
4380     old = progdefs_crc_sum(old, str);
4381     progdefs_crc_file(str);
4382     return old;
4383 }
4384
4385 static void generate_checksum(parser_t *parser)
4386 {
4387     uint16_t   crc = 0xFFFF;
4388     size_t     i;
4389     ast_value *value;
4390
4391         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4392         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4393         /*
4394         progdefs_crc_file("\tint\tpad;\n");
4395         progdefs_crc_file("\tint\tofs_return[3];\n");
4396         progdefs_crc_file("\tint\tofs_parm0[3];\n");
4397         progdefs_crc_file("\tint\tofs_parm1[3];\n");
4398         progdefs_crc_file("\tint\tofs_parm2[3];\n");
4399         progdefs_crc_file("\tint\tofs_parm3[3];\n");
4400         progdefs_crc_file("\tint\tofs_parm4[3];\n");
4401         progdefs_crc_file("\tint\tofs_parm5[3];\n");
4402         progdefs_crc_file("\tint\tofs_parm6[3];\n");
4403         progdefs_crc_file("\tint\tofs_parm7[3];\n");
4404         */
4405         for (i = 0; i < parser->crc_globals; ++i) {
4406             if (!ast_istype(parser->globals[i], ast_value))
4407                 continue;
4408             value = (ast_value*)(parser->globals[i]);
4409             switch (value->expression.vtype) {
4410                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4411                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4412                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4413                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4414                 default:
4415                     crc = progdefs_crc_both(crc, "\tint\t");
4416                     break;
4417             }
4418             crc = progdefs_crc_both(crc, value->name);
4419             crc = progdefs_crc_both(crc, ";\n");
4420         }
4421         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4422         for (i = 0; i < parser->crc_fields; ++i) {
4423             if (!ast_istype(parser->fields[i], ast_value))
4424                 continue;
4425             value = (ast_value*)(parser->fields[i]);
4426             switch (value->expression.next->expression.vtype) {
4427                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4428                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4429                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4430                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4431                 default:
4432                     crc = progdefs_crc_both(crc, "\tint\t");
4433                     break;
4434             }
4435             crc = progdefs_crc_both(crc, value->name);
4436             crc = progdefs_crc_both(crc, ";\n");
4437         }
4438         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4439
4440         code_crc = crc;
4441 }
4442
4443 static parser_t *parser;
4444
4445 bool parser_init()
4446 {
4447     size_t i;
4448
4449     parser = (parser_t*)mem_a(sizeof(parser_t));
4450     if (!parser)
4451         return false;
4452
4453     memset(parser, 0, sizeof(*parser));
4454
4455     for (i = 0; i < operator_count; ++i) {
4456         if (operators[i].id == opid1('=')) {
4457             parser->assign_op = operators+i;
4458             break;
4459         }
4460     }
4461     if (!parser->assign_op) {
4462         printf("internal error: initializing parser: failed to find assign operator\n");
4463         mem_d(parser);
4464         return false;
4465     }
4466
4467     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
4468     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4469     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4470     vec_push(parser->_blocktypedefs, 0);
4471     return true;
4472 }
4473
4474 bool parser_compile()
4475 {
4476     /* initial lexer/parser state */
4477     parser->lex->flags.noops = true;
4478
4479     if (parser_next(parser))
4480     {
4481         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4482         {
4483             if (!parser_global_statement(parser)) {
4484                 if (parser->tok == TOKEN_EOF)
4485                     parseerror(parser, "unexpected eof");
4486                 else if (!parser->errors)
4487                     parseerror(parser, "there have been errors, bailing out");
4488                 lex_close(parser->lex);
4489                 parser->lex = NULL;
4490                 return false;
4491             }
4492         }
4493     } else {
4494         parseerror(parser, "parse error");
4495         lex_close(parser->lex);
4496         parser->lex = NULL;
4497         return false;
4498     }
4499
4500     lex_close(parser->lex);
4501     parser->lex = NULL;
4502
4503     return !parser->errors;
4504 }
4505
4506 bool parser_compile_file(const char *filename)
4507 {
4508     parser->lex = lex_open(filename);
4509     if (!parser->lex) {
4510         con_err("failed to open file \"%s\"\n", filename);
4511         return false;
4512     }
4513     return parser_compile();
4514 }
4515
4516 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4517 {
4518     parser->lex = lex_open_string(str, len, name);
4519     if (!parser->lex) {
4520         con_err("failed to create lexer for string \"%s\"\n", name);
4521         return false;
4522     }
4523     return parser_compile();
4524 }
4525
4526 bool parser_compile_string(const char *name, const char *str)
4527 {
4528     parser->lex = lex_open_string(str, strlen(str), name);
4529     if (!parser->lex) {
4530         con_err("failed to create lexer for string \"%s\"\n", name);
4531         return false;
4532     }
4533     return parser_compile();
4534 }
4535
4536 void parser_cleanup()
4537 {
4538     size_t i;
4539     for (i = 0; i < vec_size(parser->accessors); ++i) {
4540         ast_delete(parser->accessors[i]->constval.vfunc);
4541         parser->accessors[i]->constval.vfunc = NULL;
4542         ast_delete(parser->accessors[i]);
4543     }
4544     for (i = 0; i < vec_size(parser->functions); ++i) {
4545         ast_delete(parser->functions[i]);
4546     }
4547     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4548         ast_delete(parser->imm_vector[i]);
4549     }
4550     for (i = 0; i < vec_size(parser->imm_string); ++i) {
4551         ast_delete(parser->imm_string[i]);
4552     }
4553     for (i = 0; i < vec_size(parser->imm_float); ++i) {
4554         ast_delete(parser->imm_float[i]);
4555     }
4556     for (i = 0; i < vec_size(parser->fields); ++i) {
4557         ast_delete(parser->fields[i]);
4558     }
4559     for (i = 0; i < vec_size(parser->globals); ++i) {
4560         ast_delete(parser->globals[i]);
4561     }
4562     vec_free(parser->accessors);
4563     vec_free(parser->functions);
4564     vec_free(parser->imm_vector);
4565     vec_free(parser->imm_string);
4566     vec_free(parser->imm_float);
4567     vec_free(parser->globals);
4568     vec_free(parser->fields);
4569
4570     for (i = 0; i < vec_size(parser->variables); ++i)
4571         util_htdel(parser->variables[i]);
4572     vec_free(parser->variables);
4573     vec_free(parser->_blocklocals);
4574     vec_free(parser->_locals);
4575
4576     for (i = 0; i < vec_size(parser->_typedefs); ++i)
4577         ast_delete(parser->_typedefs[i]);
4578     vec_free(parser->_typedefs);
4579     for (i = 0; i < vec_size(parser->typedefs); ++i)
4580         util_htdel(parser->typedefs[i]);
4581     vec_free(parser->typedefs);
4582     vec_free(parser->_blocktypedefs);
4583
4584     vec_free(parser->_block_ctx);
4585
4586     vec_free(parser->labels);
4587     vec_free(parser->gotos);
4588
4589     mem_d(parser);
4590 }
4591
4592 bool parser_finish(const char *output)
4593 {
4594     size_t i;
4595     ir_builder *ir;
4596     bool retval = true;
4597
4598     if (!parser->errors)
4599     {
4600         ir = ir_builder_new("gmqcc_out");
4601         if (!ir) {
4602             con_out("failed to allocate builder\n");
4603             return false;
4604         }
4605
4606         for (i = 0; i < vec_size(parser->fields); ++i) {
4607             ast_value *field;
4608             bool hasvalue;
4609             if (!ast_istype(parser->fields[i], ast_value))
4610                 continue;
4611             field = (ast_value*)parser->fields[i];
4612             hasvalue = field->hasvalue;
4613             field->hasvalue = false;
4614             if (!ast_global_codegen((ast_value*)field, ir, true)) {
4615                 con_out("failed to generate field %s\n", field->name);
4616                 ir_builder_delete(ir);
4617                 return false;
4618             }
4619             if (hasvalue) {
4620                 ir_value *ifld;
4621                 ast_expression *subtype;
4622                 field->hasvalue = true;
4623                 subtype = field->expression.next;
4624                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4625                 if (subtype->expression.vtype == TYPE_FIELD)
4626                     ifld->fieldtype = subtype->expression.next->expression.vtype;
4627                 else if (subtype->expression.vtype == TYPE_FUNCTION)
4628                     ifld->outtype = subtype->expression.next->expression.vtype;
4629                 (void)!ir_value_set_field(field->ir_v, ifld);
4630             }
4631         }
4632         for (i = 0; i < vec_size(parser->globals); ++i) {
4633             ast_value *asvalue;
4634             if (!ast_istype(parser->globals[i], ast_value))
4635                 continue;
4636             asvalue = (ast_value*)(parser->globals[i]);
4637             if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4638                 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4639                                                "unused global: `%s`", asvalue->name);
4640             }
4641             if (!ast_global_codegen(asvalue, ir, false)) {
4642                 con_out("failed to generate global %s\n", asvalue->name);
4643                 ir_builder_delete(ir);
4644                 return false;
4645             }
4646         }
4647         for (i = 0; i < vec_size(parser->imm_float); ++i) {
4648             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4649                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4650                 ir_builder_delete(ir);
4651                 return false;
4652             }
4653         }
4654         for (i = 0; i < vec_size(parser->imm_string); ++i) {
4655             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4656                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4657                 ir_builder_delete(ir);
4658                 return false;
4659             }
4660         }
4661         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4662             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4663                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4664                 ir_builder_delete(ir);
4665                 return false;
4666             }
4667         }
4668         for (i = 0; i < vec_size(parser->globals); ++i) {
4669             ast_value *asvalue;
4670             if (!ast_istype(parser->globals[i], ast_value))
4671                 continue;
4672             asvalue = (ast_value*)(parser->globals[i]);
4673             if (!ast_generate_accessors(asvalue, ir)) {
4674                 ir_builder_delete(ir);
4675                 return false;
4676             }
4677         }
4678         for (i = 0; i < vec_size(parser->fields); ++i) {
4679             ast_value *asvalue;
4680             asvalue = (ast_value*)(parser->fields[i]->expression.next);
4681
4682             if (!ast_istype((ast_expression*)asvalue, ast_value))
4683                 continue;
4684             if (asvalue->expression.vtype != TYPE_ARRAY)
4685                 continue;
4686             if (!ast_generate_accessors(asvalue, ir)) {
4687                 ir_builder_delete(ir);
4688                 return false;
4689             }
4690         }
4691         for (i = 0; i < vec_size(parser->functions); ++i) {
4692             if (!ast_function_codegen(parser->functions[i], ir)) {
4693                 con_out("failed to generate function %s\n", parser->functions[i]->name);
4694                 ir_builder_delete(ir);
4695                 return false;
4696             }
4697         }
4698         if (opts_dump)
4699             ir_builder_dump(ir, con_out);
4700         for (i = 0; i < vec_size(parser->functions); ++i) {
4701             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4702                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4703                 ir_builder_delete(ir);
4704                 return false;
4705             }
4706         }
4707
4708         if (retval) {
4709             if (opts_dumpfin)
4710                 ir_builder_dump(ir, con_out);
4711
4712             generate_checksum(parser);
4713
4714             if (!ir_builder_generate(ir, output)) {
4715                 con_out("*** failed to generate output file\n");
4716                 ir_builder_delete(ir);
4717                 return false;
4718             }
4719         }
4720
4721         ir_builder_delete(ir);
4722         return retval;
4723     }
4724
4725     con_out("*** there were compile errors\n");
4726     return false;
4727 }