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