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