I'm writing a Lisp to C translator and I have a problem with handling strings. This is a code that transforms an unary Lisp function to a C equivalent:
define(F) --> fun_unary(F), !.
fun_unary(F) --> "(define (", label(Fun), spaces, label(Arg1), ")", spaces, expr(Body), ")",
{swritef(F, "data *%t(data *%t) { return(%t); }", [Fun, Arg1, Body])}, !.
funs([F]) --> define(F), !.
funs([F|Fs]) --> define(F), spaces, funs(Fs), !.
Now I want to read any number of functions and return them as a single string. The above funs
is the best I could come up with, but it works like this:
?- funs(F, "(define (carzero l) (= (car l) 0)) (define (zero n) (= 0 n))", []).
F = ["data *carzero(data *l) { return(eq(car(l), make_atom_int(0))); }", "data *zero(data *n) { return(eq(make_atom_int(0), n)); }"].
While I want something like this:
F = "data *carzero(data *l) { return(eq(car(l), make_atom_int(0))); }\n\ndata *zero(data *n) { return(eq(make_atom_int(0), n)); }".
so that I can nicely swritef
is into a complete program, between #include
s and main(). An alternative solution is to modify the highest level translator to handle the list. It curently looks like this:
program(P) --> define(F), {swritef(P, "#include \"lisp2c.h\" \n\n%t \nint main() { return 0; }", [F])}, !.
How would I do any of these two? I'm using SWI Prolog.
malloc
space for each variable. So far, only#t
and()
are initialised just once and I allocate space for each number every time it's used, but I'm planning to keep a list of numbers that are already allocated and reuse them if necessary (byassert
, probably). – Shennashensi