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