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