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