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