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