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