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