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