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