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