]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Fix a very possible bug
[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     /* parse into the expression */
2089     if (!parser_next(parser)) {
2090         parseerror(parser, "expected 'while' condition after opening paren");
2091         return false;
2092     }
2093     /* parse the condition */
2094     cond = parse_expression_leave(parser, false);
2095     if (!cond)
2096         return false;
2097     /* closing paren */
2098     if (parser->tok != ')') {
2099         parseerror(parser, "expected closing paren after 'while' condition");
2100         ast_delete(cond);
2101         return false;
2102     }
2103     /* parse into the 'then' branch */
2104     if (!parser_next(parser)) {
2105         parseerror(parser, "expected while-loop body");
2106         ast_delete(cond);
2107         return false;
2108     }
2109     if (!parse_statement_or_block(parser, &ontrue)) {
2110         ast_delete(cond);
2111         return false;
2112     }
2113
2114     cond = process_condition(parser, cond, &ifnot);
2115     if (!cond) {
2116         ast_delete(ontrue);
2117         return false;
2118     }
2119     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2120     *out = (ast_expression*)aloop;
2121     return true;
2122 }
2123
2124 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2125 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2126 {
2127     bool rv;
2128     char *label = NULL;
2129
2130     /* skip the 'do' and get the body */
2131     if (!parser_next(parser)) {
2132         if (OPTS_FLAG(LOOP_LABELS))
2133             parseerror(parser, "expected loop label or body");
2134         else
2135             parseerror(parser, "expected loop body");
2136         return false;
2137     }
2138
2139     if (parser->tok == ':') {
2140         if (!OPTS_FLAG(LOOP_LABELS))
2141             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2142         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2143             parseerror(parser, "expected loop label");
2144             return false;
2145         }
2146         label = util_strdup(parser_tokval(parser));
2147         if (!parser_next(parser)) {
2148             mem_d(label);
2149             parseerror(parser, "expected loop body");
2150             return false;
2151         }
2152     }
2153
2154     vec_push(parser->breaks, label);
2155     vec_push(parser->continues, label);
2156
2157     rv = parse_dowhile_go(parser, block, out);
2158     if (label)
2159         mem_d(label);
2160     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2161         parseerror(parser, "internal error: label stack corrupted");
2162         rv = false;
2163         ast_delete(*out);
2164         *out = NULL;
2165     }
2166     else {
2167         vec_pop(parser->breaks);
2168         vec_pop(parser->continues);
2169     }
2170     return rv;
2171 }
2172
2173 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2174 {
2175     ast_loop *aloop;
2176     ast_expression *cond, *ontrue;
2177
2178     bool ifnot = false;
2179
2180     lex_ctx ctx = parser_ctx(parser);
2181
2182     (void)block; /* not touching */
2183
2184     if (!parse_statement_or_block(parser, &ontrue))
2185         return false;
2186
2187     /* expect the "while" */
2188     if (parser->tok != TOKEN_KEYWORD ||
2189         strcmp(parser_tokval(parser), "while"))
2190     {
2191         parseerror(parser, "expected 'while' and condition");
2192         ast_delete(ontrue);
2193         return false;
2194     }
2195
2196     /* skip the 'while' and check for opening paren */
2197     if (!parser_next(parser) || parser->tok != '(') {
2198         parseerror(parser, "expected 'while' condition in parenthesis");
2199         ast_delete(ontrue);
2200         return false;
2201     }
2202     /* parse into the expression */
2203     if (!parser_next(parser)) {
2204         parseerror(parser, "expected 'while' condition after opening paren");
2205         ast_delete(ontrue);
2206         return false;
2207     }
2208     /* parse the condition */
2209     cond = parse_expression_leave(parser, false);
2210     if (!cond)
2211         return false;
2212     /* closing paren */
2213     if (parser->tok != ')') {
2214         parseerror(parser, "expected closing paren after 'while' condition");
2215         ast_delete(ontrue);
2216         ast_delete(cond);
2217         return false;
2218     }
2219     /* parse on */
2220     if (!parser_next(parser) || parser->tok != ';') {
2221         parseerror(parser, "expected semicolon after condition");
2222         ast_delete(ontrue);
2223         ast_delete(cond);
2224         return false;
2225     }
2226
2227     if (!parser_next(parser)) {
2228         parseerror(parser, "parse error");
2229         ast_delete(ontrue);
2230         ast_delete(cond);
2231         return false;
2232     }
2233
2234     cond = process_condition(parser, cond, &ifnot);
2235     if (!cond) {
2236         ast_delete(ontrue);
2237         return false;
2238     }
2239     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2240     *out = (ast_expression*)aloop;
2241     return true;
2242 }
2243
2244 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2245 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2246 {
2247     bool rv;
2248     char *label = NULL;
2249
2250     /* skip the 'for' and check for opening paren */
2251     if (!parser_next(parser)) {
2252         if (OPTS_FLAG(LOOP_LABELS))
2253             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2254         else
2255             parseerror(parser, "expected 'for' expressions in parenthesis");
2256         return false;
2257     }
2258
2259     if (parser->tok == ':') {
2260         if (!OPTS_FLAG(LOOP_LABELS))
2261             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2262         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2263             parseerror(parser, "expected loop label");
2264             return false;
2265         }
2266         label = util_strdup(parser_tokval(parser));
2267         if (!parser_next(parser)) {
2268             mem_d(label);
2269             parseerror(parser, "expected 'for' expressions in parenthesis");
2270             return false;
2271         }
2272     }
2273
2274     if (parser->tok != '(') {
2275         parseerror(parser, "expected 'for' expressions in parenthesis");
2276         return false;
2277     }
2278
2279     vec_push(parser->breaks, label);
2280     vec_push(parser->continues, label);
2281
2282     rv = parse_for_go(parser, block, out);
2283     if (label)
2284         mem_d(label);
2285     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2286         parseerror(parser, "internal error: label stack corrupted");
2287         rv = false;
2288         ast_delete(*out);
2289         *out = NULL;
2290     }
2291     else {
2292         vec_pop(parser->breaks);
2293         vec_pop(parser->continues);
2294     }
2295     return rv;
2296 }
2297 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2298 {
2299     ast_loop       *aloop;
2300     ast_expression *initexpr, *cond, *increment, *ontrue;
2301     ast_value      *typevar;
2302
2303     bool retval = true;
2304     bool ifnot  = false;
2305
2306     lex_ctx ctx = parser_ctx(parser);
2307
2308     parser_enterblock(parser);
2309
2310     initexpr  = NULL;
2311     cond      = NULL;
2312     increment = NULL;
2313     ontrue    = NULL;
2314
2315     /* parse into the expression */
2316     if (!parser_next(parser)) {
2317         parseerror(parser, "expected 'for' initializer after opening paren");
2318         goto onerr;
2319     }
2320
2321     typevar = NULL;
2322     if (parser->tok == TOKEN_IDENT)
2323         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2324
2325     if (typevar || parser->tok == TOKEN_TYPENAME) {
2326         if (opts.standard != COMPILER_GMQCC) {
2327             if (parsewarning(parser, WARN_EXTENSIONS,
2328                              "current standard does not allow variable declarations in for-loop initializers"))
2329                 goto onerr;
2330         }
2331         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, false))
2332             goto onerr;
2333     }
2334     else if (parser->tok != ';')
2335     {
2336         initexpr = parse_expression_leave(parser, false);
2337         if (!initexpr)
2338             goto onerr;
2339     }
2340
2341     /* move on to condition */
2342     if (parser->tok != ';') {
2343         parseerror(parser, "expected semicolon after for-loop initializer");
2344         goto onerr;
2345     }
2346     if (!parser_next(parser)) {
2347         parseerror(parser, "expected for-loop condition");
2348         goto onerr;
2349     }
2350
2351     /* parse the condition */
2352     if (parser->tok != ';') {
2353         cond = parse_expression_leave(parser, false);
2354         if (!cond)
2355             goto onerr;
2356     }
2357
2358     /* move on to incrementor */
2359     if (parser->tok != ';') {
2360         parseerror(parser, "expected semicolon after for-loop initializer");
2361         goto onerr;
2362     }
2363     if (!parser_next(parser)) {
2364         parseerror(parser, "expected for-loop condition");
2365         goto onerr;
2366     }
2367
2368     /* parse the incrementor */
2369     if (parser->tok != ')') {
2370         increment = parse_expression_leave(parser, false);
2371         if (!increment)
2372             goto onerr;
2373         if (!ast_side_effects(increment)) {
2374             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2375                 goto onerr;
2376         }
2377     }
2378
2379     /* closing paren */
2380     if (parser->tok != ')') {
2381         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2382         goto onerr;
2383     }
2384     /* parse into the 'then' branch */
2385     if (!parser_next(parser)) {
2386         parseerror(parser, "expected for-loop body");
2387         goto onerr;
2388     }
2389     if (!parse_statement_or_block(parser, &ontrue))
2390         goto onerr;
2391
2392     if (cond) {
2393         cond = process_condition(parser, cond, &ifnot);
2394         if (!cond)
2395             goto onerr;
2396     }
2397     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2398     *out = (ast_expression*)aloop;
2399
2400     if (!parser_leaveblock(parser))
2401         retval = false;
2402     return retval;
2403 onerr:
2404     if (initexpr)  ast_delete(initexpr);
2405     if (cond)      ast_delete(cond);
2406     if (increment) ast_delete(increment);
2407     (void)!parser_leaveblock(parser);
2408     return false;
2409 }
2410
2411 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2412 {
2413     ast_expression *exp = NULL;
2414     ast_return     *ret = NULL;
2415     ast_value      *expected = parser->function->vtype;
2416
2417     lex_ctx ctx = parser_ctx(parser);
2418
2419     (void)block; /* not touching */
2420
2421     if (!parser_next(parser)) {
2422         parseerror(parser, "expected return expression");
2423         return false;
2424     }
2425
2426     if (parser->tok != ';') {
2427         exp = parse_expression(parser, false);
2428         if (!exp)
2429             return false;
2430
2431         if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2432             parseerror(parser, "return with invalid expression");
2433         }
2434
2435         ret = ast_return_new(ctx, exp);
2436         if (!ret) {
2437             ast_delete(exp);
2438             return false;
2439         }
2440     } else {
2441         if (!parser_next(parser))
2442             parseerror(parser, "parse error");
2443         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2444             if (opts.standard != COMPILER_GMQCC)
2445                 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2446             else
2447                 parseerror(parser, "return without value");
2448         }
2449         ret = ast_return_new(ctx, NULL);
2450     }
2451     *out = (ast_expression*)ret;
2452     return true;
2453 }
2454
2455 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2456 {
2457     size_t       i;
2458     unsigned int levels = 0;
2459     lex_ctx      ctx = parser_ctx(parser);
2460     const char **loops = (is_continue ? parser->continues : parser->breaks);
2461
2462     (void)block; /* not touching */
2463     if (!parser_next(parser)) {
2464         parseerror(parser, "expected semicolon or loop label");
2465         return false;
2466     }
2467
2468     if (parser->tok == TOKEN_IDENT) {
2469         if (!OPTS_FLAG(LOOP_LABELS))
2470             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2471         i = vec_size(loops);
2472         while (i--) {
2473             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2474                 break;
2475             if (!i) {
2476                 parseerror(parser, "no such loop to %s: `%s`",
2477                            (is_continue ? "continue" : "break out of"),
2478                            parser_tokval(parser));
2479                 return false;
2480             }
2481             ++levels;
2482         }
2483         if (!parser_next(parser)) {
2484             parseerror(parser, "expected semicolon");
2485             return false;
2486         }
2487     }
2488
2489     if (parser->tok != ';') {
2490         parseerror(parser, "expected semicolon");
2491         return false;
2492     }
2493
2494     if (!parser_next(parser))
2495         parseerror(parser, "parse error");
2496
2497     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2498     return true;
2499 }
2500
2501 /* returns true when it was a variable qualifier, false otherwise!
2502  * on error, cvq is set to CV_WRONG
2503  */
2504 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *noreturn, bool *is_static)
2505 {
2506     bool had_const    = false;
2507     bool had_var      = false;
2508     bool had_noref    = false;
2509     bool had_noreturn = false;
2510     bool had_attrib   = false;
2511     bool had_static   = false;
2512
2513     *cvq = CV_NONE;
2514     for (;;) {
2515         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2516             had_attrib = true;
2517             /* parse an attribute */
2518             if (!parser_next(parser)) {
2519                 parseerror(parser, "expected attribute after `[[`");
2520                 *cvq = CV_WRONG;
2521                 return false;
2522             }
2523             if (!strcmp(parser_tokval(parser), "noreturn")) {
2524                 had_noreturn = true;
2525                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2526                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2527                     *cvq = CV_WRONG;
2528                     return false;
2529                 }
2530             }
2531             else if (!strcmp(parser_tokval(parser), "noref")) {
2532                 had_noref = true;
2533                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2534                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2535                     *cvq = CV_WRONG;
2536                     return false;
2537                 }
2538             }
2539             else
2540             {
2541                 /* Skip tokens until we hit a ]] */
2542                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2543                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2544                     if (!parser_next(parser)) {
2545                         parseerror(parser, "error inside attribute");
2546                         *cvq = CV_WRONG;
2547                         return false;
2548                     }
2549                 }
2550             }
2551         }
2552         else if (!strcmp(parser_tokval(parser), "static"))
2553             had_static = true;
2554         else if (!strcmp(parser_tokval(parser), "const"))
2555             had_const = true;
2556         else if (!strcmp(parser_tokval(parser), "var"))
2557             had_var = true;
2558         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2559             had_var = true;
2560         else if (!strcmp(parser_tokval(parser), "noref"))
2561             had_noref = true;
2562         else if (!had_const && !had_var && !had_noref && !had_noreturn && !had_attrib && !had_static) {
2563             return false;
2564         }
2565         else
2566             break;
2567         if (!parser_next(parser))
2568             goto onerr;
2569     }
2570     if (had_const)
2571         *cvq = CV_CONST;
2572     else if (had_var)
2573         *cvq = CV_VAR;
2574     else
2575         *cvq = CV_NONE;
2576     *noref     = had_noref;
2577     *noreturn  = had_noreturn;
2578     *is_static = had_static;
2579     return true;
2580 onerr:
2581     parseerror(parser, "parse error after variable qualifier");
2582     *cvq = CV_WRONG;
2583     return true;
2584 }
2585
2586 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2587 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2588 {
2589     bool rv;
2590     char *label = NULL;
2591
2592     /* skip the 'while' and get the body */
2593     if (!parser_next(parser)) {
2594         if (OPTS_FLAG(LOOP_LABELS))
2595             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2596         else
2597             parseerror(parser, "expected 'switch' operand in parenthesis");
2598         return false;
2599     }
2600
2601     if (parser->tok == ':') {
2602         if (!OPTS_FLAG(LOOP_LABELS))
2603             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2604         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2605             parseerror(parser, "expected loop label");
2606             return false;
2607         }
2608         label = util_strdup(parser_tokval(parser));
2609         if (!parser_next(parser)) {
2610             mem_d(label);
2611             parseerror(parser, "expected 'switch' operand in parenthesis");
2612             return false;
2613         }
2614     }
2615
2616     if (parser->tok != '(') {
2617         parseerror(parser, "expected 'switch' operand in parenthesis");
2618         return false;
2619     }
2620
2621     vec_push(parser->breaks, label);
2622
2623     rv = parse_switch_go(parser, block, out);
2624     if (label)
2625         mem_d(label);
2626     if (vec_last(parser->breaks) != label) {
2627         parseerror(parser, "internal error: label stack corrupted");
2628         rv = false;
2629         ast_delete(*out);
2630         *out = NULL;
2631     }
2632     else {
2633         vec_pop(parser->breaks);
2634     }
2635     return rv;
2636 }
2637
2638 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2639 {
2640     ast_expression *operand;
2641     ast_value      *opval;
2642     ast_value      *typevar;
2643     ast_switch     *switchnode;
2644     ast_switch_case swcase;
2645
2646     int  cvq;
2647     bool noref, noreturn, is_static;
2648
2649     lex_ctx ctx = parser_ctx(parser);
2650
2651     (void)block; /* not touching */
2652     (void)opval;
2653
2654     /* parse into the expression */
2655     if (!parser_next(parser)) {
2656         parseerror(parser, "expected switch operand");
2657         return false;
2658     }
2659     /* parse the operand */
2660     operand = parse_expression_leave(parser, false);
2661     if (!operand)
2662         return false;
2663
2664     switchnode = ast_switch_new(ctx, operand);
2665
2666     /* closing paren */
2667     if (parser->tok != ')') {
2668         ast_delete(switchnode);
2669         parseerror(parser, "expected closing paren after 'switch' operand");
2670         return false;
2671     }
2672
2673     /* parse over the opening paren */
2674     if (!parser_next(parser) || parser->tok != '{') {
2675         ast_delete(switchnode);
2676         parseerror(parser, "expected list of cases");
2677         return false;
2678     }
2679
2680     if (!parser_next(parser)) {
2681         ast_delete(switchnode);
2682         parseerror(parser, "expected 'case' or 'default'");
2683         return false;
2684     }
2685
2686     /* new block; allow some variables to be declared here */
2687     parser_enterblock(parser);
2688     while (true) {
2689         typevar = NULL;
2690         if (parser->tok == TOKEN_IDENT)
2691             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2692         if (typevar || parser->tok == TOKEN_TYPENAME) {
2693             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false)) {
2694                 ast_delete(switchnode);
2695                 return false;
2696             }
2697             continue;
2698         }
2699         if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn, &is_static))
2700         {
2701             if (cvq == CV_WRONG) {
2702                 ast_delete(switchnode);
2703                 return false;
2704             }
2705             if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn, is_static)) {
2706                 ast_delete(switchnode);
2707                 return false;
2708             }
2709             continue;
2710         }
2711         break;
2712     }
2713
2714     /* case list! */
2715     while (parser->tok != '}') {
2716         ast_block *caseblock;
2717
2718         if (!strcmp(parser_tokval(parser), "case")) {
2719             if (!parser_next(parser)) {
2720                 ast_delete(switchnode);
2721                 parseerror(parser, "expected expression for case");
2722                 return false;
2723             }
2724             swcase.value = parse_expression_leave(parser, false);
2725             if (!swcase.value) {
2726                 ast_delete(switchnode);
2727                 parseerror(parser, "expected expression for case");
2728                 return false;
2729             }
2730             if (!OPTS_FLAG(RELAXED_SWITCH)) {
2731                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2732                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2733                     ast_unref(operand);
2734                     return false;
2735                 }
2736             }
2737         }
2738         else if (!strcmp(parser_tokval(parser), "default")) {
2739             swcase.value = NULL;
2740             if (!parser_next(parser)) {
2741                 ast_delete(switchnode);
2742                 parseerror(parser, "expected colon");
2743                 return false;
2744             }
2745         }
2746         else {
2747             ast_delete(switchnode);
2748             parseerror(parser, "expected 'case' or 'default'");
2749             return false;
2750         }
2751
2752         /* Now the colon and body */
2753         if (parser->tok != ':') {
2754             if (swcase.value) ast_unref(swcase.value);
2755             ast_delete(switchnode);
2756             parseerror(parser, "expected colon");
2757             return false;
2758         }
2759
2760         if (!parser_next(parser)) {
2761             if (swcase.value) ast_unref(swcase.value);
2762             ast_delete(switchnode);
2763             parseerror(parser, "expected statements or case");
2764             return false;
2765         }
2766         caseblock = ast_block_new(parser_ctx(parser));
2767         if (!caseblock) {
2768             if (swcase.value) ast_unref(swcase.value);
2769             ast_delete(switchnode);
2770             return false;
2771         }
2772         swcase.code = (ast_expression*)caseblock;
2773         vec_push(switchnode->cases, swcase);
2774         while (true) {
2775             ast_expression *expr;
2776             if (parser->tok == '}')
2777                 break;
2778             if (parser->tok == TOKEN_KEYWORD) {
2779                 if (!strcmp(parser_tokval(parser), "case") ||
2780                     !strcmp(parser_tokval(parser), "default"))
2781                 {
2782                     break;
2783                 }
2784             }
2785             if (!parse_statement(parser, caseblock, &expr, true)) {
2786                 ast_delete(switchnode);
2787                 return false;
2788             }
2789             if (!expr)
2790                 continue;
2791             if (!ast_block_add_expr(caseblock, expr)) {
2792                 ast_delete(switchnode);
2793                 return false;
2794             }
2795         }
2796     }
2797
2798     parser_leaveblock(parser);
2799
2800     /* closing paren */
2801     if (parser->tok != '}') {
2802         ast_delete(switchnode);
2803         parseerror(parser, "expected closing paren of case list");
2804         return false;
2805     }
2806     if (!parser_next(parser)) {
2807         ast_delete(switchnode);
2808         parseerror(parser, "parse error after switch");
2809         return false;
2810     }
2811     *out = (ast_expression*)switchnode;
2812     return true;
2813 }
2814
2815 static bool parse_goto(parser_t *parser, ast_expression **out)
2816 {
2817     size_t    i;
2818     ast_goto *gt;
2819
2820     if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2821         parseerror(parser, "expected label name after `goto`");
2822         return false;
2823     }
2824
2825     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2826
2827     for (i = 0; i < vec_size(parser->labels); ++i) {
2828         if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2829             ast_goto_set_label(gt, parser->labels[i]);
2830             break;
2831         }
2832     }
2833     if (i == vec_size(parser->labels))
2834         vec_push(parser->gotos, gt);
2835
2836     if (!parser_next(parser) || parser->tok != ';') {
2837         parseerror(parser, "semicolon expected after goto label");
2838         return false;
2839     }
2840     if (!parser_next(parser)) {
2841         parseerror(parser, "parse error after goto");
2842         return false;
2843     }
2844
2845     *out = (ast_expression*)gt;
2846     return true;
2847 }
2848
2849 static bool parse_skipwhite(parser_t *parser)
2850 {
2851     do {
2852         if (!parser_next(parser))
2853             return false;
2854     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2855     return parser->tok < TOKEN_ERROR;
2856 }
2857
2858 static bool parse_eol(parser_t *parser)
2859 {
2860     if (!parse_skipwhite(parser))
2861         return false;
2862     return parser->tok == TOKEN_EOL;
2863 }
2864
2865 static bool parse_pragma_do(parser_t *parser)
2866 {
2867     if (!parser_next(parser) ||
2868         parser->tok != TOKEN_IDENT ||
2869         strcmp(parser_tokval(parser), "pragma"))
2870     {
2871         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2872         return false;
2873     }
2874     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2875         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2876         return false;
2877     }
2878
2879     if (!strcmp(parser_tokval(parser), "noref")) {
2880         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2881             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2882             return false;
2883         }
2884         parser->noref = !!parser_token(parser)->constval.i;
2885         if (!parse_eol(parser)) {
2886             parseerror(parser, "parse error after `noref` pragma");
2887             return false;
2888         }
2889     }
2890     else
2891     {
2892         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2893         return false;
2894     }
2895
2896     return true;
2897 }
2898
2899 static bool parse_pragma(parser_t *parser)
2900 {
2901     bool rv;
2902     parser->lex->flags.preprocessing = true;
2903     parser->lex->flags.mergelines = true;
2904     rv = parse_pragma_do(parser);
2905     if (parser->tok != TOKEN_EOL) {
2906         parseerror(parser, "junk after pragma");
2907         rv = false;
2908     }
2909     parser->lex->flags.preprocessing = false;
2910     parser->lex->flags.mergelines = false;
2911     if (!parser_next(parser)) {
2912         parseerror(parser, "parse error after pragma");
2913         rv = false;
2914     }
2915     return rv;
2916 }
2917
2918 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2919 {
2920     bool       noref, noreturn, is_static;
2921     int        cvq = CV_NONE;
2922     ast_value *typevar = NULL;
2923
2924     *out = NULL;
2925
2926     if (parser->tok == TOKEN_IDENT)
2927         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2928
2929     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2930     {
2931         /* local variable */
2932         if (!block) {
2933             parseerror(parser, "cannot declare a variable from here");
2934             return false;
2935         }
2936         if (opts.standard == COMPILER_QCC) {
2937             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2938                 return false;
2939         }
2940         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false))
2941             return false;
2942         return true;
2943     }
2944     else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn, &is_static))
2945     {
2946         if (cvq == CV_WRONG)
2947             return false;
2948         return parse_variable(parser, block, true, cvq, NULL, noref, noreturn, is_static);
2949     }
2950     else if (parser->tok == TOKEN_KEYWORD)
2951     {
2952         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2953         {
2954             char ty[1024];
2955             ast_value *tdef;
2956
2957             if (!parser_next(parser)) {
2958                 parseerror(parser, "parse error after __builtin_debug_printtype");
2959                 return false;
2960             }
2961
2962             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2963             {
2964                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2965                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2966                 if (!parser_next(parser)) {
2967                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2968                     return false;
2969                 }
2970             }
2971             else
2972             {
2973                 if (!parse_statement(parser, block, out, allow_cases))
2974                     return false;
2975                 if (!*out)
2976                     con_out("__builtin_debug_printtype: got no output node\n");
2977                 else
2978                 {
2979                     ast_type_to_string(*out, ty, sizeof(ty));
2980                     con_out("__builtin_debug_printtype: `%s`\n", ty);
2981                 }
2982             }
2983             return true;
2984         }
2985         else if (!strcmp(parser_tokval(parser), "return"))
2986         {
2987             return parse_return(parser, block, out);
2988         }
2989         else if (!strcmp(parser_tokval(parser), "if"))
2990         {
2991             return parse_if(parser, block, out);
2992         }
2993         else if (!strcmp(parser_tokval(parser), "while"))
2994         {
2995             return parse_while(parser, block, out);
2996         }
2997         else if (!strcmp(parser_tokval(parser), "do"))
2998         {
2999             return parse_dowhile(parser, block, out);
3000         }
3001         else if (!strcmp(parser_tokval(parser), "for"))
3002         {
3003             if (opts.standard == COMPILER_QCC) {
3004                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3005                     return false;
3006             }
3007             return parse_for(parser, block, out);
3008         }
3009         else if (!strcmp(parser_tokval(parser), "break"))
3010         {
3011             return parse_break_continue(parser, block, out, false);
3012         }
3013         else if (!strcmp(parser_tokval(parser), "continue"))
3014         {
3015             return parse_break_continue(parser, block, out, true);
3016         }
3017         else if (!strcmp(parser_tokval(parser), "switch"))
3018         {
3019             return parse_switch(parser, block, out);
3020         }
3021         else if (!strcmp(parser_tokval(parser), "case") ||
3022                  !strcmp(parser_tokval(parser), "default"))
3023         {
3024             if (!allow_cases) {
3025                 parseerror(parser, "unexpected 'case' label");
3026                 return false;
3027             }
3028             return true;
3029         }
3030         else if (!strcmp(parser_tokval(parser), "goto"))
3031         {
3032             return parse_goto(parser, out);
3033         }
3034         else if (!strcmp(parser_tokval(parser), "typedef"))
3035         {
3036             if (!parser_next(parser)) {
3037                 parseerror(parser, "expected type definition after 'typedef'");
3038                 return false;
3039             }
3040             return parse_typedef(parser);
3041         }
3042         parseerror(parser, "Unexpected keyword");
3043         return false;
3044     }
3045     else if (parser->tok == '{')
3046     {
3047         ast_block *inner;
3048         inner = parse_block(parser);
3049         if (!inner)
3050             return false;
3051         *out = (ast_expression*)inner;
3052         return true;
3053     }
3054     else if (parser->tok == ':')
3055     {
3056         size_t i;
3057         ast_label *label;
3058         if (!parser_next(parser)) {
3059             parseerror(parser, "expected label name");
3060             return false;
3061         }
3062         if (parser->tok != TOKEN_IDENT) {
3063             parseerror(parser, "label must be an identifier");
3064             return false;
3065         }
3066         label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
3067         if (!label)
3068             return false;
3069         vec_push(parser->labels, label);
3070         *out = (ast_expression*)label;
3071         if (!parser_next(parser)) {
3072             parseerror(parser, "parse error after label");
3073             return false;
3074         }
3075         for (i = 0; i < vec_size(parser->gotos); ++i) {
3076             if (!strcmp(parser->gotos[i]->name, label->name)) {
3077                 ast_goto_set_label(parser->gotos[i], label);
3078                 vec_remove(parser->gotos, i, 1);
3079                 --i;
3080             }
3081         }
3082         return true;
3083     }
3084     else if (parser->tok == ';')
3085     {
3086         if (!parser_next(parser)) {
3087             parseerror(parser, "parse error after empty statement");
3088             return false;
3089         }
3090         return true;
3091     }
3092     else
3093     {
3094         ast_expression *exp = parse_expression(parser, false);
3095         if (!exp)
3096             return false;
3097         *out = exp;
3098         if (!ast_side_effects(exp)) {
3099             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3100                 return false;
3101         }
3102         return true;
3103     }
3104 }
3105
3106 static bool parse_block_into(parser_t *parser, ast_block *block)
3107 {
3108     bool   retval = true;
3109
3110     parser_enterblock(parser);
3111
3112     if (!parser_next(parser)) { /* skip the '{' */
3113         parseerror(parser, "expected function body");
3114         goto cleanup;
3115     }
3116
3117     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3118     {
3119         ast_expression *expr = NULL;
3120         if (parser->tok == '}')
3121             break;
3122
3123         if (!parse_statement(parser, block, &expr, false)) {
3124             /* parseerror(parser, "parse error"); */
3125             block = NULL;
3126             goto cleanup;
3127         }
3128         if (!expr)
3129             continue;
3130         if (!ast_block_add_expr(block, expr)) {
3131             ast_delete(block);
3132             block = NULL;
3133             goto cleanup;
3134         }
3135     }
3136
3137     if (parser->tok != '}') {
3138         block = NULL;
3139     } else {
3140         (void)parser_next(parser);
3141     }
3142
3143 cleanup:
3144     if (!parser_leaveblock(parser))
3145         retval = false;
3146     return retval && !!block;
3147 }
3148
3149 static ast_block* parse_block(parser_t *parser)
3150 {
3151     ast_block *block;
3152     block = ast_block_new(parser_ctx(parser));
3153     if (!block)
3154         return NULL;
3155     if (!parse_block_into(parser, block)) {
3156         ast_block_delete(block);
3157         return NULL;
3158     }
3159     return block;
3160 }
3161
3162 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3163 {
3164     if (parser->tok == '{') {
3165         *out = (ast_expression*)parse_block(parser);
3166         return !!*out;
3167     }
3168     return parse_statement(parser, NULL, out, false);
3169 }
3170
3171 static bool create_vector_members(ast_value *var, ast_member **me)
3172 {
3173     size_t i;
3174     size_t len = strlen(var->name);
3175
3176     for (i = 0; i < 3; ++i) {
3177         char *name = (char*)mem_a(len+3);
3178         memcpy(name, var->name, len);
3179         name[len+0] = '_';
3180         name[len+1] = 'x'+i;
3181         name[len+2] = 0;
3182         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3183         mem_d(name);
3184         if (!me[i])
3185             break;
3186     }
3187     if (i == 3)
3188         return true;
3189
3190     /* unroll */
3191     do { ast_member_delete(me[--i]); } while(i);
3192     return false;
3193 }
3194
3195 static bool parse_function_body(parser_t *parser, ast_value *var)
3196 {
3197     ast_block      *block = NULL;
3198     ast_function   *func;
3199     ast_function   *old;
3200     size_t          parami;
3201
3202     ast_expression *framenum  = NULL;
3203     ast_expression *nextthink = NULL;
3204     /* None of the following have to be deleted */
3205     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3206     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3207     bool            has_frame_think;
3208
3209     bool retval = true;
3210
3211     has_frame_think = false;
3212     old = parser->function;
3213
3214     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3215         parseerror(parser, "gotos/labels leaking");
3216         return false;
3217     }
3218
3219     if (var->expression.flags & AST_FLAG_VARIADIC) {
3220         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3221                          "variadic function with implementation will not be able to access additional parameters"))
3222         {
3223             return false;
3224         }
3225     }
3226
3227     if (parser->tok == '[') {
3228         /* got a frame definition: [ framenum, nextthink ]
3229          * this translates to:
3230          * self.frame = framenum;
3231          * self.nextthink = time + 0.1;
3232          * self.think = nextthink;
3233          */
3234         nextthink = NULL;
3235
3236         fld_think     = parser_find_field(parser, "think");
3237         fld_nextthink = parser_find_field(parser, "nextthink");
3238         fld_frame     = parser_find_field(parser, "frame");
3239         if (!fld_think || !fld_nextthink || !fld_frame) {
3240             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3241             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3242             return false;
3243         }
3244         gbl_time      = parser_find_global(parser, "time");
3245         gbl_self      = parser_find_global(parser, "self");
3246         if (!gbl_time || !gbl_self) {
3247             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3248             parseerror(parser, "please declare the following globals: `time`, `self`");
3249             return false;
3250         }
3251
3252         if (!parser_next(parser))
3253             return false;
3254
3255         framenum = parse_expression_leave(parser, true);
3256         if (!framenum) {
3257             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3258             return false;
3259         }
3260         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3261             ast_unref(framenum);
3262             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3263             return false;
3264         }
3265
3266         if (parser->tok != ',') {
3267             ast_unref(framenum);
3268             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3269             parseerror(parser, "Got a %i\n", parser->tok);
3270             return false;
3271         }
3272
3273         if (!parser_next(parser)) {
3274             ast_unref(framenum);
3275             return false;
3276         }
3277
3278         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3279         {
3280             /* qc allows the use of not-yet-declared functions here
3281              * - this automatically creates a prototype */
3282             ast_value      *thinkfunc;
3283             ast_expression *functype = fld_think->expression.next;
3284
3285             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3286             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3287                 ast_unref(framenum);
3288                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3289                 return false;
3290             }
3291
3292             if (!parser_next(parser)) {
3293                 ast_unref(framenum);
3294                 ast_delete(thinkfunc);
3295                 return false;
3296             }
3297
3298             vec_push(parser->globals, (ast_expression*)thinkfunc);
3299             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3300             nextthink = (ast_expression*)thinkfunc;
3301
3302         } else {
3303             nextthink = parse_expression_leave(parser, true);
3304             if (!nextthink) {
3305                 ast_unref(framenum);
3306                 parseerror(parser, "expected a think-function in [frame,think] notation");
3307                 return false;
3308             }
3309         }
3310
3311         if (!ast_istype(nextthink, ast_value)) {
3312             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3313             retval = false;
3314         }
3315
3316         if (retval && parser->tok != ']') {
3317             parseerror(parser, "expected closing `]` for [frame,think] notation");
3318             retval = false;
3319         }
3320
3321         if (retval && !parser_next(parser)) {
3322             retval = false;
3323         }
3324
3325         if (retval && parser->tok != '{') {
3326             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3327             retval = false;
3328         }
3329
3330         if (!retval) {
3331             ast_unref(nextthink);
3332             ast_unref(framenum);
3333             return false;
3334         }
3335
3336         has_frame_think = true;
3337     }
3338
3339     block = ast_block_new(parser_ctx(parser));
3340     if (!block) {
3341         parseerror(parser, "failed to allocate block");
3342         if (has_frame_think) {
3343             ast_unref(nextthink);
3344             ast_unref(framenum);
3345         }
3346         return false;
3347     }
3348
3349     if (has_frame_think) {
3350         lex_ctx ctx;
3351         ast_expression *self_frame;
3352         ast_expression *self_nextthink;
3353         ast_expression *self_think;
3354         ast_expression *time_plus_1;
3355         ast_store *store_frame;
3356         ast_store *store_nextthink;
3357         ast_store *store_think;
3358
3359         ctx = parser_ctx(parser);
3360         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3361         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3362         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3363
3364         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3365                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3366
3367         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3368             if (self_frame)     ast_delete(self_frame);
3369             if (self_nextthink) ast_delete(self_nextthink);
3370             if (self_think)     ast_delete(self_think);
3371             if (time_plus_1)    ast_delete(time_plus_1);
3372             retval = false;
3373         }
3374
3375         if (retval)
3376         {
3377             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3378             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3379             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3380
3381             if (!store_frame) {
3382                 ast_delete(self_frame);
3383                 retval = false;
3384             }
3385             if (!store_nextthink) {
3386                 ast_delete(self_nextthink);
3387                 retval = false;
3388             }
3389             if (!store_think) {
3390                 ast_delete(self_think);
3391                 retval = false;
3392             }
3393             if (!retval) {
3394                 if (store_frame)     ast_delete(store_frame);
3395                 if (store_nextthink) ast_delete(store_nextthink);
3396                 if (store_think)     ast_delete(store_think);
3397                 retval = false;
3398             }
3399             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3400                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3401                 !ast_block_add_expr(block, (ast_expression*)store_think))
3402             {
3403                 retval = false;
3404             }
3405         }
3406
3407         if (!retval) {
3408             parseerror(parser, "failed to generate code for [frame,think]");
3409             ast_unref(nextthink);
3410             ast_unref(framenum);
3411             ast_delete(block);
3412             return false;
3413         }
3414     }
3415
3416     parser_enterblock(parser);
3417
3418     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3419         size_t     e;
3420         ast_value *param = var->expression.params[parami];
3421         ast_member *me[3];
3422
3423         if (param->expression.vtype != TYPE_VECTOR &&
3424             (param->expression.vtype != TYPE_FIELD ||
3425              param->expression.next->expression.vtype != TYPE_VECTOR))
3426         {
3427             continue;
3428         }
3429
3430         if (!create_vector_members(param, me)) {
3431             ast_block_delete(block);
3432             return false;
3433         }
3434
3435         for (e = 0; e < 3; ++e) {
3436             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3437             ast_block_collect(block, (ast_expression*)me[e]);
3438         }
3439     }
3440
3441     func = ast_function_new(ast_ctx(var), var->name, var);
3442     if (!func) {
3443         parseerror(parser, "failed to allocate function for `%s`", var->name);
3444         ast_block_delete(block);
3445         goto enderr;
3446     }
3447     vec_push(parser->functions, func);
3448
3449     parser->function = func;
3450     if (!parse_block_into(parser, block)) {
3451         ast_block_delete(block);
3452         goto enderrfn;
3453     }
3454
3455     vec_push(func->blocks, block);
3456
3457     parser->function = old;
3458     if (!parser_leaveblock(parser))
3459         retval = false;
3460     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3461         parseerror(parser, "internal error: local scopes left");
3462         retval = false;
3463     }
3464
3465     if (parser->tok == ';')
3466         return parser_next(parser);
3467     else if (opts.standard == COMPILER_QCC)
3468         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3469     return retval;
3470
3471 enderrfn:
3472     vec_pop(parser->functions);
3473     ast_function_delete(func);
3474     var->constval.vfunc = NULL;
3475
3476 enderr:
3477     (void)!parser_leaveblock(parser);
3478     parser->function = old;
3479     return false;
3480 }
3481
3482 static ast_expression *array_accessor_split(
3483     parser_t  *parser,
3484     ast_value *array,
3485     ast_value *index,
3486     size_t     middle,
3487     ast_expression *left,
3488     ast_expression *right
3489     )
3490 {
3491     ast_ifthen *ifthen;
3492     ast_binary *cmp;
3493
3494     lex_ctx ctx = ast_ctx(array);
3495
3496     if (!left || !right) {
3497         if (left)  ast_delete(left);
3498         if (right) ast_delete(right);
3499         return NULL;
3500     }
3501
3502     cmp = ast_binary_new(ctx, INSTR_LT,
3503                          (ast_expression*)index,
3504                          (ast_expression*)parser_const_float(parser, middle));
3505     if (!cmp) {
3506         ast_delete(left);
3507         ast_delete(right);
3508         parseerror(parser, "internal error: failed to create comparison for array setter");
3509         return NULL;
3510     }
3511
3512     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3513     if (!ifthen) {
3514         ast_delete(cmp); /* will delete left and right */
3515         parseerror(parser, "internal error: failed to create conditional jump for array setter");
3516         return NULL;
3517     }
3518
3519     return (ast_expression*)ifthen;
3520 }
3521
3522 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3523 {
3524     lex_ctx ctx = ast_ctx(array);
3525
3526     if (from+1 == afterend) {
3527         /* set this value */
3528         ast_block       *block;
3529         ast_return      *ret;
3530         ast_array_index *subscript;
3531         ast_store       *st;
3532         int assignop = type_store_instr[value->expression.vtype];
3533
3534         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3535             assignop = INSTR_STORE_V;
3536
3537         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3538         if (!subscript)
3539             return NULL;
3540
3541         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3542         if (!st) {
3543             ast_delete(subscript);
3544             return NULL;
3545         }
3546
3547         block = ast_block_new(ctx);
3548         if (!block) {
3549             ast_delete(st);
3550             return NULL;
3551         }
3552
3553         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3554             ast_delete(block);
3555             return NULL;
3556         }
3557
3558         ret = ast_return_new(ctx, NULL);
3559         if (!ret) {
3560             ast_delete(block);
3561             return NULL;
3562         }
3563
3564         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3565             ast_delete(block);
3566             return NULL;
3567         }
3568
3569         return (ast_expression*)block;
3570     } else {
3571         ast_expression *left, *right;
3572         size_t diff = afterend - from;
3573         size_t middle = from + diff/2;
3574         left  = array_setter_node(parser, array, index, value, from, middle);
3575         right = array_setter_node(parser, array, index, value, middle, afterend);
3576         return array_accessor_split(parser, array, index, middle, left, right);
3577     }
3578 }
3579
3580 static ast_expression *array_field_setter_node(
3581     parser_t  *parser,
3582     ast_value *array,
3583     ast_value *entity,
3584     ast_value *index,
3585     ast_value *value,
3586     size_t     from,
3587     size_t     afterend)
3588 {
3589     lex_ctx ctx = ast_ctx(array);
3590
3591     if (from+1 == afterend) {
3592         /* set this value */
3593         ast_block       *block;
3594         ast_return      *ret;
3595         ast_entfield    *entfield;
3596         ast_array_index *subscript;
3597         ast_store       *st;
3598         int assignop = type_storep_instr[value->expression.vtype];
3599
3600         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3601             assignop = INSTR_STOREP_V;
3602
3603         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3604         if (!subscript)
3605             return NULL;
3606
3607         entfield = ast_entfield_new_force(ctx,
3608                                           (ast_expression*)entity,
3609                                           (ast_expression*)subscript,
3610                                           (ast_expression*)subscript);
3611         if (!entfield) {
3612             ast_delete(subscript);
3613             return NULL;
3614         }
3615
3616         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3617         if (!st) {
3618             ast_delete(entfield);
3619             return NULL;
3620         }
3621
3622         block = ast_block_new(ctx);
3623         if (!block) {
3624             ast_delete(st);
3625             return NULL;
3626         }
3627
3628         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3629             ast_delete(block);
3630             return NULL;
3631         }
3632
3633         ret = ast_return_new(ctx, NULL);
3634         if (!ret) {
3635             ast_delete(block);
3636             return NULL;
3637         }
3638
3639         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3640             ast_delete(block);
3641             return NULL;
3642         }
3643
3644         return (ast_expression*)block;
3645     } else {
3646         ast_expression *left, *right;
3647         size_t diff = afterend - from;
3648         size_t middle = from + diff/2;
3649         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
3650         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3651         return array_accessor_split(parser, array, index, middle, left, right);
3652     }
3653 }
3654
3655 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3656 {
3657     lex_ctx ctx = ast_ctx(array);
3658
3659     if (from+1 == afterend) {
3660         ast_return      *ret;
3661         ast_array_index *subscript;
3662
3663         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3664         if (!subscript)
3665             return NULL;
3666
3667         ret = ast_return_new(ctx, (ast_expression*)subscript);
3668         if (!ret) {
3669             ast_delete(subscript);
3670             return NULL;
3671         }
3672
3673         return (ast_expression*)ret;
3674     } else {
3675         ast_expression *left, *right;
3676         size_t diff = afterend - from;
3677         size_t middle = from + diff/2;
3678         left  = array_getter_node(parser, array, index, from, middle);
3679         right = array_getter_node(parser, array, index, middle, afterend);
3680         return array_accessor_split(parser, array, index, middle, left, right);
3681     }
3682 }
3683
3684 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3685 {
3686     ast_function   *func = NULL;
3687     ast_value      *fval = NULL;
3688     ast_block      *body = NULL;
3689
3690     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3691     if (!fval) {
3692         parseerror(parser, "failed to create accessor function value");
3693         return false;
3694     }
3695
3696     func = ast_function_new(ast_ctx(array), funcname, fval);
3697     if (!func) {
3698         ast_delete(fval);
3699         parseerror(parser, "failed to create accessor function node");
3700         return false;
3701     }
3702
3703     body = ast_block_new(ast_ctx(array));
3704     if (!body) {
3705         parseerror(parser, "failed to create block for array accessor");
3706         ast_delete(fval);
3707         ast_delete(func);
3708         return false;
3709     }
3710
3711     vec_push(func->blocks, body);
3712     *out = fval;
3713
3714     vec_push(parser->accessors, fval);
3715
3716     return true;
3717 }
3718
3719 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3720 {
3721     ast_expression *root = NULL;
3722     ast_value      *index = NULL;
3723     ast_value      *value = NULL;
3724     ast_function   *func;
3725     ast_value      *fval;
3726
3727     if (!ast_istype(array->expression.next, ast_value)) {
3728         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3729         return false;
3730     }
3731
3732     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3733         return false;
3734     func = fval->constval.vfunc;
3735     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3736
3737     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3738     value = ast_value_copy((ast_value*)array->expression.next);
3739
3740     if (!index || !value) {
3741         parseerror(parser, "failed to create locals for array accessor");
3742         goto cleanup;
3743     }
3744     (void)!ast_value_set_name(value, "value"); /* not important */
3745     vec_push(fval->expression.params, index);
3746     vec_push(fval->expression.params, value);
3747
3748     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3749     if (!root) {
3750         parseerror(parser, "failed to build accessor search tree");
3751         goto cleanup;
3752     }
3753
3754     array->setter = fval;
3755     return ast_block_add_expr(func->blocks[0], root);
3756 cleanup:
3757     if (index) ast_delete(index);
3758     if (value) ast_delete(value);
3759     if (root)  ast_delete(root);
3760     ast_delete(func);
3761     ast_delete(fval);
3762     return false;
3763 }
3764
3765 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3766 {
3767     ast_expression *root = NULL;
3768     ast_value      *entity = NULL;
3769     ast_value      *index = NULL;
3770     ast_value      *value = NULL;
3771     ast_function   *func;
3772     ast_value      *fval;
3773
3774     if (!ast_istype(array->expression.next, ast_value)) {
3775         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3776         return false;
3777     }
3778
3779     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3780         return false;
3781     func = fval->constval.vfunc;
3782     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3783
3784     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3785     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
3786     value  = ast_value_copy((ast_value*)array->expression.next);
3787     if (!entity || !index || !value) {
3788         parseerror(parser, "failed to create locals for array accessor");
3789         goto cleanup;
3790     }
3791     (void)!ast_value_set_name(value, "value"); /* not important */
3792     vec_push(fval->expression.params, entity);
3793     vec_push(fval->expression.params, index);
3794     vec_push(fval->expression.params, value);
3795
3796     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3797     if (!root) {
3798         parseerror(parser, "failed to build accessor search tree");
3799         goto cleanup;
3800     }
3801
3802     array->setter = fval;
3803     return ast_block_add_expr(func->blocks[0], root);
3804 cleanup:
3805     if (entity) ast_delete(entity);
3806     if (index)  ast_delete(index);
3807     if (value)  ast_delete(value);
3808     if (root)   ast_delete(root);
3809     ast_delete(func);
3810     ast_delete(fval);
3811     return false;
3812 }
3813
3814 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3815 {
3816     ast_expression *root = NULL;
3817     ast_value      *index = NULL;
3818     ast_value      *fval;
3819     ast_function   *func;
3820
3821     /* NOTE: checking array->expression.next rather than elemtype since
3822      * for fields elemtype is a temporary fieldtype.
3823      */
3824     if (!ast_istype(array->expression.next, ast_value)) {
3825         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3826         return false;
3827     }
3828
3829     if (!parser_create_array_accessor(parser, array, funcname, &fval))
3830         return false;
3831     func = fval->constval.vfunc;
3832     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3833
3834     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3835
3836     if (!index) {
3837         parseerror(parser, "failed to create locals for array accessor");
3838         goto cleanup;
3839     }
3840     vec_push(fval->expression.params, index);
3841
3842     root = array_getter_node(parser, array, index, 0, array->expression.count);
3843     if (!root) {
3844         parseerror(parser, "failed to build accessor search tree");
3845         goto cleanup;
3846     }
3847
3848     array->getter = fval;
3849     return ast_block_add_expr(func->blocks[0], root);
3850 cleanup:
3851     if (index) ast_delete(index);
3852     if (root)  ast_delete(root);
3853     ast_delete(func);
3854     ast_delete(fval);
3855     return false;
3856 }
3857
3858 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3859 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3860 {
3861     lex_ctx     ctx;
3862     size_t      i;
3863     ast_value **params;
3864     ast_value  *param;
3865     ast_value  *fval;
3866     bool        first = true;
3867     bool        variadic = false;
3868
3869     ctx = parser_ctx(parser);
3870
3871     /* for the sake of less code we parse-in in this function */
3872     if (!parser_next(parser)) {
3873         parseerror(parser, "expected parameter list");
3874         return NULL;
3875     }
3876
3877     params = NULL;
3878
3879     /* parse variables until we hit a closing paren */
3880     while (parser->tok != ')') {
3881         if (!first) {
3882             /* there must be commas between them */
3883             if (parser->tok != ',') {
3884                 parseerror(parser, "expected comma or end of parameter list");
3885                 goto on_error;
3886             }
3887             if (!parser_next(parser)) {
3888                 parseerror(parser, "expected parameter");
3889                 goto on_error;
3890             }
3891         }
3892         first = false;
3893
3894         if (parser->tok == TOKEN_DOTS) {
3895             /* '...' indicates a varargs function */
3896             variadic = true;
3897             if (!parser_next(parser)) {
3898                 parseerror(parser, "expected parameter");
3899                 return NULL;
3900             }
3901             if (parser->tok != ')') {
3902                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3903                 goto on_error;
3904             }
3905         }
3906         else
3907         {
3908             /* for anything else just parse a typename */
3909             param = parse_typename(parser, NULL, NULL);
3910             if (!param)
3911                 goto on_error;
3912             vec_push(params, param);
3913             if (param->expression.vtype >= TYPE_VARIANT) {
3914                 char tname[1024]; /* typename is reserved in C++ */
3915                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
3916                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
3917                 goto on_error;
3918             }
3919         }
3920     }
3921
3922     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3923         vec_free(params);
3924
3925     /* sanity check */
3926     if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3927         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3928
3929     /* parse-out */
3930     if (!parser_next(parser)) {
3931         parseerror(parser, "parse error after typename");
3932         goto on_error;
3933     }
3934
3935     /* now turn 'var' into a function type */
3936     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3937     fval->expression.next     = (ast_expression*)var;
3938     if (variadic)
3939         fval->expression.flags |= AST_FLAG_VARIADIC;
3940     var = fval;
3941
3942     var->expression.params = params;
3943     params = NULL;
3944
3945     return var;
3946
3947 on_error:
3948     ast_delete(var);
3949     for (i = 0; i < vec_size(params); ++i)
3950         ast_delete(params[i]);
3951     vec_free(params);
3952     return NULL;
3953 }
3954
3955 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3956 {
3957     ast_expression *cexp;
3958     ast_value      *cval, *tmp;
3959     lex_ctx ctx;
3960
3961     ctx = parser_ctx(parser);
3962
3963     if (!parser_next(parser)) {
3964         ast_delete(var);
3965         parseerror(parser, "expected array-size");
3966         return NULL;
3967     }
3968
3969     cexp = parse_expression_leave(parser, true);
3970
3971     if (!cexp || !ast_istype(cexp, ast_value)) {
3972         if (cexp)
3973             ast_unref(cexp);
3974         ast_delete(var);
3975         parseerror(parser, "expected array-size as constant positive integer");
3976         return NULL;
3977     }
3978     cval = (ast_value*)cexp;
3979
3980     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3981     tmp->expression.next = (ast_expression*)var;
3982     var = tmp;
3983
3984     if (cval->expression.vtype == TYPE_INTEGER)
3985         tmp->expression.count = cval->constval.vint;
3986     else if (cval->expression.vtype == TYPE_FLOAT)
3987         tmp->expression.count = cval->constval.vfloat;
3988     else {
3989         ast_unref(cexp);
3990         ast_delete(var);
3991         parseerror(parser, "array-size must be a positive integer constant");
3992         return NULL;
3993     }
3994     ast_unref(cexp);
3995
3996     if (parser->tok != ']') {
3997         ast_delete(var);
3998         parseerror(parser, "expected ']' after array-size");
3999         return NULL;
4000     }
4001     if (!parser_next(parser)) {
4002         ast_delete(var);
4003         parseerror(parser, "error after parsing array size");
4004         return NULL;
4005     }
4006     return var;
4007 }
4008
4009 /* Parse a complete typename.
4010  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4011  * but when parsing variables separated by comma
4012  * 'storebase' should point to where the base-type should be kept.
4013  * The base type makes up every bit of type information which comes *before* the
4014  * variable name.
4015  *
4016  * The following will be parsed in its entirety:
4017  *     void() foo()
4018  * The 'basetype' in this case is 'void()'
4019  * and if there's a comma after it, say:
4020  *     void() foo(), bar
4021  * then the type-information 'void()' can be stored in 'storebase'
4022  */
4023 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4024 {
4025     ast_value *var, *tmp;
4026     lex_ctx    ctx;
4027
4028     const char *name = NULL;
4029     bool        isfield  = false;
4030     bool        wasarray = false;
4031     size_t      morefields = 0;
4032
4033     ctx = parser_ctx(parser);
4034
4035     /* types may start with a dot */
4036     if (parser->tok == '.') {
4037         isfield = true;
4038         /* if we parsed a dot we need a typename now */
4039         if (!parser_next(parser)) {
4040             parseerror(parser, "expected typename for field definition");
4041             return NULL;
4042         }
4043
4044         /* Further dots are handled seperately because they won't be part of the
4045          * basetype
4046          */
4047         while (parser->tok == '.') {
4048             ++morefields;
4049             if (!parser_next(parser)) {
4050                 parseerror(parser, "expected typename for field definition");
4051                 return NULL;
4052             }
4053         }
4054     }
4055     if (parser->tok == TOKEN_IDENT)
4056         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4057     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4058         parseerror(parser, "expected typename");
4059         return NULL;
4060     }
4061
4062     /* generate the basic type value */
4063     if (cached_typedef) {
4064         var = ast_value_copy(cached_typedef);
4065         ast_value_set_name(var, "<type(from_def)>");
4066     } else
4067         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4068
4069     for (; morefields; --morefields) {
4070         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4071         tmp->expression.next = (ast_expression*)var;
4072         var = tmp;
4073     }
4074
4075     /* do not yet turn into a field - remember:
4076      * .void() foo; is a field too
4077      * .void()() foo; is a function
4078      */
4079
4080     /* parse on */
4081     if (!parser_next(parser)) {
4082         ast_delete(var);
4083         parseerror(parser, "parse error after typename");
4084         return NULL;
4085     }
4086
4087     /* an opening paren now starts the parameter-list of a function
4088      * this is where original-QC has parameter lists.
4089      * We allow a single parameter list here.
4090      * Much like fteqcc we don't allow `float()() x`
4091      */
4092     if (parser->tok == '(') {
4093         var = parse_parameter_list(parser, var);
4094         if (!var)
4095             return NULL;
4096     }
4097
4098     /* store the base if requested */
4099     if (storebase) {
4100         *storebase = ast_value_copy(var);
4101         if (isfield) {
4102             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4103             tmp->expression.next = (ast_expression*)*storebase;
4104             *storebase = tmp;
4105         }
4106     }
4107
4108     /* there may be a name now */
4109     if (parser->tok == TOKEN_IDENT) {
4110         name = util_strdup(parser_tokval(parser));
4111         /* parse on */
4112         if (!parser_next(parser)) {
4113             ast_delete(var);
4114             parseerror(parser, "error after variable or field declaration");
4115             return NULL;
4116         }
4117     }
4118
4119     /* now this may be an array */
4120     if (parser->tok == '[') {
4121         wasarray = true;
4122         var = parse_arraysize(parser, var);
4123         if (!var)
4124             return NULL;
4125     }
4126
4127     /* This is the point where we can turn it into a field */
4128     if (isfield) {
4129         /* turn it into a field if desired */
4130         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4131         tmp->expression.next = (ast_expression*)var;
4132         var = tmp;
4133     }
4134
4135     /* now there may be function parens again */
4136     if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4137         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4138     if (parser->tok == '(' && wasarray)
4139         parseerror(parser, "arrays as part of a return type is not supported");
4140     while (parser->tok == '(') {
4141         var = parse_parameter_list(parser, var);
4142         if (!var) {
4143             if (name)
4144                 mem_d((void*)name);
4145             ast_delete(var);
4146             return NULL;
4147         }
4148     }
4149
4150     /* finally name it */
4151     if (name) {
4152         if (!ast_value_set_name(var, name)) {
4153             ast_delete(var);
4154             parseerror(parser, "internal error: failed to set name");
4155             return NULL;
4156         }
4157         /* free the name, ast_value_set_name duplicates */
4158         mem_d((void*)name);
4159     }
4160
4161     return var;
4162 }
4163
4164 static bool parse_typedef(parser_t *parser)
4165 {
4166     ast_value      *typevar, *oldtype;
4167     ast_expression *old;
4168
4169     typevar = parse_typename(parser, NULL, NULL);
4170
4171     if (!typevar)
4172         return false;
4173
4174     if ( (old = parser_find_var(parser, typevar->name)) ) {
4175         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4176                    " -> `%s` has been declared here: %s:%i",
4177                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4178         ast_delete(typevar);
4179         return false;
4180     }
4181
4182     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4183         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4184                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4185         ast_delete(typevar);
4186         return false;
4187     }
4188
4189     vec_push(parser->_typedefs, typevar);
4190     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4191
4192     if (parser->tok != ';') {
4193         parseerror(parser, "expected semicolon after typedef");
4194         return false;
4195     }
4196     if (!parser_next(parser)) {
4197         parseerror(parser, "parse error after typedef");
4198         return false;
4199     }
4200
4201     return true;
4202 }
4203
4204 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)
4205 {
4206     ast_value *var;
4207     ast_value *proto;
4208     ast_expression *old;
4209     bool       was_end;
4210     size_t     i;
4211
4212     ast_value *basetype = NULL;
4213     bool      retval    = true;
4214     bool      isparam   = false;
4215     bool      isvector  = false;
4216     bool      cleanvar  = true;
4217     bool      wasarray  = false;
4218
4219     ast_member *me[3];
4220
4221     if (!localblock && is_static)
4222         parseerror(parser, "`static` qualifier is not supported in global scope");
4223
4224     /* get the first complete variable */
4225     var = parse_typename(parser, &basetype, cached_typedef);
4226     if (!var) {
4227         if (basetype)
4228             ast_delete(basetype);
4229         return false;
4230     }
4231
4232     while (true) {
4233         proto = NULL;
4234         wasarray = false;
4235
4236         /* Part 0: finish the type */
4237         if (parser->tok == '(') {
4238             if (opts.standard == COMPILER_QCC)
4239                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4240             var = parse_parameter_list(parser, var);
4241             if (!var) {
4242                 retval = false;
4243                 goto cleanup;
4244             }
4245         }
4246         /* we only allow 1-dimensional arrays */
4247         if (parser->tok == '[') {
4248             wasarray = true;
4249             var = parse_arraysize(parser, var);
4250             if (!var) {
4251                 retval = false;
4252                 goto cleanup;
4253             }
4254         }
4255         if (parser->tok == '(' && wasarray) {
4256             parseerror(parser, "arrays as part of a return type is not supported");
4257             /* we'll still parse the type completely for now */
4258         }
4259         /* for functions returning functions */
4260         while (parser->tok == '(') {
4261             if (opts.standard == COMPILER_QCC)
4262                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4263             var = parse_parameter_list(parser, var);
4264             if (!var) {
4265                 retval = false;
4266                 goto cleanup;
4267             }
4268         }
4269
4270         var->cvq = qualifier;
4271         /* in a noref section we simply bump the usecount */
4272         if (noref || parser->noref)
4273             var->uses++;
4274         if (noreturn)
4275             var->expression.flags |= AST_FLAG_NORETURN;
4276
4277         /* Part 1:
4278          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4279          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4280          * is then filled with the previous definition and the parameter-names replaced.
4281          */
4282         if (!localblock) {
4283             /* Deal with end_sys_ vars */
4284             was_end = false;
4285             if (!strcmp(var->name, "end_sys_globals")) {
4286                 var->uses++;
4287                 parser->crc_globals = vec_size(parser->globals);
4288                 was_end = true;
4289             }
4290             else if (!strcmp(var->name, "end_sys_fields")) {
4291                 var->uses++;
4292                 parser->crc_fields = vec_size(parser->fields);
4293                 was_end = true;
4294             }
4295             if (was_end && var->expression.vtype == TYPE_FIELD) {
4296                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4297                                  "global '%s' hint should not be a field",
4298                                  parser_tokval(parser)))
4299                 {
4300                     retval = false;
4301                     goto cleanup;
4302                 }
4303             }
4304
4305             if (!nofields && var->expression.vtype == TYPE_FIELD)
4306             {
4307                 /* deal with field declarations */
4308                 old = parser_find_field(parser, var->name);
4309                 if (old) {
4310                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4311                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4312                     {
4313                         retval = false;
4314                         goto cleanup;
4315                     }
4316                     ast_delete(var);
4317                     var = NULL;
4318                     goto skipvar;
4319                     /*
4320                     parseerror(parser, "field `%s` already declared here: %s:%i",
4321                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4322                     retval = false;
4323                     goto cleanup;
4324                     */
4325                 }
4326                 if (opts.standard == COMPILER_QCC &&
4327                     (old = parser_find_global(parser, var->name)))
4328                 {
4329                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4330                     parseerror(parser, "field `%s` already declared here: %s:%i",
4331                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4332                     retval = false;
4333                     goto cleanup;
4334                 }
4335             }
4336             else
4337             {
4338                 /* deal with other globals */
4339                 old = parser_find_global(parser, var->name);
4340                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4341                 {
4342                     /* This is a function which had a prototype */
4343                     if (!ast_istype(old, ast_value)) {
4344                         parseerror(parser, "internal error: prototype is not an ast_value");
4345                         retval = false;
4346                         goto cleanup;
4347                     }
4348                     proto = (ast_value*)old;
4349                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4350                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4351                                    proto->name,
4352                                    ast_ctx(proto).file, ast_ctx(proto).line);
4353                         retval = false;
4354                         goto cleanup;
4355                     }
4356                     /* we need the new parameter-names */
4357                     for (i = 0; i < vec_size(proto->expression.params); ++i)
4358                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4359                     ast_delete(var);
4360                     var = proto;
4361                 }
4362                 else
4363                 {
4364                     /* other globals */
4365                     if (old) {
4366                         if (opts.standard == COMPILER_GMQCC) {
4367                             parseerror(parser, "global `%s` already declared here: %s:%i",
4368                                        var->name, ast_ctx(old).file, ast_ctx(old).line);
4369                             retval = false;
4370                             goto cleanup;
4371                         } else {
4372                             if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4373                                              "global `%s` already declared here: %s:%i",
4374                                              var->name, ast_ctx(old).file, ast_ctx(old).line))
4375                             {
4376                                 retval = false;
4377                                 goto cleanup;
4378                             }
4379                             proto = (ast_value*)old;
4380                             if (!ast_istype(old, ast_value)) {
4381                                 parseerror(parser, "internal error: not an ast_value");
4382                                 retval = false;
4383                                 proto = NULL;
4384                                 goto cleanup;
4385                             }
4386                             ast_delete(var);
4387                             var = proto;
4388                         }
4389                     }
4390                     if (opts.standard == COMPILER_QCC &&
4391                         (old = parser_find_field(parser, var->name)))
4392                     {
4393                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4394                         parseerror(parser, "global `%s` already declared here: %s:%i",
4395                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
4396                         retval = false;
4397                         goto cleanup;
4398                     }
4399                 }
4400             }
4401         }
4402         else /* it's not a global */
4403         {
4404             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4405             if (old && !isparam) {
4406                 parseerror(parser, "local `%s` already declared here: %s:%i",
4407                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4408                 retval = false;
4409                 goto cleanup;
4410             }
4411             old = parser_find_local(parser, var->name, 0, &isparam);
4412             if (old && isparam) {
4413                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4414                                  "local `%s` is shadowing a parameter", var->name))
4415                 {
4416                     parseerror(parser, "local `%s` already declared here: %s:%i",
4417                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4418                     retval = false;
4419                     goto cleanup;
4420                 }
4421                 if (opts.standard != COMPILER_GMQCC) {
4422                     ast_delete(var);
4423                     var = NULL;
4424                     goto skipvar;
4425                 }
4426             }
4427         }
4428
4429         /* Part 2:
4430          * Create the global/local, and deal with vector types.
4431          */
4432         if (!proto) {
4433             if (var->expression.vtype == TYPE_VECTOR)
4434                 isvector = true;
4435             else if (var->expression.vtype == TYPE_FIELD &&
4436                      var->expression.next->expression.vtype == TYPE_VECTOR)
4437                 isvector = true;
4438
4439             if (isvector) {
4440                 if (!create_vector_members(var, me)) {
4441                     retval = false;
4442                     goto cleanup;
4443                 }
4444             }
4445
4446             if (!localblock) {
4447                 /* deal with global variables, fields, functions */
4448                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4449                     var->isfield = true;
4450                     vec_push(parser->fields, (ast_expression*)var);
4451                     util_htset(parser->htfields, var->name, var);
4452                     if (isvector) {
4453                         for (i = 0; i < 3; ++i) {
4454                             vec_push(parser->fields, (ast_expression*)me[i]);
4455                             util_htset(parser->htfields, me[i]->name, me[i]);
4456                         }
4457                     }
4458                 }
4459                 else {
4460                     vec_push(parser->globals, (ast_expression*)var);
4461                     util_htset(parser->htglobals, var->name, var);
4462                     if (isvector) {
4463                         for (i = 0; i < 3; ++i) {
4464                             vec_push(parser->globals, (ast_expression*)me[i]);
4465                             util_htset(parser->htglobals, me[i]->name, me[i]);
4466                         }
4467                     }
4468                 }
4469             } else {
4470                 if (is_static) {
4471                     /* a static adds itself to be generated like any other global
4472                      * but is added to the local namespace instead
4473                      */
4474                     char   *defname = NULL;
4475                     size_t  prefix_len, ln;
4476
4477                     ln = strlen(parser->function->name);
4478                     vec_append(defname, ln, parser->function->name);
4479
4480                     vec_append(defname, 2, "::");
4481                     /* remember the length up to here */
4482                     prefix_len = vec_size(defname);
4483
4484                     /* Add it to the local scope */
4485                     util_htset(vec_last(parser->variables), var->name, (void*)var);
4486                     /* now rename the global */
4487                     ln = strlen(var->name);
4488                     vec_append(defname, ln, var->name);
4489                     ast_value_set_name(var, defname);
4490
4491                     /* push it to the to-be-generated globals */
4492                     vec_push(parser->globals, (ast_expression*)var);
4493
4494                     /* same game for the vector members */
4495                     if (isvector) {
4496                         for (i = 0; i < 3; ++i) {
4497                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4498
4499                             vec_shrinkto(defname, prefix_len);
4500                             ln = strlen(me[i]->name);
4501                             vec_append(defname, ln, me[i]->name);
4502                             ast_member_set_name(me[i], defname);
4503
4504                             vec_push(parser->globals, (ast_expression*)me[i]);
4505                         }
4506                     }
4507                     vec_free(defname);
4508                 } else {
4509                     vec_push(localblock->locals, var);
4510                     parser_addlocal(parser, var->name, (ast_expression*)var);
4511                     if (isvector) {
4512                         for (i = 0; i < 3; ++i) {
4513                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4514                             ast_block_collect(localblock, (ast_expression*)me[i]);
4515                         }
4516                     }
4517                 }
4518             }
4519         }
4520         me[0] = me[1] = me[2] = NULL;
4521         cleanvar = false;
4522         /* Part 2.2
4523          * deal with arrays
4524          */
4525         if (var->expression.vtype == TYPE_ARRAY) {
4526             char name[1024];
4527             snprintf(name, sizeof(name), "%s##SET", var->name);
4528             if (!parser_create_array_setter(parser, var, name))
4529                 goto cleanup;
4530             snprintf(name, sizeof(name), "%s##GET", var->name);
4531             if (!parser_create_array_getter(parser, var, var->expression.next, name))
4532                 goto cleanup;
4533         }
4534         else if (!localblock && !nofields &&
4535                  var->expression.vtype == TYPE_FIELD &&
4536                  var->expression.next->expression.vtype == TYPE_ARRAY)
4537         {
4538             char name[1024];
4539             ast_expression *telem;
4540             ast_value      *tfield;
4541             ast_value      *array = (ast_value*)var->expression.next;
4542
4543             if (!ast_istype(var->expression.next, ast_value)) {
4544                 parseerror(parser, "internal error: field element type must be an ast_value");
4545                 goto cleanup;
4546             }
4547
4548             snprintf(name, sizeof(name), "%s##SETF", var->name);
4549             if (!parser_create_array_field_setter(parser, array, name))
4550                 goto cleanup;
4551
4552             telem = ast_type_copy(ast_ctx(var), array->expression.next);
4553             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4554             tfield->expression.next = telem;
4555             snprintf(name, sizeof(name), "%s##GETFP", var->name);
4556             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4557                 ast_delete(tfield);
4558                 goto cleanup;
4559             }
4560             ast_delete(tfield);
4561         }
4562
4563 skipvar:
4564         if (parser->tok == ';') {
4565             ast_delete(basetype);
4566             if (!parser_next(parser)) {
4567                 parseerror(parser, "error after variable declaration");
4568                 return false;
4569             }
4570             return true;
4571         }
4572
4573         if (parser->tok == ',')
4574             goto another;
4575
4576         /*
4577         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4578         */
4579         if (!var) {
4580             parseerror(parser, "missing comma or semicolon while parsing variables");
4581             break;
4582         }
4583
4584         if (localblock && opts.standard == COMPILER_QCC) {
4585             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4586                              "initializing expression turns variable `%s` into a constant in this standard",
4587                              var->name) )
4588             {
4589                 break;
4590             }
4591         }
4592
4593         if (parser->tok != '{') {
4594             if (parser->tok != '=') {
4595                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4596                 break;
4597             }
4598
4599             if (!parser_next(parser)) {
4600                 parseerror(parser, "error parsing initializer");
4601                 break;
4602             }
4603         }
4604         else if (opts.standard == COMPILER_QCC) {
4605             parseerror(parser, "expected '=' before function body in this standard");
4606         }
4607
4608         if (parser->tok == '#') {
4609             ast_function *func = NULL;
4610
4611             if (localblock) {
4612                 parseerror(parser, "cannot declare builtins within functions");
4613                 break;
4614             }
4615             if (var->expression.vtype != TYPE_FUNCTION) {
4616                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4617                 break;
4618             }
4619             if (!parser_next(parser)) {
4620                 parseerror(parser, "expected builtin number");
4621                 break;
4622             }
4623             if (parser->tok != TOKEN_INTCONST) {
4624                 parseerror(parser, "builtin number must be an integer constant");
4625                 break;
4626             }
4627             if (parser_token(parser)->constval.i < 0) {
4628                 parseerror(parser, "builtin number must be an integer greater than zero");
4629                 break;
4630             }
4631
4632             if (var->hasvalue) {
4633                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4634                                     "builtin `%s` has already been defined\n"
4635                                     " -> previous declaration here: %s:%i",
4636                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4637             }
4638             else
4639             {
4640                 func = ast_function_new(ast_ctx(var), var->name, var);
4641                 if (!func) {
4642                     parseerror(parser, "failed to allocate function for `%s`", var->name);
4643                     break;
4644                 }
4645                 vec_push(parser->functions, func);
4646
4647                 func->builtin = -parser_token(parser)->constval.i-1;
4648             }
4649
4650             if (!parser_next(parser)) {
4651                 parseerror(parser, "expected comma or semicolon");
4652                 if (func)
4653                     ast_function_delete(func);
4654                 var->constval.vfunc = NULL;
4655                 break;
4656             }
4657         }
4658         else if (parser->tok == '{' || parser->tok == '[')
4659         {
4660             if (localblock) {
4661                 parseerror(parser, "cannot declare functions within functions");
4662                 break;
4663             }
4664
4665             if (proto)
4666                 ast_ctx(proto) = parser_ctx(parser);
4667
4668             if (!parse_function_body(parser, var))
4669                 break;
4670             ast_delete(basetype);
4671             for (i = 0; i < vec_size(parser->gotos); ++i)
4672                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4673             vec_free(parser->gotos);
4674             vec_free(parser->labels);
4675             return true;
4676         } else {
4677             ast_expression *cexp;
4678             ast_value      *cval;
4679
4680             cexp = parse_expression_leave(parser, true);
4681             if (!cexp)
4682                 break;
4683
4684             if (!localblock) {
4685                 cval = (ast_value*)cexp;
4686                 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4687                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4688                 else
4689                 {
4690                     if (opts.standard != COMPILER_GMQCC &&
4691                         !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4692                         qualifier != CV_VAR)
4693                     {
4694                         var->cvq = CV_CONST;
4695                     }
4696                     var->hasvalue = true;
4697                     if (cval->expression.vtype == TYPE_STRING)
4698                         var->constval.vstring = parser_strdup(cval->constval.vstring);
4699                     else if (cval->expression.vtype == TYPE_FIELD)
4700                         var->constval.vfield = cval;
4701                     else
4702                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4703                     ast_unref(cval);
4704                 }
4705             } else {
4706                 int cvq;
4707                 shunt sy = { NULL, NULL };
4708                 cvq = var->cvq;
4709                 var->cvq = CV_NONE;
4710                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4711                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4712                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4713                 if (!parser_sy_apply_operator(parser, &sy))
4714                     ast_unref(cexp);
4715                 else {
4716                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4717                         parseerror(parser, "internal error: leaked operands");
4718                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4719                         break;
4720                 }
4721                 vec_free(sy.out);
4722                 vec_free(sy.ops);
4723                 var->cvq = cvq;
4724             }
4725         }
4726
4727 another:
4728         if (parser->tok == ',') {
4729             if (!parser_next(parser)) {
4730                 parseerror(parser, "expected another variable");
4731                 break;
4732             }
4733
4734             if (parser->tok != TOKEN_IDENT) {
4735                 parseerror(parser, "expected another variable");
4736                 break;
4737             }
4738             var = ast_value_copy(basetype);
4739             cleanvar = true;
4740             ast_value_set_name(var, parser_tokval(parser));
4741             if (!parser_next(parser)) {
4742                 parseerror(parser, "error parsing variable declaration");
4743                 break;
4744             }
4745             continue;
4746         }
4747
4748         if (parser->tok != ';') {
4749             parseerror(parser, "missing semicolon after variables");
4750             break;
4751         }
4752
4753         if (!parser_next(parser)) {
4754             parseerror(parser, "parse error after variable declaration");
4755             break;
4756         }
4757
4758         ast_delete(basetype);
4759         return true;
4760     }
4761
4762     if (cleanvar && var)
4763         ast_delete(var);
4764     ast_delete(basetype);
4765     return false;
4766
4767 cleanup:
4768     ast_delete(basetype);
4769     if (cleanvar && var)
4770         ast_delete(var);
4771     if (me[0]) ast_member_delete(me[0]);
4772     if (me[1]) ast_member_delete(me[1]);
4773     if (me[2]) ast_member_delete(me[2]);
4774     return retval;
4775 }
4776
4777 static bool parser_global_statement(parser_t *parser)
4778 {
4779     int        cvq       = CV_WRONG;
4780     bool       noref     = false;
4781     bool       noreturn  = false;
4782     bool       is_static = false;
4783     ast_value *istype    = NULL;
4784
4785     if (parser->tok == TOKEN_IDENT)
4786         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4787
4788     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4789     {
4790         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, false);
4791     }
4792     else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn, &is_static))
4793     {
4794         if (cvq == CV_WRONG)
4795             return false;
4796         return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn, is_static);
4797     }
4798     else if (parser->tok == TOKEN_KEYWORD)
4799     {
4800         if (!strcmp(parser_tokval(parser), "typedef")) {
4801             if (!parser_next(parser)) {
4802                 parseerror(parser, "expected type definition after 'typedef'");
4803                 return false;
4804             }
4805             return parse_typedef(parser);
4806         }
4807         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4808         return false;
4809     }
4810     else if (parser->tok == '#')
4811     {
4812         return parse_pragma(parser);
4813     }
4814     else if (parser->tok == '$')
4815     {
4816         if (!parser_next(parser)) {
4817             parseerror(parser, "parse error");
4818             return false;
4819         }
4820     }
4821     else
4822     {
4823         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4824         return false;
4825     }
4826     return true;
4827 }
4828
4829 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4830 {
4831     return util_crc16(old, str, strlen(str));
4832 }
4833
4834 static void progdefs_crc_file(const char *str)
4835 {
4836     /* write to progdefs.h here */
4837     (void)str;
4838 }
4839
4840 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4841 {
4842     old = progdefs_crc_sum(old, str);
4843     progdefs_crc_file(str);
4844     return old;
4845 }
4846
4847 static void generate_checksum(parser_t *parser)
4848 {
4849     uint16_t   crc = 0xFFFF;
4850     size_t     i;
4851     ast_value *value;
4852
4853     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4854     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4855     /*
4856     progdefs_crc_file("\tint\tpad;\n");
4857     progdefs_crc_file("\tint\tofs_return[3];\n");
4858     progdefs_crc_file("\tint\tofs_parm0[3];\n");
4859     progdefs_crc_file("\tint\tofs_parm1[3];\n");
4860     progdefs_crc_file("\tint\tofs_parm2[3];\n");
4861     progdefs_crc_file("\tint\tofs_parm3[3];\n");
4862     progdefs_crc_file("\tint\tofs_parm4[3];\n");
4863     progdefs_crc_file("\tint\tofs_parm5[3];\n");
4864     progdefs_crc_file("\tint\tofs_parm6[3];\n");
4865     progdefs_crc_file("\tint\tofs_parm7[3];\n");
4866     */
4867     for (i = 0; i < parser->crc_globals; ++i) {
4868         if (!ast_istype(parser->globals[i], ast_value))
4869             continue;
4870         value = (ast_value*)(parser->globals[i]);
4871         switch (value->expression.vtype) {
4872             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4873             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4874             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4875             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4876             default:
4877                 crc = progdefs_crc_both(crc, "\tint\t");
4878                 break;
4879         }
4880         crc = progdefs_crc_both(crc, value->name);
4881         crc = progdefs_crc_both(crc, ";\n");
4882     }
4883     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4884     for (i = 0; i < parser->crc_fields; ++i) {
4885         if (!ast_istype(parser->fields[i], ast_value))
4886             continue;
4887         value = (ast_value*)(parser->fields[i]);
4888         switch (value->expression.next->expression.vtype) {
4889             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4890             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4891             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4892             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4893             default:
4894                 crc = progdefs_crc_both(crc, "\tint\t");
4895                 break;
4896         }
4897         crc = progdefs_crc_both(crc, value->name);
4898         crc = progdefs_crc_both(crc, ";\n");
4899     }
4900     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4901
4902     code_crc = crc;
4903 }
4904
4905 static parser_t *parser;
4906
4907 bool parser_init()
4908 {
4909     size_t i;
4910
4911     parser = (parser_t*)mem_a(sizeof(parser_t));
4912     if (!parser)
4913         return false;
4914
4915     memset(parser, 0, sizeof(*parser));
4916
4917     for (i = 0; i < operator_count; ++i) {
4918         if (operators[i].id == opid1('=')) {
4919             parser->assign_op = operators+i;
4920             break;
4921         }
4922     }
4923     if (!parser->assign_op) {
4924         printf("internal error: initializing parser: failed to find assign operator\n");
4925         mem_d(parser);
4926         return false;
4927     }
4928
4929     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
4930     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4931     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4932     vec_push(parser->_blocktypedefs, 0);
4933     return true;
4934 }
4935
4936 bool parser_compile()
4937 {
4938     /* initial lexer/parser state */
4939     parser->lex->flags.noops = true;
4940
4941     if (parser_next(parser))
4942     {
4943         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4944         {
4945             if (!parser_global_statement(parser)) {
4946                 if (parser->tok == TOKEN_EOF)
4947                     parseerror(parser, "unexpected eof");
4948                 else if (compile_errors)
4949                     parseerror(parser, "there have been errors, bailing out");
4950                 lex_close(parser->lex);
4951                 parser->lex = NULL;
4952                 return false;
4953             }
4954         }
4955     } else {
4956         parseerror(parser, "parse error");
4957         lex_close(parser->lex);
4958         parser->lex = NULL;
4959         return false;
4960     }
4961
4962     lex_close(parser->lex);
4963     parser->lex = NULL;
4964
4965     return !compile_errors;
4966 }
4967
4968 bool parser_compile_file(const char *filename)
4969 {
4970     parser->lex = lex_open(filename);
4971     if (!parser->lex) {
4972         con_err("failed to open file \"%s\"\n", filename);
4973         return false;
4974     }
4975     return parser_compile();
4976 }
4977
4978 bool parser_compile_string(const char *name, const char *str, size_t len)
4979 {
4980     parser->lex = lex_open_string(str, len, name);
4981     if (!parser->lex) {
4982         con_err("failed to create lexer for string \"%s\"\n", name);
4983         return false;
4984     }
4985     return parser_compile();
4986 }
4987
4988 void parser_cleanup()
4989 {
4990     size_t i;
4991     for (i = 0; i < vec_size(parser->accessors); ++i) {
4992         ast_delete(parser->accessors[i]->constval.vfunc);
4993         parser->accessors[i]->constval.vfunc = NULL;
4994         ast_delete(parser->accessors[i]);
4995     }
4996     for (i = 0; i < vec_size(parser->functions); ++i) {
4997         ast_delete(parser->functions[i]);
4998     }
4999     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5000         ast_delete(parser->imm_vector[i]);
5001     }
5002     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5003         ast_delete(parser->imm_string[i]);
5004     }
5005     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5006         ast_delete(parser->imm_float[i]);
5007     }
5008     for (i = 0; i < vec_size(parser->fields); ++i) {
5009         ast_delete(parser->fields[i]);
5010     }
5011     for (i = 0; i < vec_size(parser->globals); ++i) {
5012         ast_delete(parser->globals[i]);
5013     }
5014     vec_free(parser->accessors);
5015     vec_free(parser->functions);
5016     vec_free(parser->imm_vector);
5017     vec_free(parser->imm_string);
5018     vec_free(parser->imm_float);
5019     vec_free(parser->globals);
5020     vec_free(parser->fields);
5021
5022     for (i = 0; i < vec_size(parser->variables); ++i)
5023         util_htdel(parser->variables[i]);
5024     vec_free(parser->variables);
5025     vec_free(parser->_blocklocals);
5026     vec_free(parser->_locals);
5027
5028     for (i = 0; i < vec_size(parser->_typedefs); ++i)
5029         ast_delete(parser->_typedefs[i]);
5030     vec_free(parser->_typedefs);
5031     for (i = 0; i < vec_size(parser->typedefs); ++i)
5032         util_htdel(parser->typedefs[i]);
5033     vec_free(parser->typedefs);
5034     vec_free(parser->_blocktypedefs);
5035
5036     vec_free(parser->_block_ctx);
5037
5038     vec_free(parser->labels);
5039     vec_free(parser->gotos);
5040     vec_free(parser->breaks);
5041     vec_free(parser->continues);
5042
5043     mem_d(parser);
5044 }
5045
5046 bool parser_finish(const char *output)
5047 {
5048     size_t i;
5049     ir_builder *ir;
5050     bool retval = true;
5051
5052     if (compile_errors) {
5053         con_out("*** there were compile errors\n");
5054         return false;
5055     }
5056
5057     ir = ir_builder_new("gmqcc_out");
5058     if (!ir) {
5059         con_out("failed to allocate builder\n");
5060         return false;
5061     }
5062
5063     for (i = 0; i < vec_size(parser->fields); ++i) {
5064         ast_value *field;
5065         bool hasvalue;
5066         if (!ast_istype(parser->fields[i], ast_value))
5067             continue;
5068         field = (ast_value*)parser->fields[i];
5069         hasvalue = field->hasvalue;
5070         field->hasvalue = false;
5071         if (!ast_global_codegen((ast_value*)field, ir, true)) {
5072             con_out("failed to generate field %s\n", field->name);
5073             ir_builder_delete(ir);
5074             return false;
5075         }
5076         if (hasvalue) {
5077             ir_value *ifld;
5078             ast_expression *subtype;
5079             field->hasvalue = true;
5080             subtype = field->expression.next;
5081             ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5082             if (subtype->expression.vtype == TYPE_FIELD)
5083                 ifld->fieldtype = subtype->expression.next->expression.vtype;
5084             else if (subtype->expression.vtype == TYPE_FUNCTION)
5085                 ifld->outtype = subtype->expression.next->expression.vtype;
5086             (void)!ir_value_set_field(field->ir_v, ifld);
5087         }
5088     }
5089     for (i = 0; i < vec_size(parser->globals); ++i) {
5090         ast_value *asvalue;
5091         if (!ast_istype(parser->globals[i], ast_value))
5092             continue;
5093         asvalue = (ast_value*)(parser->globals[i]);
5094         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5095             retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5096                                            "unused global: `%s`", asvalue->name);
5097         }
5098         if (!ast_global_codegen(asvalue, ir, false)) {
5099             con_out("failed to generate global %s\n", asvalue->name);
5100             ir_builder_delete(ir);
5101             return false;
5102         }
5103     }
5104     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5105         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5106             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5107             ir_builder_delete(ir);
5108             return false;
5109         }
5110     }
5111     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5112         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5113             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5114             ir_builder_delete(ir);
5115             return false;
5116         }
5117     }
5118     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5119         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5120             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5121             ir_builder_delete(ir);
5122             return false;
5123         }
5124     }
5125     for (i = 0; i < vec_size(parser->globals); ++i) {
5126         ast_value *asvalue;
5127         if (!ast_istype(parser->globals[i], ast_value))
5128             continue;
5129         asvalue = (ast_value*)(parser->globals[i]);
5130         if (!ast_generate_accessors(asvalue, ir)) {
5131             ir_builder_delete(ir);
5132             return false;
5133         }
5134     }
5135     for (i = 0; i < vec_size(parser->fields); ++i) {
5136         ast_value *asvalue;
5137         asvalue = (ast_value*)(parser->fields[i]->expression.next);
5138
5139         if (!ast_istype((ast_expression*)asvalue, ast_value))
5140             continue;
5141         if (asvalue->expression.vtype != TYPE_ARRAY)
5142             continue;
5143         if (!ast_generate_accessors(asvalue, ir)) {
5144             ir_builder_delete(ir);
5145             return false;
5146         }
5147     }
5148     for (i = 0; i < vec_size(parser->functions); ++i) {
5149         if (!ast_function_codegen(parser->functions[i], ir)) {
5150             con_out("failed to generate function %s\n", parser->functions[i]->name);
5151             ir_builder_delete(ir);
5152             return false;
5153         }
5154     }
5155     if (opts.dump)
5156         ir_builder_dump(ir, con_out);
5157     for (i = 0; i < vec_size(parser->functions); ++i) {
5158         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5159             con_out("failed to finalize function %s\n", parser->functions[i]->name);
5160             ir_builder_delete(ir);
5161             return false;
5162         }
5163     }
5164
5165     if (compile_Werrors) {
5166         con_out("*** there were warnings treated as errors\n");
5167         compile_show_werrors();
5168         retval = false;
5169     }
5170
5171     if (retval) {
5172         if (opts.dumpfin)
5173             ir_builder_dump(ir, con_out);
5174
5175         generate_checksum(parser);
5176
5177         if (!ir_builder_generate(ir, output)) {
5178             con_out("*** failed to generate output file\n");
5179             ir_builder_delete(ir);
5180             return false;
5181         }
5182     }
5183
5184     ir_builder_delete(ir);
5185     return retval;
5186 }