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