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