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