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