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