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