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