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