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