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