]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
stashing sample ast iteration functionality in this branch
[xonotic/gmqcc.git] / ast.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 <stdlib.h>
25 #include <string.h>
26
27 #include "gmqcc.h"
28 #include "ast.h"
29 #include "parser.h"
30
31 #define ast_instantiate(T, ctx, destroyfn, iterfn)                  \
32     T* self = (T*)mem_a(sizeof(T));                                 \
33     if (!self) {                                                    \
34         return NULL;                                                \
35     }                                                               \
36     ast_node_init((ast_node*)self, ctx, TYPE_##T);                  \
37     ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn;     \
38     if (iterfn) {                                                   \
39         ( (ast_node*)self )->next_child = (ast_node_next_child*)iterfn; \
40     }
41
42 /*
43  * forward declarations, these need not be in ast.h for obvious
44  * static reasons.
45  */
46 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
47 static ast_node* ast_member_next_child(ast_member*,ast_node*);
48 static void ast_array_index_delete(ast_array_index*);
49 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
50 static ast_node* ast_array_index_next_child(ast_array_index*,ast_node*);
51 static void ast_argpipe_delete(ast_argpipe*);
52 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
53 static ast_node* ast_argpipe_next_child(ast_argpipe*,ast_node*);
54 static void ast_store_delete(ast_store*);
55 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
56 static ast_node* ast_store_next_child(ast_store*,ast_node*);
57 static void ast_ifthen_delete(ast_ifthen*);
58 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
59 static ast_node* ast_ifthen_next_child(ast_ifthen*,ast_node*);
60 static void ast_ternary_delete(ast_ternary*);
61 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
62 static ast_node* ast_ternary_next_child(ast_ternary*,ast_node*);
63 static void ast_loop_delete(ast_loop*);
64 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
65 static ast_node* ast_loop_next_child(ast_loop*,ast_node*);
66 static void ast_breakcont_delete(ast_breakcont*);
67 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
68 static ast_node* ast_breakcont_next_child(ast_breakcont*,ast_node*);
69 static void ast_switch_delete(ast_switch*);
70 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
71 static ast_node* ast_switch_next_child(ast_switch*,ast_node*);
72 static void ast_label_delete(ast_label*);
73 static void ast_label_register_goto(ast_label*, ast_goto*);
74 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
75 static ast_node* ast_label_next_child(ast_label*,ast_node*);
76 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
77 static void ast_goto_delete(ast_goto*);
78 static ast_node* ast_goto_next_child(ast_goto*,ast_node*);
79 static void ast_call_delete(ast_call*);
80 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
81 static ast_node* ast_call_next_child(ast_call*,ast_node*);
82 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
83 static ast_node* ast_block_next_child(ast_block*,ast_node*);
84 static void ast_unary_delete(ast_unary*);
85 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
86 static ast_node* ast_unary_next_child(ast_unary*,ast_node*);
87 static void ast_entfield_delete(ast_entfield*);
88 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
89 static ast_node* ast_entfield_next_child(ast_entfield*,ast_node*);
90 static void ast_return_delete(ast_return*);
91 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
92 static ast_node* ast_return_next_child(ast_return*,ast_node*);
93 static void ast_binstore_delete(ast_binstore*);
94 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
95 static ast_node* ast_binstore_next_child(ast_binstore*,ast_node*);
96 static void ast_binary_delete(ast_binary*);
97 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
98 static ast_node* ast_binary_next_child(ast_binary*,ast_node*);
99 static ast_node* ast_value_next_child(ast_value*,ast_node*);
100 static ast_node* ast_function_next_child(ast_function*,ast_node*);
101
102 /* It must not be possible to get here. */
103 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
104 {
105     (void)self;
106     con_err("ast node missing destroy()\n");
107     exit(EXIT_FAILURE);
108 }
109
110 static ast_node* _ast_node_next_child(ast_node *self, ast_node *prev)
111 {
112     (void)self;
113     (void)prev;
114     return NULL;
115 }
116
117 /* Initialize main ast node aprts */
118 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
119 {
120     self->context = ctx;
121     self->destroy = &_ast_node_destroy;
122     self->next_child = &_ast_node_next_child;
123     self->keep    = false;
124     self->nodetype = nodetype;
125     self->side_effects = false;
126 }
127
128 /* weight and side effects */
129 static void _ast_propagate_effects(ast_node *self, ast_node *other)
130 {
131     if (ast_side_effects(other))
132         ast_side_effects(self) = true;
133 }
134 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
135
136 /* General expression initialization */
137 static void ast_expression_init(ast_expression *self,
138                                 ast_expression_codegen *codegen)
139 {
140     self->codegen  = codegen;
141     self->vtype    = TYPE_VOID;
142     self->next     = NULL;
143     self->outl     = NULL;
144     self->outr     = NULL;
145     self->params   = NULL;
146     self->count    = 0;
147     self->flags    = 0;
148     self->varparam = NULL;
149 }
150
151 static void ast_expression_delete(ast_expression *self)
152 {
153     size_t i;
154     if (self->next)
155         ast_delete(self->next);
156     for (i = 0; i < vec_size(self->params); ++i) {
157         ast_delete(self->params[i]);
158     }
159     vec_free(self->params);
160     if (self->varparam)
161         ast_delete(self->varparam);
162 }
163
164 static void ast_expression_delete_full(ast_expression *self)
165 {
166     ast_expression_delete(self);
167     mem_d(self);
168 }
169
170 ast_value* ast_value_copy(const ast_value *self)
171 {
172     size_t i;
173     const ast_expression *fromex;
174     ast_expression       *selfex;
175     ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
176     if (self->expression.next) {
177         cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
178     }
179     fromex   = &self->expression;
180     selfex = &cp->expression;
181     selfex->count    = fromex->count;
182     selfex->flags    = fromex->flags;
183     for (i = 0; i < vec_size(fromex->params); ++i) {
184         ast_value *v = ast_value_copy(fromex->params[i]);
185         vec_push(selfex->params, v);
186     }
187     return cp;
188 }
189
190 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
191 {
192     size_t i;
193     const ast_expression *fromex;
194     ast_expression       *selfex;
195     self->vtype = other->vtype;
196     if (other->next) {
197         self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
198     }
199     fromex = other;
200     selfex = self;
201     selfex->count    = fromex->count;
202     selfex->flags    = fromex->flags;
203     for (i = 0; i < vec_size(fromex->params); ++i) {
204         ast_value *v = ast_value_copy(fromex->params[i]);
205         vec_push(selfex->params, v);
206     }
207 }
208
209 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
210 {
211     ast_instantiate(ast_expression, ctx, ast_expression_delete_full, NULL);
212     ast_expression_init(self, NULL);
213     self->codegen = NULL;
214     self->next    = NULL;
215     self->vtype   = vtype;
216     return self;
217 }
218
219 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
220 {
221     size_t i;
222     const ast_expression *fromex;
223     ast_expression       *selfex;
224
225     if (!ex)
226         return NULL;
227     else
228     {
229         ast_instantiate(ast_expression, ctx, ast_expression_delete_full, NULL);
230         ast_expression_init(self, NULL);
231
232         fromex = ex;
233         selfex = self;
234
235         /* This may never be codegen()d */
236         selfex->codegen = NULL;
237
238         selfex->vtype = fromex->vtype;
239         if (fromex->next)
240             selfex->next = ast_type_copy(ctx, fromex->next);
241         else
242             selfex->next = NULL;
243
244         selfex->count    = fromex->count;
245         selfex->flags    = fromex->flags;
246         for (i = 0; i < vec_size(fromex->params); ++i) {
247             ast_value *v = ast_value_copy(fromex->params[i]);
248             vec_push(selfex->params, v);
249         }
250
251         return self;
252     }
253 }
254
255 bool ast_compare_type(ast_expression *a, ast_expression *b)
256 {
257     if (a->vtype == TYPE_NIL ||
258         b->vtype == TYPE_NIL)
259         return true;
260     if (a->vtype != b->vtype)
261         return false;
262     if (!a->next != !b->next)
263         return false;
264     if (vec_size(a->params) != vec_size(b->params))
265         return false;
266     if ((a->flags & AST_FLAG_TYPE_MASK) !=
267         (b->flags & AST_FLAG_TYPE_MASK) )
268     {
269         return false;
270     }
271     if (vec_size(a->params)) {
272         size_t i;
273         for (i = 0; i < vec_size(a->params); ++i) {
274             if (!ast_compare_type((ast_expression*)a->params[i],
275                                   (ast_expression*)b->params[i]))
276                 return false;
277         }
278     }
279     if (a->next)
280         return ast_compare_type(a->next, b->next);
281     return true;
282 }
283
284 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
285 {
286     const char *typestr;
287     size_t typelen;
288     size_t i;
289
290     if (!e) {
291         if (pos + 6 >= bufsize)
292             goto full;
293         util_strncpy(buf + pos, "(null)", 6);
294         return pos + 6;
295     }
296
297     if (pos + 1 >= bufsize)
298         goto full;
299
300     switch (e->vtype) {
301         case TYPE_VARIANT:
302             util_strncpy(buf + pos, "(variant)", 9);
303             return pos + 9;
304
305         case TYPE_FIELD:
306             buf[pos++] = '.';
307             return ast_type_to_string_impl(e->next, buf, bufsize, pos);
308
309         case TYPE_POINTER:
310             if (pos + 3 >= bufsize)
311                 goto full;
312             buf[pos++] = '*';
313             buf[pos++] = '(';
314             pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
315             if (pos + 1 >= bufsize)
316                 goto full;
317             buf[pos++] = ')';
318             return pos;
319
320         case TYPE_FUNCTION:
321             pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
322             if (pos + 2 >= bufsize)
323                 goto full;
324             if (!vec_size(e->params)) {
325                 buf[pos++] = '(';
326                 buf[pos++] = ')';
327                 return pos;
328             }
329             buf[pos++] = '(';
330             pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
331             for (i = 1; i < vec_size(e->params); ++i) {
332                 if (pos + 2 >= bufsize)
333                     goto full;
334                 buf[pos++] = ',';
335                 buf[pos++] = ' ';
336                 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
337             }
338             if (pos + 1 >= bufsize)
339                 goto full;
340             buf[pos++] = ')';
341             return pos;
342
343         case TYPE_ARRAY:
344             pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
345             if (pos + 1 >= bufsize)
346                 goto full;
347             buf[pos++] = '[';
348             pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
349             if (pos + 1 >= bufsize)
350                 goto full;
351             buf[pos++] = ']';
352             return pos;
353
354         default:
355             typestr = type_name[e->vtype];
356             typelen = strlen(typestr);
357             if (pos + typelen >= bufsize)
358                 goto full;
359             util_strncpy(buf + pos, typestr, typelen);
360             return pos + typelen;
361     }
362
363 full:
364     buf[bufsize-3] = '.';
365     buf[bufsize-2] = '.';
366     buf[bufsize-1] = '.';
367     return bufsize;
368 }
369
370 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
371 {
372     size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
373     buf[pos] = 0;
374 }
375
376 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
377 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
378 {
379     ast_instantiate(ast_value, ctx, ast_value_delete, ast_value_next_child);
380     ast_expression_init((ast_expression*)self,
381                         (ast_expression_codegen*)&ast_value_codegen);
382     self->expression.node.keep = true; /* keep */
383
384     self->name = name ? util_strdup(name) : NULL;
385     self->expression.vtype = t;
386     self->expression.next  = NULL;
387     self->isfield  = false;
388     self->cvq      = CV_NONE;
389     self->hasvalue = false;
390     self->isimm    = false;
391     self->uses     = 0;
392     memset(&self->constval, 0, sizeof(self->constval));
393     self->initlist = NULL;
394
395     self->ir_v           = NULL;
396     self->ir_values      = NULL;
397     self->ir_value_count = 0;
398
399     self->setter = NULL;
400     self->getter = NULL;
401     self->desc   = NULL;
402
403     self->argcounter = NULL;
404     self->intrinsic = false;
405
406     return self;
407 }
408
409 void ast_value_delete(ast_value* self)
410 {
411     if (self->name)
412         mem_d((void*)self->name);
413     if (self->argcounter)
414         mem_d((void*)self->argcounter);
415     if (self->hasvalue) {
416         switch (self->expression.vtype)
417         {
418         case TYPE_STRING:
419             mem_d((void*)self->constval.vstring);
420             break;
421         case TYPE_FUNCTION:
422             /* unlink us from the function node */
423             self->constval.vfunc->vtype = NULL;
424             break;
425         /* NOTE: delete function? currently collected in
426          * the parser structure
427          */
428         default:
429             break;
430         }
431     }
432     if (self->ir_values)
433         mem_d(self->ir_values);
434
435     if (self->desc)
436         mem_d(self->desc);
437
438     if (self->initlist) {
439         if (self->expression.next->vtype == TYPE_STRING) {
440             /* strings are allocated, free them */
441             size_t i, len = vec_size(self->initlist);
442             /* in theory, len should be expression.count
443              * but let's not take any chances */
444             for (i = 0; i < len; ++i) {
445                 if (self->initlist[i].vstring)
446                     mem_d(self->initlist[i].vstring);
447             }
448         }
449         vec_free(self->initlist);
450     }
451
452     ast_expression_delete((ast_expression*)self);
453     mem_d(self);
454 }
455
456 void ast_value_params_add(ast_value *self, ast_value *p)
457 {
458     vec_push(self->expression.params, p);
459 }
460
461 bool ast_value_set_name(ast_value *self, const char *name)
462 {
463     if (self->name)
464         mem_d((void*)self->name);
465     self->name = util_strdup(name);
466     return !!self->name;
467 }
468
469 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
470                            ast_expression* left, ast_expression* right)
471 {
472     ast_instantiate(ast_binary, ctx, ast_binary_delete, ast_binary_next_child);
473     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
474
475     self->op = op;
476     self->left = left;
477     self->right = right;
478     self->right_first = false;
479
480     ast_propagate_effects(self, left);
481     ast_propagate_effects(self, right);
482
483     if (op >= INSTR_EQ_F && op <= INSTR_GT)
484         self->expression.vtype = TYPE_FLOAT;
485     else if (op == INSTR_AND || op == INSTR_OR) {
486         if (OPTS_FLAG(PERL_LOGIC))
487             ast_type_adopt(self, right);
488         else
489             self->expression.vtype = TYPE_FLOAT;
490     }
491     else if (op == INSTR_BITAND || op == INSTR_BITOR)
492         self->expression.vtype = TYPE_FLOAT;
493     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
494         self->expression.vtype = TYPE_VECTOR;
495     else if (op == INSTR_MUL_V)
496         self->expression.vtype = TYPE_FLOAT;
497     else
498         self->expression.vtype = left->vtype;
499
500     /* references all */
501     self->refs = AST_REF_ALL;
502
503     return self;
504 }
505
506 void ast_binary_delete(ast_binary *self)
507 {
508     if (self->refs & AST_REF_LEFT)  ast_unref(self->left);
509     if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
510
511     ast_expression_delete((ast_expression*)self);
512     mem_d(self);
513 }
514
515 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
516                                ast_expression* left, ast_expression* right)
517 {
518     ast_instantiate(ast_binstore, ctx, ast_binstore_delete, ast_binstore_next_child);
519     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
520
521     ast_side_effects(self) = true;
522
523     self->opstore = storop;
524     self->opbin   = op;
525     self->dest    = left;
526     self->source  = right;
527
528     self->keep_dest = false;
529
530     ast_type_adopt(self, left);
531     return self;
532 }
533
534 void ast_binstore_delete(ast_binstore *self)
535 {
536     if (!self->keep_dest)
537         ast_unref(self->dest);
538     ast_unref(self->source);
539     ast_expression_delete((ast_expression*)self);
540     mem_d(self);
541 }
542
543 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
544                          ast_expression *expr)
545 {
546     ast_instantiate(ast_unary, ctx, ast_unary_delete, ast_unary_next_child);
547     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
548
549     self->op      = op;
550     self->operand = expr;
551
552
553     if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
554         ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
555
556         /* Handle for double negation */
557         if (((ast_unary*)expr)->op == op)
558             prev = (ast_unary*)((ast_unary*)expr)->operand;
559
560         if (ast_istype(prev, ast_unary)) {
561             ast_expression_delete((ast_expression*)self);
562             mem_d(self);
563             ++opts_optimizationcount[OPTIM_PEEPHOLE];
564             return prev;
565         }
566     }
567
568     ast_propagate_effects(self, expr);
569
570     if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
571         self->expression.vtype = TYPE_FLOAT;
572     } else if (op == VINSTR_NEG_V) {
573         self->expression.vtype = TYPE_VECTOR;
574     } else {
575         compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
576     }
577
578     return self;
579 }
580
581 void ast_unary_delete(ast_unary *self)
582 {
583     if (self->operand) ast_unref(self->operand);
584     ast_expression_delete((ast_expression*)self);
585     mem_d(self);
586 }
587
588 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
589 {
590     ast_instantiate(ast_return, ctx, ast_return_delete, ast_return_next_child);
591     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
592
593     self->operand = expr;
594
595     if (expr)
596         ast_propagate_effects(self, expr);
597
598     return self;
599 }
600
601 void ast_return_delete(ast_return *self)
602 {
603     if (self->operand)
604         ast_unref(self->operand);
605     ast_expression_delete((ast_expression*)self);
606     mem_d(self);
607 }
608
609 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
610 {
611     if (field->vtype != TYPE_FIELD) {
612         compile_error(ctx, "ast_entfield_new with expression not of type field");
613         return NULL;
614     }
615     return ast_entfield_new_force(ctx, entity, field, field->next);
616 }
617
618 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
619 {
620     ast_instantiate(ast_entfield, ctx, ast_entfield_delete, ast_entfield_next_child);
621
622     if (!outtype) {
623         mem_d(self);
624         /* Error: field has no type... */
625         return NULL;
626     }
627
628     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
629
630     self->entity = entity;
631     self->field  = field;
632     ast_propagate_effects(self, entity);
633     ast_propagate_effects(self, field);
634
635     ast_type_adopt(self, outtype);
636     return self;
637 }
638
639 void ast_entfield_delete(ast_entfield *self)
640 {
641     ast_unref(self->entity);
642     ast_unref(self->field);
643     ast_expression_delete((ast_expression*)self);
644     mem_d(self);
645 }
646
647 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
648 {
649     ast_instantiate(ast_member, ctx, ast_member_delete, ast_member_next_child);
650     if (field >= 3) {
651         mem_d(self);
652         return NULL;
653     }
654
655     if (owner->vtype != TYPE_VECTOR &&
656         owner->vtype != TYPE_FIELD) {
657         compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
658         mem_d(self);
659         return NULL;
660     }
661
662     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
663     self->expression.node.keep = true; /* keep */
664
665     if (owner->vtype == TYPE_VECTOR) {
666         self->expression.vtype = TYPE_FLOAT;
667         self->expression.next  = NULL;
668     } else {
669         self->expression.vtype = TYPE_FIELD;
670         self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
671     }
672
673     self->rvalue = false;
674     self->owner  = owner;
675     ast_propagate_effects(self, owner);
676
677     self->field = field;
678     if (name)
679         self->name = util_strdup(name);
680     else
681         self->name = NULL;
682
683     return self;
684 }
685
686 void ast_member_delete(ast_member *self)
687 {
688     /* The owner is always an ast_value, which has .keep=true,
689      * also: ast_members are usually deleted after the owner, thus
690      * this will cause invalid access
691     ast_unref(self->owner);
692      * once we allow (expression).x to access a vector-member, we need
693      * to change this: preferably by creating an alternate ast node for this
694      * purpose that is not garbage-collected.
695     */
696     ast_expression_delete((ast_expression*)self);
697     mem_d(self->name);
698     mem_d(self);
699 }
700
701 bool ast_member_set_name(ast_member *self, const char *name)
702 {
703     if (self->name)
704         mem_d((void*)self->name);
705     self->name = util_strdup(name);
706     return !!self->name;
707 }
708
709 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
710 {
711     ast_expression *outtype;
712     ast_instantiate(ast_array_index, ctx, ast_array_index_delete, ast_array_index_next_child);
713
714     outtype = array->next;
715     if (!outtype) {
716         mem_d(self);
717         /* Error: field has no type... */
718         return NULL;
719     }
720
721     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
722
723     self->array = array;
724     self->index = index;
725     ast_propagate_effects(self, array);
726     ast_propagate_effects(self, index);
727
728     ast_type_adopt(self, outtype);
729     if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
730         if (self->expression.vtype != TYPE_ARRAY) {
731             compile_error(ast_ctx(self), "array_index node on type");
732             ast_array_index_delete(self);
733             return NULL;
734         }
735         self->array = outtype;
736         self->expression.vtype = TYPE_FIELD;
737     }
738
739     return self;
740 }
741
742 void ast_array_index_delete(ast_array_index *self)
743 {
744     if (self->array)
745         ast_unref(self->array);
746     if (self->index)
747         ast_unref(self->index);
748     ast_expression_delete((ast_expression*)self);
749     mem_d(self);
750 }
751
752 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
753 {
754     ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete, ast_argpipe_next_child);
755     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
756     self->index = index;
757     self->expression.vtype = TYPE_NOEXPR;
758     return self;
759 }
760
761 void ast_argpipe_delete(ast_argpipe *self)
762 {
763     if (self->index)
764         ast_unref(self->index);
765     ast_expression_delete((ast_expression*)self);
766     mem_d(self);
767 }
768
769 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
770 {
771     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete, ast_ifthen_next_child);
772     if (!ontrue && !onfalse) {
773         /* because it is invalid */
774         mem_d(self);
775         return NULL;
776     }
777     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
778
779     self->cond     = cond;
780     self->on_true  = ontrue;
781     self->on_false = onfalse;
782     ast_propagate_effects(self, cond);
783     if (ontrue)
784         ast_propagate_effects(self, ontrue);
785     if (onfalse)
786         ast_propagate_effects(self, onfalse);
787
788     return self;
789 }
790
791 void ast_ifthen_delete(ast_ifthen *self)
792 {
793     ast_unref(self->cond);
794     if (self->on_true)
795         ast_unref(self->on_true);
796     if (self->on_false)
797         ast_unref(self->on_false);
798     ast_expression_delete((ast_expression*)self);
799     mem_d(self);
800 }
801
802 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
803 {
804     ast_expression *exprtype = ontrue;
805     ast_instantiate(ast_ternary, ctx, ast_ternary_delete, ast_ternary_next_child);
806     /* This time NEITHER must be NULL */
807     if (!ontrue || !onfalse) {
808         mem_d(self);
809         return NULL;
810     }
811     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
812
813     self->cond     = cond;
814     self->on_true  = ontrue;
815     self->on_false = onfalse;
816     ast_propagate_effects(self, cond);
817     ast_propagate_effects(self, ontrue);
818     ast_propagate_effects(self, onfalse);
819
820     if (ontrue->vtype == TYPE_NIL)
821         exprtype = onfalse;
822     ast_type_adopt(self, exprtype);
823
824     return self;
825 }
826
827 void ast_ternary_delete(ast_ternary *self)
828 {
829     /* the if()s are only there because computed-gotos can set them
830      * to NULL
831      */
832     if (self->cond)     ast_unref(self->cond);
833     if (self->on_true)  ast_unref(self->on_true);
834     if (self->on_false) ast_unref(self->on_false);
835     ast_expression_delete((ast_expression*)self);
836     mem_d(self);
837 }
838
839 ast_loop* ast_loop_new(lex_ctx_t ctx,
840                        ast_expression *initexpr,
841                        ast_expression *precond, bool pre_not,
842                        ast_expression *postcond, bool post_not,
843                        ast_expression *increment,
844                        ast_expression *body)
845 {
846     ast_instantiate(ast_loop, ctx, ast_loop_delete, ast_loop_next_child);
847     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
848
849     self->initexpr  = initexpr;
850     self->precond   = precond;
851     self->postcond  = postcond;
852     self->increment = increment;
853     self->body      = body;
854
855     self->pre_not   = pre_not;
856     self->post_not  = post_not;
857
858     if (initexpr)
859         ast_propagate_effects(self, initexpr);
860     if (precond)
861         ast_propagate_effects(self, precond);
862     if (postcond)
863         ast_propagate_effects(self, postcond);
864     if (increment)
865         ast_propagate_effects(self, increment);
866     if (body)
867         ast_propagate_effects(self, body);
868
869     return self;
870 }
871
872 void ast_loop_delete(ast_loop *self)
873 {
874     if (self->initexpr)
875         ast_unref(self->initexpr);
876     if (self->precond)
877         ast_unref(self->precond);
878     if (self->postcond)
879         ast_unref(self->postcond);
880     if (self->increment)
881         ast_unref(self->increment);
882     if (self->body)
883         ast_unref(self->body);
884     ast_expression_delete((ast_expression*)self);
885     mem_d(self);
886 }
887
888 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
889 {
890     ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete, ast_breakcont_next_child);
891     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
892
893     self->is_continue = iscont;
894     self->levels      = levels;
895
896     return self;
897 }
898
899 void ast_breakcont_delete(ast_breakcont *self)
900 {
901     ast_expression_delete((ast_expression*)self);
902     mem_d(self);
903 }
904
905 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
906 {
907     ast_instantiate(ast_switch, ctx, ast_switch_delete, ast_switch_next_child);
908     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
909
910     self->operand = op;
911     self->cases   = NULL;
912
913     ast_propagate_effects(self, op);
914
915     return self;
916 }
917
918 void ast_switch_delete(ast_switch *self)
919 {
920     size_t i;
921     ast_unref(self->operand);
922
923     for (i = 0; i < vec_size(self->cases); ++i) {
924         if (self->cases[i].value)
925             ast_unref(self->cases[i].value);
926         ast_unref(self->cases[i].code);
927     }
928     vec_free(self->cases);
929
930     ast_expression_delete((ast_expression*)self);
931     mem_d(self);
932 }
933
934 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
935 {
936     ast_instantiate(ast_label, ctx, ast_label_delete, ast_label_next_child);
937     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
938
939     self->expression.vtype = TYPE_NOEXPR;
940
941     self->name      = util_strdup(name);
942     self->irblock   = NULL;
943     self->gotos     = NULL;
944     self->undefined = undefined;
945
946     return self;
947 }
948
949 void ast_label_delete(ast_label *self)
950 {
951     mem_d((void*)self->name);
952     vec_free(self->gotos);
953     ast_expression_delete((ast_expression*)self);
954     mem_d(self);
955 }
956
957 static void ast_label_register_goto(ast_label *self, ast_goto *g)
958 {
959     vec_push(self->gotos, g);
960 }
961
962 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
963 {
964     ast_instantiate(ast_goto, ctx, ast_goto_delete, ast_goto_next_child);
965     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
966
967     self->name    = util_strdup(name);
968     self->target  = NULL;
969     self->irblock_from = NULL;
970
971     return self;
972 }
973
974 void ast_goto_delete(ast_goto *self)
975 {
976     mem_d((void*)self->name);
977     ast_expression_delete((ast_expression*)self);
978     mem_d(self);
979 }
980
981 void ast_goto_set_label(ast_goto *self, ast_label *label)
982 {
983     self->target = label;
984 }
985
986 ast_call* ast_call_new(lex_ctx_t ctx,
987                        ast_expression *funcexpr)
988 {
989     ast_instantiate(ast_call, ctx, ast_call_delete, ast_call_next_child);
990     if (!funcexpr->next) {
991         compile_error(ctx, "not a function");
992         mem_d(self);
993         return NULL;
994     }
995     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
996
997     ast_side_effects(self) = true;
998
999     self->params   = NULL;
1000     self->func     = funcexpr;
1001     self->va_count = NULL;
1002
1003     ast_type_adopt(self, funcexpr->next);
1004
1005     return self;
1006 }
1007
1008 void ast_call_delete(ast_call *self)
1009 {
1010     size_t i;
1011     for (i = 0; i < vec_size(self->params); ++i)
1012         ast_unref(self->params[i]);
1013     vec_free(self->params);
1014
1015     if (self->func)
1016         ast_unref(self->func);
1017
1018     if (self->va_count)
1019         ast_unref(self->va_count);
1020
1021     ast_expression_delete((ast_expression*)self);
1022     mem_d(self);
1023 }
1024
1025 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1026 {
1027     char texp[1024];
1028     char tgot[1024];
1029     if (!exp_type)
1030         return true;
1031     if (!va_type || !ast_compare_type(va_type, exp_type))
1032     {
1033         if (va_type && exp_type)
1034         {
1035             ast_type_to_string(va_type,  tgot, sizeof(tgot));
1036             ast_type_to_string(exp_type, texp, sizeof(texp));
1037             if (OPTS_FLAG(UNSAFE_VARARGS)) {
1038                 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1039                                     "piped variadic argument differs in type: constrained to type %s, expected type %s",
1040                                     tgot, texp))
1041                     return false;
1042             } else {
1043                 compile_error(ast_ctx(self),
1044                               "piped variadic argument differs in type: constrained to type %s, expected type %s",
1045                               tgot, texp);
1046                 return false;
1047             }
1048         }
1049         else
1050         {
1051             ast_type_to_string(exp_type, texp, sizeof(texp));
1052             if (OPTS_FLAG(UNSAFE_VARARGS)) {
1053                 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1054                                     "piped variadic argument may differ in type: expected type %s",
1055                                     texp))
1056                     return false;
1057             } else {
1058                 compile_error(ast_ctx(self),
1059                               "piped variadic argument may differ in type: expected type %s",
1060                               texp);
1061                 return false;
1062             }
1063         }
1064     }
1065     return true;
1066 }
1067
1068 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1069 {
1070     char texp[1024];
1071     char tgot[1024];
1072     size_t i;
1073     bool   retval = true;
1074     const  ast_expression *func = self->func;
1075     size_t count = vec_size(self->params);
1076     if (count > vec_size(func->params))
1077         count = vec_size(func->params);
1078
1079     for (i = 0; i < count; ++i) {
1080         if (ast_istype(self->params[i], ast_argpipe)) {
1081             /* warn about type safety instead */
1082             if (i+1 != count) {
1083                 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1084                 return false;
1085             }
1086             if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1087                 retval = false;
1088         }
1089         else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1090         {
1091             ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1092             ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1093             compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1094                      (unsigned int)(i+1), texp, tgot);
1095             /* we don't immediately return */
1096             retval = false;
1097         }
1098     }
1099     count = vec_size(self->params);
1100     if (count > vec_size(func->params) && func->varparam) {
1101         for (; i < count; ++i) {
1102             if (ast_istype(self->params[i], ast_argpipe)) {
1103                 /* warn about type safety instead */
1104                 if (i+1 != count) {
1105                     compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1106                     return false;
1107                 }
1108                 if (!ast_call_check_vararg(self, va_type, func->varparam))
1109                     retval = false;
1110             }
1111             else if (!ast_compare_type(self->params[i], func->varparam))
1112             {
1113                 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1114                 ast_type_to_string(func->varparam, texp, sizeof(texp));
1115                 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1116                          (unsigned int)(i+1), texp, tgot);
1117                 /* we don't immediately return */
1118                 retval = false;
1119             }
1120         }
1121     }
1122     return retval;
1123 }
1124
1125 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1126                          ast_expression *dest, ast_expression *source)
1127 {
1128     ast_instantiate(ast_store, ctx, ast_store_delete, ast_store_next_child);
1129     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1130
1131     ast_side_effects(self) = true;
1132
1133     self->op = op;
1134     self->dest = dest;
1135     self->source = source;
1136
1137     ast_type_adopt(self, dest);
1138
1139     return self;
1140 }
1141
1142 void ast_store_delete(ast_store *self)
1143 {
1144     ast_unref(self->dest);
1145     ast_unref(self->source);
1146     ast_expression_delete((ast_expression*)self);
1147     mem_d(self);
1148 }
1149
1150 ast_block* ast_block_new(lex_ctx_t ctx)
1151 {
1152     ast_instantiate(ast_block, ctx, ast_block_delete, ast_block_next_child);
1153     ast_expression_init((ast_expression*)self,
1154                         (ast_expression_codegen*)&ast_block_codegen);
1155
1156     self->locals  = NULL;
1157     self->exprs   = NULL;
1158     self->collect = NULL;
1159
1160     return self;
1161 }
1162
1163 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1164 {
1165     ast_propagate_effects(self, e);
1166     vec_push(self->exprs, e);
1167     if (self->expression.next) {
1168         ast_delete(self->expression.next);
1169         self->expression.next = NULL;
1170     }
1171     ast_type_adopt(self, e);
1172     return true;
1173 }
1174
1175 void ast_block_collect(ast_block *self, ast_expression *expr)
1176 {
1177     vec_push(self->collect, expr);
1178     expr->node.keep = true;
1179 }
1180
1181 void ast_block_delete(ast_block *self)
1182 {
1183     size_t i;
1184     for (i = 0; i < vec_size(self->exprs); ++i)
1185         ast_unref(self->exprs[i]);
1186     vec_free(self->exprs);
1187     for (i = 0; i < vec_size(self->locals); ++i)
1188         ast_delete(self->locals[i]);
1189     vec_free(self->locals);
1190     for (i = 0; i < vec_size(self->collect); ++i)
1191         ast_delete(self->collect[i]);
1192     vec_free(self->collect);
1193     ast_expression_delete((ast_expression*)self);
1194     mem_d(self);
1195 }
1196
1197 void ast_block_set_type(ast_block *self, ast_expression *from)
1198 {
1199     if (self->expression.next)
1200         ast_delete(self->expression.next);
1201     ast_type_adopt(self, from);
1202 }
1203
1204 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1205 {
1206     ast_instantiate(ast_function, ctx, ast_function_delete, ast_function_next_child);
1207
1208     if (!vtype) {
1209         compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1210         goto cleanup;
1211     } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1212     } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1213         compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1214                  (int)!vtype,
1215                  (int)vtype->hasvalue,
1216                  vtype->expression.vtype);
1217         goto cleanup;
1218     }
1219
1220     self->vtype  = vtype;
1221     self->name   = name ? util_strdup(name) : NULL;
1222     self->blocks = NULL;
1223
1224     self->labelcount = 0;
1225     self->builtin = 0;
1226
1227     self->ir_func = NULL;
1228     self->curblock = NULL;
1229
1230     self->breakblocks    = NULL;
1231     self->continueblocks = NULL;
1232
1233     vtype->hasvalue = true;
1234     vtype->constval.vfunc = self;
1235
1236     self->varargs          = NULL;
1237     self->argc             = NULL;
1238     self->fixedparams      = NULL;
1239     self->return_value     = NULL;
1240
1241     return self;
1242
1243 cleanup:
1244     mem_d(self);
1245     return NULL;
1246 }
1247
1248 void ast_function_delete(ast_function *self)
1249 {
1250     size_t i;
1251     if (self->name)
1252         mem_d((void*)self->name);
1253     if (self->vtype) {
1254         /* ast_value_delete(self->vtype); */
1255         self->vtype->hasvalue = false;
1256         self->vtype->constval.vfunc = NULL;
1257         /* We use unref - if it was stored in a global table it is supposed
1258          * to be deleted from *there*
1259          */
1260         ast_unref(self->vtype);
1261     }
1262     for (i = 0; i < vec_size(self->blocks); ++i)
1263         ast_delete(self->blocks[i]);
1264     vec_free(self->blocks);
1265     vec_free(self->breakblocks);
1266     vec_free(self->continueblocks);
1267     if (self->varargs)
1268         ast_delete(self->varargs);
1269     if (self->argc)
1270         ast_delete(self->argc);
1271     if (self->fixedparams)
1272         ast_unref(self->fixedparams);
1273     if (self->return_value)
1274         ast_unref(self->return_value);
1275     mem_d(self);
1276 }
1277
1278 const char* ast_function_label(ast_function *self, const char *prefix)
1279 {
1280     size_t id;
1281     size_t len;
1282     char  *from;
1283
1284     if (!OPTS_OPTION_BOOL(OPTION_DUMP)    &&
1285         !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1286         !OPTS_OPTION_BOOL(OPTION_DEBUG))
1287     {
1288         return NULL;
1289     }
1290
1291     id  = (self->labelcount++);
1292     len = strlen(prefix);
1293
1294     from = self->labelbuf + sizeof(self->labelbuf)-1;
1295     *from-- = 0;
1296     do {
1297         *from-- = (id%10) + '0';
1298         id /= 10;
1299     } while (id);
1300     ++from;
1301     memcpy(from - len, prefix, len);
1302     return from - len;
1303 }
1304
1305 /*********************************************************************/
1306 /* AST codegen part
1307  * by convention you must never pass NULL to the 'ir_value **out'
1308  * parameter. If you really don't care about the output, pass a dummy.
1309  * But I can't imagine a pituation where the output is truly unnecessary.
1310  */
1311
1312 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1313 {
1314     if (out->vtype == TYPE_FIELD)
1315         out->fieldtype = self->next->vtype;
1316     if (out->vtype == TYPE_FUNCTION)
1317         out->outtype = self->next->vtype;
1318 }
1319
1320 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1321
1322 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1323 {
1324     (void)func;
1325     (void)lvalue;
1326     if (self->expression.vtype == TYPE_NIL) {
1327         *out = func->ir_func->owner->nil;
1328         return true;
1329     }
1330     /* NOTE: This is the codegen for a variable used in an expression.
1331      * It is not the codegen to generate the value. For this purpose,
1332      * ast_local_codegen and ast_global_codegen are to be used before this
1333      * is executed. ast_function_codegen should take care of its locals,
1334      * and the ast-user should take care of ast_global_codegen to be used
1335      * on all the globals.
1336      */
1337     if (!self->ir_v) {
1338         char tname[1024]; /* typename is reserved in C++ */
1339         ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1340         compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1341         return false;
1342     }
1343     *out = self->ir_v;
1344     return true;
1345 }
1346
1347 static bool ast_global_array_set(ast_value *self)
1348 {
1349     size_t count = vec_size(self->initlist);
1350     size_t i;
1351
1352     if (count > self->expression.count) {
1353         compile_error(ast_ctx(self), "too many elements in initializer");
1354         count = self->expression.count;
1355     }
1356     else if (count < self->expression.count) {
1357         /* add this?
1358         compile_warning(ast_ctx(self), "not all elements are initialized");
1359         */
1360     }
1361
1362     for (i = 0; i != count; ++i) {
1363         switch (self->expression.next->vtype) {
1364             case TYPE_FLOAT:
1365                 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1366                     return false;
1367                 break;
1368             case TYPE_VECTOR:
1369                 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1370                     return false;
1371                 break;
1372             case TYPE_STRING:
1373                 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1374                     return false;
1375                 break;
1376             case TYPE_ARRAY:
1377                 /* we don't support them in any other place yet either */
1378                 compile_error(ast_ctx(self), "TODO: nested arrays");
1379                 return false;
1380             case TYPE_FUNCTION:
1381                 /* this requiers a bit more work - similar to the fields I suppose */
1382                 compile_error(ast_ctx(self), "global of type function not properly generated");
1383                 return false;
1384             case TYPE_FIELD:
1385                 if (!self->initlist[i].vfield) {
1386                     compile_error(ast_ctx(self), "field constant without vfield set");
1387                     return false;
1388                 }
1389                 if (!self->initlist[i].vfield->ir_v) {
1390                     compile_error(ast_ctx(self), "field constant generated before its field");
1391                     return false;
1392                 }
1393                 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1394                     return false;
1395                 break;
1396             default:
1397                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1398                 break;
1399         }
1400     }
1401     return true;
1402 }
1403
1404 static bool check_array(ast_value *self, ast_value *array)
1405 {
1406     if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1407         compile_error(ast_ctx(self), "array without size: %s", self->name);
1408         return false;
1409     }
1410     /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1411     if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1412         compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1413         return false;
1414     }
1415     return true;
1416 }
1417
1418 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1419 {
1420     ir_value *v = NULL;
1421
1422     if (self->expression.vtype == TYPE_NIL) {
1423         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1424         return false;
1425     }
1426
1427     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1428     {
1429         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1430         if (!func)
1431             return false;
1432         func->context = ast_ctx(self);
1433         func->value->context = ast_ctx(self);
1434
1435         self->constval.vfunc->ir_func = func;
1436         self->ir_v = func->value;
1437         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1438             self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1439         if (self->expression.flags & AST_FLAG_ERASEABLE)
1440             self->ir_v->flags |= IR_FLAG_ERASEABLE;
1441         /* The function is filled later on ast_function_codegen... */
1442         return true;
1443     }
1444
1445     if (isfield && self->expression.vtype == TYPE_FIELD) {
1446         ast_expression *fieldtype = self->expression.next;
1447
1448         if (self->hasvalue) {
1449             compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1450             goto error;
1451         }
1452
1453         if (fieldtype->vtype == TYPE_ARRAY) {
1454             size_t ai;
1455             char   *name;
1456             size_t  namelen;
1457
1458             ast_expression *elemtype;
1459             int             vtype;
1460             ast_value      *array = (ast_value*)fieldtype;
1461
1462             if (!ast_istype(fieldtype, ast_value)) {
1463                 compile_error(ast_ctx(self), "internal error: ast_value required");
1464                 return false;
1465             }
1466
1467             if (!check_array(self, array))
1468                 return false;
1469
1470             elemtype = array->expression.next;
1471             vtype = elemtype->vtype;
1472
1473             v = ir_builder_create_field(ir, self->name, vtype);
1474             if (!v) {
1475                 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1476                 return false;
1477             }
1478             v->context = ast_ctx(self);
1479             v->unique_life = true;
1480             v->locked      = true;
1481             array->ir_v = self->ir_v = v;
1482
1483             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1484                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1485             if (self->expression.flags & AST_FLAG_ERASEABLE)
1486                 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1487
1488             namelen = strlen(self->name);
1489             name    = (char*)mem_a(namelen + 16);
1490             util_strncpy(name, self->name, namelen);
1491
1492             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1493             array->ir_values[0] = v;
1494             for (ai = 1; ai < array->expression.count; ++ai) {
1495                 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1496                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1497                 if (!array->ir_values[ai]) {
1498                     mem_d(name);
1499                     compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1500                     return false;
1501                 }
1502                 array->ir_values[ai]->context = ast_ctx(self);
1503                 array->ir_values[ai]->unique_life = true;
1504                 array->ir_values[ai]->locked      = true;
1505                 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1506                     self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1507             }
1508             mem_d(name);
1509         }
1510         else
1511         {
1512             v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1513             if (!v)
1514                 return false;
1515             v->context = ast_ctx(self);
1516             self->ir_v = v;
1517             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1518                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1519
1520             if (self->expression.flags & AST_FLAG_ERASEABLE)
1521                 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1522         }
1523         return true;
1524     }
1525
1526     if (self->expression.vtype == TYPE_ARRAY) {
1527         size_t ai;
1528         char   *name;
1529         size_t  namelen;
1530
1531         ast_expression *elemtype = self->expression.next;
1532         int vtype = elemtype->vtype;
1533
1534         if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1535             compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1536             return false;
1537         }
1538
1539         /* same as with field arrays */
1540         if (!check_array(self, self))
1541             return false;
1542
1543         v = ir_builder_create_global(ir, self->name, vtype);
1544         if (!v) {
1545             compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1546             return false;
1547         }
1548         v->context = ast_ctx(self);
1549         v->unique_life = true;
1550         v->locked      = true;
1551
1552         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1553             v->flags |= IR_FLAG_INCLUDE_DEF;
1554         if (self->expression.flags & AST_FLAG_ERASEABLE)
1555             self->ir_v->flags |= IR_FLAG_ERASEABLE;
1556
1557         namelen = strlen(self->name);
1558         name    = (char*)mem_a(namelen + 16);
1559         util_strncpy(name, self->name, namelen);
1560
1561         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1562         self->ir_values[0] = v;
1563         for (ai = 1; ai < self->expression.count; ++ai) {
1564             util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1565             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1566             if (!self->ir_values[ai]) {
1567                 mem_d(name);
1568                 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1569                 return false;
1570             }
1571             self->ir_values[ai]->context = ast_ctx(self);
1572             self->ir_values[ai]->unique_life = true;
1573             self->ir_values[ai]->locked      = true;
1574             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1575                 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1576         }
1577         mem_d(name);
1578     }
1579     else
1580     {
1581         /* Arrays don't do this since there's no "array" value which spans across the
1582          * whole thing.
1583          */
1584         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1585         if (!v) {
1586             compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1587             return false;
1588         }
1589         codegen_output_type(self, v);
1590         v->context = ast_ctx(self);
1591     }
1592
1593     /* link us to the ir_value */
1594     v->cvq = self->cvq;
1595     self->ir_v = v;
1596
1597     if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1598         self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1599     if (self->expression.flags & AST_FLAG_ERASEABLE)
1600         self->ir_v->flags |= IR_FLAG_ERASEABLE;
1601
1602     /* initialize */
1603     if (self->hasvalue) {
1604         switch (self->expression.vtype)
1605         {
1606             case TYPE_FLOAT:
1607                 if (!ir_value_set_float(v, self->constval.vfloat))
1608                     goto error;
1609                 break;
1610             case TYPE_VECTOR:
1611                 if (!ir_value_set_vector(v, self->constval.vvec))
1612                     goto error;
1613                 break;
1614             case TYPE_STRING:
1615                 if (!ir_value_set_string(v, self->constval.vstring))
1616                     goto error;
1617                 break;
1618             case TYPE_ARRAY:
1619                 ast_global_array_set(self);
1620                 break;
1621             case TYPE_FUNCTION:
1622                 compile_error(ast_ctx(self), "global of type function not properly generated");
1623                 goto error;
1624                 /* Cannot generate an IR value for a function,
1625                  * need a pointer pointing to a function rather.
1626                  */
1627             case TYPE_FIELD:
1628                 if (!self->constval.vfield) {
1629                     compile_error(ast_ctx(self), "field constant without vfield set");
1630                     goto error;
1631                 }
1632                 if (!self->constval.vfield->ir_v) {
1633                     compile_error(ast_ctx(self), "field constant generated before its field");
1634                     goto error;
1635                 }
1636                 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1637                     goto error;
1638                 break;
1639             default:
1640                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1641                 break;
1642         }
1643     }
1644     return true;
1645
1646 error: /* clean up */
1647     if(v) ir_value_delete(v);
1648     return false;
1649 }
1650
1651 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1652 {
1653     ir_value *v = NULL;
1654
1655     if (self->expression.vtype == TYPE_NIL) {
1656         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1657         return false;
1658     }
1659
1660     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1661     {
1662         /* Do we allow local functions? I think not...
1663          * this is NOT a function pointer atm.
1664          */
1665         return false;
1666     }
1667
1668     if (self->expression.vtype == TYPE_ARRAY) {
1669         size_t ai;
1670         char   *name;
1671         size_t  namelen;
1672
1673         ast_expression *elemtype = self->expression.next;
1674         int vtype = elemtype->vtype;
1675
1676         func->flags |= IR_FLAG_HAS_ARRAYS;
1677
1678         if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1679             compile_error(ast_ctx(self), "array-parameters are not supported");
1680             return false;
1681         }
1682
1683         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1684         if (!check_array(self, self))
1685             return false;
1686
1687         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1688         if (!self->ir_values) {
1689             compile_error(ast_ctx(self), "failed to allocate array values");
1690             return false;
1691         }
1692
1693         v = ir_function_create_local(func, self->name, vtype, param);
1694         if (!v) {
1695             compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1696             return false;
1697         }
1698         v->context = ast_ctx(self);
1699         v->unique_life = true;
1700         v->locked      = true;
1701
1702         namelen = strlen(self->name);
1703         name    = (char*)mem_a(namelen + 16);
1704         util_strncpy(name, self->name, namelen);
1705
1706         self->ir_values[0] = v;
1707         for (ai = 1; ai < self->expression.count; ++ai) {
1708             util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1709             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1710             if (!self->ir_values[ai]) {
1711                 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1712                 return false;
1713             }
1714             self->ir_values[ai]->context = ast_ctx(self);
1715             self->ir_values[ai]->unique_life = true;
1716             self->ir_values[ai]->locked      = true;
1717         }
1718         mem_d(name);
1719     }
1720     else
1721     {
1722         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1723         if (!v)
1724             return false;
1725         codegen_output_type(self, v);
1726         v->context = ast_ctx(self);
1727     }
1728
1729     /* A constant local... hmmm...
1730      * I suppose the IR will have to deal with this
1731      */
1732     if (self->hasvalue) {
1733         switch (self->expression.vtype)
1734         {
1735             case TYPE_FLOAT:
1736                 if (!ir_value_set_float(v, self->constval.vfloat))
1737                     goto error;
1738                 break;
1739             case TYPE_VECTOR:
1740                 if (!ir_value_set_vector(v, self->constval.vvec))
1741                     goto error;
1742                 break;
1743             case TYPE_STRING:
1744                 if (!ir_value_set_string(v, self->constval.vstring))
1745                     goto error;
1746                 break;
1747             default:
1748                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1749                 break;
1750         }
1751     }
1752
1753     /* link us to the ir_value */
1754     v->cvq = self->cvq;
1755     self->ir_v = v;
1756
1757     if (!ast_generate_accessors(self, func->owner))
1758         return false;
1759     return true;
1760
1761 error: /* clean up */
1762     ir_value_delete(v);
1763     return false;
1764 }
1765
1766 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1767 {
1768     size_t i;
1769     bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1770     if (!self->setter || !self->getter)
1771         return true;
1772     for (i = 0; i < self->expression.count; ++i) {
1773         if (!self->ir_values) {
1774             compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1775             return false;
1776         }
1777         if (!self->ir_values[i]) {
1778             compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1779             return false;
1780         }
1781         if (self->ir_values[i]->life) {
1782             compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1783             return false;
1784         }
1785     }
1786
1787     opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1788     if (self->setter) {
1789         if (!ast_global_codegen  (self->setter, ir, false) ||
1790             !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1791             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1792         {
1793             compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1794             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1795             return false;
1796         }
1797     }
1798     if (self->getter) {
1799         if (!ast_global_codegen  (self->getter, ir, false) ||
1800             !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1801             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1802         {
1803             compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1804             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1805             return false;
1806         }
1807     }
1808     for (i = 0; i < self->expression.count; ++i) {
1809         vec_free(self->ir_values[i]->life);
1810     }
1811     opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1812     return true;
1813 }
1814
1815 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1816 {
1817     ir_function *irf;
1818     ir_value    *dummy;
1819     ast_expression         *ec;
1820     ast_expression_codegen *cgen;
1821
1822     size_t    i;
1823
1824     (void)ir;
1825
1826     irf = self->ir_func;
1827     if (!irf) {
1828         compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1829         return false;
1830     }
1831
1832     /* fill the parameter list */
1833     ec = &self->vtype->expression;
1834     for (i = 0; i < vec_size(ec->params); ++i)
1835     {
1836         if (ec->params[i]->expression.vtype == TYPE_FIELD)
1837             vec_push(irf->params, ec->params[i]->expression.next->vtype);
1838         else
1839             vec_push(irf->params, ec->params[i]->expression.vtype);
1840         if (!self->builtin) {
1841             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1842                 return false;
1843         }
1844     }
1845
1846     if (self->varargs) {
1847         if (!ast_local_codegen(self->varargs, self->ir_func, true))
1848             return false;
1849         irf->max_varargs = self->varargs->expression.count;
1850     }
1851
1852     if (self->builtin) {
1853         irf->builtin = self->builtin;
1854         return true;
1855     }
1856
1857     /* have a local return value variable? */
1858     if (self->return_value) {
1859         if (!ast_local_codegen(self->return_value, self->ir_func, false))
1860             return false;
1861     }
1862
1863     if (!vec_size(self->blocks)) {
1864         compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1865         return false;
1866     }
1867
1868     irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1869     if (!self->curblock) {
1870         compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1871         return false;
1872     }
1873
1874     if (self->argc) {
1875         ir_value *va_count;
1876         ir_value *fixed;
1877         ir_value *sub;
1878         if (!ast_local_codegen(self->argc, self->ir_func, true))
1879             return false;
1880         cgen = self->argc->expression.codegen;
1881         if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1882             return false;
1883         cgen = self->fixedparams->expression.codegen;
1884         if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1885             return false;
1886         sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1887                                     ast_function_label(self, "va_count"), INSTR_SUB_F,
1888                                     ir_builder_get_va_count(ir), fixed);
1889         if (!sub)
1890             return false;
1891         if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1892                                       va_count, sub))
1893         {
1894             return false;
1895         }
1896     }
1897
1898     for (i = 0; i < vec_size(self->blocks); ++i) {
1899         cgen = self->blocks[i]->expression.codegen;
1900         if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1901             return false;
1902     }
1903
1904     /* TODO: check return types */
1905     if (!self->curblock->final)
1906     {
1907         if (!self->vtype->expression.next ||
1908             self->vtype->expression.next->vtype == TYPE_VOID)
1909         {
1910             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1911         }
1912         else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1913         {
1914             if (self->return_value) {
1915                 cgen = self->return_value->expression.codegen;
1916                 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1917                     return false;
1918                 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1919             }
1920             else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1921                                 "control reaches end of non-void function (`%s`) via %s",
1922                                 self->name, self->curblock->label))
1923             {
1924                 return false;
1925             }
1926             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1927         }
1928     }
1929     return true;
1930 }
1931
1932 static bool starts_a_label(ast_expression *ex)
1933 {
1934     while (ex && ast_istype(ex, ast_block)) {
1935         ast_block *b = (ast_block*)ex;
1936         ex = b->exprs[0];
1937     }
1938     if (!ex)
1939         return false;
1940     return ast_istype(ex, ast_label);
1941 }
1942
1943 /* Note, you will not see ast_block_codegen generate ir_blocks.
1944  * To the AST and the IR, blocks are 2 different things.
1945  * In the AST it represents a block of code, usually enclosed in
1946  * curly braces {...}.
1947  * While in the IR it represents a block in terms of control-flow.
1948  */
1949 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1950 {
1951     size_t i;
1952
1953     /* We don't use this
1954      * Note: an ast-representation using the comma-operator
1955      * of the form: (a, b, c) = x should not assign to c...
1956      */
1957     if (lvalue) {
1958         compile_error(ast_ctx(self), "not an l-value (code-block)");
1959         return false;
1960     }
1961
1962     if (self->expression.outr) {
1963         *out = self->expression.outr;
1964         return true;
1965     }
1966
1967     /* output is NULL at first, we'll have each expression
1968      * assign to out output, thus, a comma-operator represention
1969      * using an ast_block will return the last generated value,
1970      * so: (b, c) + a  executed both b and c, and returns c,
1971      * which is then added to a.
1972      */
1973     *out = NULL;
1974
1975     /* generate locals */
1976     for (i = 0; i < vec_size(self->locals); ++i)
1977     {
1978         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1979             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1980                 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1981             return false;
1982         }
1983     }
1984
1985     for (i = 0; i < vec_size(self->exprs); ++i)
1986     {
1987         ast_expression_codegen *gen;
1988         if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1989             if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1990                 return false;
1991             continue;
1992         }
1993         gen = self->exprs[i]->codegen;
1994         if (!(*gen)(self->exprs[i], func, false, out))
1995             return false;
1996     }
1997
1998     self->expression.outr = *out;
1999
2000     return true;
2001 }
2002
2003 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
2004 {
2005     ast_expression_codegen *cgen;
2006     ir_value *left  = NULL;
2007     ir_value *right = NULL;
2008
2009     ast_value       *arr;
2010     ast_value       *idx = 0;
2011     ast_array_index *ai = NULL;
2012
2013     if (lvalue && self->expression.outl) {
2014         *out = self->expression.outl;
2015         return true;
2016     }
2017
2018     if (!lvalue && self->expression.outr) {
2019         *out = self->expression.outr;
2020         return true;
2021     }
2022
2023     if (ast_istype(self->dest, ast_array_index))
2024     {
2025
2026         ai = (ast_array_index*)self->dest;
2027         idx = (ast_value*)ai->index;
2028
2029         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2030             ai = NULL;
2031     }
2032
2033     if (ai) {
2034         /* we need to call the setter */
2035         ir_value  *iridx, *funval;
2036         ir_instr  *call;
2037
2038         if (lvalue) {
2039             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2040             return false;
2041         }
2042
2043         arr = (ast_value*)ai->array;
2044         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2045             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2046             return false;
2047         }
2048
2049         cgen = idx->expression.codegen;
2050         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2051             return false;
2052
2053         cgen = arr->setter->expression.codegen;
2054         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2055             return false;
2056
2057         cgen = self->source->codegen;
2058         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2059             return false;
2060
2061         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2062         if (!call)
2063             return false;
2064         ir_call_param(call, iridx);
2065         ir_call_param(call, right);
2066         self->expression.outr = right;
2067     }
2068     else
2069     {
2070         /* regular code */
2071
2072         cgen = self->dest->codegen;
2073         /* lvalue! */
2074         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2075             return false;
2076         self->expression.outl = left;
2077
2078         cgen = self->source->codegen;
2079         /* rvalue! */
2080         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2081             return false;
2082
2083         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2084             return false;
2085         self->expression.outr = right;
2086     }
2087
2088     /* Theoretically, an assinment returns its left side as an
2089      * lvalue, if we don't need an lvalue though, we return
2090      * the right side as an rvalue, otherwise we have to
2091      * somehow know whether or not we need to dereference the pointer
2092      * on the left side - that is: OP_LOAD if it was an address.
2093      * Also: in original QC we cannot OP_LOADP *anyway*.
2094      */
2095     *out = (lvalue ? left : right);
2096
2097     return true;
2098 }
2099
2100 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2101 {
2102     ast_expression_codegen *cgen;
2103     ir_value *left, *right;
2104
2105     /* A binary operation cannot yield an l-value */
2106     if (lvalue) {
2107         compile_error(ast_ctx(self), "not an l-value (binop)");
2108         return false;
2109     }
2110
2111     if (self->expression.outr) {
2112         *out = self->expression.outr;
2113         return true;
2114     }
2115
2116     if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2117         (self->op == INSTR_AND || self->op == INSTR_OR))
2118     {
2119         /* NOTE: The short-logic path will ignore right_first */
2120
2121         /* short circuit evaluation */
2122         ir_block *other, *merge;
2123         ir_block *from_left, *from_right;
2124         ir_instr *phi;
2125         size_t    merge_id;
2126
2127         /* prepare end-block */
2128         merge_id = vec_size(func->ir_func->blocks);
2129         merge    = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2130
2131         /* generate the left expression */
2132         cgen = self->left->codegen;
2133         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2134             return false;
2135         /* remember the block */
2136         from_left = func->curblock;
2137
2138         /* create a new block for the right expression */
2139         other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2140         if (self->op == INSTR_AND) {
2141             /* on AND: left==true -> other */
2142             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2143                 return false;
2144         } else {
2145             /* on OR: left==false -> other */
2146             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2147                 return false;
2148         }
2149         /* use the likely flag */
2150         vec_last(func->curblock->instr)->likely = true;
2151
2152         /* enter the right-expression's block */
2153         func->curblock = other;
2154         /* generate */
2155         cgen = self->right->codegen;
2156         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2157             return false;
2158         /* remember block */
2159         from_right = func->curblock;
2160
2161         /* jump to the merge block */
2162         if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2163             return false;
2164
2165         vec_remove(func->ir_func->blocks, merge_id, 1);
2166         vec_push(func->ir_func->blocks, merge);
2167
2168         func->curblock = merge;
2169         phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2170                                   ast_function_label(func, "sce_value"),
2171                                   self->expression.vtype);
2172         ir_phi_add(phi, from_left, left);
2173         ir_phi_add(phi, from_right, right);
2174         *out = ir_phi_value(phi);
2175         if (!*out)
2176             return false;
2177
2178         if (!OPTS_FLAG(PERL_LOGIC)) {
2179             /* cast-to-bool */
2180             if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2181                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2182                                              ast_function_label(func, "sce_bool_v"),
2183                                              INSTR_NOT_V, *out);
2184                 if (!*out)
2185                     return false;
2186                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2187                                              ast_function_label(func, "sce_bool"),
2188                                              INSTR_NOT_F, *out);
2189                 if (!*out)
2190                     return false;
2191             }
2192             else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2193                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2194                                              ast_function_label(func, "sce_bool_s"),
2195                                              INSTR_NOT_S, *out);
2196                 if (!*out)
2197                     return false;
2198                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2199                                              ast_function_label(func, "sce_bool"),
2200                                              INSTR_NOT_F, *out);
2201                 if (!*out)
2202                     return false;
2203             }
2204             else {
2205                 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2206                                              ast_function_label(func, "sce_bool"),
2207                                              INSTR_AND, *out, *out);
2208                 if (!*out)
2209                     return false;
2210             }
2211         }
2212
2213         self->expression.outr = *out;
2214         codegen_output_type(self, *out);
2215         return true;
2216     }
2217
2218     if (self->right_first) {
2219         cgen = self->right->codegen;
2220         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2221             return false;
2222         cgen = self->left->codegen;
2223         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2224             return false;
2225     } else {
2226         cgen = self->left->codegen;
2227         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2228             return false;
2229         cgen = self->right->codegen;
2230         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2231             return false;
2232     }
2233
2234     *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2235                                  self->op, left, right);
2236     if (!*out)
2237         return false;
2238     self->expression.outr = *out;
2239     codegen_output_type(self, *out);
2240
2241     return true;
2242 }
2243
2244 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2245 {
2246     ast_expression_codegen *cgen;
2247     ir_value *leftl = NULL, *leftr, *right, *bin;
2248
2249     ast_value       *arr;
2250     ast_value       *idx = 0;
2251     ast_array_index *ai = NULL;
2252     ir_value        *iridx = NULL;
2253
2254     if (lvalue && self->expression.outl) {
2255         *out = self->expression.outl;
2256         return true;
2257     }
2258
2259     if (!lvalue && self->expression.outr) {
2260         *out = self->expression.outr;
2261         return true;
2262     }
2263
2264     if (ast_istype(self->dest, ast_array_index))
2265     {
2266
2267         ai = (ast_array_index*)self->dest;
2268         idx = (ast_value*)ai->index;
2269
2270         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2271             ai = NULL;
2272     }
2273
2274     /* for a binstore we need both an lvalue and an rvalue for the left side */
2275     /* rvalue of destination! */
2276     if (ai) {
2277         cgen = idx->expression.codegen;
2278         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2279             return false;
2280     }
2281     cgen = self->dest->codegen;
2282     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2283         return false;
2284
2285     /* source as rvalue only */
2286     cgen = self->source->codegen;
2287     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2288         return false;
2289
2290     /* now the binary */
2291     bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2292                                 self->opbin, leftr, right);
2293     self->expression.outr = bin;
2294
2295
2296     if (ai) {
2297         /* we need to call the setter */
2298         ir_value  *funval;
2299         ir_instr  *call;
2300
2301         if (lvalue) {
2302             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2303             return false;
2304         }
2305
2306         arr = (ast_value*)ai->array;
2307         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2308             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2309             return false;
2310         }
2311
2312         cgen = arr->setter->expression.codegen;
2313         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2314             return false;
2315
2316         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2317         if (!call)
2318             return false;
2319         ir_call_param(call, iridx);
2320         ir_call_param(call, bin);
2321         self->expression.outr = bin;
2322     } else {
2323         /* now store them */
2324         cgen = self->dest->codegen;
2325         /* lvalue of destination */
2326         if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2327             return false;
2328         self->expression.outl = leftl;
2329
2330         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2331             return false;
2332         self->expression.outr = bin;
2333     }
2334
2335     /* Theoretically, an assinment returns its left side as an
2336      * lvalue, if we don't need an lvalue though, we return
2337      * the right side as an rvalue, otherwise we have to
2338      * somehow know whether or not we need to dereference the pointer
2339      * on the left side - that is: OP_LOAD if it was an address.
2340      * Also: in original QC we cannot OP_LOADP *anyway*.
2341      */
2342     *out = (lvalue ? leftl : bin);
2343
2344     return true;
2345 }
2346
2347 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2348 {
2349     ast_expression_codegen *cgen;
2350     ir_value *operand;
2351
2352     /* An unary operation cannot yield an l-value */
2353     if (lvalue) {
2354         compile_error(ast_ctx(self), "not an l-value (binop)");
2355         return false;
2356     }
2357
2358     if (self->expression.outr) {
2359         *out = self->expression.outr;
2360         return true;
2361     }
2362
2363     cgen = self->operand->codegen;
2364     /* lvalue! */
2365     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2366         return false;
2367
2368     *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2369                                  self->op, operand);
2370     if (!*out)
2371         return false;
2372     self->expression.outr = *out;
2373
2374     return true;
2375 }
2376
2377 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2378 {
2379     ast_expression_codegen *cgen;
2380     ir_value *operand;
2381
2382     *out = NULL;
2383
2384     /* In the context of a return operation, we don't actually return
2385      * anything...
2386      */
2387     if (lvalue) {
2388         compile_error(ast_ctx(self), "return-expression is not an l-value");
2389         return false;
2390     }
2391
2392     if (self->expression.outr) {
2393         compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2394         return false;
2395     }
2396     self->expression.outr = (ir_value*)1;
2397
2398     if (self->operand) {
2399         cgen = self->operand->codegen;
2400         /* lvalue! */
2401         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2402             return false;
2403
2404         if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2405             return false;
2406     } else {
2407         if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2408             return false;
2409     }
2410
2411     return true;
2412 }
2413
2414 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2415 {
2416     ast_expression_codegen *cgen;
2417     ir_value *ent, *field;
2418
2419     /* This function needs to take the 'lvalue' flag into account!
2420      * As lvalue we provide a field-pointer, as rvalue we provide the
2421      * value in a temp.
2422      */
2423
2424     if (lvalue && self->expression.outl) {
2425         *out = self->expression.outl;
2426         return true;
2427     }
2428
2429     if (!lvalue && self->expression.outr) {
2430         *out = self->expression.outr;
2431         return true;
2432     }
2433
2434     cgen = self->entity->codegen;
2435     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2436         return false;
2437
2438     cgen = self->field->codegen;
2439     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2440         return false;
2441
2442     if (lvalue) {
2443         /* address! */
2444         *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2445                                             ent, field);
2446     } else {
2447         *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2448                                              ent, field, self->expression.vtype);
2449         /* Done AFTER error checking:
2450         codegen_output_type(self, *out);
2451         */
2452     }
2453     if (!*out) {
2454         compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2455                  (lvalue ? "ADDRESS" : "FIELD"),
2456                  type_name[self->expression.vtype]);
2457         return false;
2458     }
2459     if (!lvalue)
2460         codegen_output_type(self, *out);
2461
2462     if (lvalue)
2463         self->expression.outl = *out;
2464     else
2465         self->expression.outr = *out;
2466
2467     /* Hm that should be it... */
2468     return true;
2469 }
2470
2471 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2472 {
2473     ast_expression_codegen *cgen;
2474     ir_value *vec;
2475
2476     /* in QC this is always an lvalue */
2477     if (lvalue && self->rvalue) {
2478         compile_error(ast_ctx(self), "not an l-value (member access)");
2479         return false;
2480     }
2481     if (self->expression.outl) {
2482         *out = self->expression.outl;
2483         return true;
2484     }
2485
2486     cgen = self->owner->codegen;
2487     if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2488         return false;
2489
2490     if (vec->vtype != TYPE_VECTOR &&
2491         !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2492     {
2493         return false;
2494     }
2495
2496     *out = ir_value_vector_member(vec, self->field);
2497     self->expression.outl = *out;
2498
2499     return (*out != NULL);
2500 }
2501
2502 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2503 {
2504     ast_value *arr;
2505     ast_value *idx;
2506
2507     if (!lvalue && self->expression.outr) {
2508         *out = self->expression.outr;
2509         return true;
2510     }
2511     if (lvalue && self->expression.outl) {
2512         *out = self->expression.outl;
2513         return true;
2514     }
2515
2516     if (!ast_istype(self->array, ast_value)) {
2517         compile_error(ast_ctx(self), "array indexing this way is not supported");
2518         /* note this would actually be pointer indexing because the left side is
2519          * not an actual array but (hopefully) an indexable expression.
2520          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2521          * support this path will be filled.
2522          */
2523         return false;
2524     }
2525
2526     arr = (ast_value*)self->array;
2527     idx = (ast_value*)self->index;
2528
2529     if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2530         /* Time to use accessor functions */
2531         ast_expression_codegen *cgen;
2532         ir_value               *iridx, *funval;
2533         ir_instr               *call;
2534
2535         if (lvalue) {
2536             compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2537             return false;
2538         }
2539
2540         if (!arr->getter) {
2541             compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2542             return false;
2543         }
2544
2545         cgen = self->index->codegen;
2546         if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2547             return false;
2548
2549         cgen = arr->getter->expression.codegen;
2550         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2551             return false;
2552
2553         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2554         if (!call)
2555             return false;
2556         ir_call_param(call, iridx);
2557
2558         *out = ir_call_value(call);
2559         self->expression.outr = *out;
2560         (*out)->vtype = self->expression.vtype;
2561         codegen_output_type(self, *out);
2562         return true;
2563     }
2564
2565     if (idx->expression.vtype == TYPE_FLOAT) {
2566         unsigned int arridx = idx->constval.vfloat;
2567         if (arridx >= self->array->count)
2568         {
2569             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2570             return false;
2571         }
2572         *out = arr->ir_values[arridx];
2573     }
2574     else if (idx->expression.vtype == TYPE_INTEGER) {
2575         unsigned int arridx = idx->constval.vint;
2576         if (arridx >= self->array->count)
2577         {
2578             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2579             return false;
2580         }
2581         *out = arr->ir_values[arridx];
2582     }
2583     else {
2584         compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2585         return false;
2586     }
2587     (*out)->vtype = self->expression.vtype;
2588     codegen_output_type(self, *out);
2589     return true;
2590 }
2591
2592 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2593 {
2594     *out = NULL;
2595     if (lvalue) {
2596         compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2597         return false;
2598     }
2599     (void)func;
2600     (void)out;
2601     compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2602     return false;
2603 }
2604
2605 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2606 {
2607     ast_expression_codegen *cgen;
2608
2609     ir_value *condval;
2610     ir_value *dummy;
2611
2612     ir_block *cond;
2613     ir_block *ontrue;
2614     ir_block *onfalse;
2615     ir_block *ontrue_endblock = NULL;
2616     ir_block *onfalse_endblock = NULL;
2617     ir_block *merge = NULL;
2618     int       fold  = 0;
2619
2620     /* We don't output any value, thus also don't care about r/lvalue */
2621     (void)out;
2622     (void)lvalue;
2623
2624     if (self->expression.outr) {
2625         compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2626         return false;
2627     }
2628     self->expression.outr = (ir_value*)1;
2629
2630     /* generate the condition */
2631     cgen = self->cond->codegen;
2632     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2633         return false;
2634     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2635     cond = func->curblock;
2636
2637     /* try constant folding away the condition */
2638     if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2639         return fold;
2640
2641     if (self->on_true) {
2642         /* create on-true block */
2643         ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2644         if (!ontrue)
2645             return false;
2646
2647         /* enter the block */
2648         func->curblock = ontrue;
2649
2650         /* generate */
2651         cgen = self->on_true->codegen;
2652         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2653             return false;
2654
2655         /* we now need to work from the current endpoint */
2656         ontrue_endblock = func->curblock;
2657     } else
2658         ontrue = NULL;
2659
2660     /* on-false path */
2661     if (self->on_false) {
2662         /* create on-false block */
2663         onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2664         if (!onfalse)
2665             return false;
2666
2667         /* enter the block */
2668         func->curblock = onfalse;
2669
2670         /* generate */
2671         cgen = self->on_false->codegen;
2672         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2673             return false;
2674
2675         /* we now need to work from the current endpoint */
2676         onfalse_endblock = func->curblock;
2677     } else
2678         onfalse = NULL;
2679
2680     /* Merge block were they all merge in to */
2681     if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2682     {
2683         merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2684         if (!merge)
2685             return false;
2686         /* add jumps ot the merge block */
2687         if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2688             return false;
2689         if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2690             return false;
2691
2692         /* Now enter the merge block */
2693         func->curblock = merge;
2694     }
2695
2696     /* we create the if here, that way all blocks are ordered :)
2697      */
2698     if (!ir_block_create_if(cond, ast_ctx(self), condval,
2699                             (ontrue  ? ontrue  : merge),
2700                             (onfalse ? onfalse : merge)))
2701     {
2702         return false;
2703     }
2704
2705     return true;
2706 }
2707
2708 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2709 {
2710     ast_expression_codegen *cgen;
2711
2712     ir_value *condval;
2713     ir_value *trueval, *falseval;
2714     ir_instr *phi;
2715
2716     ir_block *cond = func->curblock;
2717     ir_block *cond_out = NULL;
2718     ir_block *ontrue, *ontrue_out = NULL;
2719     ir_block *onfalse, *onfalse_out = NULL;
2720     ir_block *merge;
2721     int       fold  = 0;
2722
2723     /* Ternary can never create an lvalue... */
2724     if (lvalue)
2725         return false;
2726
2727     /* In theory it shouldn't be possible to pass through a node twice, but
2728      * in case we add any kind of optimization pass for the AST itself, it
2729      * may still happen, thus we remember a created ir_value and simply return one
2730      * if it already exists.
2731      */
2732     if (self->expression.outr) {
2733         *out = self->expression.outr;
2734         return true;
2735     }
2736
2737     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2738
2739     /* generate the condition */
2740     func->curblock = cond;
2741     cgen = self->cond->codegen;
2742     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2743         return false;
2744     cond_out = func->curblock;
2745
2746     /* try constant folding away the condition */
2747     if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2748         return fold;
2749
2750     /* create on-true block */
2751     ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2752     if (!ontrue)
2753         return false;
2754     else
2755     {
2756         /* enter the block */
2757         func->curblock = ontrue;
2758
2759         /* generate */
2760         cgen = self->on_true->codegen;
2761         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2762             return false;
2763
2764         ontrue_out = func->curblock;
2765     }
2766
2767     /* create on-false block */
2768     onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2769     if (!onfalse)
2770         return false;
2771     else
2772     {
2773         /* enter the block */
2774         func->curblock = onfalse;
2775
2776         /* generate */
2777         cgen = self->on_false->codegen;
2778         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2779             return false;
2780
2781         onfalse_out = func->curblock;
2782     }
2783
2784     /* create merge block */
2785     merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2786     if (!merge)
2787         return false;
2788     /* jump to merge block */
2789     if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2790         return false;
2791     if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2792         return false;
2793
2794     /* create if instruction */
2795     if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2796         return false;
2797
2798     /* Now enter the merge block */
2799     func->curblock = merge;
2800
2801     /* Here, now, we need a PHI node
2802      * but first some sanity checking...
2803      */
2804     if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2805         /* error("ternary with different types on the two sides"); */
2806         compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2807         return false;
2808     }
2809
2810     /* create PHI */
2811     phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2812     if (!phi) {
2813         compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2814         return false;
2815     }
2816     ir_phi_add(phi, ontrue_out,  trueval);
2817     ir_phi_add(phi, onfalse_out, falseval);
2818
2819     self->expression.outr = ir_phi_value(phi);
2820     *out = self->expression.outr;
2821
2822     codegen_output_type(self, *out);
2823
2824     return true;
2825 }
2826
2827 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2828 {
2829     ast_expression_codegen *cgen;
2830
2831     ir_value *dummy      = NULL;
2832     ir_value *precond    = NULL;
2833     ir_value *postcond   = NULL;
2834
2835     /* Since we insert some jumps "late" so we have blocks
2836      * ordered "nicely", we need to keep track of the actual end-blocks
2837      * of expressions to add the jumps to.
2838      */
2839     ir_block *bbody      = NULL, *end_bbody      = NULL;
2840     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2841     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2842     ir_block *bincrement = NULL, *end_bincrement = NULL;
2843     ir_block *bout       = NULL, *bin            = NULL;
2844
2845     /* let's at least move the outgoing block to the end */
2846     size_t    bout_id;
2847
2848     /* 'break' and 'continue' need to be able to find the right blocks */
2849     ir_block *bcontinue     = NULL;
2850     ir_block *bbreak        = NULL;
2851
2852     ir_block *tmpblock      = NULL;
2853
2854     (void)lvalue;
2855     (void)out;
2856
2857     if (self->expression.outr) {
2858         compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2859         return false;
2860     }
2861     self->expression.outr = (ir_value*)1;
2862
2863     /* NOTE:
2864      * Should we ever need some kind of block ordering, better make this function
2865      * move blocks around than write a block ordering algorithm later... after all
2866      * the ast and ir should work together, not against each other.
2867      */
2868
2869     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2870      * anyway if for example it contains a ternary.
2871      */
2872     if (self->initexpr)
2873     {
2874         cgen = self->initexpr->codegen;
2875         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2876             return false;
2877     }
2878
2879     /* Store the block from which we enter this chaos */
2880     bin = func->curblock;
2881
2882     /* The pre-loop condition needs its own block since we
2883      * need to be able to jump to the start of that expression.
2884      */
2885     if (self->precond)
2886     {
2887         bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2888         if (!bprecond)
2889             return false;
2890
2891         /* the pre-loop-condition the least important place to 'continue' at */
2892         bcontinue = bprecond;
2893
2894         /* enter */
2895         func->curblock = bprecond;
2896
2897         /* generate */
2898         cgen = self->precond->codegen;
2899         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2900             return false;
2901
2902         end_bprecond = func->curblock;
2903     } else {
2904         bprecond = end_bprecond = NULL;
2905     }
2906
2907     /* Now the next blocks won't be ordered nicely, but we need to
2908      * generate them this early for 'break' and 'continue'.
2909      */
2910     if (self->increment) {
2911         bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2912         if (!bincrement)
2913             return false;
2914         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2915     } else {
2916         bincrement = end_bincrement = NULL;
2917     }
2918
2919     if (self->postcond) {
2920         bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2921         if (!bpostcond)
2922             return false;
2923         bcontinue = bpostcond; /* postcond comes before the increment */
2924     } else {
2925         bpostcond = end_bpostcond = NULL;
2926     }
2927
2928     bout_id = vec_size(func->ir_func->blocks);
2929     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2930     if (!bout)
2931         return false;
2932     bbreak = bout;
2933
2934     /* The loop body... */
2935     /* if (self->body) */
2936     {
2937         bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2938         if (!bbody)
2939             return false;
2940
2941         /* enter */
2942         func->curblock = bbody;
2943
2944         vec_push(func->breakblocks,    bbreak);
2945         if (bcontinue)
2946             vec_push(func->continueblocks, bcontinue);
2947         else
2948             vec_push(func->continueblocks, bbody);
2949
2950         /* generate */
2951         if (self->body) {
2952             cgen = self->body->codegen;
2953             if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2954                 return false;
2955         }
2956
2957         end_bbody = func->curblock;
2958         vec_pop(func->breakblocks);
2959         vec_pop(func->continueblocks);
2960     }
2961
2962     /* post-loop-condition */
2963     if (self->postcond)
2964     {
2965         /* enter */
2966         func->curblock = bpostcond;
2967
2968         /* generate */
2969         cgen = self->postcond->codegen;
2970         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2971             return false;
2972
2973         end_bpostcond = func->curblock;
2974     }
2975
2976     /* The incrementor */
2977     if (self->increment)
2978     {
2979         /* enter */
2980         func->curblock = bincrement;
2981
2982         /* generate */
2983         cgen = self->increment->codegen;
2984         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2985             return false;
2986
2987         end_bincrement = func->curblock;
2988     }
2989
2990     /* In any case now, we continue from the outgoing block */
2991     func->curblock = bout;
2992
2993     /* Now all blocks are in place */
2994     /* From 'bin' we jump to whatever comes first */
2995     if      (bprecond)   tmpblock = bprecond;
2996     else                 tmpblock = bbody;    /* can never be null */
2997
2998     /* DEAD CODE
2999     else if (bpostcond)  tmpblock = bpostcond;
3000     else                 tmpblock = bout;
3001     */
3002
3003     if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
3004         return false;
3005
3006     /* From precond */
3007     if (bprecond)
3008     {
3009         ir_block *ontrue, *onfalse;
3010         ontrue = bbody; /* can never be null */
3011
3012         /* all of this is dead code
3013         else if (bincrement) ontrue = bincrement;
3014         else                 ontrue = bpostcond;
3015         */
3016
3017         onfalse = bout;
3018         if (self->pre_not) {
3019             tmpblock = ontrue;
3020             ontrue   = onfalse;
3021             onfalse  = tmpblock;
3022         }
3023         if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3024             return false;
3025     }
3026
3027     /* from body */
3028     if (bbody)
3029     {
3030         if      (bincrement) tmpblock = bincrement;
3031         else if (bpostcond)  tmpblock = bpostcond;
3032         else if (bprecond)   tmpblock = bprecond;
3033         else                 tmpblock = bbody;
3034         if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3035             return false;
3036     }
3037
3038     /* from increment */
3039     if (bincrement)
3040     {
3041         if      (bpostcond)  tmpblock = bpostcond;
3042         else if (bprecond)   tmpblock = bprecond;
3043         else if (bbody)      tmpblock = bbody;
3044         else                 tmpblock = bout;
3045         if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3046             return false;
3047     }
3048
3049     /* from postcond */
3050     if (bpostcond)
3051     {
3052         ir_block *ontrue, *onfalse;
3053         if      (bprecond)   ontrue = bprecond;
3054         else                 ontrue = bbody; /* can never be null */
3055
3056         /* all of this is dead code
3057         else if (bincrement) ontrue = bincrement;
3058         else                 ontrue = bpostcond;
3059         */
3060
3061         onfalse = bout;
3062         if (self->post_not) {
3063             tmpblock = ontrue;
3064             ontrue   = onfalse;
3065             onfalse  = tmpblock;
3066         }
3067         if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3068             return false;
3069     }
3070
3071     /* Move 'bout' to the end */
3072     vec_remove(func->ir_func->blocks, bout_id, 1);
3073     vec_push(func->ir_func->blocks, bout);
3074
3075     return true;
3076 }
3077
3078 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3079 {
3080     ir_block *target;
3081
3082     *out = NULL;
3083
3084     if (lvalue) {
3085         compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3086         return false;
3087     }
3088
3089     if (self->expression.outr) {
3090         compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3091         return false;
3092     }
3093     self->expression.outr = (ir_value*)1;
3094
3095     if (self->is_continue)
3096         target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3097     else
3098         target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3099
3100     if (!target) {
3101         compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3102         return false;
3103     }
3104
3105     if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3106         return false;
3107     return true;
3108 }
3109
3110 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3111 {
3112     ast_expression_codegen *cgen;
3113
3114     ast_switch_case *def_case     = NULL;
3115     ir_block        *def_bfall    = NULL;
3116     ir_block        *def_bfall_to = NULL;
3117     bool set_def_bfall_to = false;
3118
3119     ir_value *dummy     = NULL;
3120     ir_value *irop      = NULL;
3121     ir_block *bout      = NULL;
3122     ir_block *bfall     = NULL;
3123     size_t    bout_id;
3124     size_t    c;
3125
3126     char      typestr[1024];
3127     uint16_t  cmpinstr;
3128
3129     if (lvalue) {
3130         compile_error(ast_ctx(self), "switch expression is not an l-value");
3131         return false;
3132     }
3133
3134     if (self->expression.outr) {
3135         compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3136         return false;
3137     }
3138     self->expression.outr = (ir_value*)1;
3139
3140     (void)lvalue;
3141     (void)out;
3142
3143     cgen = self->operand->codegen;
3144     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3145         return false;
3146
3147     if (!vec_size(self->cases))
3148         return true;
3149
3150     cmpinstr = type_eq_instr[irop->vtype];
3151     if (cmpinstr >= VINSTR_END) {
3152         ast_type_to_string(self->operand, typestr, sizeof(typestr));
3153         compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3154         return false;
3155     }
3156
3157     bout_id = vec_size(func->ir_func->blocks);
3158     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3159     if (!bout)
3160         return false;
3161
3162     /* setup the break block */
3163     vec_push(func->breakblocks, bout);
3164
3165     /* Now create all cases */
3166     for (c = 0; c < vec_size(self->cases); ++c) {
3167         ir_value *cond, *val;
3168         ir_block *bcase, *bnot;
3169         size_t bnot_id;
3170
3171         ast_switch_case *swcase = &self->cases[c];
3172
3173         if (swcase->value) {
3174             /* A regular case */
3175             /* generate the condition operand */
3176             cgen = swcase->value->codegen;
3177             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3178                 return false;
3179             /* generate the condition */
3180             cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3181             if (!cond)
3182                 return false;
3183
3184             bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3185             bnot_id = vec_size(func->ir_func->blocks);
3186             bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3187             if (!bcase || !bnot)
3188                 return false;
3189             if (set_def_bfall_to) {
3190                 set_def_bfall_to = false;
3191                 def_bfall_to = bcase;
3192             }
3193             if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3194                 return false;
3195
3196             /* Make the previous case-end fall through */
3197             if (bfall && !bfall->final) {
3198                 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3199                     return false;
3200             }
3201
3202             /* enter the case */
3203             func->curblock = bcase;
3204             cgen = swcase->code->codegen;
3205             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3206                 return false;
3207
3208             /* remember this block to fall through from */
3209             bfall = func->curblock;
3210
3211             /* enter the else and move it down */
3212             func->curblock = bnot;
3213             vec_remove(func->ir_func->blocks, bnot_id, 1);
3214             vec_push(func->ir_func->blocks, bnot);
3215         } else {
3216             /* The default case */
3217             /* Remember where to fall through from: */
3218             def_bfall = bfall;
3219             bfall     = NULL;
3220             /* remember which case it was */
3221             def_case  = swcase;
3222             /* And the next case will be remembered */
3223             set_def_bfall_to = true;
3224         }
3225     }
3226
3227     /* Jump from the last bnot to bout */
3228     if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3229         /*
3230         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3231         */
3232         return false;
3233     }
3234
3235     /* If there was a default case, put it down here */
3236     if (def_case) {
3237         ir_block *bcase;
3238
3239         /* No need to create an extra block */
3240         bcase = func->curblock;
3241
3242         /* Insert the fallthrough jump */
3243         if (def_bfall && !def_bfall->final) {
3244             if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3245                 return false;
3246         }
3247
3248         /* Now generate the default code */
3249         cgen = def_case->code->codegen;
3250         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3251             return false;
3252
3253         /* see if we need to fall through */
3254         if (def_bfall_to && !func->curblock->final)
3255         {
3256             if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3257                 return false;
3258         }
3259     }
3260
3261     /* Jump from the last bnot to bout */
3262     if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3263         return false;
3264     /* enter the outgoing block */
3265     func->curblock = bout;
3266
3267     /* restore the break block */
3268     vec_pop(func->breakblocks);
3269
3270     /* Move 'bout' to the end, it's nicer */
3271     vec_remove(func->ir_func->blocks, bout_id, 1);
3272     vec_push(func->ir_func->blocks, bout);
3273
3274     return true;
3275 }
3276
3277 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3278 {
3279     size_t i;
3280     ir_value *dummy;
3281
3282     if (self->undefined) {
3283         compile_error(ast_ctx(self), "internal error: ast_label never defined");
3284         return false;
3285     }
3286
3287     *out = NULL;
3288     if (lvalue) {
3289         compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3290         return false;
3291     }
3292
3293     /* simply create a new block and jump to it */
3294     self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3295     if (!self->irblock) {
3296         compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3297         return false;
3298     }
3299     if (!func->curblock->final) {
3300         if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3301             return false;
3302     }
3303
3304     /* enter the new block */
3305     func->curblock = self->irblock;
3306
3307     /* Generate all the leftover gotos */
3308     for (i = 0; i < vec_size(self->gotos); ++i) {
3309         if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3310             return false;
3311     }
3312
3313     return true;
3314 }
3315
3316 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3317 {
3318     *out = NULL;
3319     if (lvalue) {
3320         compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3321         return false;
3322     }
3323
3324     if (self->target->irblock) {
3325         if (self->irblock_from) {
3326             /* we already tried once, this is the callback */
3327             self->irblock_from->final = false;
3328             if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3329                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3330                 return false;
3331             }
3332         }
3333         else
3334         {
3335             if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3336                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3337                 return false;
3338             }
3339         }
3340     }
3341     else
3342     {
3343         /* the target has not yet been created...
3344          * close this block in a sneaky way:
3345          */
3346         func->curblock->final = true;
3347         self->irblock_from = func->curblock;
3348         ast_label_register_goto(self->target, self);
3349     }
3350
3351     return true;
3352 }
3353
3354 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3355 {
3356     ast_expression_codegen *cgen;
3357     ir_value              **params;
3358     ir_instr               *callinstr;
3359     size_t i;
3360
3361     ir_value *funval = NULL;
3362
3363     /* return values are never lvalues */
3364     if (lvalue) {
3365         compile_error(ast_ctx(self), "not an l-value (function call)");
3366         return false;
3367     }
3368
3369     if (self->expression.outr) {
3370         *out = self->expression.outr;
3371         return true;
3372     }
3373
3374     cgen = self->func->codegen;
3375     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3376         return false;
3377     if (!funval)
3378         return false;
3379
3380     params = NULL;
3381
3382     /* parameters */
3383     for (i = 0; i < vec_size(self->params); ++i)
3384     {
3385         ir_value *param;
3386         ast_expression *expr = self->params[i];
3387
3388         cgen = expr->codegen;
3389         if (!(*cgen)(expr, func, false, &param))
3390             goto error;
3391         if (!param)
3392             goto error;
3393         vec_push(params, param);
3394     }
3395
3396     /* varargs counter */
3397     if (self->va_count) {
3398         ir_value   *va_count;
3399         ir_builder *builder = func->curblock->owner->owner;
3400         cgen = self->va_count->codegen;
3401         if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3402             return false;
3403         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3404                                       ir_builder_get_va_count(builder), va_count))
3405         {
3406             return false;
3407         }
3408     }
3409
3410     callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3411                                      ast_function_label(func, "call"),
3412                                      funval, !!(self->func->flags & AST_FLAG_NORETURN));
3413     if (!callinstr)
3414         goto error;
3415
3416     for (i = 0; i < vec_size(params); ++i) {
3417         ir_call_param(callinstr, params[i]);
3418     }
3419
3420     *out = ir_call_value(callinstr);
3421     self->expression.outr = *out;
3422
3423     codegen_output_type(self, *out);
3424
3425     vec_free(params);
3426     return true;
3427 error:
3428     vec_free(params);
3429     return false;
3430 }
3431
3432 /* iterator functions */
3433 static ast_node* ast_member_next_child(ast_member *self, ast_node *cur) {
3434     (void)self; (void)cur;
3435     return NULL;
3436 }
3437
3438 static ast_node* ast_value_next_child(ast_value *self, ast_node *cur) {
3439     (void)self; (void)cur;
3440     return NULL;
3441 }
3442
3443 static ast_node* ast_array_index_next_child(ast_array_index *self, ast_node *cur) {
3444     if (cur == (ast_node*)self)
3445         return (ast_node*)self->array;
3446     if (cur == (ast_node*)self->array)
3447         return (ast_node*)self->index;
3448     return NULL;
3449 }
3450
3451 static ast_node* ast_argpipe_next_child(ast_argpipe *self, ast_node *cur) {
3452     if (cur == (ast_node*)self)
3453         return (ast_node*)self->index;
3454     return NULL;
3455 }
3456
3457 static ast_node* ast_store_next_child(ast_store *self, ast_node *cur) {
3458     if (cur == (ast_node*)self)
3459         return (ast_node*)self->dest;
3460     if (cur == (ast_node*)self->dest)
3461         return (ast_node*)self->source;
3462     return NULL;
3463 }
3464
3465 static ast_node* ast_ifthen_next_child(ast_ifthen *self, ast_node *cur) {
3466     if (cur == (ast_node*)self) {
3467         if (self->cond)    return (ast_node*)self->cond;
3468         if (self->on_true) return (ast_node*)self->on_true;
3469         return (ast_node*)self->on_false;
3470     }
3471     if (self->cond && cur == (ast_node*)self->cond) {
3472         if (self->on_true) return (ast_node*)self->on_true;
3473         return (ast_node*)self->on_false;
3474     }
3475     if (self->on_true && cur == (ast_node*)self->on_true)
3476         return (ast_node*)self->on_false;
3477     return NULL;
3478 }
3479
3480 static ast_node* ast_ternary_next_child(ast_ternary *self, ast_node *cur) {
3481     if (cur == (ast_node*)self)
3482         return (ast_node*)self->cond;
3483     if (self->cond && cur == (ast_node*)self->cond)
3484         return (ast_node*)self->on_true;
3485     if (self->on_true && cur == (ast_node*)self->on_true)
3486         return (ast_node*)self->on_false;
3487     return NULL;
3488 }
3489
3490 static ast_node* ast_loop_next_child(ast_loop *self, ast_node *cur) {
3491     if (cur == (ast_node*)self) {
3492         /* If only we'd use ?: then this would be: return a ?: b ?: c ?: d; */
3493         if (self->initexpr)  return (ast_node*)self->initexpr;
3494         if (self->precond)   return (ast_node*)self->precond;
3495         if (self->body)      return (ast_node*)self->body;
3496         if (self->postcond)  return (ast_node*)self->postcond;
3497         return (ast_node*)self->increment;
3498     }
3499     if (self->initexpr && cur == (ast_node*)self->initexpr) {
3500         if (self->precond)   return (ast_node*)self->precond;
3501         if (self->body)      return (ast_node*)self->body;
3502         if (self->postcond)  return (ast_node*)self->postcond;
3503         return (ast_node*)self->increment;
3504     }
3505     if (self->precond && cur == (ast_node*)self->precond) {
3506         if (self->body)      return (ast_node*)self->body;
3507         if (self->postcond)  return (ast_node*)self->postcond;
3508         return (ast_node*)self->increment;
3509     }
3510     if (self->body && cur == (ast_node*)self->body) {
3511         if (self->postcond)  return (ast_node*)self->postcond;
3512         return (ast_node*)self->increment;
3513     }
3514     return NULL;
3515 }
3516
3517 static ast_node* ast_breakcont_next_child(ast_breakcont *self, ast_node *cur) {
3518     (void)self; (void)cur;
3519     return NULL;
3520 }
3521
3522 static ast_node* ast_switch_next_child(ast_switch *self, ast_node *cur) {
3523     size_t i, cases;
3524     if (cur == (ast_node*)self)
3525         return (ast_node*)self->operand;
3526     cases = vec_size(self->cases);
3527     if (!cases)
3528         return NULL;
3529     if (cur == (ast_node*)self->operand)
3530         return (ast_node*)self->cases[0].value;
3531     for (i = 0; i != cases; ++i) {
3532         if (cur == (ast_node*)self->cases[i].value)
3533             return (ast_node*)self->cases[i].code;
3534         if (cur == (ast_node*)self->cases[i].code) {
3535             return (i+1 != cases) ? (ast_node*)self->cases[i+1].value
3536                                   : NULL;
3537         }
3538     }
3539     return NULL;
3540 }
3541
3542 static ast_node* ast_label_next_child(ast_label *self, ast_node *cur) {
3543     (void)self; (void)cur;
3544     return NULL;
3545 }
3546
3547 static ast_node* ast_goto_next_child(ast_goto *self, ast_node *cur) {
3548     (void)self; (void)cur;
3549     return NULL;
3550 }
3551
3552 static ast_node* ast_call_next_child(ast_call *self, ast_node *cur) {
3553     size_t i, params;
3554     if (cur == (ast_node*)self)
3555         return (ast_node*)self->func;
3556     params = vec_size(self->params);
3557     if (!params)
3558         return NULL;
3559     if (cur == (ast_node*)self->func)
3560         return (ast_node*)self->params[0];
3561     for (i = 1; i != params; ++i) {
3562         if (cur == (ast_node*)self->params[i-1])
3563             return (ast_node*)self->params[i];
3564     }
3565     return NULL;
3566 }
3567
3568 static ast_node* ast_block_next_child(ast_block *self, ast_node *cur) {
3569     size_t i, exprs = vec_size(self->exprs);
3570     if (!exprs)
3571         return NULL;
3572     if (cur == (ast_node*)self)
3573         return (ast_node*)self->exprs[0];
3574     for (i = 1; i != exprs; ++i) {
3575         if (cur == (ast_node*)self->exprs[i-1])
3576             return (ast_node*)self->exprs[i];
3577     }
3578     return NULL;
3579 }
3580
3581 static ast_node* ast_unary_next_child(ast_unary *self, ast_node *cur) {
3582     if (cur == (ast_node*)self)
3583         return (ast_node*)self->operand;
3584     return NULL;
3585 }
3586
3587 static ast_node* ast_entfield_next_child(ast_entfield *self, ast_node *cur) {
3588     if (cur == (ast_node*)self)
3589         return (ast_node*)self->entity;
3590     if (cur == (ast_node*)self->entity)
3591         return (ast_node*)self->field;
3592     return NULL;
3593 }
3594
3595 static ast_node* ast_return_next_child(ast_return *self, ast_node *cur) {
3596     if (cur == (ast_node*)self)
3597         return (ast_node*)self->operand;
3598     return NULL;
3599 }
3600
3601 static ast_node* ast_binstore_next_child(ast_binstore *self, ast_node *cur) {
3602     if (cur == (ast_node*)self)
3603         return (ast_node*)self->dest;
3604     if (cur == (ast_node*)self->dest)
3605         return (ast_node*)self->source;
3606     return NULL;
3607 }
3608
3609 static ast_node* ast_binary_next_child(ast_binary *self, ast_node *cur) {
3610     if (cur == (ast_node*)self)
3611         return (ast_node*)self->left;
3612     if (cur == (ast_node*)self->left)
3613         return (ast_node*)self->right;
3614     return NULL;
3615 }
3616
3617 static ast_node* ast_function_next_child(ast_function *self, ast_node *cur) {
3618     size_t i, blocks = vec_size(self->blocks);
3619     if (!blocks)
3620         return NULL;
3621     if (cur == (ast_node*)self)
3622         return (ast_node*)self->blocks[0];
3623     for (i = 1; i != blocks; ++i) {
3624         if (cur == (ast_node*)self->blocks[i-1])
3625             return (ast_node*)self->blocks[i];
3626     }
3627     return NULL;
3628 }