]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
sqrt and normalize builtins
[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                             }
1653                         }
1654
1655                         if (correct) {
1656                             parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1657                             mem_d(correct);
1658                             goto onerr;
1659                         }
1660                     }
1661                     parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1662                     goto onerr;
1663                 }
1664             }
1665             else
1666             {
1667                 if (ast_istype(var, ast_value)) {
1668                     ((ast_value*)var)->uses++;
1669                 }
1670                 else if (ast_istype(var, ast_member)) {
1671                     ast_member *mem = (ast_member*)var;
1672                     if (ast_istype(mem->owner, ast_value))
1673                         ((ast_value*)(mem->owner))->uses++;
1674                 }
1675             }
1676             vec_push(sy.out, syexp(parser_ctx(parser), var));
1677             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1678         }
1679         else if (parser->tok == TOKEN_FLOATCONST) {
1680             ast_value *val;
1681             if (wantop) {
1682                 parseerror(parser, "expected operator or end of statement, got constant");
1683                 goto onerr;
1684             }
1685             wantop = true;
1686             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1687             if (!val)
1688                 return NULL;
1689             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1690             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1691         }
1692         else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1693             ast_value *val;
1694             if (wantop) {
1695                 parseerror(parser, "expected operator or end of statement, got constant");
1696                 goto onerr;
1697             }
1698             wantop = true;
1699             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1700             if (!val)
1701                 return NULL;
1702             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1703             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1704         }
1705         else if (parser->tok == TOKEN_STRINGCONST) {
1706             ast_value *val;
1707             if (wantop) {
1708                 parseerror(parser, "expected operator or end of statement, got constant");
1709                 goto onerr;
1710             }
1711             wantop = true;
1712             val = parser_const_string(parser, parser_tokval(parser), false);
1713             if (!val)
1714                 return NULL;
1715             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1716             DEBUGSHUNTDO(con_out("push string\n"));
1717         }
1718         else if (parser->tok == TOKEN_VECTORCONST) {
1719             ast_value *val;
1720             if (wantop) {
1721                 parseerror(parser, "expected operator or end of statement, got constant");
1722                 goto onerr;
1723             }
1724             wantop = true;
1725             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1726             if (!val)
1727                 return NULL;
1728             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1729             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1730                                 parser_token(parser)->constval.v.x,
1731                                 parser_token(parser)->constval.v.y,
1732                                 parser_token(parser)->constval.v.z));
1733         }
1734         else if (parser->tok == '(') {
1735             parseerror(parser, "internal error: '(' should be classified as operator");
1736             goto onerr;
1737         }
1738         else if (parser->tok == '[') {
1739             parseerror(parser, "internal error: '[' should be classified as operator");
1740             goto onerr;
1741         }
1742         else if (parser->tok == ')') {
1743             if (wantop) {
1744                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1745                 --parens;
1746                 if (parens < 0)
1747                     break;
1748                 /* we do expect an operator next */
1749                 /* closing an opening paren */
1750                 if (!parser_close_paren(parser, &sy, false))
1751                     goto onerr;
1752                 if (vec_last(parser->pot) != POT_PAREN) {
1753                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1754                     goto onerr;
1755                 }
1756                 vec_pop(parser->pot);
1757             } else {
1758                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1759                 --parens;
1760                 if (parens < 0)
1761                     break;
1762                 /* allowed for function calls */
1763                 if (!parser_close_paren(parser, &sy, true))
1764                     goto onerr;
1765                 if (vec_last(parser->pot) != POT_PAREN) {
1766                     parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1767                     goto onerr;
1768                 }
1769                 vec_pop(parser->pot);
1770             }
1771             wantop = true;
1772         }
1773         else if (parser->tok == ']') {
1774             if (!wantop)
1775                 parseerror(parser, "operand expected");
1776             --parens;
1777             if (parens < 0)
1778                 break;
1779             if (!parser_close_paren(parser, &sy, false))
1780                 goto onerr;
1781             if (vec_last(parser->pot) != POT_PAREN) {
1782                 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1783                 goto onerr;
1784             }
1785             vec_pop(parser->pot);
1786             wantop = true;
1787         }
1788         else if (parser->tok == TOKEN_TYPENAME) {
1789             parseerror(parser, "unexpected typename");
1790             goto onerr;
1791         }
1792         else if (parser->tok != TOKEN_OPERATOR) {
1793             if (wantop) {
1794                 parseerror(parser, "expected operator or end of statement");
1795                 goto onerr;
1796             }
1797             break;
1798         }
1799         else
1800         {
1801             /* classify the operator */
1802             const oper_info *op;
1803             const oper_info *olast = NULL;
1804             size_t o;
1805             for (o = 0; o < operator_count; ++o) {
1806                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1807                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1808                     !strcmp(parser_tokval(parser), operators[o].op))
1809                 {
1810                     break;
1811                 }
1812             }
1813             if (o == operator_count) {
1814                 /* no operator found... must be the end of the statement */
1815                 break;
1816             }
1817             /* found an operator */
1818             op = &operators[o];
1819
1820             /* when declaring variables, a comma starts a new variable */
1821             if (op->id == opid1(',') && !parens && stopatcomma) {
1822                 /* fixup the token */
1823                 parser->tok = ',';
1824                 break;
1825             }
1826
1827             /* a colon without a pervious question mark cannot be a ternary */
1828             if (!ternaries && op->id == opid2(':','?')) {
1829                 parser->tok = ':';
1830                 break;
1831             }
1832
1833             if (op->id == opid1(',')) {
1834                 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1835                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1836                 }
1837             }
1838
1839             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1840                 olast = &operators[vec_last(sy.ops).etype-1];
1841
1842 #define IsAssignOp(x) (\
1843                 (x) == opid1('=') || \
1844                 (x) == opid2('+','=') || \
1845                 (x) == opid2('-','=') || \
1846                 (x) == opid2('*','=') || \
1847                 (x) == opid2('/','=') || \
1848                 (x) == opid2('%','=') || \
1849                 (x) == opid2('&','=') || \
1850                 (x) == opid2('|','=') || \
1851                 (x) == opid3('&','~','=') \
1852                 )
1853             if (warn_truthvalue) {
1854                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1855                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1856                      (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1857                    )
1858                 {
1859                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1860                     warn_truthvalue = false;
1861                 }
1862             }
1863
1864             while (olast && (
1865                     (op->prec < olast->prec) ||
1866                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1867             {
1868                 if (!parser_sy_apply_operator(parser, &sy))
1869                     goto onerr;
1870                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1871                     olast = &operators[vec_last(sy.ops).etype-1];
1872                 else
1873                     olast = NULL;
1874             }
1875
1876             if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1877                 /* for gmqcc standard: open up the namespace of the previous type */
1878                 ast_expression *prevex = vec_last(sy.out).out;
1879                 if (!prevex) {
1880                     parseerror(parser, "unexpected member operator");
1881                     goto onerr;
1882                 }
1883                 if (prevex->expression.vtype == TYPE_ENTITY)
1884                     parser->memberof = TYPE_ENTITY;
1885                 else if (prevex->expression.vtype == TYPE_VECTOR)
1886                     parser->memberof = TYPE_VECTOR;
1887                 else {
1888                     parseerror(parser, "type error: type has no members");
1889                     goto onerr;
1890                 }
1891                 gotmemberof = true;
1892             }
1893
1894             if (op->id == opid1('(')) {
1895                 if (wantop) {
1896                     size_t sycount = vec_size(sy.out);
1897                     DEBUGSHUNTDO(con_out("push [op] (\n"));
1898                     ++parens; vec_push(parser->pot, POT_PAREN);
1899                     /* we expected an operator, this is the function-call operator */
1900                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1901                 } else {
1902                     ++parens; vec_push(parser->pot, POT_PAREN);
1903                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1904                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
1905                 }
1906                 wantop = false;
1907             } else if (op->id == opid1('[')) {
1908                 if (!wantop) {
1909                     parseerror(parser, "unexpected array subscript");
1910                     goto onerr;
1911                 }
1912                 ++parens; vec_push(parser->pot, POT_PAREN);
1913                 /* push both the operator and the paren, this makes life easier */
1914                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1915                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1916                 wantop = false;
1917             } else if (op->id == opid2('?',':')) {
1918                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1919                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1920                 wantop = false;
1921                 ++ternaries;
1922                 vec_push(parser->pot, POT_TERNARY1);
1923             } else if (op->id == opid2(':','?')) {
1924                 if (!vec_size(parser->pot)) {
1925                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1926                     goto onerr;
1927                 }
1928                 if (vec_last(parser->pot) != POT_TERNARY1) {
1929                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1930                     goto onerr;
1931                 }
1932                 if (!parser_close_paren(parser, &sy, false))
1933                     goto onerr;
1934                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1935                 wantop = false;
1936                 --ternaries;
1937             } else {
1938                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1939                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1940                 wantop = !!(op->flags & OP_SUFFIX);
1941             }
1942         }
1943         if (!parser_next(parser)) {
1944             goto onerr;
1945         }
1946         if (parser->tok == ';' ||
1947             (!parens && parser->tok == ']'))
1948         {
1949             break;
1950         }
1951     }
1952
1953     while (vec_size(sy.ops)) {
1954         if (!parser_sy_apply_operator(parser, &sy))
1955             goto onerr;
1956     }
1957
1958     parser->lex->flags.noops = true;
1959     if (!vec_size(sy.out)) {
1960         parseerror(parser, "empty expression");
1961         expr = NULL;
1962     } else
1963         expr = sy.out[0].out;
1964     vec_free(sy.out);
1965     vec_free(sy.ops);
1966     DEBUGSHUNTDO(con_out("shunt done\n"));
1967     if (vec_size(parser->pot)) {
1968         parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1969         return NULL;
1970     }
1971     vec_free(parser->pot);
1972     return expr;
1973
1974 onerr:
1975     parser->lex->flags.noops = true;
1976     vec_free(sy.out);
1977     vec_free(sy.ops);
1978     return NULL;
1979 }
1980
1981 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1982 {
1983     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1984     if (!e)
1985         return NULL;
1986     if (!parser_next(parser)) {
1987         ast_delete(e);
1988         return NULL;
1989     }
1990     return e;
1991 }
1992
1993 static void parser_enterblock(parser_t *parser)
1994 {
1995     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1996     vec_push(parser->_blocklocals, vec_size(parser->_locals));
1997     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1998     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1999     vec_push(parser->_block_ctx, parser_ctx(parser));
2000
2001     /* corrector */
2002     vec_push(parser->correct_variables, correct_trie_new());
2003     vec_push(parser->correct_variables_score, NULL);
2004 }
2005
2006 static bool parser_leaveblock(parser_t *parser)
2007 {
2008     bool   rv = true;
2009     size_t locals, typedefs;
2010
2011     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2012         parseerror(parser, "internal error: parser_leaveblock with no block");
2013         return false;
2014     }
2015
2016     util_htdel(vec_last(parser->variables));
2017     correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2018
2019     vec_pop(parser->variables);
2020     vec_pop(parser->correct_variables);
2021     vec_pop(parser->correct_variables_score);
2022     if (!vec_size(parser->_blocklocals)) {
2023         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2024         return false;
2025     }
2026
2027     locals = vec_last(parser->_blocklocals);
2028     vec_pop(parser->_blocklocals);
2029     while (vec_size(parser->_locals) != locals) {
2030         ast_expression *e = vec_last(parser->_locals);
2031         ast_value      *v = (ast_value*)e;
2032         vec_pop(parser->_locals);
2033         if (ast_istype(e, ast_value) && !v->uses) {
2034             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2035                 rv = false;
2036         }
2037     }
2038
2039     typedefs = vec_last(parser->_blocktypedefs);
2040     while (vec_size(parser->_typedefs) != typedefs) {
2041         ast_delete(vec_last(parser->_typedefs));
2042         vec_pop(parser->_typedefs);
2043     }
2044     util_htdel(vec_last(parser->typedefs));
2045     vec_pop(parser->typedefs);
2046
2047     vec_pop(parser->_block_ctx);
2048
2049     return rv;
2050 }
2051
2052 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2053 {
2054     vec_push(parser->_locals, e);
2055     util_htset(vec_last(parser->variables), name, (void*)e);
2056
2057     /* corrector */
2058     correct_add (
2059          vec_last(parser->correct_variables),
2060         &vec_last(parser->correct_variables_score),
2061         name
2062     );
2063 }
2064
2065 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2066 {
2067     bool       ifnot = false;
2068     ast_unary *unary;
2069     ast_expression *prev;
2070
2071     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2072     {
2073         prev = cond;
2074         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2075         if (!cond) {
2076             ast_unref(prev);
2077             parseerror(parser, "internal error: failed to process condition");
2078             return NULL;
2079         }
2080         ifnot = !ifnot;
2081     }
2082     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2083     {
2084         /* vector types need to be cast to true booleans */
2085         ast_binary *bin = (ast_binary*)cond;
2086         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2087         {
2088             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2089             prev = cond;
2090             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2091             if (!cond) {
2092                 ast_unref(prev);
2093                 parseerror(parser, "internal error: failed to process condition");
2094                 return NULL;
2095             }
2096             ifnot = !ifnot;
2097         }
2098     }
2099
2100     unary = (ast_unary*)cond;
2101     while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2102     {
2103         cond = unary->operand;
2104         unary->operand = NULL;
2105         ast_delete(unary);
2106         ifnot = !ifnot;
2107         unary = (ast_unary*)cond;
2108     }
2109
2110     if (!cond)
2111         parseerror(parser, "internal error: failed to process condition");
2112
2113     if (ifnot) *_ifnot = !*_ifnot;
2114     return cond;
2115 }
2116
2117 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2118 {
2119     ast_ifthen *ifthen;
2120     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2121     bool ifnot = false;
2122
2123     lex_ctx ctx = parser_ctx(parser);
2124
2125     (void)block; /* not touching */
2126
2127     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2128     if (!parser_next(parser)) {
2129         parseerror(parser, "expected condition or 'not'");
2130         return false;
2131     }
2132     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2133         ifnot = true;
2134         if (!parser_next(parser)) {
2135             parseerror(parser, "expected condition in parenthesis");
2136             return false;
2137         }
2138     }
2139     if (parser->tok != '(') {
2140         parseerror(parser, "expected 'if' condition in parenthesis");
2141         return false;
2142     }
2143     /* parse into the expression */
2144     if (!parser_next(parser)) {
2145         parseerror(parser, "expected 'if' condition after opening paren");
2146         return false;
2147     }
2148     /* parse the condition */
2149     cond = parse_expression_leave(parser, false, true, false);
2150     if (!cond)
2151         return false;
2152     /* closing paren */
2153     if (parser->tok != ')') {
2154         parseerror(parser, "expected closing paren after 'if' condition");
2155         ast_delete(cond);
2156         return false;
2157     }
2158     /* parse into the 'then' branch */
2159     if (!parser_next(parser)) {
2160         parseerror(parser, "expected statement for on-true branch of 'if'");
2161         ast_delete(cond);
2162         return false;
2163     }
2164     if (!parse_statement_or_block(parser, &ontrue)) {
2165         ast_delete(cond);
2166         return false;
2167     }
2168     if (!ontrue)
2169         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2170     /* check for an else */
2171     if (!strcmp(parser_tokval(parser), "else")) {
2172         /* parse into the 'else' branch */
2173         if (!parser_next(parser)) {
2174             parseerror(parser, "expected on-false branch after 'else'");
2175             ast_delete(ontrue);
2176             ast_delete(cond);
2177             return false;
2178         }
2179         if (!parse_statement_or_block(parser, &onfalse)) {
2180             ast_delete(ontrue);
2181             ast_delete(cond);
2182             return false;
2183         }
2184     }
2185
2186     cond = process_condition(parser, cond, &ifnot);
2187     if (!cond) {
2188         if (ontrue)  ast_delete(ontrue);
2189         if (onfalse) ast_delete(onfalse);
2190         return false;
2191     }
2192
2193     if (ifnot)
2194         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2195     else
2196         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2197     *out = (ast_expression*)ifthen;
2198     return true;
2199 }
2200
2201 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2202 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2203 {
2204     bool rv;
2205     char *label = NULL;
2206
2207     /* skip the 'while' and get the body */
2208     if (!parser_next(parser)) {
2209         if (OPTS_FLAG(LOOP_LABELS))
2210             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2211         else
2212             parseerror(parser, "expected 'while' condition in parenthesis");
2213         return false;
2214     }
2215
2216     if (parser->tok == ':') {
2217         if (!OPTS_FLAG(LOOP_LABELS))
2218             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2219         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2220             parseerror(parser, "expected loop label");
2221             return false;
2222         }
2223         label = util_strdup(parser_tokval(parser));
2224         if (!parser_next(parser)) {
2225             mem_d(label);
2226             parseerror(parser, "expected 'while' condition in parenthesis");
2227             return false;
2228         }
2229     }
2230
2231     if (parser->tok != '(') {
2232         parseerror(parser, "expected 'while' condition in parenthesis");
2233         return false;
2234     }
2235
2236     vec_push(parser->breaks, label);
2237     vec_push(parser->continues, label);
2238
2239     rv = parse_while_go(parser, block, out);
2240     if (label)
2241         mem_d(label);
2242     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2243         parseerror(parser, "internal error: label stack corrupted");
2244         rv = false;
2245         ast_delete(*out);
2246         *out = NULL;
2247     }
2248     else {
2249         vec_pop(parser->breaks);
2250         vec_pop(parser->continues);
2251     }
2252     return rv;
2253 }
2254
2255 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2256 {
2257     ast_loop *aloop;
2258     ast_expression *cond, *ontrue;
2259
2260     bool ifnot = false;
2261
2262     lex_ctx ctx = parser_ctx(parser);
2263
2264     (void)block; /* not touching */
2265
2266     /* parse into the expression */
2267     if (!parser_next(parser)) {
2268         parseerror(parser, "expected 'while' condition after opening paren");
2269         return false;
2270     }
2271     /* parse the condition */
2272     cond = parse_expression_leave(parser, false, true, false);
2273     if (!cond)
2274         return false;
2275     /* closing paren */
2276     if (parser->tok != ')') {
2277         parseerror(parser, "expected closing paren after 'while' condition");
2278         ast_delete(cond);
2279         return false;
2280     }
2281     /* parse into the 'then' branch */
2282     if (!parser_next(parser)) {
2283         parseerror(parser, "expected while-loop body");
2284         ast_delete(cond);
2285         return false;
2286     }
2287     if (!parse_statement_or_block(parser, &ontrue)) {
2288         ast_delete(cond);
2289         return false;
2290     }
2291
2292     cond = process_condition(parser, cond, &ifnot);
2293     if (!cond) {
2294         ast_delete(ontrue);
2295         return false;
2296     }
2297     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2298     *out = (ast_expression*)aloop;
2299     return true;
2300 }
2301
2302 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2303 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2304 {
2305     bool rv;
2306     char *label = NULL;
2307
2308     /* skip the 'do' and get the body */
2309     if (!parser_next(parser)) {
2310         if (OPTS_FLAG(LOOP_LABELS))
2311             parseerror(parser, "expected loop label or body");
2312         else
2313             parseerror(parser, "expected loop body");
2314         return false;
2315     }
2316
2317     if (parser->tok == ':') {
2318         if (!OPTS_FLAG(LOOP_LABELS))
2319             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2320         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2321             parseerror(parser, "expected loop label");
2322             return false;
2323         }
2324         label = util_strdup(parser_tokval(parser));
2325         if (!parser_next(parser)) {
2326             mem_d(label);
2327             parseerror(parser, "expected loop body");
2328             return false;
2329         }
2330     }
2331
2332     vec_push(parser->breaks, label);
2333     vec_push(parser->continues, label);
2334
2335     rv = parse_dowhile_go(parser, block, out);
2336     if (label)
2337         mem_d(label);
2338     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2339         parseerror(parser, "internal error: label stack corrupted");
2340         rv = false;
2341         ast_delete(*out);
2342         *out = NULL;
2343     }
2344     else {
2345         vec_pop(parser->breaks);
2346         vec_pop(parser->continues);
2347     }
2348     return rv;
2349 }
2350
2351 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2352 {
2353     ast_loop *aloop;
2354     ast_expression *cond, *ontrue;
2355
2356     bool ifnot = false;
2357
2358     lex_ctx ctx = parser_ctx(parser);
2359
2360     (void)block; /* not touching */
2361
2362     if (!parse_statement_or_block(parser, &ontrue))
2363         return false;
2364
2365     /* expect the "while" */
2366     if (parser->tok != TOKEN_KEYWORD ||
2367         strcmp(parser_tokval(parser), "while"))
2368     {
2369         parseerror(parser, "expected 'while' and condition");
2370         ast_delete(ontrue);
2371         return false;
2372     }
2373
2374     /* skip the 'while' and check for opening paren */
2375     if (!parser_next(parser) || parser->tok != '(') {
2376         parseerror(parser, "expected 'while' condition in parenthesis");
2377         ast_delete(ontrue);
2378         return false;
2379     }
2380     /* parse into the expression */
2381     if (!parser_next(parser)) {
2382         parseerror(parser, "expected 'while' condition after opening paren");
2383         ast_delete(ontrue);
2384         return false;
2385     }
2386     /* parse the condition */
2387     cond = parse_expression_leave(parser, false, true, false);
2388     if (!cond)
2389         return false;
2390     /* closing paren */
2391     if (parser->tok != ')') {
2392         parseerror(parser, "expected closing paren after 'while' condition");
2393         ast_delete(ontrue);
2394         ast_delete(cond);
2395         return false;
2396     }
2397     /* parse on */
2398     if (!parser_next(parser) || parser->tok != ';') {
2399         parseerror(parser, "expected semicolon after condition");
2400         ast_delete(ontrue);
2401         ast_delete(cond);
2402         return false;
2403     }
2404
2405     if (!parser_next(parser)) {
2406         parseerror(parser, "parse error");
2407         ast_delete(ontrue);
2408         ast_delete(cond);
2409         return false;
2410     }
2411
2412     cond = process_condition(parser, cond, &ifnot);
2413     if (!cond) {
2414         ast_delete(ontrue);
2415         return false;
2416     }
2417     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2418     *out = (ast_expression*)aloop;
2419     return true;
2420 }
2421
2422 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2423 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2424 {
2425     bool rv;
2426     char *label = NULL;
2427
2428     /* skip the 'for' and check for opening paren */
2429     if (!parser_next(parser)) {
2430         if (OPTS_FLAG(LOOP_LABELS))
2431             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2432         else
2433             parseerror(parser, "expected 'for' expressions in parenthesis");
2434         return false;
2435     }
2436
2437     if (parser->tok == ':') {
2438         if (!OPTS_FLAG(LOOP_LABELS))
2439             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2440         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2441             parseerror(parser, "expected loop label");
2442             return false;
2443         }
2444         label = util_strdup(parser_tokval(parser));
2445         if (!parser_next(parser)) {
2446             mem_d(label);
2447             parseerror(parser, "expected 'for' expressions in parenthesis");
2448             return false;
2449         }
2450     }
2451
2452     if (parser->tok != '(') {
2453         parseerror(parser, "expected 'for' expressions in parenthesis");
2454         return false;
2455     }
2456
2457     vec_push(parser->breaks, label);
2458     vec_push(parser->continues, label);
2459
2460     rv = parse_for_go(parser, block, out);
2461     if (label)
2462         mem_d(label);
2463     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2464         parseerror(parser, "internal error: label stack corrupted");
2465         rv = false;
2466         ast_delete(*out);
2467         *out = NULL;
2468     }
2469     else {
2470         vec_pop(parser->breaks);
2471         vec_pop(parser->continues);
2472     }
2473     return rv;
2474 }
2475 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2476 {
2477     ast_loop       *aloop;
2478     ast_expression *initexpr, *cond, *increment, *ontrue;
2479     ast_value      *typevar;
2480
2481     bool retval = true;
2482     bool ifnot  = false;
2483
2484     lex_ctx ctx = parser_ctx(parser);
2485
2486     parser_enterblock(parser);
2487
2488     initexpr  = NULL;
2489     cond      = NULL;
2490     increment = NULL;
2491     ontrue    = NULL;
2492
2493     /* parse into the expression */
2494     if (!parser_next(parser)) {
2495         parseerror(parser, "expected 'for' initializer after opening paren");
2496         goto onerr;
2497     }
2498
2499     typevar = NULL;
2500     if (parser->tok == TOKEN_IDENT)
2501         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2502
2503     if (typevar || parser->tok == TOKEN_TYPENAME) {
2504 #if 0
2505         if (opts.standard != COMPILER_GMQCC) {
2506             if (parsewarning(parser, WARN_EXTENSIONS,
2507                              "current standard does not allow variable declarations in for-loop initializers"))
2508                 goto onerr;
2509         }
2510 #endif
2511         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2512             goto onerr;
2513     }
2514     else if (parser->tok != ';')
2515     {
2516         initexpr = parse_expression_leave(parser, false, false, false);
2517         if (!initexpr)
2518             goto onerr;
2519     }
2520
2521     /* move on to condition */
2522     if (parser->tok != ';') {
2523         parseerror(parser, "expected semicolon after for-loop initializer");
2524         goto onerr;
2525     }
2526     if (!parser_next(parser)) {
2527         parseerror(parser, "expected for-loop condition");
2528         goto onerr;
2529     }
2530
2531     /* parse the condition */
2532     if (parser->tok != ';') {
2533         cond = parse_expression_leave(parser, false, true, false);
2534         if (!cond)
2535             goto onerr;
2536     }
2537
2538     /* move on to incrementor */
2539     if (parser->tok != ';') {
2540         parseerror(parser, "expected semicolon after for-loop initializer");
2541         goto onerr;
2542     }
2543     if (!parser_next(parser)) {
2544         parseerror(parser, "expected for-loop condition");
2545         goto onerr;
2546     }
2547
2548     /* parse the incrementor */
2549     if (parser->tok != ')') {
2550         increment = parse_expression_leave(parser, false, false, false);
2551         if (!increment)
2552             goto onerr;
2553         if (!ast_side_effects(increment)) {
2554             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2555                 goto onerr;
2556         }
2557     }
2558
2559     /* closing paren */
2560     if (parser->tok != ')') {
2561         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2562         goto onerr;
2563     }
2564     /* parse into the 'then' branch */
2565     if (!parser_next(parser)) {
2566         parseerror(parser, "expected for-loop body");
2567         goto onerr;
2568     }
2569     if (!parse_statement_or_block(parser, &ontrue))
2570         goto onerr;
2571
2572     if (cond) {
2573         cond = process_condition(parser, cond, &ifnot);
2574         if (!cond)
2575             goto onerr;
2576     }
2577     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2578     *out = (ast_expression*)aloop;
2579
2580     if (!parser_leaveblock(parser))
2581         retval = false;
2582     return retval;
2583 onerr:
2584     if (initexpr)  ast_delete(initexpr);
2585     if (cond)      ast_delete(cond);
2586     if (increment) ast_delete(increment);
2587     (void)!parser_leaveblock(parser);
2588     return false;
2589 }
2590
2591 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2592 {
2593     ast_expression *exp = NULL;
2594     ast_return     *ret = NULL;
2595     ast_value      *expected = parser->function->vtype;
2596
2597     lex_ctx ctx = parser_ctx(parser);
2598
2599     (void)block; /* not touching */
2600
2601     if (!parser_next(parser)) {
2602         parseerror(parser, "expected return expression");
2603         return false;
2604     }
2605
2606     if (parser->tok != ';') {
2607         exp = parse_expression(parser, false, false);
2608         if (!exp)
2609             return false;
2610
2611         if (exp->expression.vtype != TYPE_NIL &&
2612             exp->expression.vtype != expected->expression.next->expression.vtype)
2613         {
2614             parseerror(parser, "return with invalid expression");
2615         }
2616
2617         ret = ast_return_new(ctx, exp);
2618         if (!ret) {
2619             ast_delete(exp);
2620             return false;
2621         }
2622     } else {
2623         if (!parser_next(parser))
2624             parseerror(parser, "parse error");
2625         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2626             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2627         }
2628         ret = ast_return_new(ctx, NULL);
2629     }
2630     *out = (ast_expression*)ret;
2631     return true;
2632 }
2633
2634 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2635 {
2636     size_t       i;
2637     unsigned int levels = 0;
2638     lex_ctx      ctx = parser_ctx(parser);
2639     const char **loops = (is_continue ? parser->continues : parser->breaks);
2640
2641     (void)block; /* not touching */
2642     if (!parser_next(parser)) {
2643         parseerror(parser, "expected semicolon or loop label");
2644         return false;
2645     }
2646
2647     if (!vec_size(loops)) {
2648         if (is_continue)
2649             parseerror(parser, "`continue` can only be used inside loops");
2650         else
2651             parseerror(parser, "`break` can only be used inside loops or switches");
2652     }
2653
2654     if (parser->tok == TOKEN_IDENT) {
2655         if (!OPTS_FLAG(LOOP_LABELS))
2656             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2657         i = vec_size(loops);
2658         while (i--) {
2659             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2660                 break;
2661             if (!i) {
2662                 parseerror(parser, "no such loop to %s: `%s`",
2663                            (is_continue ? "continue" : "break out of"),
2664                            parser_tokval(parser));
2665                 return false;
2666             }
2667             ++levels;
2668         }
2669         if (!parser_next(parser)) {
2670             parseerror(parser, "expected semicolon");
2671             return false;
2672         }
2673     }
2674
2675     if (parser->tok != ';') {
2676         parseerror(parser, "expected semicolon");
2677         return false;
2678     }
2679
2680     if (!parser_next(parser))
2681         parseerror(parser, "parse error");
2682
2683     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2684     return true;
2685 }
2686
2687 /* returns true when it was a variable qualifier, false otherwise!
2688  * on error, cvq is set to CV_WRONG
2689  */
2690 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2691 {
2692     bool had_const    = false;
2693     bool had_var      = false;
2694     bool had_noref    = false;
2695     bool had_attrib   = false;
2696     bool had_static   = false;
2697     uint32_t flags    = 0;
2698
2699     *cvq = CV_NONE;
2700     for (;;) {
2701         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2702             had_attrib = true;
2703             /* parse an attribute */
2704             if (!parser_next(parser)) {
2705                 parseerror(parser, "expected attribute after `[[`");
2706                 *cvq = CV_WRONG;
2707                 return false;
2708             }
2709             if (!strcmp(parser_tokval(parser), "noreturn")) {
2710                 flags |= AST_FLAG_NORETURN;
2711                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2712                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2713                     *cvq = CV_WRONG;
2714                     return false;
2715                 }
2716             }
2717             else if (!strcmp(parser_tokval(parser), "noref")) {
2718                 had_noref = true;
2719                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2720                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2721                     *cvq = CV_WRONG;
2722                     return false;
2723                 }
2724             }
2725             else if (!strcmp(parser_tokval(parser), "inline")) {
2726                 flags |= AST_FLAG_INLINE;
2727                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2728                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2729                     *cvq = CV_WRONG;
2730                     return false;
2731                 }
2732             }
2733
2734
2735             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2736                 flags   |= AST_FLAG_DEPRECATED;
2737                 *message = NULL;
2738                 
2739                 if (!parser_next(parser)) {
2740                     parseerror(parser, "parse error in attribute");
2741                     goto argerr;
2742                 }
2743
2744                 if (parser->tok == '(') {
2745                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2746                         parseerror(parser, "`deprecated` attribute missing parameter");
2747                         goto argerr;
2748                     }
2749
2750                     *message = util_strdup(parser_tokval(parser));
2751
2752                     if (!parser_next(parser)) {
2753                         parseerror(parser, "parse error in attribute");
2754                         goto argerr;
2755                     }
2756
2757                     if(parser->tok != ')') {
2758                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2759                         goto argerr;
2760                     }
2761
2762                     if (!parser_next(parser)) {
2763                         parseerror(parser, "parse error in attribute");
2764                         goto argerr;
2765                     }
2766                 }
2767                 /* no message */
2768                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2769                     parseerror(parser, "`deprecated` attribute expected `]]`");
2770
2771                     argerr: /* ugly */
2772                     if (*message) mem_d(*message);
2773                     *message = NULL;
2774                     *cvq     = CV_WRONG;
2775                     return false;
2776                 }
2777             }
2778             else
2779             {
2780                 /* Skip tokens until we hit a ]] */
2781                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2782                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2783                     if (!parser_next(parser)) {
2784                         parseerror(parser, "error inside attribute");
2785                         *cvq = CV_WRONG;
2786                         return false;
2787                     }
2788                 }
2789             }
2790         }
2791         else if (!strcmp(parser_tokval(parser), "static"))
2792             had_static = true;
2793         else if (!strcmp(parser_tokval(parser), "const"))
2794             had_const = true;
2795         else if (!strcmp(parser_tokval(parser), "var"))
2796             had_var = true;
2797         else if (with_local && !strcmp(parser_tokval(parser), "local"))
2798             had_var = true;
2799         else if (!strcmp(parser_tokval(parser), "noref"))
2800             had_noref = true;
2801         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2802             return false;
2803         }
2804         else
2805             break;
2806         if (!parser_next(parser))
2807             goto onerr;
2808     }
2809     if (had_const)
2810         *cvq = CV_CONST;
2811     else if (had_var)
2812         *cvq = CV_VAR;
2813     else
2814         *cvq = CV_NONE;
2815     *noref     = had_noref;
2816     *is_static = had_static;
2817     *_flags    = flags;
2818     return true;
2819 onerr:
2820     parseerror(parser, "parse error after variable qualifier");
2821     *cvq = CV_WRONG;
2822     return true;
2823 }
2824
2825 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2826 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2827 {
2828     bool rv;
2829     char *label = NULL;
2830
2831     /* skip the 'while' and get the body */
2832     if (!parser_next(parser)) {
2833         if (OPTS_FLAG(LOOP_LABELS))
2834             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2835         else
2836             parseerror(parser, "expected 'switch' operand in parenthesis");
2837         return false;
2838     }
2839
2840     if (parser->tok == ':') {
2841         if (!OPTS_FLAG(LOOP_LABELS))
2842             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2843         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2844             parseerror(parser, "expected loop label");
2845             return false;
2846         }
2847         label = util_strdup(parser_tokval(parser));
2848         if (!parser_next(parser)) {
2849             mem_d(label);
2850             parseerror(parser, "expected 'switch' operand in parenthesis");
2851             return false;
2852         }
2853     }
2854
2855     if (parser->tok != '(') {
2856         parseerror(parser, "expected 'switch' operand in parenthesis");
2857         return false;
2858     }
2859
2860     vec_push(parser->breaks, label);
2861
2862     rv = parse_switch_go(parser, block, out);
2863     if (label)
2864         mem_d(label);
2865     if (vec_last(parser->breaks) != label) {
2866         parseerror(parser, "internal error: label stack corrupted");
2867         rv = false;
2868         ast_delete(*out);
2869         *out = NULL;
2870     }
2871     else {
2872         vec_pop(parser->breaks);
2873     }
2874     return rv;
2875 }
2876
2877 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2878 {
2879     ast_expression *operand;
2880     ast_value      *opval;
2881     ast_value      *typevar;
2882     ast_switch     *switchnode;
2883     ast_switch_case swcase;
2884
2885     int  cvq;
2886     bool noref, is_static;
2887     uint32_t qflags = 0;
2888
2889     lex_ctx ctx = parser_ctx(parser);
2890
2891     (void)block; /* not touching */
2892     (void)opval;
2893
2894     /* parse into the expression */
2895     if (!parser_next(parser)) {
2896         parseerror(parser, "expected switch operand");
2897         return false;
2898     }
2899     /* parse the operand */
2900     operand = parse_expression_leave(parser, false, false, false);
2901     if (!operand)
2902         return false;
2903
2904     switchnode = ast_switch_new(ctx, operand);
2905
2906     /* closing paren */
2907     if (parser->tok != ')') {
2908         ast_delete(switchnode);
2909         parseerror(parser, "expected closing paren after 'switch' operand");
2910         return false;
2911     }
2912
2913     /* parse over the opening paren */
2914     if (!parser_next(parser) || parser->tok != '{') {
2915         ast_delete(switchnode);
2916         parseerror(parser, "expected list of cases");
2917         return false;
2918     }
2919
2920     if (!parser_next(parser)) {
2921         ast_delete(switchnode);
2922         parseerror(parser, "expected 'case' or 'default'");
2923         return false;
2924     }
2925
2926     /* new block; allow some variables to be declared here */
2927     parser_enterblock(parser);
2928     while (true) {
2929         typevar = NULL;
2930         if (parser->tok == TOKEN_IDENT)
2931             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2932         if (typevar || parser->tok == TOKEN_TYPENAME) {
2933             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2934                 ast_delete(switchnode);
2935                 return false;
2936             }
2937             continue;
2938         }
2939         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2940         {
2941             if (cvq == CV_WRONG) {
2942                 ast_delete(switchnode);
2943                 return false;
2944             }
2945             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2946                 ast_delete(switchnode);
2947                 return false;
2948             }
2949             continue;
2950         }
2951         break;
2952     }
2953
2954     /* case list! */
2955     while (parser->tok != '}') {
2956         ast_block *caseblock;
2957
2958         if (!strcmp(parser_tokval(parser), "case")) {
2959             if (!parser_next(parser)) {
2960                 ast_delete(switchnode);
2961                 parseerror(parser, "expected expression for case");
2962                 return false;
2963             }
2964             swcase.value = parse_expression_leave(parser, false, false, false);
2965             if (!swcase.value) {
2966                 ast_delete(switchnode);
2967                 parseerror(parser, "expected expression for case");
2968                 return false;
2969             }
2970             if (!OPTS_FLAG(RELAXED_SWITCH)) {
2971                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2972                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2973                     ast_unref(operand);
2974                     return false;
2975                 }
2976             }
2977         }
2978         else if (!strcmp(parser_tokval(parser), "default")) {
2979             swcase.value = NULL;
2980             if (!parser_next(parser)) {
2981                 ast_delete(switchnode);
2982                 parseerror(parser, "expected colon");
2983                 return false;
2984             }
2985         }
2986         else {
2987             ast_delete(switchnode);
2988             parseerror(parser, "expected 'case' or 'default'");
2989             return false;
2990         }
2991
2992         /* Now the colon and body */
2993         if (parser->tok != ':') {
2994             if (swcase.value) ast_unref(swcase.value);
2995             ast_delete(switchnode);
2996             parseerror(parser, "expected colon");
2997             return false;
2998         }
2999
3000         if (!parser_next(parser)) {
3001             if (swcase.value) ast_unref(swcase.value);
3002             ast_delete(switchnode);
3003             parseerror(parser, "expected statements or case");
3004             return false;
3005         }
3006         caseblock = ast_block_new(parser_ctx(parser));
3007         if (!caseblock) {
3008             if (swcase.value) ast_unref(swcase.value);
3009             ast_delete(switchnode);
3010             return false;
3011         }
3012         swcase.code = (ast_expression*)caseblock;
3013         vec_push(switchnode->cases, swcase);
3014         while (true) {
3015             ast_expression *expr;
3016             if (parser->tok == '}')
3017                 break;
3018             if (parser->tok == TOKEN_KEYWORD) {
3019                 if (!strcmp(parser_tokval(parser), "case") ||
3020                     !strcmp(parser_tokval(parser), "default"))
3021                 {
3022                     break;
3023                 }
3024             }
3025             if (!parse_statement(parser, caseblock, &expr, true)) {
3026                 ast_delete(switchnode);
3027                 return false;
3028             }
3029             if (!expr)
3030                 continue;
3031             if (!ast_block_add_expr(caseblock, expr)) {
3032                 ast_delete(switchnode);
3033                 return false;
3034             }
3035         }
3036     }
3037
3038     parser_leaveblock(parser);
3039
3040     /* closing paren */
3041     if (parser->tok != '}') {
3042         ast_delete(switchnode);
3043         parseerror(parser, "expected closing paren of case list");
3044         return false;
3045     }
3046     if (!parser_next(parser)) {
3047         ast_delete(switchnode);
3048         parseerror(parser, "parse error after switch");
3049         return false;
3050     }
3051     *out = (ast_expression*)switchnode;
3052     return true;
3053 }
3054
3055 /* parse computed goto sides */
3056 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3057     ast_expression *on_true;
3058     ast_expression *on_false;
3059     ast_expression *cond;
3060
3061     if (!*side)
3062         return NULL;
3063
3064     if (ast_istype(*side, ast_ternary)) {
3065         ast_ternary *tern = (ast_ternary*)*side;
3066         on_true  = parse_goto_computed(parser, &tern->on_true);
3067         on_false = parse_goto_computed(parser, &tern->on_false);
3068
3069         if (!on_true || !on_false) {
3070             parseerror(parser, "expected label or expression in ternary");
3071             if (on_true) ast_unref(on_true);
3072             if (on_false) ast_unref(on_false);
3073             return NULL;
3074         }
3075
3076         cond = tern->cond;
3077         tern->cond = NULL;
3078         ast_delete(tern);
3079         *side = NULL;
3080         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3081     } else if (ast_istype(*side, ast_label)) {
3082         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3083         ast_goto_set_label(gt, ((ast_label*)*side));
3084         *side = NULL;
3085         return (ast_expression*)gt;
3086     }
3087     return NULL;
3088 }
3089
3090 static bool parse_goto(parser_t *parser, ast_expression **out)
3091 {
3092     ast_goto       *gt = NULL;
3093     ast_expression *lbl;
3094
3095     if (!parser_next(parser))
3096         return false;
3097
3098     if (parser->tok != TOKEN_IDENT) {
3099         ast_expression *expression;
3100
3101         /* could be an expression i.e computed goto :-) */
3102         if (parser->tok != '(') {
3103             parseerror(parser, "expected label name after `goto`");
3104             return false;
3105         }
3106
3107         /* failed to parse expression for goto */
3108         if (!(expression = parse_expression(parser, false, true)) ||
3109             !(*out = parse_goto_computed(parser, &expression))) {
3110             parseerror(parser, "invalid goto expression");
3111             ast_unref(expression);
3112             return false;
3113         }
3114
3115         return true;
3116     }
3117
3118     /* not computed goto */
3119     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3120     lbl = parser_find_label(parser, gt->name);
3121     if (lbl) {
3122         if (!ast_istype(lbl, ast_label)) {
3123             parseerror(parser, "internal error: label is not an ast_label");
3124             ast_delete(gt);
3125             return false;
3126         }
3127         ast_goto_set_label(gt, (ast_label*)lbl);
3128     }
3129     else
3130         vec_push(parser->gotos, gt);
3131
3132     if (!parser_next(parser) || parser->tok != ';') {
3133         parseerror(parser, "semicolon expected after goto label");
3134         return false;
3135     }
3136     if (!parser_next(parser)) {
3137         parseerror(parser, "parse error after goto");
3138         return false;
3139     }
3140
3141     *out = (ast_expression*)gt;
3142     return true;
3143 }
3144
3145 static bool parse_skipwhite(parser_t *parser)
3146 {
3147     do {
3148         if (!parser_next(parser))
3149             return false;
3150     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3151     return parser->tok < TOKEN_ERROR;
3152 }
3153
3154 static bool parse_eol(parser_t *parser)
3155 {
3156     if (!parse_skipwhite(parser))
3157         return false;
3158     return parser->tok == TOKEN_EOL;
3159 }
3160
3161 static bool parse_pragma_do(parser_t *parser)
3162 {
3163     if (!parser_next(parser) ||
3164         parser->tok != TOKEN_IDENT ||
3165         strcmp(parser_tokval(parser), "pragma"))
3166     {
3167         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3168         return false;
3169     }
3170     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3171         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3172         return false;
3173     }
3174
3175     if (!strcmp(parser_tokval(parser), "noref")) {
3176         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3177             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3178             return false;
3179         }
3180         parser->noref = !!parser_token(parser)->constval.i;
3181         if (!parse_eol(parser)) {
3182             parseerror(parser, "parse error after `noref` pragma");
3183             return false;
3184         }
3185     }
3186     else
3187     {
3188         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3189         return false;
3190     }
3191
3192     return true;
3193 }
3194
3195 static bool parse_pragma(parser_t *parser)
3196 {
3197     bool rv;
3198     parser->lex->flags.preprocessing = true;
3199     parser->lex->flags.mergelines = true;
3200     rv = parse_pragma_do(parser);
3201     if (parser->tok != TOKEN_EOL) {
3202         parseerror(parser, "junk after pragma");
3203         rv = false;
3204     }
3205     parser->lex->flags.preprocessing = false;
3206     parser->lex->flags.mergelines = false;
3207     if (!parser_next(parser)) {
3208         parseerror(parser, "parse error after pragma");
3209         rv = false;
3210     }
3211     return rv;
3212 }
3213
3214 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3215 {
3216     bool       noref, is_static;
3217     int        cvq     = CV_NONE;
3218     uint32_t   qflags  = 0;
3219     ast_value *typevar = NULL;
3220     char      *vstring = NULL;
3221
3222     *out = NULL;
3223
3224     if (parser->tok == TOKEN_IDENT)
3225         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3226
3227     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3228     {
3229         /* local variable */
3230         if (!block) {
3231             parseerror(parser, "cannot declare a variable from here");
3232             return false;
3233         }
3234         if (opts.standard == COMPILER_QCC) {
3235             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3236                 return false;
3237         }
3238         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3239             return false;
3240         return true;
3241     }
3242     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3243     {
3244         if (cvq == CV_WRONG)
3245             return false;
3246         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3247     }
3248     else if (parser->tok == TOKEN_KEYWORD)
3249     {
3250         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3251         {
3252             char ty[1024];
3253             ast_value *tdef;
3254
3255             if (!parser_next(parser)) {
3256                 parseerror(parser, "parse error after __builtin_debug_printtype");
3257                 return false;
3258             }
3259
3260             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3261             {
3262                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3263                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3264                 if (!parser_next(parser)) {
3265                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3266                     return false;
3267                 }
3268             }
3269             else
3270             {
3271                 if (!parse_statement(parser, block, out, allow_cases))
3272                     return false;
3273                 if (!*out)
3274                     con_out("__builtin_debug_printtype: got no output node\n");
3275                 else
3276                 {
3277                     ast_type_to_string(*out, ty, sizeof(ty));
3278                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3279                 }
3280             }
3281             return true;
3282         }
3283         else if (!strcmp(parser_tokval(parser), "return"))
3284         {
3285             return parse_return(parser, block, out);
3286         }
3287         else if (!strcmp(parser_tokval(parser), "if"))
3288         {
3289             return parse_if(parser, block, out);
3290         }
3291         else if (!strcmp(parser_tokval(parser), "while"))
3292         {
3293             return parse_while(parser, block, out);
3294         }
3295         else if (!strcmp(parser_tokval(parser), "do"))
3296         {
3297             return parse_dowhile(parser, block, out);
3298         }
3299         else if (!strcmp(parser_tokval(parser), "for"))
3300         {
3301             if (opts.standard == COMPILER_QCC) {
3302                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3303                     return false;
3304             }
3305             return parse_for(parser, block, out);
3306         }
3307         else if (!strcmp(parser_tokval(parser), "break"))
3308         {
3309             return parse_break_continue(parser, block, out, false);
3310         }
3311         else if (!strcmp(parser_tokval(parser), "continue"))
3312         {
3313             return parse_break_continue(parser, block, out, true);
3314         }
3315         else if (!strcmp(parser_tokval(parser), "switch"))
3316         {
3317             return parse_switch(parser, block, out);
3318         }
3319         else if (!strcmp(parser_tokval(parser), "case") ||
3320                  !strcmp(parser_tokval(parser), "default"))
3321         {
3322             if (!allow_cases) {
3323                 parseerror(parser, "unexpected 'case' label");
3324                 return false;
3325             }
3326             return true;
3327         }
3328         else if (!strcmp(parser_tokval(parser), "goto"))
3329         {
3330             return parse_goto(parser, out);
3331         }
3332         else if (!strcmp(parser_tokval(parser), "typedef"))
3333         {
3334             if (!parser_next(parser)) {
3335                 parseerror(parser, "expected type definition after 'typedef'");
3336                 return false;
3337             }
3338             return parse_typedef(parser);
3339         }
3340         parseerror(parser, "Unexpected keyword");
3341         return false;
3342     }
3343     else if (parser->tok == '{')
3344     {
3345         ast_block *inner;
3346         inner = parse_block(parser);
3347         if (!inner)
3348             return false;
3349         *out = (ast_expression*)inner;
3350         return true;
3351     }
3352     else if (parser->tok == ':')
3353     {
3354         size_t i;
3355         ast_label *label;
3356         if (!parser_next(parser)) {
3357             parseerror(parser, "expected label name");
3358             return false;
3359         }
3360         if (parser->tok != TOKEN_IDENT) {
3361             parseerror(parser, "label must be an identifier");
3362             return false;
3363         }
3364         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3365         if (label) {
3366             if (!label->undefined) {
3367                 parseerror(parser, "label `%s` already defined", label->name);
3368                 return false;
3369             }
3370             label->undefined = false;
3371         }
3372         else {
3373             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3374             vec_push(parser->labels, label);
3375         }
3376         *out = (ast_expression*)label;
3377         if (!parser_next(parser)) {
3378             parseerror(parser, "parse error after label");
3379             return false;
3380         }
3381         for (i = 0; i < vec_size(parser->gotos); ++i) {
3382             if (!strcmp(parser->gotos[i]->name, label->name)) {
3383                 ast_goto_set_label(parser->gotos[i], label);
3384                 vec_remove(parser->gotos, i, 1);
3385                 --i;
3386             }
3387         }
3388         return true;
3389     }
3390     else if (parser->tok == ';')
3391     {
3392         if (!parser_next(parser)) {
3393             parseerror(parser, "parse error after empty statement");
3394             return false;
3395         }
3396         return true;
3397     }
3398     else
3399     {
3400         ast_expression *exp = parse_expression(parser, false, false);
3401         if (!exp)
3402             return false;
3403         *out = exp;
3404         if (!ast_side_effects(exp)) {
3405             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3406                 return false;
3407         }
3408         return true;
3409     }
3410 }
3411
3412 static bool parse_block_into(parser_t *parser, ast_block *block)
3413 {
3414     bool   retval = true;
3415
3416     parser_enterblock(parser);
3417
3418     if (!parser_next(parser)) { /* skip the '{' */
3419         parseerror(parser, "expected function body");
3420         goto cleanup;
3421     }
3422
3423     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3424     {
3425         ast_expression *expr = NULL;
3426         if (parser->tok == '}')
3427             break;
3428
3429         if (!parse_statement(parser, block, &expr, false)) {
3430             /* parseerror(parser, "parse error"); */
3431             block = NULL;
3432             goto cleanup;
3433         }
3434         if (!expr)
3435             continue;
3436         if (!ast_block_add_expr(block, expr)) {
3437             ast_delete(block);
3438             block = NULL;
3439             goto cleanup;
3440         }
3441     }
3442
3443     if (parser->tok != '}') {
3444         block = NULL;
3445     } else {
3446         (void)parser_next(parser);
3447     }
3448
3449 cleanup:
3450     if (!parser_leaveblock(parser))
3451         retval = false;
3452     return retval && !!block;
3453 }
3454
3455 static ast_block* parse_block(parser_t *parser)
3456 {
3457     ast_block *block;
3458     block = ast_block_new(parser_ctx(parser));
3459     if (!block)
3460         return NULL;
3461     if (!parse_block_into(parser, block)) {
3462         ast_block_delete(block);
3463         return NULL;
3464     }
3465     return block;
3466 }
3467
3468 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3469 {
3470     if (parser->tok == '{') {
3471         *out = (ast_expression*)parse_block(parser);
3472         return !!*out;
3473     }
3474     return parse_statement(parser, NULL, out, false);
3475 }
3476
3477 static bool create_vector_members(ast_value *var, ast_member **me)
3478 {
3479     size_t i;
3480     size_t len = strlen(var->name);
3481
3482     for (i = 0; i < 3; ++i) {
3483         char *name = (char*)mem_a(len+3);
3484         memcpy(name, var->name, len);
3485         name[len+0] = '_';
3486         name[len+1] = 'x'+i;
3487         name[len+2] = 0;
3488         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3489         mem_d(name);
3490         if (!me[i])
3491             break;
3492     }
3493     if (i == 3)
3494         return true;
3495
3496     /* unroll */
3497     do { ast_member_delete(me[--i]); } while(i);
3498     return false;
3499 }
3500
3501 static bool parse_function_body(parser_t *parser, ast_value *var)
3502 {
3503     ast_block      *block = NULL;
3504     ast_function   *func;
3505     ast_function   *old;
3506     size_t          parami;
3507
3508     ast_expression *framenum  = NULL;
3509     ast_expression *nextthink = NULL;
3510     /* None of the following have to be deleted */
3511     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3512     ast_expression *gbl_time = NULL, *gbl_self = NULL;
3513     bool            has_frame_think;
3514
3515     bool retval = true;
3516
3517     has_frame_think = false;
3518     old = parser->function;
3519
3520     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3521         parseerror(parser, "gotos/labels leaking");
3522         return false;
3523     }
3524
3525     if (var->expression.flags & AST_FLAG_VARIADIC) {
3526         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3527                          "variadic function with implementation will not be able to access additional parameters"))
3528         {
3529             return false;
3530         }
3531     }
3532
3533     if (parser->tok == '[') {
3534         /* got a frame definition: [ framenum, nextthink ]
3535          * this translates to:
3536          * self.frame = framenum;
3537          * self.nextthink = time + 0.1;
3538          * self.think = nextthink;
3539          */
3540         nextthink = NULL;
3541
3542         fld_think     = parser_find_field(parser, "think");
3543         fld_nextthink = parser_find_field(parser, "nextthink");
3544         fld_frame     = parser_find_field(parser, "frame");
3545         if (!fld_think || !fld_nextthink || !fld_frame) {
3546             parseerror(parser, "cannot use [frame,think] notation without the required fields");
3547             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3548             return false;
3549         }
3550         gbl_time      = parser_find_global(parser, "time");
3551         gbl_self      = parser_find_global(parser, "self");
3552         if (!gbl_time || !gbl_self) {
3553             parseerror(parser, "cannot use [frame,think] notation without the required globals");
3554             parseerror(parser, "please declare the following globals: `time`, `self`");
3555             return false;
3556         }
3557
3558         if (!parser_next(parser))
3559             return false;
3560
3561         framenum = parse_expression_leave(parser, true, false, false);
3562         if (!framenum) {
3563             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3564             return false;
3565         }
3566         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3567             ast_unref(framenum);
3568             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3569             return false;
3570         }
3571
3572         if (parser->tok != ',') {
3573             ast_unref(framenum);
3574             parseerror(parser, "expected comma after frame number in [frame,think] notation");
3575             parseerror(parser, "Got a %i\n", parser->tok);
3576             return false;
3577         }
3578
3579         if (!parser_next(parser)) {
3580             ast_unref(framenum);
3581             return false;
3582         }
3583
3584         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3585         {
3586             /* qc allows the use of not-yet-declared functions here
3587              * - this automatically creates a prototype */
3588             ast_value      *thinkfunc;
3589             ast_expression *functype = fld_think->expression.next;
3590
3591             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3592             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3593                 ast_unref(framenum);
3594                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3595                 return false;
3596             }
3597
3598             if (!parser_next(parser)) {
3599                 ast_unref(framenum);
3600                 ast_delete(thinkfunc);
3601                 return false;
3602             }
3603
3604             vec_push(parser->globals, (ast_expression*)thinkfunc);
3605             util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3606
3607             nextthink = (ast_expression*)thinkfunc;
3608
3609         } else {
3610             nextthink = parse_expression_leave(parser, true, false, false);
3611             if (!nextthink) {
3612                 ast_unref(framenum);
3613                 parseerror(parser, "expected a think-function in [frame,think] notation");
3614                 return false;
3615             }
3616         }
3617
3618         if (!ast_istype(nextthink, ast_value)) {
3619             parseerror(parser, "think-function in [frame,think] notation must be a constant");
3620             retval = false;
3621         }
3622
3623         if (retval && parser->tok != ']') {
3624             parseerror(parser, "expected closing `]` for [frame,think] notation");
3625             retval = false;
3626         }
3627
3628         if (retval && !parser_next(parser)) {
3629             retval = false;
3630         }
3631
3632         if (retval && parser->tok != '{') {
3633             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3634             retval = false;
3635         }
3636
3637         if (!retval) {
3638             ast_unref(nextthink);
3639             ast_unref(framenum);
3640             return false;
3641         }
3642
3643         has_frame_think = true;
3644     }
3645
3646     block = ast_block_new(parser_ctx(parser));
3647     if (!block) {
3648         parseerror(parser, "failed to allocate block");
3649         if (has_frame_think) {
3650             ast_unref(nextthink);
3651             ast_unref(framenum);
3652         }
3653         return false;
3654     }
3655
3656     if (has_frame_think) {
3657         lex_ctx ctx;
3658         ast_expression *self_frame;
3659         ast_expression *self_nextthink;
3660         ast_expression *self_think;
3661         ast_expression *time_plus_1;
3662         ast_store *store_frame;
3663         ast_store *store_nextthink;
3664         ast_store *store_think;
3665
3666         ctx = parser_ctx(parser);
3667         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3668         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3669         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3670
3671         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3672                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3673
3674         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3675             if (self_frame)     ast_delete(self_frame);
3676             if (self_nextthink) ast_delete(self_nextthink);
3677             if (self_think)     ast_delete(self_think);
3678             if (time_plus_1)    ast_delete(time_plus_1);
3679             retval = false;
3680         }
3681
3682         if (retval)
3683         {
3684             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
3685             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
3686             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
3687
3688             if (!store_frame) {
3689                 ast_delete(self_frame);
3690                 retval = false;
3691             }
3692             if (!store_nextthink) {
3693                 ast_delete(self_nextthink);
3694                 retval = false;
3695             }
3696             if (!store_think) {
3697                 ast_delete(self_think);
3698                 retval = false;
3699             }
3700             if (!retval) {
3701                 if (store_frame)     ast_delete(store_frame);
3702                 if (store_nextthink) ast_delete(store_nextthink);
3703                 if (store_think)     ast_delete(store_think);
3704                 retval = false;
3705             }
3706             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3707                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3708                 !ast_block_add_expr(block, (ast_expression*)store_think))
3709             {
3710                 retval = false;
3711             }
3712         }
3713
3714         if (!retval) {
3715             parseerror(parser, "failed to generate code for [frame,think]");
3716             ast_unref(nextthink);
3717             ast_unref(framenum);
3718             ast_delete(block);
3719             return false;
3720         }
3721     }
3722
3723     parser_enterblock(parser);
3724
3725     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3726         size_t     e;
3727         ast_value *param = var->expression.params[parami];
3728         ast_member *me[3];
3729
3730         if (param->expression.vtype != TYPE_VECTOR &&
3731             (param->expression.vtype != TYPE_FIELD ||
3732              param->expression.next->expression.vtype != TYPE_VECTOR))
3733         {
3734             continue;
3735         }
3736
3737         if (!create_vector_members(param, me)) {
3738             ast_block_delete(block);
3739             return false;
3740         }
3741
3742         for (e = 0; e < 3; ++e) {
3743             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3744             ast_block_collect(block, (ast_expression*)me[e]);
3745         }
3746     }
3747
3748     func = ast_function_new(ast_ctx(var), var->name, var);
3749     if (!func) {
3750         parseerror(parser, "failed to allocate function for `%s`", var->name);
3751         ast_block_delete(block);
3752         goto enderr;
3753     }
3754     vec_push(parser->functions, func);
3755
3756     parser->function = func;
3757     if (!parse_block_into(parser, block)) {
3758         ast_block_delete(block);
3759         goto enderrfn;
3760     }
3761
3762     vec_push(func->blocks, block);
3763
3764     parser->function = old;
3765     if (!parser_leaveblock(parser))
3766         retval = false;
3767     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3768         parseerror(parser, "internal error: local scopes left");
3769         retval = false;
3770     }
3771
3772     if (parser->tok == ';')
3773         return parser_next(parser);
3774     else if (opts.standard == COMPILER_QCC)
3775         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3776     return retval;
3777
3778 enderrfn:
3779     vec_pop(parser->functions);
3780     ast_function_delete(func);
3781     var->constval.vfunc = NULL;
3782
3783 enderr:
3784     (void)!parser_leaveblock(parser);
3785     parser->function = old;
3786     return false;
3787 }
3788
3789 static ast_expression *array_accessor_split(
3790     parser_t  *parser,
3791     ast_value *array,
3792     ast_value *index,
3793     size_t     middle,
3794     ast_expression *left,
3795     ast_expression *right
3796     )
3797 {
3798     ast_ifthen *ifthen;
3799     ast_binary *cmp;
3800
3801     lex_ctx ctx = ast_ctx(array);
3802
3803     if (!left || !right) {
3804         if (left)  ast_delete(left);
3805         if (right) ast_delete(right);
3806         return NULL;
3807     }
3808
3809     cmp = ast_binary_new(ctx, INSTR_LT,
3810                          (ast_expression*)index,
3811                          (ast_expression*)parser_const_float(parser, middle));
3812     if (!cmp) {
3813         ast_delete(left);
3814         ast_delete(right);
3815         parseerror(parser, "internal error: failed to create comparison for array setter");
3816         return NULL;
3817     }
3818
3819     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3820     if (!ifthen) {
3821         ast_delete(cmp); /* will delete left and right */
3822         parseerror(parser, "internal error: failed to create conditional jump for array setter");
3823         return NULL;
3824     }
3825
3826     return (ast_expression*)ifthen;
3827 }
3828
3829 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3830 {
3831     lex_ctx ctx = ast_ctx(array);
3832
3833     if (from+1 == afterend) {
3834         /* set this value */
3835         ast_block       *block;
3836         ast_return      *ret;
3837         ast_array_index *subscript;
3838         ast_store       *st;
3839         int assignop = type_store_instr[value->expression.vtype];
3840
3841         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3842             assignop = INSTR_STORE_V;
3843
3844         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3845         if (!subscript)
3846             return NULL;
3847
3848         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3849         if (!st) {
3850             ast_delete(subscript);
3851             return NULL;
3852         }
3853
3854         block = ast_block_new(ctx);
3855         if (!block) {
3856             ast_delete(st);
3857             return NULL;
3858         }
3859
3860         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3861             ast_delete(block);
3862             return NULL;
3863         }
3864
3865         ret = ast_return_new(ctx, NULL);
3866         if (!ret) {
3867             ast_delete(block);
3868             return NULL;
3869         }
3870
3871         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3872             ast_delete(block);
3873             return NULL;
3874         }
3875
3876         return (ast_expression*)block;
3877     } else {
3878         ast_expression *left, *right;
3879         size_t diff = afterend - from;
3880         size_t middle = from + diff/2;
3881         left  = array_setter_node(parser, array, index, value, from, middle);
3882         right = array_setter_node(parser, array, index, value, middle, afterend);
3883         return array_accessor_split(parser, array, index, middle, left, right);
3884     }
3885 }
3886
3887 static ast_expression *array_field_setter_node(
3888     parser_t  *parser,
3889     ast_value *array,
3890     ast_value *entity,
3891     ast_value *index,
3892     ast_value *value,
3893     size_t     from,
3894     size_t     afterend)
3895 {
3896     lex_ctx ctx = ast_ctx(array);
3897
3898     if (from+1 == afterend) {
3899         /* set this value */
3900         ast_block       *block;
3901         ast_return      *ret;
3902         ast_entfield    *entfield;
3903         ast_array_index *subscript;
3904         ast_store       *st;
3905         int assignop = type_storep_instr[value->expression.vtype];
3906
3907         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3908             assignop = INSTR_STOREP_V;
3909
3910         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3911         if (!subscript)
3912             return NULL;
3913
3914         entfield = ast_entfield_new_force(ctx,
3915                                           (ast_expression*)entity,
3916                                           (ast_expression*)subscript,
3917                                           (ast_expression*)subscript);
3918         if (!entfield) {
3919             ast_delete(subscript);
3920             return NULL;
3921         }
3922
3923         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3924         if (!st) {
3925             ast_delete(entfield);
3926             return NULL;
3927         }
3928
3929         block = ast_block_new(ctx);
3930         if (!block) {
3931             ast_delete(st);
3932             return NULL;
3933         }
3934
3935         if (!ast_block_add_expr(block, (ast_expression*)st)) {
3936             ast_delete(block);
3937             return NULL;
3938         }
3939
3940         ret = ast_return_new(ctx, NULL);
3941         if (!ret) {
3942             ast_delete(block);
3943             return NULL;
3944         }
3945
3946         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3947             ast_delete(block);
3948             return NULL;
3949         }
3950
3951         return (ast_expression*)block;
3952     } else {
3953         ast_expression *left, *right;
3954         size_t diff = afterend - from;
3955         size_t middle = from + diff/2;
3956         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
3957         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3958         return array_accessor_split(parser, array, index, middle, left, right);
3959     }
3960 }
3961
3962 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3963 {
3964     lex_ctx ctx = ast_ctx(array);
3965
3966     if (from+1 == afterend) {
3967         ast_return      *ret;
3968         ast_array_index *subscript;
3969
3970         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3971         if (!subscript)
3972             return NULL;
3973
3974         ret = ast_return_new(ctx, (ast_expression*)subscript);
3975         if (!ret) {
3976             ast_delete(subscript);
3977             return NULL;
3978         }
3979
3980         return (ast_expression*)ret;
3981     } else {
3982         ast_expression *left, *right;
3983         size_t diff = afterend - from;
3984         size_t middle = from + diff/2;
3985         left  = array_getter_node(parser, array, index, from, middle);
3986         right = array_getter_node(parser, array, index, middle, afterend);
3987         return array_accessor_split(parser, array, index, middle, left, right);
3988     }
3989 }
3990
3991 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3992 {
3993     ast_function   *func = NULL;
3994     ast_value      *fval = NULL;
3995     ast_block      *body = NULL;
3996
3997     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3998     if (!fval) {
3999         parseerror(parser, "failed to create accessor function value");
4000         return false;
4001     }
4002
4003     func = ast_function_new(ast_ctx(array), funcname, fval);
4004     if (!func) {
4005         ast_delete(fval);
4006         parseerror(parser, "failed to create accessor function node");
4007         return false;
4008     }
4009
4010     body = ast_block_new(ast_ctx(array));
4011     if (!body) {
4012         parseerror(parser, "failed to create block for array accessor");
4013         ast_delete(fval);
4014         ast_delete(func);
4015         return false;
4016     }
4017
4018     vec_push(func->blocks, body);
4019     *out = fval;
4020
4021     vec_push(parser->accessors, fval);
4022
4023     return true;
4024 }
4025
4026 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4027 {
4028     ast_expression *root = NULL;
4029     ast_value      *index = NULL;
4030     ast_value      *value = NULL;
4031     ast_function   *func;
4032     ast_value      *fval;
4033
4034     if (!ast_istype(array->expression.next, ast_value)) {
4035         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4036         return false;
4037     }
4038
4039     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4040         return false;
4041     func = fval->constval.vfunc;
4042     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4043
4044     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4045     value = ast_value_copy((ast_value*)array->expression.next);
4046
4047     if (!index || !value) {
4048         parseerror(parser, "failed to create locals for array accessor");
4049         goto cleanup;
4050     }
4051     (void)!ast_value_set_name(value, "value"); /* not important */
4052     vec_push(fval->expression.params, index);
4053     vec_push(fval->expression.params, value);
4054
4055     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
4056     if (!root) {
4057         parseerror(parser, "failed to build accessor search tree");
4058         goto cleanup;
4059     }
4060
4061     array->setter = fval;
4062     return ast_block_add_expr(func->blocks[0], root);
4063 cleanup:
4064     if (index) ast_delete(index);
4065     if (value) ast_delete(value);
4066     if (root)  ast_delete(root);
4067     ast_delete(func);
4068     ast_delete(fval);
4069     return false;
4070 }
4071
4072 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4073 {
4074     ast_expression *root = NULL;
4075     ast_value      *entity = NULL;
4076     ast_value      *index = NULL;
4077     ast_value      *value = NULL;
4078     ast_function   *func;
4079     ast_value      *fval;
4080
4081     if (!ast_istype(array->expression.next, ast_value)) {
4082         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4083         return false;
4084     }
4085
4086     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4087         return false;
4088     func = fval->constval.vfunc;
4089     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4090
4091     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4092     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4093     value  = ast_value_copy((ast_value*)array->expression.next);
4094     if (!entity || !index || !value) {
4095         parseerror(parser, "failed to create locals for array accessor");
4096         goto cleanup;
4097     }
4098     (void)!ast_value_set_name(value, "value"); /* not important */
4099     vec_push(fval->expression.params, entity);
4100     vec_push(fval->expression.params, index);
4101     vec_push(fval->expression.params, value);
4102
4103     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4104     if (!root) {
4105         parseerror(parser, "failed to build accessor search tree");
4106         goto cleanup;
4107     }
4108
4109     array->setter = fval;
4110     return ast_block_add_expr(func->blocks[0], root);
4111 cleanup:
4112     if (entity) ast_delete(entity);
4113     if (index)  ast_delete(index);
4114     if (value)  ast_delete(value);
4115     if (root)   ast_delete(root);
4116     ast_delete(func);
4117     ast_delete(fval);
4118     return false;
4119 }
4120
4121 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4122 {
4123     ast_expression *root = NULL;
4124     ast_value      *index = NULL;
4125     ast_value      *fval;
4126     ast_function   *func;
4127
4128     /* NOTE: checking array->expression.next rather than elemtype since
4129      * for fields elemtype is a temporary fieldtype.
4130      */
4131     if (!ast_istype(array->expression.next, ast_value)) {
4132         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4133         return false;
4134     }
4135
4136     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4137         return false;
4138     func = fval->constval.vfunc;
4139     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4140
4141     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4142
4143     if (!index) {
4144         parseerror(parser, "failed to create locals for array accessor");
4145         goto cleanup;
4146     }
4147     vec_push(fval->expression.params, index);
4148
4149     root = array_getter_node(parser, array, index, 0, array->expression.count);
4150     if (!root) {
4151         parseerror(parser, "failed to build accessor search tree");
4152         goto cleanup;
4153     }
4154
4155     array->getter = fval;
4156     return ast_block_add_expr(func->blocks[0], root);
4157 cleanup:
4158     if (index) ast_delete(index);
4159     if (root)  ast_delete(root);
4160     ast_delete(func);
4161     ast_delete(fval);
4162     return false;
4163 }
4164
4165 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4166 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4167 {
4168     lex_ctx     ctx;
4169     size_t      i;
4170     ast_value **params;
4171     ast_value  *param;
4172     ast_value  *fval;
4173     bool        first = true;
4174     bool        variadic = false;
4175
4176     ctx = parser_ctx(parser);
4177
4178     /* for the sake of less code we parse-in in this function */
4179     if (!parser_next(parser)) {
4180         parseerror(parser, "expected parameter list");
4181         return NULL;
4182     }
4183
4184     params = NULL;
4185
4186     /* parse variables until we hit a closing paren */
4187     while (parser->tok != ')') {
4188         if (!first) {
4189             /* there must be commas between them */
4190             if (parser->tok != ',') {
4191                 parseerror(parser, "expected comma or end of parameter list");
4192                 goto on_error;
4193             }
4194             if (!parser_next(parser)) {
4195                 parseerror(parser, "expected parameter");
4196                 goto on_error;
4197             }
4198         }
4199         first = false;
4200
4201         if (parser->tok == TOKEN_DOTS) {
4202             /* '...' indicates a varargs function */
4203             variadic = true;
4204             if (!parser_next(parser)) {
4205                 parseerror(parser, "expected parameter");
4206                 return NULL;
4207             }
4208             if (parser->tok != ')') {
4209                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4210                 goto on_error;
4211             }
4212         }
4213         else
4214         {
4215             /* for anything else just parse a typename */
4216             param = parse_typename(parser, NULL, NULL);
4217             if (!param)
4218                 goto on_error;
4219             vec_push(params, param);
4220             if (param->expression.vtype >= TYPE_VARIANT) {
4221                 char tname[1024]; /* typename is reserved in C++ */
4222                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4223                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4224                 goto on_error;
4225             }
4226         }
4227     }
4228
4229     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4230         vec_free(params);
4231
4232     /* sanity check */
4233     if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4234         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4235
4236     /* parse-out */
4237     if (!parser_next(parser)) {
4238         parseerror(parser, "parse error after typename");
4239         goto on_error;
4240     }
4241
4242     /* now turn 'var' into a function type */
4243     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4244     fval->expression.next     = (ast_expression*)var;
4245     if (variadic)
4246         fval->expression.flags |= AST_FLAG_VARIADIC;
4247     var = fval;
4248
4249     var->expression.params = params;
4250     params = NULL;
4251
4252     return var;
4253
4254 on_error:
4255     ast_delete(var);
4256     for (i = 0; i < vec_size(params); ++i)
4257         ast_delete(params[i]);
4258     vec_free(params);
4259     return NULL;
4260 }
4261
4262 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4263 {
4264     ast_expression *cexp;
4265     ast_value      *cval, *tmp;
4266     lex_ctx ctx;
4267
4268     ctx = parser_ctx(parser);
4269
4270     if (!parser_next(parser)) {
4271         ast_delete(var);
4272         parseerror(parser, "expected array-size");
4273         return NULL;
4274     }
4275
4276     cexp = parse_expression_leave(parser, true, false, false);
4277
4278     if (!cexp || !ast_istype(cexp, ast_value)) {
4279         if (cexp)
4280             ast_unref(cexp);
4281         ast_delete(var);
4282         parseerror(parser, "expected array-size as constant positive integer");
4283         return NULL;
4284     }
4285     cval = (ast_value*)cexp;
4286
4287     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4288     tmp->expression.next = (ast_expression*)var;
4289     var = tmp;
4290
4291     if (cval->expression.vtype == TYPE_INTEGER)
4292         tmp->expression.count = cval->constval.vint;
4293     else if (cval->expression.vtype == TYPE_FLOAT)
4294         tmp->expression.count = cval->constval.vfloat;
4295     else {
4296         ast_unref(cexp);
4297         ast_delete(var);
4298         parseerror(parser, "array-size must be a positive integer constant");
4299         return NULL;
4300     }
4301     ast_unref(cexp);
4302
4303     if (parser->tok != ']') {
4304         ast_delete(var);
4305         parseerror(parser, "expected ']' after array-size");
4306         return NULL;
4307     }
4308     if (!parser_next(parser)) {
4309         ast_delete(var);
4310         parseerror(parser, "error after parsing array size");
4311         return NULL;
4312     }
4313     return var;
4314 }
4315
4316 /* Parse a complete typename.
4317  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4318  * but when parsing variables separated by comma
4319  * 'storebase' should point to where the base-type should be kept.
4320  * The base type makes up every bit of type information which comes *before* the
4321  * variable name.
4322  *
4323  * The following will be parsed in its entirety:
4324  *     void() foo()
4325  * The 'basetype' in this case is 'void()'
4326  * and if there's a comma after it, say:
4327  *     void() foo(), bar
4328  * then the type-information 'void()' can be stored in 'storebase'
4329  */
4330 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4331 {
4332     ast_value *var, *tmp;
4333     lex_ctx    ctx;
4334
4335     const char *name = NULL;
4336     bool        isfield  = false;
4337     bool        wasarray = false;
4338     size_t      morefields = 0;
4339
4340     ctx = parser_ctx(parser);
4341
4342     /* types may start with a dot */
4343     if (parser->tok == '.') {
4344         isfield = true;
4345         /* if we parsed a dot we need a typename now */
4346         if (!parser_next(parser)) {
4347             parseerror(parser, "expected typename for field definition");
4348             return NULL;
4349         }
4350
4351         /* Further dots are handled seperately because they won't be part of the
4352          * basetype
4353          */
4354         while (parser->tok == '.') {
4355             ++morefields;
4356             if (!parser_next(parser)) {
4357                 parseerror(parser, "expected typename for field definition");
4358                 return NULL;
4359             }
4360         }
4361     }
4362     if (parser->tok == TOKEN_IDENT)
4363         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4364     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4365         parseerror(parser, "expected typename");
4366         return NULL;
4367     }
4368
4369     /* generate the basic type value */
4370     if (cached_typedef) {
4371         var = ast_value_copy(cached_typedef);
4372         ast_value_set_name(var, "<type(from_def)>");
4373     } else
4374         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4375
4376     for (; morefields; --morefields) {
4377         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4378         tmp->expression.next = (ast_expression*)var;
4379         var = tmp;
4380     }
4381
4382     /* do not yet turn into a field - remember:
4383      * .void() foo; is a field too
4384      * .void()() foo; is a function
4385      */
4386
4387     /* parse on */
4388     if (!parser_next(parser)) {
4389         ast_delete(var);
4390         parseerror(parser, "parse error after typename");
4391         return NULL;
4392     }
4393
4394     /* an opening paren now starts the parameter-list of a function
4395      * this is where original-QC has parameter lists.
4396      * We allow a single parameter list here.
4397      * Much like fteqcc we don't allow `float()() x`
4398      */
4399     if (parser->tok == '(') {
4400         var = parse_parameter_list(parser, var);
4401         if (!var)
4402             return NULL;
4403     }
4404
4405     /* store the base if requested */
4406     if (storebase) {
4407         *storebase = ast_value_copy(var);
4408         if (isfield) {
4409             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4410             tmp->expression.next = (ast_expression*)*storebase;
4411             *storebase = tmp;
4412         }
4413     }
4414
4415     /* there may be a name now */
4416     if (parser->tok == TOKEN_IDENT) {
4417         name = util_strdup(parser_tokval(parser));
4418         /* parse on */
4419         if (!parser_next(parser)) {
4420             ast_delete(var);
4421             parseerror(parser, "error after variable or field declaration");
4422             return NULL;
4423         }
4424     }
4425
4426     /* now this may be an array */
4427     if (parser->tok == '[') {
4428         wasarray = true;
4429         var = parse_arraysize(parser, var);
4430         if (!var)
4431             return NULL;
4432     }
4433
4434     /* This is the point where we can turn it into a field */
4435     if (isfield) {
4436         /* turn it into a field if desired */
4437         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4438         tmp->expression.next = (ast_expression*)var;
4439         var = tmp;
4440     }
4441
4442     /* now there may be function parens again */
4443     if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4444         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4445     if (parser->tok == '(' && wasarray)
4446         parseerror(parser, "arrays as part of a return type is not supported");
4447     while (parser->tok == '(') {
4448         var = parse_parameter_list(parser, var);
4449         if (!var) {
4450             if (name)
4451                 mem_d((void*)name);
4452             ast_delete(var);
4453             return NULL;
4454         }
4455     }
4456
4457     /* finally name it */
4458     if (name) {
4459         if (!ast_value_set_name(var, name)) {
4460             ast_delete(var);
4461             parseerror(parser, "internal error: failed to set name");
4462             return NULL;
4463         }
4464         /* free the name, ast_value_set_name duplicates */
4465         mem_d((void*)name);
4466     }
4467
4468     return var;
4469 }
4470
4471 static bool parse_typedef(parser_t *parser)
4472 {
4473     ast_value      *typevar, *oldtype;
4474     ast_expression *old;
4475
4476     typevar = parse_typename(parser, NULL, NULL);
4477
4478     if (!typevar)
4479         return false;
4480
4481     if ( (old = parser_find_var(parser, typevar->name)) ) {
4482         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4483                    " -> `%s` has been declared here: %s:%i",
4484                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4485         ast_delete(typevar);
4486         return false;
4487     }
4488
4489     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4490         parseerror(parser, "type `%s` has already been declared here: %s:%i",
4491                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4492         ast_delete(typevar);
4493         return false;
4494     }
4495
4496     vec_push(parser->_typedefs, typevar);
4497     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4498
4499     if (parser->tok != ';') {
4500         parseerror(parser, "expected semicolon after typedef");
4501         return false;
4502     }
4503     if (!parser_next(parser)) {
4504         parseerror(parser, "parse error after typedef");
4505         return false;
4506     }
4507
4508     return true;
4509 }
4510
4511 static const char *cvq_to_str(int cvq) {
4512     switch (cvq) {
4513         case CV_NONE:  return "none";
4514         case CV_VAR:   return "`var`";
4515         case CV_CONST: return "`const`";
4516         default:       return "<INVALID>";
4517     }
4518 }
4519
4520 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4521 {
4522     bool av, ao;
4523     if (proto->cvq != var->cvq) {
4524         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4525               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4526               parser->tok == '='))
4527         {
4528             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4529                                  "`%s` declared with different qualifiers: %s\n"
4530                                  " -> previous declaration here: %s:%i uses %s",
4531                                  var->name, cvq_to_str(var->cvq),
4532                                  ast_ctx(proto).file, ast_ctx(proto).line,
4533                                  cvq_to_str(proto->cvq));
4534         }
4535     }
4536     av = (var  ->expression.flags & AST_FLAG_NORETURN);
4537     ao = (proto->expression.flags & AST_FLAG_NORETURN);
4538     if (!av != !ao) {
4539         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4540                              "`%s` declared with different attributes%s\n"
4541                              " -> previous declaration here: %s:%i",
4542                              var->name, (av ? ": noreturn" : ""),
4543                              ast_ctx(proto).file, ast_ctx(proto).line,
4544                              (ao ? ": noreturn" : ""));
4545     }
4546     return true;
4547 }
4548
4549 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)
4550 {
4551     ast_value *var;
4552     ast_value *proto;
4553     ast_expression *old;
4554     bool       was_end;
4555     size_t     i;
4556
4557     ast_value *basetype = NULL;
4558     bool      retval    = true;
4559     bool      isparam   = false;
4560     bool      isvector  = false;
4561     bool      cleanvar  = true;
4562     bool      wasarray  = false;
4563
4564     ast_member *me[3];
4565
4566     if (!localblock && is_static)
4567         parseerror(parser, "`static` qualifier is not supported in global scope");
4568
4569     /* get the first complete variable */
4570     var = parse_typename(parser, &basetype, cached_typedef);
4571     if (!var) {
4572         if (basetype)
4573             ast_delete(basetype);
4574         return false;
4575     }
4576
4577     while (true) {
4578         proto = NULL;
4579         wasarray = false;
4580
4581         /* Part 0: finish the type */
4582         if (parser->tok == '(') {
4583             if (opts.standard == COMPILER_QCC)
4584                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4585             var = parse_parameter_list(parser, var);
4586             if (!var) {
4587                 retval = false;
4588                 goto cleanup;
4589             }
4590         }
4591         /* we only allow 1-dimensional arrays */
4592         if (parser->tok == '[') {
4593             wasarray = true;
4594             var = parse_arraysize(parser, var);
4595             if (!var) {
4596                 retval = false;
4597                 goto cleanup;
4598             }
4599         }
4600         if (parser->tok == '(' && wasarray) {
4601             parseerror(parser, "arrays as part of a return type is not supported");
4602             /* we'll still parse the type completely for now */
4603         }
4604         /* for functions returning functions */
4605         while (parser->tok == '(') {
4606             if (opts.standard == COMPILER_QCC)
4607                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4608             var = parse_parameter_list(parser, var);
4609             if (!var) {
4610                 retval = false;
4611                 goto cleanup;
4612             }
4613         }
4614
4615         var->cvq = qualifier;
4616         var->expression.flags |= qflags;
4617         if (var->expression.flags & AST_FLAG_DEPRECATED)
4618             var->desc = vstring;
4619
4620         /* Part 1:
4621          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4622          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4623          * is then filled with the previous definition and the parameter-names replaced.
4624          */
4625         if (!strcmp(var->name, "nil")) {
4626             if (OPTS_FLAG(UNTYPED_NIL)) {
4627                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4628                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4629             } else
4630                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4631         }
4632         if (!localblock) {
4633             /* Deal with end_sys_ vars */
4634             was_end = false;
4635             if (!strcmp(var->name, "end_sys_globals")) {
4636                 var->uses++;
4637                 parser->crc_globals = vec_size(parser->globals);
4638                 was_end = true;
4639             }
4640             else if (!strcmp(var->name, "end_sys_fields")) {
4641                 var->uses++;
4642                 parser->crc_fields = vec_size(parser->fields);
4643                 was_end = true;
4644             }
4645             if (was_end && var->expression.vtype == TYPE_FIELD) {
4646                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4647                                  "global '%s' hint should not be a field",
4648                                  parser_tokval(parser)))
4649                 {
4650                     retval = false;
4651                     goto cleanup;
4652                 }
4653             }
4654
4655             if (!nofields && var->expression.vtype == TYPE_FIELD)
4656             {
4657                 /* deal with field declarations */
4658                 old = parser_find_field(parser, var->name);
4659                 if (old) {
4660                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4661                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4662                     {
4663                         retval = false;
4664                         goto cleanup;
4665                     }
4666                     ast_delete(var);
4667                     var = NULL;
4668                     goto skipvar;
4669                     /*
4670                     parseerror(parser, "field `%s` already declared here: %s:%i",
4671                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4672                     retval = false;
4673                     goto cleanup;
4674                     */
4675                 }
4676                 if (opts.standard == COMPILER_QCC &&
4677                     (old = parser_find_global(parser, var->name)))
4678                 {
4679                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4680                     parseerror(parser, "field `%s` already declared here: %s:%i",
4681                                var->name, ast_ctx(old).file, ast_ctx(old).line);
4682                     retval = false;
4683                     goto cleanup;
4684                 }
4685             }
4686             else
4687             {
4688                 /* deal with other globals */
4689                 old = parser_find_global(parser, var->name);
4690                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4691                 {
4692                     /* This is a function which had a prototype */
4693                     if (!ast_istype(old, ast_value)) {
4694                         parseerror(parser, "internal error: prototype is not an ast_value");
4695                         retval = false;
4696                         goto cleanup;
4697                     }
4698                     proto = (ast_value*)old;
4699                     proto->desc = var->desc;
4700                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4701                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4702                                    proto->name,
4703                                    ast_ctx(proto).file, ast_ctx(proto).line);
4704                         retval = false;
4705                         goto cleanup;
4706                     }
4707                     /* we need the new parameter-names */
4708                     for (i = 0; i < vec_size(proto->expression.params); ++i)
4709                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4710                     if (!parser_check_qualifiers(parser, var, proto)) {
4711                         retval = false;
4712                         if (proto->desc) 
4713                             mem_d(proto->desc);
4714                         proto = NULL;
4715                         goto cleanup;
4716                     }
4717                     proto->expression.flags |= var->expression.flags;
4718                     ast_delete(var);
4719                     var = proto;
4720                 }
4721                 else
4722                 {
4723                     /* other globals */
4724                     if (old) {
4725                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4726                                          "global `%s` already declared here: %s:%i",
4727                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
4728                         {
4729                             retval = false;
4730                             goto cleanup;
4731                         }
4732                         proto = (ast_value*)old;
4733                         if (!ast_istype(old, ast_value)) {
4734                             parseerror(parser, "internal error: not an ast_value");
4735                             retval = false;
4736                             proto = NULL;
4737                             goto cleanup;
4738                         }
4739                         if (!parser_check_qualifiers(parser, var, proto)) {
4740                             retval = false;
4741                             proto = NULL;
4742                             goto cleanup;
4743                         }
4744                         proto->expression.flags |= var->expression.flags;
4745                         ast_delete(var);
4746                         var = proto;
4747                     }
4748                     if (opts.standard == COMPILER_QCC &&
4749                         (old = parser_find_field(parser, var->name)))
4750                     {
4751                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4752                         parseerror(parser, "global `%s` already declared here: %s:%i",
4753                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
4754                         retval = false;
4755                         goto cleanup;
4756                     }
4757                 }
4758             }
4759         }
4760         else /* it's not a global */
4761         {
4762             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4763             if (old && !isparam) {
4764                 parseerror(parser, "local `%s` already declared here: %s:%i",
4765                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4766                 retval = false;
4767                 goto cleanup;
4768             }
4769             old = parser_find_local(parser, var->name, 0, &isparam);
4770             if (old && isparam) {
4771                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4772                                  "local `%s` is shadowing a parameter", var->name))
4773                 {
4774                     parseerror(parser, "local `%s` already declared here: %s:%i",
4775                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4776                     retval = false;
4777                     goto cleanup;
4778                 }
4779                 if (opts.standard != COMPILER_GMQCC) {
4780                     ast_delete(var);
4781                     var = NULL;
4782                     goto skipvar;
4783                 }
4784             }
4785         }
4786
4787         /* in a noref section we simply bump the usecount */
4788         if (noref || parser->noref)
4789             var->uses++;
4790
4791         /* Part 2:
4792          * Create the global/local, and deal with vector types.
4793          */
4794         if (!proto) {
4795             if (var->expression.vtype == TYPE_VECTOR)
4796                 isvector = true;
4797             else if (var->expression.vtype == TYPE_FIELD &&
4798                      var->expression.next->expression.vtype == TYPE_VECTOR)
4799                 isvector = true;
4800
4801             if (isvector) {
4802                 if (!create_vector_members(var, me)) {
4803                     retval = false;
4804                     goto cleanup;
4805                 }
4806             }
4807
4808             if (!localblock) {
4809                 /* deal with global variables, fields, functions */
4810                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4811                     var->isfield = true;
4812                     vec_push(parser->fields, (ast_expression*)var);
4813                     util_htset(parser->htfields, var->name, var);
4814                     if (isvector) {
4815                         for (i = 0; i < 3; ++i) {
4816                             vec_push(parser->fields, (ast_expression*)me[i]);
4817                             util_htset(parser->htfields, me[i]->name, me[i]);
4818                         }
4819                     }
4820                 }
4821                 else {
4822                     vec_push(parser->globals, (ast_expression*)var);
4823                     util_htset(parser->htglobals, var->name, var);
4824                     if (isvector) {
4825                         for (i = 0; i < 3; ++i) {
4826                             vec_push(parser->globals, (ast_expression*)me[i]);
4827                             util_htset(parser->htglobals, me[i]->name, me[i]);
4828                         }
4829                     }
4830                 }
4831             } else {
4832                 if (is_static) {
4833                     /* a static adds itself to be generated like any other global
4834                      * but is added to the local namespace instead
4835                      */
4836                     char   *defname = NULL;
4837                     size_t  prefix_len, ln;
4838
4839                     ln = strlen(parser->function->name);
4840                     vec_append(defname, ln, parser->function->name);
4841
4842                     vec_append(defname, 2, "::");
4843                     /* remember the length up to here */
4844                     prefix_len = vec_size(defname);
4845
4846                     /* Add it to the local scope */
4847                     util_htset(vec_last(parser->variables), var->name, (void*)var);
4848
4849                     /* corrector */
4850                     correct_add (
4851                          vec_last(parser->correct_variables),
4852                         &vec_last(parser->correct_variables_score),
4853                         var->name
4854                     );
4855
4856                     /* now rename the global */
4857                     ln = strlen(var->name);
4858                     vec_append(defname, ln, var->name);
4859                     ast_value_set_name(var, defname);
4860
4861                     /* push it to the to-be-generated globals */
4862                     vec_push(parser->globals, (ast_expression*)var);
4863
4864                     /* same game for the vector members */
4865                     if (isvector) {
4866                         for (i = 0; i < 3; ++i) {
4867                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4868
4869                             /* corrector */
4870                             correct_add(
4871                                  vec_last(parser->correct_variables),
4872                                 &vec_last(parser->correct_variables_score),
4873                                 me[i]->name
4874                             );
4875
4876                             vec_shrinkto(defname, prefix_len);
4877                             ln = strlen(me[i]->name);
4878                             vec_append(defname, ln, me[i]->name);
4879                             ast_member_set_name(me[i], defname);
4880
4881                             vec_push(parser->globals, (ast_expression*)me[i]);
4882                         }
4883                     }
4884                     vec_free(defname);
4885                 } else {
4886                     vec_push(localblock->locals, var);
4887                     parser_addlocal(parser, var->name, (ast_expression*)var);
4888                     if (isvector) {
4889                         for (i = 0; i < 3; ++i) {
4890                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4891                             ast_block_collect(localblock, (ast_expression*)me[i]);
4892                         }
4893                     }
4894                 }
4895             }
4896         }
4897         me[0] = me[1] = me[2] = NULL;
4898         cleanvar = false;
4899         /* Part 2.2
4900          * deal with arrays
4901          */
4902         if (var->expression.vtype == TYPE_ARRAY) {
4903             char name[1024];
4904             snprintf(name, sizeof(name), "%s##SET", var->name);
4905             if (!parser_create_array_setter(parser, var, name))
4906                 goto cleanup;
4907             snprintf(name, sizeof(name), "%s##GET", var->name);
4908             if (!parser_create_array_getter(parser, var, var->expression.next, name))
4909                 goto cleanup;
4910         }
4911         else if (!localblock && !nofields &&
4912                  var->expression.vtype == TYPE_FIELD &&
4913                  var->expression.next->expression.vtype == TYPE_ARRAY)
4914         {
4915             char name[1024];
4916             ast_expression *telem;
4917             ast_value      *tfield;
4918             ast_value      *array = (ast_value*)var->expression.next;
4919
4920             if (!ast_istype(var->expression.next, ast_value)) {
4921                 parseerror(parser, "internal error: field element type must be an ast_value");
4922                 goto cleanup;
4923             }
4924
4925             snprintf(name, sizeof(name), "%s##SETF", var->name);
4926             if (!parser_create_array_field_setter(parser, array, name))
4927                 goto cleanup;
4928
4929             telem = ast_type_copy(ast_ctx(var), array->expression.next);
4930             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4931             tfield->expression.next = telem;
4932             snprintf(name, sizeof(name), "%s##GETFP", var->name);
4933             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4934                 ast_delete(tfield);
4935                 goto cleanup;
4936             }
4937             ast_delete(tfield);
4938         }
4939
4940 skipvar:
4941         if (parser->tok == ';') {
4942             ast_delete(basetype);
4943             if (!parser_next(parser)) {
4944                 parseerror(parser, "error after variable declaration");
4945                 return false;
4946             }
4947             return true;
4948         }
4949
4950         if (parser->tok == ',')
4951             goto another;
4952
4953         /*
4954         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4955         */
4956         if (!var) {
4957             parseerror(parser, "missing comma or semicolon while parsing variables");
4958             break;
4959         }
4960
4961         if (localblock && opts.standard == COMPILER_QCC) {
4962             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4963                              "initializing expression turns variable `%s` into a constant in this standard",
4964                              var->name) )
4965             {
4966                 break;
4967             }
4968         }
4969
4970         if (parser->tok != '{') {
4971             if (parser->tok != '=') {
4972                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4973                 break;
4974             }
4975
4976             if (!parser_next(parser)) {
4977                 parseerror(parser, "error parsing initializer");
4978                 break;
4979             }
4980         }
4981         else if (opts.standard == COMPILER_QCC) {
4982             parseerror(parser, "expected '=' before function body in this standard");
4983         }
4984
4985         if (parser->tok == '#') {
4986             ast_function *func = NULL;
4987
4988             if (localblock) {
4989                 parseerror(parser, "cannot declare builtins within functions");
4990                 break;
4991             }
4992             if (var->expression.vtype != TYPE_FUNCTION) {
4993                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4994                 break;
4995             }
4996             if (!parser_next(parser)) {
4997                 parseerror(parser, "expected builtin number");
4998                 break;
4999             }
5000             if (parser->tok != TOKEN_INTCONST) {
5001                 parseerror(parser, "builtin number must be an integer constant");
5002                 break;
5003             }
5004             if (parser_token(parser)->constval.i < 0) {
5005                 parseerror(parser, "builtin number must be an integer greater than zero");
5006                 break;
5007             }
5008
5009             if (var->hasvalue) {
5010                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5011                                     "builtin `%s` has already been defined\n"
5012                                     " -> previous declaration here: %s:%i",
5013                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5014             }
5015             else
5016             {
5017                 func = ast_function_new(ast_ctx(var), var->name, var);
5018                 if (!func) {
5019                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5020                     break;
5021                 }
5022                 vec_push(parser->functions, func);
5023
5024                 func->builtin = -parser_token(parser)->constval.i-1;
5025             }
5026
5027             if (!parser_next(parser)) {
5028                 parseerror(parser, "expected comma or semicolon");
5029                 if (func)
5030                     ast_function_delete(func);
5031                 var->constval.vfunc = NULL;
5032                 break;
5033             }
5034         }
5035         else if (parser->tok == '{' || parser->tok == '[')
5036         {
5037             if (localblock) {
5038                 parseerror(parser, "cannot declare functions within functions");
5039                 break;
5040             }
5041
5042             if (proto)
5043                 ast_ctx(proto) = parser_ctx(parser);
5044
5045             if (!parse_function_body(parser, var))
5046                 break;
5047             ast_delete(basetype);
5048             for (i = 0; i < vec_size(parser->gotos); ++i)
5049                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5050             vec_free(parser->gotos);
5051             vec_free(parser->labels);
5052             return true;
5053         } else {
5054             ast_expression *cexp;
5055             ast_value      *cval;
5056
5057             cexp = parse_expression_leave(parser, true, false, false);
5058             if (!cexp)
5059                 break;
5060
5061             if (!localblock) {
5062                 cval = (ast_value*)cexp;
5063                 if (cval != parser->nil &&
5064                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5065                    )
5066                 {
5067                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5068                 }
5069                 else
5070                 {
5071                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5072                         qualifier != CV_VAR)
5073                     {
5074                         var->cvq = CV_CONST;
5075                     }
5076                     if (cval == parser->nil)
5077                         var->expression.flags |= AST_FLAG_INITIALIZED;
5078                     else
5079                     {
5080                         var->hasvalue = true;
5081                         if (cval->expression.vtype == TYPE_STRING)
5082                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5083                         else if (cval->expression.vtype == TYPE_FIELD)
5084                             var->constval.vfield = cval;
5085                         else
5086                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5087                         ast_unref(cval);
5088                     }
5089                 }
5090             } else {
5091                 int cvq;
5092                 shunt sy = { NULL, NULL };
5093                 cvq = var->cvq;
5094                 var->cvq = CV_NONE;
5095                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5096                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5097                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5098                 if (!parser_sy_apply_operator(parser, &sy))
5099                     ast_unref(cexp);
5100                 else {
5101                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5102                         parseerror(parser, "internal error: leaked operands");
5103                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5104                         break;
5105                 }
5106                 vec_free(sy.out);
5107                 vec_free(sy.ops);
5108                 var->cvq = cvq;
5109             }
5110         }
5111
5112 another:
5113         if (parser->tok == ',') {
5114             if (!parser_next(parser)) {
5115                 parseerror(parser, "expected another variable");
5116                 break;
5117             }
5118
5119             if (parser->tok != TOKEN_IDENT) {
5120                 parseerror(parser, "expected another variable");
5121                 break;
5122             }
5123             var = ast_value_copy(basetype);
5124             cleanvar = true;
5125             ast_value_set_name(var, parser_tokval(parser));
5126             if (!parser_next(parser)) {
5127                 parseerror(parser, "error parsing variable declaration");
5128                 break;
5129             }
5130             continue;
5131         }
5132
5133         if (parser->tok != ';') {
5134             parseerror(parser, "missing semicolon after variables");
5135             break;
5136         }
5137
5138         if (!parser_next(parser)) {
5139             parseerror(parser, "parse error after variable declaration");
5140             break;
5141         }
5142
5143         ast_delete(basetype);
5144         return true;
5145     }
5146
5147     if (cleanvar && var)
5148         ast_delete(var);
5149     ast_delete(basetype);
5150     return false;
5151
5152 cleanup:
5153     ast_delete(basetype);
5154     if (cleanvar && var)
5155         ast_delete(var);
5156     if (me[0]) ast_member_delete(me[0]);
5157     if (me[1]) ast_member_delete(me[1]);
5158     if (me[2]) ast_member_delete(me[2]);
5159     return retval;
5160 }
5161
5162 static bool parser_global_statement(parser_t *parser)
5163 {
5164     int        cvq       = CV_WRONG;
5165     bool       noref     = false;
5166     bool       is_static = false;
5167     uint32_t   qflags    = 0;
5168     ast_value *istype    = NULL;
5169     char      *vstring   = NULL;
5170
5171     if (parser->tok == TOKEN_IDENT)
5172         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5173
5174     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5175     {
5176         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5177     }
5178     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5179     {
5180         if (cvq == CV_WRONG)
5181             return false;
5182         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5183     }
5184     else if (parser->tok == TOKEN_KEYWORD)
5185     {
5186         if (!strcmp(parser_tokval(parser), "typedef")) {
5187             if (!parser_next(parser)) {
5188                 parseerror(parser, "expected type definition after 'typedef'");
5189                 return false;
5190             }
5191             return parse_typedef(parser);
5192         }
5193         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5194         return false;
5195     }
5196     else if (parser->tok == '#')
5197     {
5198         return parse_pragma(parser);
5199     }
5200     else if (parser->tok == '$')
5201     {
5202         if (!parser_next(parser)) {
5203             parseerror(parser, "parse error");
5204             return false;
5205         }
5206     }
5207     else
5208     {
5209         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5210         return false;
5211     }
5212     return true;
5213 }
5214
5215 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5216 {
5217     return util_crc16(old, str, strlen(str));
5218 }
5219
5220 static void progdefs_crc_file(const char *str)
5221 {
5222     /* write to progdefs.h here */
5223     (void)str;
5224 }
5225
5226 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5227 {
5228     old = progdefs_crc_sum(old, str);
5229     progdefs_crc_file(str);
5230     return old;
5231 }
5232
5233 static void generate_checksum(parser_t *parser)
5234 {
5235     uint16_t   crc = 0xFFFF;
5236     size_t     i;
5237     ast_value *value;
5238
5239     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5240     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5241     /*
5242     progdefs_crc_file("\tint\tpad;\n");
5243     progdefs_crc_file("\tint\tofs_return[3];\n");
5244     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5245     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5246     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5247     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5248     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5249     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5250     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5251     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5252     */
5253     for (i = 0; i < parser->crc_globals; ++i) {
5254         if (!ast_istype(parser->globals[i], ast_value))
5255             continue;
5256         value = (ast_value*)(parser->globals[i]);
5257         switch (value->expression.vtype) {
5258             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5259             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5260             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5261             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5262             default:
5263                 crc = progdefs_crc_both(crc, "\tint\t");
5264                 break;
5265         }
5266         crc = progdefs_crc_both(crc, value->name);
5267         crc = progdefs_crc_both(crc, ";\n");
5268     }
5269     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5270     for (i = 0; i < parser->crc_fields; ++i) {
5271         if (!ast_istype(parser->fields[i], ast_value))
5272             continue;
5273         value = (ast_value*)(parser->fields[i]);
5274         switch (value->expression.next->expression.vtype) {
5275             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5276             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5277             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5278             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5279             default:
5280                 crc = progdefs_crc_both(crc, "\tint\t");
5281                 break;
5282         }
5283         crc = progdefs_crc_both(crc, value->name);
5284         crc = progdefs_crc_both(crc, ";\n");
5285     }
5286     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5287
5288     code_crc = crc;
5289 }
5290
5291 static parser_t *parser;
5292
5293 bool parser_init()
5294 {
5295     lex_ctx empty_ctx;
5296     size_t i;
5297
5298     parser = (parser_t*)mem_a(sizeof(parser_t));
5299     if (!parser)
5300         return false;
5301
5302     memset(parser, 0, sizeof(*parser));
5303
5304     for (i = 0; i < operator_count; ++i) {
5305         if (operators[i].id == opid1('=')) {
5306             parser->assign_op = operators+i;
5307             break;
5308         }
5309     }
5310     if (!parser->assign_op) {
5311         printf("internal error: initializing parser: failed to find assign operator\n");
5312         mem_d(parser);
5313         return false;
5314     }
5315
5316     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
5317     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5318     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5319     vec_push(parser->_blocktypedefs, 0);
5320
5321     empty_ctx.file = "<internal>";
5322     empty_ctx.line = 0;
5323     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5324     parser->nil->cvq = CV_CONST;
5325     if (OPTS_FLAG(UNTYPED_NIL))
5326         util_htset(parser->htglobals, "nil", (void*)parser->nil);
5327     return true;
5328 }
5329
5330 bool parser_compile()
5331 {
5332     /* initial lexer/parser state */
5333     parser->lex->flags.noops = true;
5334
5335     if (parser_next(parser))
5336     {
5337         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5338         {
5339             if (!parser_global_statement(parser)) {
5340                 if (parser->tok == TOKEN_EOF)
5341                     parseerror(parser, "unexpected eof");
5342                 else if (compile_errors)
5343                     parseerror(parser, "there have been errors, bailing out");
5344                 lex_close(parser->lex);
5345                 parser->lex = NULL;
5346                 return false;
5347             }
5348         }
5349     } else {
5350         parseerror(parser, "parse error");
5351         lex_close(parser->lex);
5352         parser->lex = NULL;
5353         return false;
5354     }
5355
5356     lex_close(parser->lex);
5357     parser->lex = NULL;
5358
5359     return !compile_errors;
5360 }
5361
5362 bool parser_compile_file(const char *filename)
5363 {
5364     parser->lex = lex_open(filename);
5365     if (!parser->lex) {
5366         con_err("failed to open file \"%s\"\n", filename);
5367         return false;
5368     }
5369     return parser_compile();
5370 }
5371
5372 bool parser_compile_string(const char *name, const char *str, size_t len)
5373 {
5374     parser->lex = lex_open_string(str, len, name);
5375     if (!parser->lex) {
5376         con_err("failed to create lexer for string \"%s\"\n", name);
5377         return false;
5378     }
5379     return parser_compile();
5380 }
5381
5382 void parser_cleanup()
5383 {
5384     size_t i;
5385     for (i = 0; i < vec_size(parser->accessors); ++i) {
5386         ast_delete(parser->accessors[i]->constval.vfunc);
5387         parser->accessors[i]->constval.vfunc = NULL;
5388         ast_delete(parser->accessors[i]);
5389     }
5390     for (i = 0; i < vec_size(parser->functions); ++i) {
5391         ast_delete(parser->functions[i]);
5392     }
5393     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5394         ast_delete(parser->imm_vector[i]);
5395     }
5396     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5397         ast_delete(parser->imm_string[i]);
5398     }
5399     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5400         ast_delete(parser->imm_float[i]);
5401     }
5402     for (i = 0; i < vec_size(parser->fields); ++i) {
5403         ast_delete(parser->fields[i]);
5404     }
5405     for (i = 0; i < vec_size(parser->globals); ++i) {
5406         ast_delete(parser->globals[i]);
5407     }
5408     vec_free(parser->accessors);
5409     vec_free(parser->functions);
5410     vec_free(parser->imm_vector);
5411     vec_free(parser->imm_string);
5412     vec_free(parser->imm_float);
5413     vec_free(parser->globals);
5414     vec_free(parser->fields);
5415
5416     for (i = 0; i < vec_size(parser->variables); ++i)
5417         util_htdel(parser->variables[i]);
5418     vec_free(parser->variables);
5419     vec_free(parser->_blocklocals);
5420     vec_free(parser->_locals);
5421
5422     /* corrector */
5423     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5424         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5425     }
5426     for (i = 0; i < vec_size(parser->correct_variables_score); ++i) {
5427         vec_free(parser->correct_variables_score[i]);
5428     }
5429     vec_free(parser->correct_variables);
5430     vec_free(parser->correct_variables_score);
5431
5432
5433     for (i = 0; i < vec_size(parser->_typedefs); ++i)
5434         ast_delete(parser->_typedefs[i]);
5435     vec_free(parser->_typedefs);
5436     for (i = 0; i < vec_size(parser->typedefs); ++i)
5437         util_htdel(parser->typedefs[i]);
5438     vec_free(parser->typedefs);
5439     vec_free(parser->_blocktypedefs);
5440
5441     vec_free(parser->_block_ctx);
5442
5443     vec_free(parser->labels);
5444     vec_free(parser->gotos);
5445     vec_free(parser->breaks);
5446     vec_free(parser->continues);
5447
5448     ast_value_delete(parser->nil);
5449
5450     mem_d(parser);
5451 }
5452
5453 bool parser_finish(const char *output)
5454 {
5455     size_t i;
5456     ir_builder *ir;
5457     bool retval = true;
5458
5459     if (compile_errors) {
5460         con_out("*** there were compile errors\n");
5461         return false;
5462     }
5463
5464     ir = ir_builder_new("gmqcc_out");
5465     if (!ir) {
5466         con_out("failed to allocate builder\n");
5467         return false;
5468     }
5469
5470     for (i = 0; i < vec_size(parser->fields); ++i) {
5471         ast_value *field;
5472         bool hasvalue;
5473         if (!ast_istype(parser->fields[i], ast_value))
5474             continue;
5475         field = (ast_value*)parser->fields[i];
5476         hasvalue = field->hasvalue;
5477         field->hasvalue = false;
5478         if (!ast_global_codegen((ast_value*)field, ir, true)) {
5479             con_out("failed to generate field %s\n", field->name);
5480             ir_builder_delete(ir);
5481             return false;
5482         }
5483         if (hasvalue) {
5484             ir_value *ifld;
5485             ast_expression *subtype;
5486             field->hasvalue = true;
5487             subtype = field->expression.next;
5488             ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5489             if (subtype->expression.vtype == TYPE_FIELD)
5490                 ifld->fieldtype = subtype->expression.next->expression.vtype;
5491             else if (subtype->expression.vtype == TYPE_FUNCTION)
5492                 ifld->outtype = subtype->expression.next->expression.vtype;
5493             (void)!ir_value_set_field(field->ir_v, ifld);
5494         }
5495     }
5496     for (i = 0; i < vec_size(parser->globals); ++i) {
5497         ast_value *asvalue;
5498         if (!ast_istype(parser->globals[i], ast_value))
5499             continue;
5500         asvalue = (ast_value*)(parser->globals[i]);
5501         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5502             retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5503                                            "unused global: `%s`", asvalue->name);
5504         }
5505         if (!ast_global_codegen(asvalue, ir, false)) {
5506             con_out("failed to generate global %s\n", asvalue->name);
5507             ir_builder_delete(ir);
5508             return false;
5509         }
5510     }
5511     for (i = 0; i < vec_size(parser->imm_float); ++i) {
5512         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5513             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5514             ir_builder_delete(ir);
5515             return false;
5516         }
5517     }
5518     for (i = 0; i < vec_size(parser->imm_string); ++i) {
5519         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5520             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5521             ir_builder_delete(ir);
5522             return false;
5523         }
5524     }
5525     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5526         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5527             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5528             ir_builder_delete(ir);
5529             return false;
5530         }
5531     }
5532     for (i = 0; i < vec_size(parser->globals); ++i) {
5533         ast_value *asvalue;
5534         if (!ast_istype(parser->globals[i], ast_value))
5535             continue;
5536         asvalue = (ast_value*)(parser->globals[i]);
5537         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5538         {
5539             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5540                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5541                                        "uninitialized constant: `%s`",
5542                                        asvalue->name);
5543             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5544                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5545                                        "uninitialized global: `%s`",
5546                                        asvalue->name);
5547         }
5548         if (!ast_generate_accessors(asvalue, ir)) {
5549             ir_builder_delete(ir);
5550             return false;
5551         }
5552     }
5553     for (i = 0; i < vec_size(parser->fields); ++i) {
5554         ast_value *asvalue;
5555         asvalue = (ast_value*)(parser->fields[i]->expression.next);
5556
5557         if (!ast_istype((ast_expression*)asvalue, ast_value))
5558             continue;
5559         if (asvalue->expression.vtype != TYPE_ARRAY)
5560             continue;
5561         if (!ast_generate_accessors(asvalue, ir)) {
5562             ir_builder_delete(ir);
5563             return false;
5564         }
5565     }
5566     for (i = 0; i < vec_size(parser->functions); ++i) {
5567         if (!ast_function_codegen(parser->functions[i], ir)) {
5568             con_out("failed to generate function %s\n", parser->functions[i]->name);
5569             ir_builder_delete(ir);
5570             return false;
5571         }
5572     }
5573     if (opts.dump)
5574         ir_builder_dump(ir, con_out);
5575     for (i = 0; i < vec_size(parser->functions); ++i) {
5576         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5577             con_out("failed to finalize function %s\n", parser->functions[i]->name);
5578             ir_builder_delete(ir);
5579             return false;
5580         }
5581     }
5582
5583     if (compile_Werrors) {
5584         con_out("*** there were warnings treated as errors\n");
5585         compile_show_werrors();
5586         retval = false;
5587     }
5588
5589     if (retval) {
5590         if (opts.dumpfin)
5591             ir_builder_dump(ir, con_out);
5592
5593         generate_checksum(parser);
5594
5595         if (!ir_builder_generate(ir, output)) {
5596             con_out("*** failed to generate output file\n");
5597             ir_builder_delete(ir);
5598             return false;
5599         }
5600     }
5601
5602     ir_builder_delete(ir);
5603     return retval;
5604 }