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