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