compile.lua
Branches > main > 064d762 > files / org / faddle / lang / compile.lua
local LIST = require("org.faddle.lang.list")
local is_list = LIST.is_list
local cons = LIST.cons
local count = LIST.count
local first = LIST.first
local rest = LIST.rest
local apply = LIST.apply
local empty = LIST.empty
local symbol = require("org.faddle.lang.symbol")
local is_symbol = symbol.is_symbol
local intern = symbol.intern
-- Still bad :p
local FN = intern("fn")
local compile
local function compile_fn(form)
local args = rest(form)
local fn_args = first(args)
local body = rest(args)
assert(#fn_args == 0)
assert(count(body) == 1)
return "function() return " .. compile(first(body)) .. " end"
end
--- Returns a string of Lua source code from the form
compile = function(form)
if is_list(form) then
if count(form) == 0 then return "__rt.list()" end
if first(form) == FN then return compile_fn(form) end
-- macro expansion :D
-- rt functions?
else
local t = type(form)
if t == "number" or t == "nil" or t == "boolean" then
return tostring(form)
elseif t == "string" then
return string.format("%q", form)
else
error("Cannot compile form of type '" .. t .. "'")
end
end
end
local loadfn = loadstring or load
local function execute(lua_source, chunk_name)
local chunk, err = loadfn("local __rt = require('org.faddle.lang.rt');return " .. lua_source, chunk_name)
if not chunk then
error(err)
else
return chunk()
end
end
return {compile = compile, execute = execute}