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