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