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