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