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