Progress so far:
The following code will accept an array of code objects, and spit out code with nested CPS calls like everything else coded so far:
Code:
Code:
Notice how "compile" is NOT written in CPS style. What I can do is re-code this in code-objects, and then compile itself, and it should do that for me automatically! (and then I'll do it again to make sure that it generates still works/generates the same as before)
The following code will accept an array of code objects, and spit out code with nested CPS calls like everything else coded so far:
Code:
var getType = function (o) {
var t = (typeof o);
if (t === 'undefined' || o === null) { return 'null'; }
if (t === 'function') { return 'native'; }
var s = Object.prototype.toString.call(o);
return (s === '[object Array]' || s === '[object Arguments]') ? 'array' : t;
};
var compile = function(code) {
var calls = [];
function getCalls(code) {
if (getType(code) !== 'array' || code.length < 1) { return code; }
var last = [];
for(var i = 0; i < code.length; i++) {
var a = code[i];
if (getType(a) === 'array') {
getCalls(a);
last.push(calls.length - 1);
} else {
last.push(JSON.stringify(a) || '' + a);
}
}
calls.push(last);
}
getCalls(code);
var src = "";
while(calls.length) {
var c = calls.pop();
var t = getType(c[0]);
var s = "return window.Objects.js.tailcall(" + (
(t !== 'string') ? "r" + c[0] :
(c[0].charAt(0) === '"') ? "window.Objects.lookup, [env, " + c[0] + ", env.env], function (f) {\rreturn window.Objects.tailcall(f" :
c[0]
) + ", [env, ";
for(var i = 1; i < c.length; i++) {
s += (i > 1 ? ", " : "") + (getType(c[i]) === 'number' ? "r" : "") + c[i];
}
src = s + "], " +
(src.length < 1 ? "cb]);" : "function(r" + calls.length + ") {\r" + src + "\r});") +
(t === "string" && c[0].charAt(0) === '"' ? "\r});" : "");
}
return src;
};
Code:
INPUT:
compile([["foo", "q"], 5, [{a:1,b:2}, "y", ["baz", "z"], "a"], "b", function x(){return "x"}])
OUTPUT (indents added manually for better visualization):
return window.Objects.js.tailcall(window.Objects.lookup, [env, "foo", env.env], function (f) {
return window.Objects.tailcall(f, [env, "q"], function(r0) {
return window.Objects.js.tailcall(window.Objects.lookup, [env, "baz", env.env], function (f) {
return window.Objects.tailcall(f, [env, "z"], function(r1) {
return window.Objects.js.tailcall({"a":1,"b":2}, [env, "y", r1, "a"], function(r2) {
return window.Objects.js.tailcall(r0, [env, 5, r2, "b", function x(){return "x"}], cb]);
});
});
});
});
});
Notice how "compile" is NOT written in CPS style. What I can do is re-code this in code-objects, and then compile itself, and it should do that for me automatically! (and then I'll do it again to make sure that it generates still works/generates the same as before)