I'm trying to make a sort of Lisp like "Apply" function with GNU Lightning: a function F that receive a pointer to a function, an argument count and an array of integers and call G with the right number of parameters.
My code is not working properly. What's wrong? How can I do?
Here the code:
#include <stdio.h>
#include <stdlib.h>
#include <lightning.h>
int f0() {
printf("f0();\n");
}
int f1(int p1) {
printf("f1(%d);\n", p1);
}
int f2(int p1, int p2) {
printf("f2(%d, %d);\n", p1, p2);
}
int f3(int p1, int p2, int p3) {
printf("f3(%d, %d %d)\n", p1, p2, p3);
}
int main (int argc, char **argv) {
init_jit(argv[0]);
jit_state_t *_jit = jit_new_state();
int (*f)(int *g, int argc, int *argv);
jit_prolog();
jit_node_t *p_g = jit_arg();
jit_node_t *p_argc = jit_arg();
jit_node_t *p_argv = jit_arg();
jit_getarg(JIT_R0, p_g);
jit_getarg(JIT_R1, p_argc);
jit_getarg(JIT_R2, p_argv);
jit_prepare();
/* for ( ; argc; argc--, argv++) */
jit_node_t *label = jit_label();
jit_node_t *zero = jit_beqi(JIT_R1, 0);
// *argv
jit_ldr_i(JIT_V0, JIT_R2);
jit_pushargr(JIT_V0);
// Go next
// argv++
jit_addi(JIT_R2, JIT_R2, sizeof(int));
// argc--
jit_subi(JIT_R1, JIT_R1, 1);
//
jit_patch_at(jit_jmpi(), label);
jit_patch(zero);
jit_finishr(JIT_R0);
jit_reti(0);
jit_epilog();
f = jit_emit();
jit_clear_state();
f((void *)f0, 0, NULL);
int a1[] = {10};
f((void *)f1, 1, a1);
int a2[] = {100, 200};
f((void *)f2, 2, a2);
int a3[] = {1000, 2000, 3000};
f((void *)f3, 3, a3);
finish_jit();
return 0;
}
Expected output:
f0();
f1(10);
f2(100,200);
f3(1000,2000,3000);
Real output:
f0();
f1(10);
f2(200, 2);
f3(3000, 3 -13360)