]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
fixed: -frelaxed-switch check was in the wrong position
[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     switchnode = ast_switch_new(ctx, operand);
2111
2112     /* closing paren */
2113     if (parser->tok != ')') {
2114         ast_delete(switchnode);
2115         parseerror(parser, "expected closing paren after 'switch' operand");
2116         return false;
2117     }
2118
2119     /* parse over the opening paren */
2120     if (!parser_next(parser) || parser->tok != '{') {
2121         ast_delete(switchnode);
2122         parseerror(parser, "expected list of cases");
2123         return false;
2124     }
2125
2126     if (!parser_next(parser)) {
2127         ast_delete(switchnode);
2128         parseerror(parser, "expected 'case' or 'default'");
2129         return false;
2130     }
2131
2132     /* case list! */
2133     while (parser->tok != '}') {
2134         ast_block *caseblock;
2135
2136         if (parser->tok != TOKEN_KEYWORD) {
2137             ast_delete(switchnode);
2138             parseerror(parser, "expected 'case' or 'default'");
2139             return false;
2140         }
2141         if (!strcmp(parser_tokval(parser), "case")) {
2142             if (!parser_next(parser)) {
2143                 ast_delete(switchnode);
2144                 parseerror(parser, "expected expression for case");
2145                 return false;
2146             }
2147             swcase.value = parse_expression_leave(parser, false);
2148             if (!swcase.value) {
2149                 ast_delete(switchnode);
2150                 parseerror(parser, "expected expression for case");
2151                 return false;
2152             }
2153             if (!OPTS_FLAG(RELAXED_SWITCH)) {
2154                 opval = (ast_value*)swcase.value;
2155                 if (!ast_istype(swcase.value, ast_value) || !opval->constant) {
2156                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2157                     ast_unref(operand);
2158                     return false;
2159                 }
2160             }
2161         }
2162         else if (!strcmp(parser_tokval(parser), "default")) {
2163             swcase.value = NULL;
2164             if (!parser_next(parser)) {
2165                 ast_delete(switchnode);
2166                 parseerror(parser, "expected colon");
2167                 return false;
2168             }
2169         }
2170
2171         /* Now the colon and body */
2172         if (parser->tok != ':') {
2173             if (swcase.value) ast_unref(swcase.value);
2174             ast_delete(switchnode);
2175             parseerror(parser, "expected colon");
2176             return false;
2177         }
2178
2179         if (!parser_next(parser)) {
2180             if (swcase.value) ast_unref(swcase.value);
2181             ast_delete(switchnode);
2182             parseerror(parser, "expected statements or case");
2183             return false;
2184         }
2185         caseblock = ast_block_new(parser_ctx(parser));
2186         if (!caseblock) {
2187             if (swcase.value) ast_unref(swcase.value);
2188             ast_delete(switchnode);
2189             return false;
2190         }
2191         swcase.code = (ast_expression*)caseblock;
2192         vec_push(switchnode->cases, swcase);
2193         while (true) {
2194             ast_expression *expr;
2195             if (parser->tok == '}')
2196                 break;
2197             if (parser->tok == TOKEN_KEYWORD) {
2198                 if (!strcmp(parser_tokval(parser), "case") ||
2199                     !strcmp(parser_tokval(parser), "default"))
2200                 {
2201                     break;
2202                 }
2203             }
2204             if (!parse_statement(parser, caseblock, &expr, true)) {
2205                 ast_delete(switchnode);
2206                 return false;
2207             }
2208             if (!expr)
2209                 continue;
2210             ast_block_add_expr(caseblock, expr);
2211         }
2212     }
2213
2214     /* closing paren */
2215     if (parser->tok != '}') {
2216         ast_delete(switchnode);
2217         parseerror(parser, "expected closing paren of case list");
2218         return false;
2219     }
2220     if (!parser_next(parser)) {
2221         ast_delete(switchnode);
2222         parseerror(parser, "parse error after switch");
2223         return false;
2224     }
2225     *out = (ast_expression*)switchnode;
2226     return true;
2227 }
2228
2229 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2230 {
2231     ast_value *typevar = NULL;
2232     if (parser->tok == TOKEN_IDENT)
2233         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2234
2235     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2236     {
2237         /* local variable */
2238         if (!block) {
2239             parseerror(parser, "cannot declare a variable from here");
2240             return false;
2241         }
2242         if (opts_standard == COMPILER_QCC) {
2243             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2244                 return false;
2245         }
2246         if (!parse_variable(parser, block, false, false, typevar))
2247             return false;
2248         *out = NULL;
2249         return true;
2250     }
2251     else if (parser->tok == TOKEN_KEYWORD)
2252     {
2253         if (!strcmp(parser_tokval(parser), "local"))
2254         {
2255             if (!block) {
2256                 parseerror(parser, "cannot declare a local variable here");
2257                 return false;
2258             }
2259             if (!parser_next(parser)) {
2260                 parseerror(parser, "expected variable declaration");
2261                 return false;
2262             }
2263             if (!parse_variable(parser, block, true, false, NULL))
2264                 return false;
2265             *out = NULL;
2266             return true;
2267         }
2268         else if (!strcmp(parser_tokval(parser), "return"))
2269         {
2270             return parse_return(parser, block, out);
2271         }
2272         else if (!strcmp(parser_tokval(parser), "if"))
2273         {
2274             return parse_if(parser, block, out);
2275         }
2276         else if (!strcmp(parser_tokval(parser), "while"))
2277         {
2278             return parse_while(parser, block, out);
2279         }
2280         else if (!strcmp(parser_tokval(parser), "do"))
2281         {
2282             return parse_dowhile(parser, block, out);
2283         }
2284         else if (!strcmp(parser_tokval(parser), "for"))
2285         {
2286             if (opts_standard == COMPILER_QCC) {
2287                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2288                     return false;
2289             }
2290             return parse_for(parser, block, out);
2291         }
2292         else if (!strcmp(parser_tokval(parser), "break"))
2293         {
2294             return parse_break_continue(parser, block, out, false);
2295         }
2296         else if (!strcmp(parser_tokval(parser), "continue"))
2297         {
2298             return parse_break_continue(parser, block, out, true);
2299         }
2300         else if (!strcmp(parser_tokval(parser), "switch"))
2301         {
2302             return parse_switch(parser, block, out);
2303         }
2304         else if (!strcmp(parser_tokval(parser), "case") ||
2305                  !strcmp(parser_tokval(parser), "default"))
2306         {
2307             if (!allow_cases) {
2308                 parseerror(parser, "unexpected 'case' label");
2309                 return false;
2310             }
2311             return true;
2312         }
2313         else if (!strcmp(parser_tokval(parser), "typedef"))
2314         {
2315             if (!parser_next(parser)) {
2316                 parseerror(parser, "expected type definition after 'typedef'");
2317                 return false;
2318             }
2319             return parse_typedef(parser);
2320         }
2321         parseerror(parser, "Unexpected keyword");
2322         return false;
2323     }
2324     else if (parser->tok == '{')
2325     {
2326         ast_block *inner;
2327         inner = parse_block(parser, false);
2328         if (!inner)
2329             return false;
2330         *out = (ast_expression*)inner;
2331         return true;
2332     }
2333     else
2334     {
2335         ast_expression *exp = parse_expression(parser, false);
2336         if (!exp)
2337             return false;
2338         *out = exp;
2339         if (!ast_side_effects(exp)) {
2340             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2341                 return false;
2342         }
2343         return true;
2344     }
2345 }
2346
2347 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2348 {
2349     bool   retval = true;
2350
2351     parser_enterblock(parser);
2352
2353     if (!parser_next(parser)) { /* skip the '{' */
2354         parseerror(parser, "expected function body");
2355         goto cleanup;
2356     }
2357
2358     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2359     {
2360         ast_expression *expr = NULL;
2361         if (parser->tok == '}')
2362             break;
2363
2364         if (!parse_statement(parser, block, &expr, false)) {
2365             /* parseerror(parser, "parse error"); */
2366             block = NULL;
2367             goto cleanup;
2368         }
2369         if (!expr)
2370             continue;
2371         ast_block_add_expr(block, expr);
2372     }
2373
2374     if (parser->tok != '}') {
2375         block = NULL;
2376     } else {
2377         if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2378         {
2379             if (!vec_size(block->exprs) ||
2380                 !ast_istype(vec_last(block->exprs), ast_return))
2381             {
2382                 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2383                     block = NULL;
2384                     goto cleanup;
2385                 }
2386             }
2387         }
2388         (void)parser_next(parser);
2389     }
2390
2391 cleanup:
2392     if (!parser_leaveblock(parser))
2393         retval = false;
2394     return retval && !!block;
2395 }
2396
2397 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2398 {
2399     ast_block *block;
2400     block = ast_block_new(parser_ctx(parser));
2401     if (!block)
2402         return NULL;
2403     if (!parse_block_into(parser, block, warnreturn)) {
2404         ast_block_delete(block);
2405         return NULL;
2406     }
2407     return block;
2408 }
2409
2410 static ast_expression* parse_statement_or_block(parser_t *parser)
2411 {
2412     ast_expression *expr = NULL;
2413     if (parser->tok == '{')
2414         return (ast_expression*)parse_block(parser, false);
2415     if (!parse_statement(parser, NULL, &expr, false))
2416         return NULL;
2417     return expr;
2418 }
2419
2420 static bool create_vector_members(ast_value *var, ast_member **me)
2421 {
2422     size_t i;
2423     size_t len = strlen(var->name);
2424
2425     for (i = 0; i < 3; ++i) {
2426         char *name = mem_a(len+3);
2427         memcpy(name, var->name, len);
2428         name[len+0] = '_';
2429         name[len+1] = 'x'+i;
2430         name[len+2] = 0;
2431         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2432         mem_d(name);
2433         if (!me[i])
2434             break;
2435     }
2436     if (i == 3)
2437         return true;
2438
2439     /* unroll */
2440     do { ast_member_delete(me[--i]); } while(i);
2441     return false;
2442 }
2443
2444 static bool parse_function_body(parser_t *parser, ast_value *var)
2445 {
2446     ast_block      *block = NULL;
2447     ast_function   *func;
2448     ast_function   *old;
2449     size_t          parami;
2450
2451     ast_expression *framenum  = NULL;
2452     ast_expression *nextthink = NULL;
2453     /* None of the following have to be deleted */
2454     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2455     ast_expression *gbl_time = NULL, *gbl_self = NULL;
2456     bool            has_frame_think;
2457
2458     bool retval = true;
2459
2460     has_frame_think = false;
2461     old = parser->function;
2462
2463     if (var->expression.variadic) {
2464         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2465                          "variadic function with implementation will not be able to access additional parameters"))
2466         {
2467             return false;
2468         }
2469     }
2470
2471     if (parser->tok == '[') {
2472         /* got a frame definition: [ framenum, nextthink ]
2473          * this translates to:
2474          * self.frame = framenum;
2475          * self.nextthink = time + 0.1;
2476          * self.think = nextthink;
2477          */
2478         nextthink = NULL;
2479
2480         fld_think     = parser_find_field(parser, "think");
2481         fld_nextthink = parser_find_field(parser, "nextthink");
2482         fld_frame     = parser_find_field(parser, "frame");
2483         if (!fld_think || !fld_nextthink || !fld_frame) {
2484             parseerror(parser, "cannot use [frame,think] notation without the required fields");
2485             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2486             return false;
2487         }
2488         gbl_time      = parser_find_global(parser, "time");
2489         gbl_self      = parser_find_global(parser, "self");
2490         if (!gbl_time || !gbl_self) {
2491             parseerror(parser, "cannot use [frame,think] notation without the required globals");
2492             parseerror(parser, "please declare the following globals: `time`, `self`");
2493             return false;
2494         }
2495
2496         if (!parser_next(parser))
2497             return false;
2498
2499         framenum = parse_expression_leave(parser, true);
2500         if (!framenum) {
2501             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2502             return false;
2503         }
2504         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
2505             ast_unref(framenum);
2506             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2507             return false;
2508         }
2509
2510         if (parser->tok != ',') {
2511             ast_unref(framenum);
2512             parseerror(parser, "expected comma after frame number in [frame,think] notation");
2513             parseerror(parser, "Got a %i\n", parser->tok);
2514             return false;
2515         }
2516
2517         if (!parser_next(parser)) {
2518             ast_unref(framenum);
2519             return false;
2520         }
2521
2522         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2523         {
2524             /* qc allows the use of not-yet-declared functions here
2525              * - this automatically creates a prototype */
2526             ast_value      *thinkfunc;
2527             ast_expression *functype = fld_think->expression.next;
2528
2529             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2530             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2531                 ast_unref(framenum);
2532                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2533                 return false;
2534             }
2535
2536             if (!parser_next(parser)) {
2537                 ast_unref(framenum);
2538                 ast_delete(thinkfunc);
2539                 return false;
2540             }
2541
2542             vec_push(parser->globals, (ast_expression*)thinkfunc);
2543             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2544             nextthink = (ast_expression*)thinkfunc;
2545
2546         } else {
2547             nextthink = parse_expression_leave(parser, true);
2548             if (!nextthink) {
2549                 ast_unref(framenum);
2550                 parseerror(parser, "expected a think-function in [frame,think] notation");
2551                 return false;
2552             }
2553         }
2554
2555         if (!ast_istype(nextthink, ast_value)) {
2556             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2557             retval = false;
2558         }
2559
2560         if (retval && parser->tok != ']') {
2561             parseerror(parser, "expected closing `]` for [frame,think] notation");
2562             retval = false;
2563         }
2564
2565         if (retval && !parser_next(parser)) {
2566             retval = false;
2567         }
2568
2569         if (retval && parser->tok != '{') {
2570             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2571             retval = false;
2572         }
2573
2574         if (!retval) {
2575             ast_unref(nextthink);
2576             ast_unref(framenum);
2577             return false;
2578         }
2579
2580         has_frame_think = true;
2581     }
2582
2583     block = ast_block_new(parser_ctx(parser));
2584     if (!block) {
2585         parseerror(parser, "failed to allocate block");
2586         if (has_frame_think) {
2587             ast_unref(nextthink);
2588             ast_unref(framenum);
2589         }
2590         return false;
2591     }
2592
2593     if (has_frame_think) {
2594         lex_ctx ctx;
2595         ast_expression *self_frame;
2596         ast_expression *self_nextthink;
2597         ast_expression *self_think;
2598         ast_expression *time_plus_1;
2599         ast_store *store_frame;
2600         ast_store *store_nextthink;
2601         ast_store *store_think;
2602
2603         ctx = parser_ctx(parser);
2604         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2605         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2606         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2607
2608         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2609                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2610
2611         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2612             if (self_frame)     ast_delete(self_frame);
2613             if (self_nextthink) ast_delete(self_nextthink);
2614             if (self_think)     ast_delete(self_think);
2615             if (time_plus_1)    ast_delete(time_plus_1);
2616             retval = false;
2617         }
2618
2619         if (retval)
2620         {
2621             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2622             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2623             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2624
2625             if (!store_frame) {
2626                 ast_delete(self_frame);
2627                 retval = false;
2628             }
2629             if (!store_nextthink) {
2630                 ast_delete(self_nextthink);
2631                 retval = false;
2632             }
2633             if (!store_think) {
2634                 ast_delete(self_think);
2635                 retval = false;
2636             }
2637             if (!retval) {
2638                 if (store_frame)     ast_delete(store_frame);
2639                 if (store_nextthink) ast_delete(store_nextthink);
2640                 if (store_think)     ast_delete(store_think);
2641                 retval = false;
2642             }
2643             ast_block_add_expr(block, (ast_expression*)store_frame);
2644             ast_block_add_expr(block, (ast_expression*)store_nextthink);
2645             ast_block_add_expr(block, (ast_expression*)store_think);
2646         }
2647
2648         if (!retval) {
2649             parseerror(parser, "failed to generate code for [frame,think]");
2650             ast_unref(nextthink);
2651             ast_unref(framenum);
2652             ast_delete(block);
2653             return false;
2654         }
2655     }
2656
2657     parser_enterblock(parser);
2658
2659     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2660         size_t     e;
2661         ast_value *param = var->expression.params[parami];
2662         ast_member *me[3];
2663
2664         if (param->expression.vtype != TYPE_VECTOR &&
2665             (param->expression.vtype != TYPE_FIELD ||
2666              param->expression.next->expression.vtype != TYPE_VECTOR))
2667         {
2668             continue;
2669         }
2670
2671         if (!create_vector_members(param, me)) {
2672             ast_block_delete(block);
2673             return false;
2674         }
2675
2676         for (e = 0; e < 3; ++e) {
2677             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2678             ast_block_collect(block, (ast_expression*)me[e]);
2679         }
2680     }
2681
2682     func = ast_function_new(ast_ctx(var), var->name, var);
2683     if (!func) {
2684         parseerror(parser, "failed to allocate function for `%s`", var->name);
2685         ast_block_delete(block);
2686         goto enderr;
2687     }
2688     vec_push(parser->functions, func);
2689
2690     parser->function = func;
2691     if (!parse_block_into(parser, block, true)) {
2692         ast_block_delete(block);
2693         goto enderrfn;
2694     }
2695
2696     vec_push(func->blocks, block);
2697
2698     parser->function = old;
2699     if (!parser_leaveblock(parser))
2700         retval = false;
2701     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2702         parseerror(parser, "internal error: local scopes left");
2703         retval = false;
2704     }
2705
2706     if (parser->tok == ';')
2707         return parser_next(parser);
2708     else if (opts_standard == COMPILER_QCC)
2709         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2710     return retval;
2711
2712 enderrfn:
2713     vec_pop(parser->functions);
2714     ast_function_delete(func);
2715     var->constval.vfunc = NULL;
2716
2717 enderr:
2718     (void)!parser_leaveblock(parser);
2719     parser->function = old;
2720     return false;
2721 }
2722
2723 static ast_expression *array_accessor_split(
2724     parser_t  *parser,
2725     ast_value *array,
2726     ast_value *index,
2727     size_t     middle,
2728     ast_expression *left,
2729     ast_expression *right
2730     )
2731 {
2732     ast_ifthen *ifthen;
2733     ast_binary *cmp;
2734
2735     lex_ctx ctx = ast_ctx(array);
2736
2737     if (!left || !right) {
2738         if (left)  ast_delete(left);
2739         if (right) ast_delete(right);
2740         return NULL;
2741     }
2742
2743     cmp = ast_binary_new(ctx, INSTR_LT,
2744                          (ast_expression*)index,
2745                          (ast_expression*)parser_const_float(parser, middle));
2746     if (!cmp) {
2747         ast_delete(left);
2748         ast_delete(right);
2749         parseerror(parser, "internal error: failed to create comparison for array setter");
2750         return NULL;
2751     }
2752
2753     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2754     if (!ifthen) {
2755         ast_delete(cmp); /* will delete left and right */
2756         parseerror(parser, "internal error: failed to create conditional jump for array setter");
2757         return NULL;
2758     }
2759
2760     return (ast_expression*)ifthen;
2761 }
2762
2763 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2764 {
2765     lex_ctx ctx = ast_ctx(array);
2766
2767     if (from+1 == afterend) {
2768         /* set this value */
2769         ast_block       *block;
2770         ast_return      *ret;
2771         ast_array_index *subscript;
2772         ast_store       *st;
2773         int assignop = type_store_instr[value->expression.vtype];
2774
2775         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2776             assignop = INSTR_STORE_V;
2777
2778         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2779         if (!subscript)
2780             return NULL;
2781
2782         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2783         if (!st) {
2784             ast_delete(subscript);
2785             return NULL;
2786         }
2787
2788         block = ast_block_new(ctx);
2789         if (!block) {
2790             ast_delete(st);
2791             return NULL;
2792         }
2793
2794         ast_block_add_expr(block, (ast_expression*)st);
2795
2796         ret = ast_return_new(ctx, NULL);
2797         if (!ret) {
2798             ast_delete(block);
2799             return NULL;
2800         }
2801
2802         ast_block_add_expr(block, (ast_expression*)ret);
2803
2804         return (ast_expression*)block;
2805     } else {
2806         ast_expression *left, *right;
2807         size_t diff = afterend - from;
2808         size_t middle = from + diff/2;
2809         left  = array_setter_node(parser, array, index, value, from, middle);
2810         right = array_setter_node(parser, array, index, value, middle, afterend);
2811         return array_accessor_split(parser, array, index, middle, left, right);
2812     }
2813 }
2814
2815 static ast_expression *array_field_setter_node(
2816     parser_t  *parser,
2817     ast_value *array,
2818     ast_value *entity,
2819     ast_value *index,
2820     ast_value *value,
2821     size_t     from,
2822     size_t     afterend)
2823 {
2824     lex_ctx ctx = ast_ctx(array);
2825
2826     if (from+1 == afterend) {
2827         /* set this value */
2828         ast_block       *block;
2829         ast_return      *ret;
2830         ast_entfield    *entfield;
2831         ast_array_index *subscript;
2832         ast_store       *st;
2833         int assignop = type_storep_instr[value->expression.vtype];
2834
2835         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2836             assignop = INSTR_STOREP_V;
2837
2838         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2839         if (!subscript)
2840             return NULL;
2841
2842         entfield = ast_entfield_new_force(ctx,
2843                                           (ast_expression*)entity,
2844                                           (ast_expression*)subscript,
2845                                           (ast_expression*)subscript);
2846         if (!entfield) {
2847             ast_delete(subscript);
2848             return NULL;
2849         }
2850
2851         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2852         if (!st) {
2853             ast_delete(entfield);
2854             return NULL;
2855         }
2856
2857         block = ast_block_new(ctx);
2858         if (!block) {
2859             ast_delete(st);
2860             return NULL;
2861         }
2862
2863         ast_block_add_expr(block, (ast_expression*)st);
2864
2865         ret = ast_return_new(ctx, NULL);
2866         if (!ret) {
2867             ast_delete(block);
2868             return NULL;
2869         }
2870
2871         ast_block_add_expr(block, (ast_expression*)ret);
2872
2873         return (ast_expression*)block;
2874     } else {
2875         ast_expression *left, *right;
2876         size_t diff = afterend - from;
2877         size_t middle = from + diff/2;
2878         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
2879         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2880         return array_accessor_split(parser, array, index, middle, left, right);
2881     }
2882 }
2883
2884 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2885 {
2886     lex_ctx ctx = ast_ctx(array);
2887
2888     if (from+1 == afterend) {
2889         ast_return      *ret;
2890         ast_array_index *subscript;
2891
2892         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2893         if (!subscript)
2894             return NULL;
2895
2896         ret = ast_return_new(ctx, (ast_expression*)subscript);
2897         if (!ret) {
2898             ast_delete(subscript);
2899             return NULL;
2900         }
2901
2902         return (ast_expression*)ret;
2903     } else {
2904         ast_expression *left, *right;
2905         size_t diff = afterend - from;
2906         size_t middle = from + diff/2;
2907         left  = array_getter_node(parser, array, index, from, middle);
2908         right = array_getter_node(parser, array, index, middle, afterend);
2909         return array_accessor_split(parser, array, index, middle, left, right);
2910     }
2911 }
2912
2913 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2914 {
2915     ast_function   *func = NULL;
2916     ast_value      *fval = NULL;
2917     ast_block      *body = NULL;
2918
2919     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2920     if (!fval) {
2921         parseerror(parser, "failed to create accessor function value");
2922         return false;
2923     }
2924
2925     func = ast_function_new(ast_ctx(array), funcname, fval);
2926     if (!func) {
2927         ast_delete(fval);
2928         parseerror(parser, "failed to create accessor function node");
2929         return false;
2930     }
2931
2932     body = ast_block_new(ast_ctx(array));
2933     if (!body) {
2934         parseerror(parser, "failed to create block for array accessor");
2935         ast_delete(fval);
2936         ast_delete(func);
2937         return false;
2938     }
2939
2940     vec_push(func->blocks, body);
2941     *out = fval;
2942
2943     vec_push(parser->accessors, fval);
2944
2945     return true;
2946 }
2947
2948 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2949 {
2950     ast_expression *root = NULL;
2951     ast_value      *index = NULL;
2952     ast_value      *value = NULL;
2953     ast_function   *func;
2954     ast_value      *fval;
2955
2956     if (!ast_istype(array->expression.next, ast_value)) {
2957         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2958         return false;
2959     }
2960
2961     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2962         return false;
2963     func = fval->constval.vfunc;
2964     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2965
2966     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2967     value = ast_value_copy((ast_value*)array->expression.next);
2968
2969     if (!index || !value) {
2970         parseerror(parser, "failed to create locals for array accessor");
2971         goto cleanup;
2972     }
2973     (void)!ast_value_set_name(value, "value"); /* not important */
2974     vec_push(fval->expression.params, index);
2975     vec_push(fval->expression.params, value);
2976
2977     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2978     if (!root) {
2979         parseerror(parser, "failed to build accessor search tree");
2980         goto cleanup;
2981     }
2982
2983     ast_block_add_expr(func->blocks[0], root);
2984     array->setter = fval;
2985     return true;
2986 cleanup:
2987     if (index) ast_delete(index);
2988     if (value) ast_delete(value);
2989     if (root)  ast_delete(root);
2990     ast_delete(func);
2991     ast_delete(fval);
2992     return false;
2993 }
2994
2995 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2996 {
2997     ast_expression *root = NULL;
2998     ast_value      *entity = NULL;
2999     ast_value      *index = NULL;
3000     ast_value      *value = NULL;
3001     ast_function   *func;
3002     ast_value      *fval;
3003
3004     if (!ast_istype(array->expression.next, ast_value)) {
3005         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3006         return false;
3007     }
3008
3009     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3010         return false;
3011     func = fval->constval.vfunc;
3012     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3013
3014     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3015     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
3016     value  = ast_value_copy((ast_value*)array->expression.next);
3017     if (!entity || !index || !value) {
3018         parseerror(parser, "failed to create locals for array accessor");
3019         goto cleanup;
3020     }
3021     (void)!ast_value_set_name(value, "value"); /* not important */
3022     vec_push(fval->expression.params, entity);
3023     vec_push(fval->expression.params, index);
3024     vec_push(fval->expression.params, value);
3025
3026     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3027     if (!root) {
3028         parseerror(parser, "failed to build accessor search tree");
3029         goto cleanup;
3030     }
3031
3032     ast_block_add_expr(func->blocks[0], root);
3033     array->setter = fval;
3034     return true;
3035 cleanup:
3036     if (entity) ast_delete(entity);
3037     if (index)  ast_delete(index);
3038     if (value)  ast_delete(value);
3039     if (root)   ast_delete(root);
3040     ast_delete(func);
3041     ast_delete(fval);
3042     return false;
3043 }
3044
3045 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3046 {
3047     ast_expression *root = NULL;
3048     ast_value      *index = NULL;
3049     ast_value      *fval;
3050     ast_function   *func;
3051
3052     /* NOTE: checking array->expression.next rather than elemtype since
3053      * for fields elemtype is a temporary fieldtype.
3054      */
3055     if (!ast_istype(array->expression.next, ast_value)) {
3056         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3057         return false;
3058     }
3059
3060     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3061         return false;
3062     func = fval->constval.vfunc;
3063     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3064
3065     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3066
3067     if (!index) {
3068         parseerror(parser, "failed to create locals for array accessor");
3069         goto cleanup;
3070     }
3071     vec_push(fval->expression.params, index);
3072
3073     root = array_getter_node(parser, array, index, 0, array->expression.count);
3074     if (!root) {
3075         parseerror(parser, "failed to build accessor search tree");
3076         goto cleanup;
3077     }
3078
3079     ast_block_add_expr(func->blocks[0], root);
3080     array->getter = fval;
3081     return true;
3082 cleanup:
3083     if (index) ast_delete(index);
3084     if (root)  ast_delete(root);
3085     ast_delete(func);
3086     ast_delete(fval);
3087     return false;
3088 }
3089
3090 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3091 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3092 {
3093     lex_ctx     ctx;
3094     size_t      i;
3095     ast_value **params;
3096     ast_value  *param;
3097     ast_value  *fval;
3098     bool        first = true;
3099     bool        variadic = false;
3100
3101     ctx = parser_ctx(parser);
3102
3103     /* for the sake of less code we parse-in in this function */
3104     if (!parser_next(parser)) {
3105         parseerror(parser, "expected parameter list");
3106         return NULL;
3107     }
3108
3109     params = NULL;
3110
3111     /* parse variables until we hit a closing paren */
3112     while (parser->tok != ')') {
3113         if (!first) {
3114             /* there must be commas between them */
3115             if (parser->tok != ',') {
3116                 parseerror(parser, "expected comma or end of parameter list");
3117                 goto on_error;
3118             }
3119             if (!parser_next(parser)) {
3120                 parseerror(parser, "expected parameter");
3121                 goto on_error;
3122             }
3123         }
3124         first = false;
3125
3126         if (parser->tok == TOKEN_DOTS) {
3127             /* '...' indicates a varargs function */
3128             variadic = true;
3129             if (!parser_next(parser)) {
3130                 parseerror(parser, "expected parameter");
3131                 return NULL;
3132             }
3133             if (parser->tok != ')') {
3134                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3135                 goto on_error;
3136             }
3137         }
3138         else
3139         {
3140             /* for anything else just parse a typename */
3141             param = parse_typename(parser, NULL, NULL);
3142             if (!param)
3143                 goto on_error;
3144             vec_push(params, param);
3145             if (param->expression.vtype >= TYPE_VARIANT) {
3146                 char typename[1024];
3147                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3148                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3149                 goto on_error;
3150             }
3151         }
3152     }
3153
3154     /* sanity check */
3155     if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3156         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3157
3158     /* parse-out */
3159     if (!parser_next(parser)) {
3160         parseerror(parser, "parse error after typename");
3161         goto on_error;
3162     }
3163
3164     /* now turn 'var' into a function type */
3165     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3166     fval->expression.next     = (ast_expression*)var;
3167     fval->expression.variadic = variadic;
3168     var = fval;
3169
3170     var->expression.params = params;
3171     params = NULL;
3172
3173     return var;
3174
3175 on_error:
3176     ast_delete(var);
3177     for (i = 0; i < vec_size(params); ++i)
3178         ast_delete(params[i]);
3179     vec_free(params);
3180     return NULL;
3181 }
3182
3183 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3184 {
3185     ast_expression *cexp;
3186     ast_value      *cval, *tmp;
3187     lex_ctx ctx;
3188
3189     ctx = parser_ctx(parser);
3190
3191     if (!parser_next(parser)) {
3192         ast_delete(var);
3193         parseerror(parser, "expected array-size");
3194         return NULL;
3195     }
3196
3197     cexp = parse_expression_leave(parser, true);
3198
3199     if (!cexp || !ast_istype(cexp, ast_value)) {
3200         if (cexp)
3201             ast_unref(cexp);
3202         ast_delete(var);
3203         parseerror(parser, "expected array-size as constant positive integer");
3204         return NULL;
3205     }
3206     cval = (ast_value*)cexp;
3207
3208     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3209     tmp->expression.next = (ast_expression*)var;
3210     var = tmp;
3211
3212     if (cval->expression.vtype == TYPE_INTEGER)
3213         tmp->expression.count = cval->constval.vint;
3214     else if (cval->expression.vtype == TYPE_FLOAT)
3215         tmp->expression.count = cval->constval.vfloat;
3216     else {
3217         ast_unref(cexp);
3218         ast_delete(var);
3219         parseerror(parser, "array-size must be a positive integer constant");
3220         return NULL;
3221     }
3222     ast_unref(cexp);
3223
3224     if (parser->tok != ']') {
3225         ast_delete(var);
3226         parseerror(parser, "expected ']' after array-size");
3227         return NULL;
3228     }
3229     if (!parser_next(parser)) {
3230         ast_delete(var);
3231         parseerror(parser, "error after parsing array size");
3232         return NULL;
3233     }
3234     return var;
3235 }
3236
3237 /* Parse a complete typename.
3238  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3239  * but when parsing variables separated by comma
3240  * 'storebase' should point to where the base-type should be kept.
3241  * The base type makes up every bit of type information which comes *before* the
3242  * variable name.
3243  *
3244  * The following will be parsed in its entirety:
3245  *     void() foo()
3246  * The 'basetype' in this case is 'void()'
3247  * and if there's a comma after it, say:
3248  *     void() foo(), bar
3249  * then the type-information 'void()' can be stored in 'storebase'
3250  */
3251 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3252 {
3253     ast_value *var, *tmp;
3254     lex_ctx    ctx;
3255
3256     const char *name = NULL;
3257     bool        isfield  = false;
3258     bool        wasarray = false;
3259     size_t      morefields = 0;
3260
3261     ctx = parser_ctx(parser);
3262
3263     /* types may start with a dot */
3264     if (parser->tok == '.') {
3265         isfield = true;
3266         /* if we parsed a dot we need a typename now */
3267         if (!parser_next(parser)) {
3268             parseerror(parser, "expected typename for field definition");
3269             return NULL;
3270         }
3271
3272         /* Further dots are handled seperately because they won't be part of the
3273          * basetype
3274          */
3275         while (parser->tok == '.') {
3276             ++morefields;
3277             if (!parser_next(parser)) {
3278                 parseerror(parser, "expected typename for field definition");
3279                 return NULL;
3280             }
3281         }
3282
3283         if (parser->tok == TOKEN_IDENT)
3284             cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3285         if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3286             parseerror(parser, "expected typename");
3287             return NULL;
3288         }
3289     }
3290
3291     /* generate the basic type value */
3292     if (cached_typedef) {
3293         var = ast_value_copy(cached_typedef);
3294         ast_value_set_name(var, "<type(from_def)>");
3295     } else
3296         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3297
3298     for (; morefields; --morefields) {
3299         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3300         tmp->expression.next = (ast_expression*)var;
3301         var = tmp;
3302     }
3303
3304     /* do not yet turn into a field - remember:
3305      * .void() foo; is a field too
3306      * .void()() foo; is a function
3307      */
3308
3309     /* parse on */
3310     if (!parser_next(parser)) {
3311         ast_delete(var);
3312         parseerror(parser, "parse error after typename");
3313         return NULL;
3314     }
3315
3316     /* an opening paren now starts the parameter-list of a function
3317      * this is where original-QC has parameter lists.
3318      * We allow a single parameter list here.
3319      * Much like fteqcc we don't allow `float()() x`
3320      */
3321     if (parser->tok == '(') {
3322         var = parse_parameter_list(parser, var);
3323         if (!var)
3324             return NULL;
3325     }
3326
3327     /* store the base if requested */
3328     if (storebase) {
3329         *storebase = ast_value_copy(var);
3330         if (isfield) {
3331             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3332             tmp->expression.next = (ast_expression*)*storebase;
3333             *storebase = tmp;
3334         }
3335     }
3336
3337     /* there may be a name now */
3338     if (parser->tok == TOKEN_IDENT) {
3339         name = util_strdup(parser_tokval(parser));
3340         /* parse on */
3341         if (!parser_next(parser)) {
3342             ast_delete(var);
3343             parseerror(parser, "error after variable or field declaration");
3344             return NULL;
3345         }
3346     }
3347
3348     /* now this may be an array */
3349     if (parser->tok == '[') {
3350         wasarray = true;
3351         var = parse_arraysize(parser, var);
3352         if (!var)
3353             return NULL;
3354     }
3355
3356     /* This is the point where we can turn it into a field */
3357     if (isfield) {
3358         /* turn it into a field if desired */
3359         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3360         tmp->expression.next = (ast_expression*)var;
3361         var = tmp;
3362     }
3363
3364     /* now there may be function parens again */
3365     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3366         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3367     if (parser->tok == '(' && wasarray)
3368         parseerror(parser, "arrays as part of a return type is not supported");
3369     while (parser->tok == '(') {
3370         var = parse_parameter_list(parser, var);
3371         if (!var) {
3372             if (name)
3373                 mem_d((void*)name);
3374             ast_delete(var);
3375             return NULL;
3376         }
3377     }
3378
3379     /* finally name it */
3380     if (name) {
3381         if (!ast_value_set_name(var, name)) {
3382             ast_delete(var);
3383             parseerror(parser, "internal error: failed to set name");
3384             return NULL;
3385         }
3386         /* free the name, ast_value_set_name duplicates */
3387         mem_d((void*)name);
3388     }
3389
3390     return var;
3391 }
3392
3393 static bool parse_typedef(parser_t *parser)
3394 {
3395     ast_value      *typevar, *oldtype;
3396     ast_expression *old;
3397
3398     typevar = parse_typename(parser, NULL, NULL);
3399
3400     if (!typevar)
3401         return false;
3402
3403     if ( (old = parser_find_var(parser, typevar->name)) ) {
3404         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3405                    " -> `%s` has been declared here: %s:%i",
3406                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3407         ast_delete(typevar);
3408         return false;
3409     }
3410
3411     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3412         parseerror(parser, "type `%s` has already been declared here: %s:%i",
3413                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3414         ast_delete(typevar);
3415         return false;
3416     }
3417
3418     vec_push(parser->_typedefs, typevar);
3419     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3420
3421     if (parser->tok != ';') {
3422         parseerror(parser, "expected semicolon after typedef");
3423         return false;
3424     }
3425     if (!parser_next(parser)) {
3426         parseerror(parser, "parse error after typedef");
3427         return false;
3428     }
3429
3430     return true;
3431 }
3432
3433 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const, ast_value *cached_typedef)
3434 {
3435     ast_value *var;
3436     ast_value *proto;
3437     ast_expression *old;
3438     bool       was_end;
3439     size_t     i;
3440
3441     ast_value *basetype = NULL;
3442     bool      retval    = true;
3443     bool      isparam   = false;
3444     bool      isvector  = false;
3445     bool      cleanvar  = true;
3446     bool      wasarray  = false;
3447
3448     ast_member *me[3];
3449
3450     /* get the first complete variable */
3451     var = parse_typename(parser, &basetype, cached_typedef);
3452     if (!var) {
3453         if (basetype)
3454             ast_delete(basetype);
3455         return false;
3456     }
3457
3458     while (true) {
3459         proto = NULL;
3460         wasarray = false;
3461
3462         /* Part 0: finish the type */
3463         if (parser->tok == '(') {
3464             if (opts_standard == COMPILER_QCC)
3465                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3466             var = parse_parameter_list(parser, var);
3467             if (!var) {
3468                 retval = false;
3469                 goto cleanup;
3470             }
3471         }
3472         /* we only allow 1-dimensional arrays */
3473         if (parser->tok == '[') {
3474             wasarray = true;
3475             var = parse_arraysize(parser, var);
3476             if (!var) {
3477                 retval = false;
3478                 goto cleanup;
3479             }
3480         }
3481         if (parser->tok == '(' && wasarray) {
3482             parseerror(parser, "arrays as part of a return type is not supported");
3483             /* we'll still parse the type completely for now */
3484         }
3485         /* for functions returning functions */
3486         while (parser->tok == '(') {
3487             if (opts_standard == COMPILER_QCC)
3488                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3489             var = parse_parameter_list(parser, var);
3490             if (!var) {
3491                 retval = false;
3492                 goto cleanup;
3493             }
3494         }
3495
3496         if (is_const)
3497             var->constant = true;
3498
3499         /* Part 1:
3500          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3501          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3502          * is then filled with the previous definition and the parameter-names replaced.
3503          */
3504         if (!localblock) {
3505             /* Deal with end_sys_ vars */
3506             was_end = false;
3507             if (!strcmp(var->name, "end_sys_globals")) {
3508                 parser->crc_globals = vec_size(parser->globals);
3509                 was_end = true;
3510             }
3511             else if (!strcmp(var->name, "end_sys_fields")) {
3512                 parser->crc_fields = vec_size(parser->fields);
3513                 was_end = true;
3514             }
3515             if (was_end && var->expression.vtype == TYPE_FIELD) {
3516                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3517                                  "global '%s' hint should not be a field",
3518                                  parser_tokval(parser)))
3519                 {
3520                     retval = false;
3521                     goto cleanup;
3522                 }
3523             }
3524
3525             if (!nofields && var->expression.vtype == TYPE_FIELD)
3526             {
3527                 /* deal with field declarations */
3528                 old = parser_find_field(parser, var->name);
3529                 if (old) {
3530                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3531                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3532                     {
3533                         retval = false;
3534                         goto cleanup;
3535                     }
3536                     ast_delete(var);
3537                     var = NULL;
3538                     goto skipvar;
3539                     /*
3540                     parseerror(parser, "field `%s` already declared here: %s:%i",
3541                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3542                     retval = false;
3543                     goto cleanup;
3544                     */
3545                 }
3546                 if (opts_standard == COMPILER_QCC &&
3547                     (old = parser_find_global(parser, var->name)))
3548                 {
3549                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3550                     parseerror(parser, "field `%s` already declared here: %s:%i",
3551                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3552                     retval = false;
3553                     goto cleanup;
3554                 }
3555             }
3556             else
3557             {
3558                 /* deal with other globals */
3559                 old = parser_find_global(parser, var->name);
3560                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3561                 {
3562                     /* This is a function which had a prototype */
3563                     if (!ast_istype(old, ast_value)) {
3564                         parseerror(parser, "internal error: prototype is not an ast_value");
3565                         retval = false;
3566                         goto cleanup;
3567                     }
3568                     proto = (ast_value*)old;
3569                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3570                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3571                                    proto->name,
3572                                    ast_ctx(proto).file, ast_ctx(proto).line);
3573                         retval = false;
3574                         goto cleanup;
3575                     }
3576                     /* we need the new parameter-names */
3577                     for (i = 0; i < vec_size(proto->expression.params); ++i)
3578                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3579                     ast_delete(var);
3580                     var = proto;
3581                 }
3582                 else
3583                 {
3584                     /* other globals */
3585                     if (old) {
3586                         if (opts_standard == COMPILER_GMQCC) {
3587                             parseerror(parser, "global `%s` already declared here: %s:%i",
3588                                        var->name, ast_ctx(old).file, ast_ctx(old).line);
3589                             retval = false;
3590                             goto cleanup;
3591                         } else {
3592                             if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3593                                              "global `%s` already declared here: %s:%i",
3594                                              var->name, ast_ctx(old).file, ast_ctx(old).line))
3595                             {
3596                                 retval = false;
3597                                 goto cleanup;
3598                             }
3599                         }
3600                     }
3601                     if (opts_standard == COMPILER_QCC &&
3602                         (old = parser_find_field(parser, var->name)))
3603                     {
3604                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3605                         parseerror(parser, "global `%s` already declared here: %s:%i",
3606                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3607                         retval = false;
3608                         goto cleanup;
3609                     }
3610                 }
3611             }
3612         }
3613         else /* it's not a global */
3614         {
3615             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3616             if (old && !isparam) {
3617                 parseerror(parser, "local `%s` already declared here: %s:%i",
3618                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3619                 retval = false;
3620                 goto cleanup;
3621             }
3622             old = parser_find_local(parser, var->name, 0, &isparam);
3623             if (old && isparam) {
3624                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3625                                  "local `%s` is shadowing a parameter", var->name))
3626                 {
3627                     parseerror(parser, "local `%s` already declared here: %s:%i",
3628                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3629                     retval = false;
3630                     goto cleanup;
3631                 }
3632                 if (opts_standard != COMPILER_GMQCC) {
3633                     ast_delete(var);
3634                     var = NULL;
3635                     goto skipvar;
3636                 }
3637             }
3638         }
3639
3640         /* Part 2:
3641          * Create the global/local, and deal with vector types.
3642          */
3643         if (!proto) {
3644             if (var->expression.vtype == TYPE_VECTOR)
3645                 isvector = true;
3646             else if (var->expression.vtype == TYPE_FIELD &&
3647                      var->expression.next->expression.vtype == TYPE_VECTOR)
3648                 isvector = true;
3649
3650             if (isvector) {
3651                 if (!create_vector_members(var, me)) {
3652                     retval = false;
3653                     goto cleanup;
3654                 }
3655             }
3656
3657             if (!localblock) {
3658                 /* deal with global variables, fields, functions */
3659                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3660                     vec_push(parser->fields, (ast_expression*)var);
3661                     util_htset(parser->htfields, var->name, var);
3662                     if (isvector) {
3663                         for (i = 0; i < 3; ++i) {
3664                             vec_push(parser->fields, (ast_expression*)me[i]);
3665                             util_htset(parser->htfields, me[i]->name, me[i]);
3666                         }
3667                     }
3668                 }
3669                 else {
3670                     vec_push(parser->globals, (ast_expression*)var);
3671                     util_htset(parser->htglobals, var->name, var);
3672                     if (isvector) {
3673                         for (i = 0; i < 3; ++i) {
3674                             vec_push(parser->globals, (ast_expression*)me[i]);
3675                             util_htset(parser->htglobals, me[i]->name, me[i]);
3676                         }
3677                     }
3678                 }
3679             } else {
3680                 vec_push(localblock->locals, var);
3681                 parser_addlocal(parser, var->name, (ast_expression*)var);
3682                 if (isvector) {
3683                     for (i = 0; i < 3; ++i) {
3684                         parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3685                         ast_block_collect(localblock, (ast_expression*)me[i]);
3686                     }
3687                 }
3688             }
3689
3690         }
3691         me[0] = me[1] = me[2] = NULL;
3692         cleanvar = false;
3693         /* Part 2.2
3694          * deal with arrays
3695          */
3696         if (var->expression.vtype == TYPE_ARRAY) {
3697             char name[1024];
3698             snprintf(name, sizeof(name), "%s##SET", var->name);
3699             if (!parser_create_array_setter(parser, var, name))
3700                 goto cleanup;
3701             snprintf(name, sizeof(name), "%s##GET", var->name);
3702             if (!parser_create_array_getter(parser, var, var->expression.next, name))
3703                 goto cleanup;
3704         }
3705         else if (!localblock && !nofields &&
3706                  var->expression.vtype == TYPE_FIELD &&
3707                  var->expression.next->expression.vtype == TYPE_ARRAY)
3708         {
3709             char name[1024];
3710             ast_expression *telem;
3711             ast_value      *tfield;
3712             ast_value      *array = (ast_value*)var->expression.next;
3713
3714             if (!ast_istype(var->expression.next, ast_value)) {
3715                 parseerror(parser, "internal error: field element type must be an ast_value");
3716                 goto cleanup;
3717             }
3718
3719             snprintf(name, sizeof(name), "%s##SETF", var->name);
3720             if (!parser_create_array_field_setter(parser, array, name))
3721                 goto cleanup;
3722
3723             telem = ast_type_copy(ast_ctx(var), array->expression.next);
3724             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3725             tfield->expression.next = telem;
3726             snprintf(name, sizeof(name), "%s##GETFP", var->name);
3727             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3728                 ast_delete(tfield);
3729                 goto cleanup;
3730             }
3731             ast_delete(tfield);
3732         }
3733
3734 skipvar:
3735         if (parser->tok == ';') {
3736             ast_delete(basetype);
3737             if (!parser_next(parser)) {
3738                 parseerror(parser, "error after variable declaration");
3739                 return false;
3740             }
3741             return true;
3742         }
3743
3744         if (parser->tok == ',')
3745             goto another;
3746
3747         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3748             parseerror(parser, "missing comma or semicolon while parsing variables");
3749             break;
3750         }
3751
3752         if (localblock && opts_standard == COMPILER_QCC) {
3753             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3754                              "initializing expression turns variable `%s` into a constant in this standard",
3755                              var->name) )
3756             {
3757                 break;
3758             }
3759         }
3760
3761         if (parser->tok != '{') {
3762             if (parser->tok != '=') {
3763                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
3764                 break;
3765             }
3766
3767             if (!parser_next(parser)) {
3768                 parseerror(parser, "error parsing initializer");
3769                 break;
3770             }
3771         }
3772         else if (opts_standard == COMPILER_QCC) {
3773             parseerror(parser, "expected '=' before function body in this standard");
3774         }
3775
3776         if (parser->tok == '#') {
3777             ast_function *func = NULL;
3778
3779             if (localblock) {
3780                 parseerror(parser, "cannot declare builtins within functions");
3781                 break;
3782             }
3783             if (var->expression.vtype != TYPE_FUNCTION) {
3784                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3785                 break;
3786             }
3787             if (!parser_next(parser)) {
3788                 parseerror(parser, "expected builtin number");
3789                 break;
3790             }
3791             if (parser->tok != TOKEN_INTCONST) {
3792                 parseerror(parser, "builtin number must be an integer constant");
3793                 break;
3794             }
3795             if (parser_token(parser)->constval.i <= 0) {
3796                 parseerror(parser, "builtin number must be an integer greater than zero");
3797                 break;
3798             }
3799
3800             if (var->hasvalue) {
3801                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
3802                                     "builtin `%s` has already been defined\n"
3803                                     " -> previous declaration here: %s:%i",
3804                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
3805             }
3806             else
3807             {
3808                 func = ast_function_new(ast_ctx(var), var->name, var);
3809                 if (!func) {
3810                     parseerror(parser, "failed to allocate function for `%s`", var->name);
3811                     break;
3812                 }
3813                 vec_push(parser->functions, func);
3814
3815                 func->builtin = -parser_token(parser)->constval.i;
3816             }
3817
3818             if (!parser_next(parser)) {
3819                 parseerror(parser, "expected comma or semicolon");
3820                 if (func)
3821                     ast_function_delete(func);
3822                 var->constval.vfunc = NULL;
3823                 break;
3824             }
3825         }
3826         else if (parser->tok == '{' || parser->tok == '[')
3827         {
3828             if (localblock) {
3829                 parseerror(parser, "cannot declare functions within functions");
3830                 break;
3831             }
3832
3833             if (!parse_function_body(parser, var))
3834                 break;
3835             ast_delete(basetype);
3836             return true;
3837         } else {
3838             ast_expression *cexp;
3839             ast_value      *cval;
3840
3841             cexp = parse_expression_leave(parser, true);
3842             if (!cexp)
3843                 break;
3844
3845             if (!localblock) {
3846                 cval = (ast_value*)cexp;
3847                 if (!ast_istype(cval, ast_value) || !cval->hasvalue)
3848                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3849                 else
3850                 {
3851                     if (opts_standard != COMPILER_GMQCC && !OPTS_FLAG(INITIALIZED_NONCONSTANTS))
3852                         var->constant = true;
3853                     var->hasvalue = true;
3854                     if (cval->expression.vtype == TYPE_STRING)
3855                         var->constval.vstring = parser_strdup(cval->constval.vstring);
3856                     else
3857                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3858                     ast_unref(cval);
3859                 }
3860             } else {
3861                 shunt sy = { NULL, NULL };
3862                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3863                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3864                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3865                 if (!parser_sy_pop(parser, &sy))
3866                     ast_unref(cexp);
3867                 else {
3868                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3869                         parseerror(parser, "internal error: leaked operands");
3870                     ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out);
3871                 }
3872                 vec_free(sy.out);
3873                 vec_free(sy.ops);
3874             }
3875         }
3876
3877 another:
3878         if (parser->tok == ',') {
3879             if (!parser_next(parser)) {
3880                 parseerror(parser, "expected another variable");
3881                 break;
3882             }
3883
3884             if (parser->tok != TOKEN_IDENT) {
3885                 parseerror(parser, "expected another variable");
3886                 break;
3887             }
3888             var = ast_value_copy(basetype);
3889             cleanvar = true;
3890             ast_value_set_name(var, parser_tokval(parser));
3891             if (!parser_next(parser)) {
3892                 parseerror(parser, "error parsing variable declaration");
3893                 break;
3894             }
3895             continue;
3896         }
3897
3898         if (parser->tok != ';') {
3899             parseerror(parser, "missing semicolon after variables");
3900             break;
3901         }
3902
3903         if (!parser_next(parser)) {
3904             parseerror(parser, "parse error after variable declaration");
3905             break;
3906         }
3907
3908         ast_delete(basetype);
3909         return true;
3910     }
3911
3912     if (cleanvar && var)
3913         ast_delete(var);
3914     ast_delete(basetype);
3915     return false;
3916
3917 cleanup:
3918     ast_delete(basetype);
3919     if (cleanvar && var)
3920         ast_delete(var);
3921     if (me[0]) ast_member_delete(me[0]);
3922     if (me[1]) ast_member_delete(me[1]);
3923     if (me[2]) ast_member_delete(me[2]);
3924     return retval;
3925 }
3926
3927 static bool parser_global_statement(parser_t *parser)
3928 {
3929     ast_value *istype = NULL;
3930     if (parser->tok == TOKEN_IDENT)
3931         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
3932
3933     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3934     {
3935         return parse_variable(parser, NULL, false, false, istype);
3936     }
3937     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
3938     {
3939         if (!strcmp(parser_tokval(parser), "var")) {
3940             if (!parser_next(parser)) {
3941                 parseerror(parser, "expected variable declaration after 'var'");
3942                 return false;
3943             }
3944             return parse_variable(parser, NULL, true, false, NULL);
3945         }
3946     }
3947     else if (parser->tok == TOKEN_KEYWORD)
3948     {
3949         if (!strcmp(parser_tokval(parser), "const")) {
3950             if (!parser_next(parser)) {
3951                 parseerror(parser, "expected variable declaration after 'const'");
3952                 return false;
3953             }
3954             if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var")) {
3955                 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `var` after const qualifier");
3956                 if (!parser_next(parser)) {
3957                     parseerror(parser, "expected variable declaration after 'const var'");
3958                     return false;
3959                 }
3960             }
3961             return parse_variable(parser, NULL, true, true, NULL);
3962         }
3963         else if (!strcmp(parser_tokval(parser), "typedef")) {
3964             if (!parser_next(parser)) {
3965                 parseerror(parser, "expected type definition after 'typedef'");
3966                 return false;
3967             }
3968             return parse_typedef(parser);
3969         }
3970         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
3971         return false;
3972     }
3973     else if (parser->tok == '$')
3974     {
3975         if (!parser_next(parser)) {
3976             parseerror(parser, "parse error");
3977             return false;
3978         }
3979     }
3980     else
3981     {
3982         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3983         return false;
3984     }
3985     return true;
3986 }
3987
3988 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3989 {
3990     return util_crc16(old, str, strlen(str));
3991 }
3992
3993 static void progdefs_crc_file(const char *str)
3994 {
3995     /* write to progdefs.h here */
3996     (void)str;
3997 }
3998
3999 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4000 {
4001     old = progdefs_crc_sum(old, str);
4002     progdefs_crc_file(str);
4003     return old;
4004 }
4005
4006 static void generate_checksum(parser_t *parser)
4007 {
4008     uint16_t   crc = 0xFFFF;
4009     size_t     i;
4010     ast_value *value;
4011
4012         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4013         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4014         /*
4015         progdefs_crc_file("\tint\tpad;\n");
4016         progdefs_crc_file("\tint\tofs_return[3];\n");
4017         progdefs_crc_file("\tint\tofs_parm0[3];\n");
4018         progdefs_crc_file("\tint\tofs_parm1[3];\n");
4019         progdefs_crc_file("\tint\tofs_parm2[3];\n");
4020         progdefs_crc_file("\tint\tofs_parm3[3];\n");
4021         progdefs_crc_file("\tint\tofs_parm4[3];\n");
4022         progdefs_crc_file("\tint\tofs_parm5[3];\n");
4023         progdefs_crc_file("\tint\tofs_parm6[3];\n");
4024         progdefs_crc_file("\tint\tofs_parm7[3];\n");
4025         */
4026         for (i = 0; i < parser->crc_globals; ++i) {
4027             if (!ast_istype(parser->globals[i], ast_value))
4028                 continue;
4029             value = (ast_value*)(parser->globals[i]);
4030             switch (value->expression.vtype) {
4031                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4032                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4033                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4034                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4035                 default:
4036                     crc = progdefs_crc_both(crc, "\tint\t");
4037                     break;
4038             }
4039             crc = progdefs_crc_both(crc, value->name);
4040             crc = progdefs_crc_both(crc, ";\n");
4041         }
4042         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4043         for (i = 0; i < parser->crc_fields; ++i) {
4044             if (!ast_istype(parser->fields[i], ast_value))
4045                 continue;
4046             value = (ast_value*)(parser->fields[i]);
4047             switch (value->expression.next->expression.vtype) {
4048                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4049                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4050                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4051                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4052                 default:
4053                     crc = progdefs_crc_both(crc, "\tint\t");
4054                     break;
4055             }
4056             crc = progdefs_crc_both(crc, value->name);
4057             crc = progdefs_crc_both(crc, ";\n");
4058         }
4059         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4060
4061         code_crc = crc;
4062 }
4063
4064 static parser_t *parser;
4065
4066 bool parser_init()
4067 {
4068     size_t i;
4069
4070     parser = (parser_t*)mem_a(sizeof(parser_t));
4071     if (!parser)
4072         return false;
4073
4074     memset(parser, 0, sizeof(*parser));
4075
4076     for (i = 0; i < operator_count; ++i) {
4077         if (operators[i].id == opid1('=')) {
4078             parser->assign_op = operators+i;
4079             break;
4080         }
4081     }
4082     if (!parser->assign_op) {
4083         printf("internal error: initializing parser: failed to find assign operator\n");
4084         mem_d(parser);
4085         return false;
4086     }
4087
4088     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
4089     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4090     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4091     vec_push(parser->_blocktypedefs, 0);
4092     return true;
4093 }
4094
4095 bool parser_compile()
4096 {
4097     /* initial lexer/parser state */
4098     parser->lex->flags.noops = true;
4099
4100     if (parser_next(parser))
4101     {
4102         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4103         {
4104             if (!parser_global_statement(parser)) {
4105                 if (parser->tok == TOKEN_EOF)
4106                     parseerror(parser, "unexpected eof");
4107                 else if (!parser->errors)
4108                     parseerror(parser, "there have been errors, bailing out");
4109                 lex_close(parser->lex);
4110                 parser->lex = NULL;
4111                 return false;
4112             }
4113         }
4114     } else {
4115         parseerror(parser, "parse error");
4116         lex_close(parser->lex);
4117         parser->lex = NULL;
4118         return false;
4119     }
4120
4121     lex_close(parser->lex);
4122     parser->lex = NULL;
4123
4124     return !parser->errors;
4125 }
4126
4127 bool parser_compile_file(const char *filename)
4128 {
4129     parser->lex = lex_open(filename);
4130     if (!parser->lex) {
4131         con_err("failed to open file \"%s\"\n", filename);
4132         return false;
4133     }
4134     return parser_compile();
4135 }
4136
4137 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4138 {
4139     parser->lex = lex_open_string(str, len, name);
4140     if (!parser->lex) {
4141         con_err("failed to create lexer for string \"%s\"\n", name);
4142         return false;
4143     }
4144     return parser_compile();
4145 }
4146
4147 bool parser_compile_string(const char *name, const char *str)
4148 {
4149     parser->lex = lex_open_string(str, strlen(str), name);
4150     if (!parser->lex) {
4151         con_err("failed to create lexer for string \"%s\"\n", name);
4152         return false;
4153     }
4154     return parser_compile();
4155 }
4156
4157 void parser_cleanup()
4158 {
4159     size_t i;
4160     for (i = 0; i < vec_size(parser->accessors); ++i) {
4161         ast_delete(parser->accessors[i]->constval.vfunc);
4162         parser->accessors[i]->constval.vfunc = NULL;
4163         ast_delete(parser->accessors[i]);
4164     }
4165     for (i = 0; i < vec_size(parser->functions); ++i) {
4166         ast_delete(parser->functions[i]);
4167     }
4168     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4169         ast_delete(parser->imm_vector[i]);
4170     }
4171     for (i = 0; i < vec_size(parser->imm_string); ++i) {
4172         ast_delete(parser->imm_string[i]);
4173     }
4174     for (i = 0; i < vec_size(parser->imm_float); ++i) {
4175         ast_delete(parser->imm_float[i]);
4176     }
4177     for (i = 0; i < vec_size(parser->fields); ++i) {
4178         ast_delete(parser->fields[i]);
4179     }
4180     for (i = 0; i < vec_size(parser->globals); ++i) {
4181         ast_delete(parser->globals[i]);
4182     }
4183     vec_free(parser->accessors);
4184     vec_free(parser->functions);
4185     vec_free(parser->imm_vector);
4186     vec_free(parser->imm_string);
4187     vec_free(parser->imm_float);
4188     vec_free(parser->globals);
4189     vec_free(parser->fields);
4190
4191     for (i = 0; i < vec_size(parser->variables); ++i)
4192         util_htdel(parser->variables[i]);
4193     vec_free(parser->variables);
4194     vec_free(parser->_blocklocals);
4195     vec_free(parser->_locals);
4196
4197     for (i = 0; i < vec_size(parser->_typedefs); ++i)
4198         ast_delete(parser->_typedefs[i]);
4199     vec_free(parser->_typedefs);
4200     for (i = 0; i < vec_size(parser->typedefs); ++i)
4201         util_htdel(parser->typedefs[i]);
4202     vec_free(parser->typedefs);
4203     vec_free(parser->_blocktypedefs);
4204
4205     mem_d(parser);
4206 }
4207
4208 bool parser_finish(const char *output)
4209 {
4210     size_t i;
4211     ir_builder *ir;
4212     bool retval = true;
4213
4214     if (!parser->errors)
4215     {
4216         ir = ir_builder_new("gmqcc_out");
4217         if (!ir) {
4218             con_out("failed to allocate builder\n");
4219             return false;
4220         }
4221
4222         for (i = 0; i < vec_size(parser->fields); ++i) {
4223             ast_value *field;
4224             bool hasvalue;
4225             if (!ast_istype(parser->fields[i], ast_value))
4226                 continue;
4227             field = (ast_value*)parser->fields[i];
4228             hasvalue = field->hasvalue;
4229             field->hasvalue = false;
4230             if (!ast_global_codegen((ast_value*)field, ir, true)) {
4231                 con_out("failed to generate field %s\n", field->name);
4232                 ir_builder_delete(ir);
4233                 return false;
4234             }
4235             if (hasvalue) {
4236                 ir_value *ifld;
4237                 ast_expression *subtype;
4238                 field->hasvalue = true;
4239                 subtype = field->expression.next;
4240                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4241                 if (subtype->expression.vtype == TYPE_FIELD)
4242                     ifld->fieldtype = subtype->expression.next->expression.vtype;
4243                 else if (subtype->expression.vtype == TYPE_FUNCTION)
4244                     ifld->outtype = subtype->expression.next->expression.vtype;
4245                 (void)!ir_value_set_field(field->ir_v, ifld);
4246             }
4247         }
4248         for (i = 0; i < vec_size(parser->globals); ++i) {
4249             ast_value *asvalue;
4250             if (!ast_istype(parser->globals[i], ast_value))
4251                 continue;
4252             asvalue = (ast_value*)(parser->globals[i]);
4253             if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4254                 if (strcmp(asvalue->name, "end_sys_globals") &&
4255                     strcmp(asvalue->name, "end_sys_fields"))
4256                 {
4257                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4258                                                    "unused global: `%s`", asvalue->name);
4259                 }
4260             }
4261             if (!ast_global_codegen(asvalue, ir, false)) {
4262                 con_out("failed to generate global %s\n", asvalue->name);
4263                 ir_builder_delete(ir);
4264                 return false;
4265             }
4266         }
4267         for (i = 0; i < vec_size(parser->imm_float); ++i) {
4268             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4269                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4270                 ir_builder_delete(ir);
4271                 return false;
4272             }
4273         }
4274         for (i = 0; i < vec_size(parser->imm_string); ++i) {
4275             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4276                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4277                 ir_builder_delete(ir);
4278                 return false;
4279             }
4280         }
4281         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4282             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4283                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4284                 ir_builder_delete(ir);
4285                 return false;
4286             }
4287         }
4288         for (i = 0; i < vec_size(parser->globals); ++i) {
4289             ast_value *asvalue;
4290             if (!ast_istype(parser->globals[i], ast_value))
4291                 continue;
4292             asvalue = (ast_value*)(parser->globals[i]);
4293             if (asvalue->setter) {
4294                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4295                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4296                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4297                 {
4298                     printf("failed to generate setter for %s\n", asvalue->name);
4299                     ir_builder_delete(ir);
4300                     return false;
4301                 }
4302             }
4303             if (asvalue->getter) {
4304                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4305                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4306                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4307                 {
4308                     printf("failed to generate getter for %s\n", asvalue->name);
4309                     ir_builder_delete(ir);
4310                     return false;
4311                 }
4312             }
4313         }
4314         for (i = 0; i < vec_size(parser->fields); ++i) {
4315             ast_value *asvalue;
4316             asvalue = (ast_value*)(parser->fields[i]->expression.next);
4317
4318             if (!ast_istype((ast_expression*)asvalue, ast_value))
4319                 continue;
4320             if (asvalue->expression.vtype != TYPE_ARRAY)
4321                 continue;
4322             if (asvalue->setter) {
4323                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4324                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4325                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4326                 {
4327                     printf("failed to generate setter for %s\n", asvalue->name);
4328                     ir_builder_delete(ir);
4329                     return false;
4330                 }
4331             }
4332             if (asvalue->getter) {
4333                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4334                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4335                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4336                 {
4337                     printf("failed to generate getter for %s\n", asvalue->name);
4338                     ir_builder_delete(ir);
4339                     return false;
4340                 }
4341             }
4342         }
4343         for (i = 0; i < vec_size(parser->functions); ++i) {
4344             if (!ast_function_codegen(parser->functions[i], ir)) {
4345                 con_out("failed to generate function %s\n", parser->functions[i]->name);
4346                 ir_builder_delete(ir);
4347                 return false;
4348             }
4349         }
4350         if (opts_dump)
4351             ir_builder_dump(ir, con_out);
4352         for (i = 0; i < vec_size(parser->functions); ++i) {
4353             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4354                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4355                 ir_builder_delete(ir);
4356                 return false;
4357             }
4358         }
4359
4360         if (retval) {
4361             if (opts_dumpfin)
4362                 ir_builder_dump(ir, con_out);
4363
4364             generate_checksum(parser);
4365
4366             if (!ir_builder_generate(ir, output)) {
4367                 con_out("*** failed to generate output file\n");
4368                 ir_builder_delete(ir);
4369                 return false;
4370             }
4371         }
4372
4373         ir_builder_delete(ir);
4374         return retval;
4375     }
4376
4377     con_out("*** there were compile errors\n");
4378     return false;
4379 }