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