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