2018-10-17 18:32:39 -07:00
#!/usr/bin/env lua
2020-09-18 12:13:53 -07:00
package.preload["fennel.binary"] = package.preload["fennel.binary"] or function(...)
local fennel = require("fennel")
local function shellout(command)
local f = io.popen(command)
local stdout = f:read("*all")
return (f:close() and stdout)
end
local function execute(cmd)
2021-09-12 22:29:05 -07:00
local _601_ = os.execute(cmd)
if (_601_ == 0) then
2020-09-18 12:13:53 -07:00
return true
2021-09-12 22:29:05 -07:00
elseif (_601_ == true) then
2020-09-18 12:13:53 -07:00
return true
2018-10-17 18:32:39 -07:00
end
2020-09-18 12:13:53 -07:00
end
local function string__3ec_hex_literal(characters)
local hex = {}
for character in characters:gmatch(".") do
table.insert(hex, ("0x%02x"):format(string.byte(character)))
end
return table.concat(hex, ", ")
end
local c_shim = "#ifdef __cplusplus\nextern \"C\" {\n#endif\n#include <lauxlib.h>\n#include <lua.h>\n#include <lualib.h>\n#ifdef __cplusplus\n}\n#endif\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#if LUA_VERSION_NUM == 501\n #define LUA_OK 0\n#endif\n\n/* Copied from lua.c */\n\nstatic lua_State *globalL = NULL;\n\nstatic void lstop (lua_State *L, lua_Debug *ar) {\n (void)ar; /* unused arg. */\n lua_sethook(L, NULL, 0, 0); /* reset hook */\n luaL_error(L, \"interrupted!\");\n}\n\nstatic void laction (int i) {\n signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */\n lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);\n}\n\nstatic void createargtable (lua_State *L, char **argv, int argc, int script) {\n int i, narg;\n if (script == argc) script = 0; /* no script name? */\n narg = argc - (script + 1); /* number of positive indices */\n lua_createtable(L, narg, script + 1);\n for (i = 0; i < argc; i++) {\n lua_pushstring(L, argv[i]);\n lua_rawseti(L, -2, i - script);\n }\n lua_setglobal(L, \"arg\");\n}\n\nstatic int msghandler (lua_State *L) {\n const char *msg = lua_tostring(L, 1);\n if (msg == NULL) { /* is error object not a string? */\n if (luaL_callmeta(L, 1, \"__tostring\") && /* does it have a metamethod */\n lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */\n return 1; /* that is the message */\n else\n msg = lua_pushfstring(L, \"(error object is a %%s value)\",\n luaL_typename(L, 1));\n }\n /* Call debug.traceback() instead of luaL_traceback() for Lua 5.1 compat. */\n lua_getglobal(L, \"debug\");\n lua_getfield(L, -1, \"traceback\");\n /* debug */\n lua_remove(L, -2);\n lua_pushstring(L, msg);\n /* original msg */\n lua_remove(L, -3);\n lua_pushinteger(L, 2); /* skip this function and traceback */\n lua_call(L, 2, 1); /* call debug.traceback */\n return 1; /* return the traceback */\n}\n\nstatic int docall (lua_State *L, int narg, int nres) {\n int status;\n int base = lua_gettop(L) - narg; /* function index */\n lua_pushcfunction(L, msghandler); /* push message handler */\n lua_insert(L, base); /* put it under function and args */\n globalL = L; /* to be available to 'laction' */\n signal(SIGINT, laction); /* set C-signal handler */\n status = lua_pcall(L, narg, nres, base);\n signal(SIGINT, SIG_DFL); /* reset C-signal handler */\n lua_remove(L, base); /* remove message handler from the stack */\n return status;\n}\n\nint main(int argc, char *argv[]) {\n lua_State *L = luaL_newstate();\n luaL_openlibs(L);\n createargtable(L, argv, argc, 0);\n\n static const unsigned char lua_loader_program[] = {\n%s\n};\n if(luaL_loadbuffer(L, (const char*)lua_loader_program,\n sizeof(lua_loader_program), \"%s\") != LUA_OK) {\n fprintf(stderr, \"luaL_loadbuffer: %%s\\n\", lua_tostring(L, -1));\n lua_close(L);\n return 1;\n }\n\n /* lua_bundle */\n lua_newtable(L);\n static const unsigned char lua_require_1[] = {\n %s\n };\n lua_pushlstring(L, (const char*)lua_require_1, sizeof(lua_require_1));\n lua_setfield(L, -2, \"%s\");\n\n%s\n\n if (docall(L, 1, LUA_MULTRET)) {\n const char *errmsg = lua_tostring(L, 1);\n if (errmsg) {\n fprintf(stderr, \"%%s\\n\", errmsg);\n }\n lua_close(L);\n return 1;\n }\n lua_close(L);\n return 0;\n}"
local function compile_fennel(filename, options)
2021-09-12 22:29:05 -07:00
local f
2020-09-18 12:13:53 -07:00
if (filename == "-") then
f = io.stdin
else
f = assert(io.open(filename, "rb"))
end
local lua_code = fennel["compile-string"](f:read("*a"), options)
f:close()
return lua_code
end
local function native_loader(native)
local nm = (os.getenv("NM") or "nm")
local out = {" /* native libraries */"}
for _, path in ipairs(native) do
for open in shellout((nm .. " " .. path)):gmatch("[^dDt] _?luaopen_([%a%p%d]+)") do
table.insert(out, (" int luaopen_%s(lua_State *L);"):format(open))
table.insert(out, (" lua_pushcfunction(L, luaopen_%s);"):format(open))
table.insert(out, (" lua_setfield(L, -2, \"%s\");\n"):format((open:sub(1, 1) .. open:sub(2):gsub("_", "."))))
end
end
return table.concat(out, "\n")
end
local function fennel__3ec(filename, native, options)
local basename = filename:gsub("(.*[\\/])(.*)", "%2")
local basename_noextension = (basename:match("(.+)%.") or basename)
local dotpath = filename:gsub("^%.%/", ""):gsub("[\\/]", ".")
local dotpath_noextension = (dotpath:match("(.+)%.") or dotpath)
2021-09-12 22:29:05 -07:00
local fennel_loader
local _604_
2020-09-18 12:13:53 -07:00
do
2021-09-12 22:29:05 -07:00
_604_ = "(do (local bundle_2_auto ...) (fn loader_3_auto [name_4_auto] (match (or (. bundle_2_auto name_4_auto) (. bundle_2_auto (.. name_4_auto \".init\"))) (mod_5_auto ? (= \"function\" (type mod_5_auto))) mod_5_auto (mod_5_auto ? (= \"string\" (type mod_5_auto))) (assert (if (= _VERSION \"Lua 5.1\") (loadstring mod_5_auto name_4_auto) (load mod_5_auto name_4_auto))) nil (values nil (: \"\n\\tmodule '%%s' not found in fennel bundle\" \"format\" name_4_auto)))) (table.insert (or package.loaders package.searchers) 2 loader_3_auto) ((assert (loader_3_auto \"%s\")) ((or unpack table.unpack) arg)))"
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
fennel_loader = _604_:format(dotpath_noextension)
2020-09-18 12:13:53 -07:00
local lua_loader = fennel["compile-string"](fennel_loader)
return c_shim:format(string__3ec_hex_literal(lua_loader), basename_noextension, string__3ec_hex_literal(compile_fennel(filename, options)), dotpath_noextension, native_loader(native))
end
local function write_c(filename, native, options)
local out_filename = (filename .. "_binary.c")
local f = assert(io.open(out_filename, "w+"))
f:write(fennel__3ec(filename, native, options))
f:close()
return out_filename
end
local function compile_binary(lua_c_path, executable_name, static_lua, lua_include_dir, native)
local cc = (os.getenv("CC") or "cc")
local rdynamic, bin_extension, ldl_3f = nil, nil, nil
2021-09-12 22:29:05 -07:00
local _606_
do
local _605_ = shellout((cc .. " -dumpmachine"))
if _605_ then
_606_ = _605_:match("mingw")
else
_606_ = _605_
end
end
if _606_ then
2020-09-18 12:13:53 -07:00
rdynamic, bin_extension, ldl_3f = "", ".exe", false
else
rdynamic, bin_extension, ldl_3f = "-rdynamic", "", true
end
2021-09-12 22:29:05 -07:00
local compile_command
local _609_
2020-09-18 12:13:53 -07:00
if ldl_3f then
2021-09-12 22:29:05 -07:00
_609_ = "-ldl"
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
_609_ = ""
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
compile_command = {cc, "-Os", lua_c_path, table.concat(native, " "), static_lua, rdynamic, "-lm", _609_, "-o", (executable_name .. bin_extension), "-I", lua_include_dir, os.getenv("CC_OPTS")}
2020-09-18 12:13:53 -07:00
if os.getenv("FENNEL_DEBUG") then
print("Compiling with", table.concat(compile_command, " "))
end
if not execute(table.concat(compile_command, " ")) then
print("failed:", table.concat(compile_command, " "))
os.exit(1)
end
if not os.getenv("FENNEL_DEBUG") then
os.remove(lua_c_path)
end
return os.exit(0)
end
local function native_path_3f(path)
2021-09-12 22:29:05 -07:00
local _614_ = path:match("%.(%a+)$")
if (_614_ == "a") then
2020-09-18 12:13:53 -07:00
return path
2021-09-12 22:29:05 -07:00
elseif (_614_ == "o") then
2020-09-18 12:13:53 -07:00
return path
2021-09-12 22:29:05 -07:00
elseif (_614_ == "so") then
2020-09-18 12:13:53 -07:00
return path
2021-09-12 22:29:05 -07:00
elseif (_614_ == "dylib") then
2020-09-18 12:13:53 -07:00
return path
else
2021-09-12 22:29:05 -07:00
local _ = _614_
2020-09-18 12:13:53 -07:00
return false
end
end
local function extract_native_args(args)
2021-09-12 22:29:05 -07:00
local native = {modules = {}, libraries = {}}
2020-09-18 12:13:53 -07:00
for i = #args, 1, -1 do
if ("--native-module" == args[i]) then
local path = assert(native_path_3f(table.remove(args, (i + 1))))
table.insert(native.modules, 1, path)
table.insert(native.libraries, 1, path)
table.remove(args, i)
end
if ("--native-library" == args[i]) then
table.insert(native.libraries, 1, assert(native_path_3f(table.remove(args, (i + 1)))))
table.remove(args, i)
end
end
if (0 < #args) then
print(table.concat(args, " "))
error(("Unknown args: " .. table.concat(args, " ")))
end
return native
end
local function compile(filename, executable_name, static_lua, lua_include_dir, options, args)
2021-09-12 22:29:05 -07:00
local _let_619_ = extract_native_args(args)
local modules = _let_619_["modules"]
local libraries = _let_619_["libraries"]
2020-09-18 12:13:53 -07:00
return compile_binary(write_c(filename, modules, options), executable_name, static_lua, lua_include_dir, libraries)
end
2021-02-01 17:09:15 -08:00
local help = ("\nUsage: %s --compile-binary FILE OUT STATIC_LUA_LIB LUA_INCLUDE_DIR\n\nCompile a binary from your Fennel program.\n\nRequires a C compiler, a copy of liblua, and Lua's dev headers. Implies\nthe --require-as-include option.\n\n FILE: the Fennel source being compiled.\n OUT: the name of the executable to generate\n STATIC_LUA_LIB: the path to the Lua library to use in the executable\n LUA_INCLUDE_DIR: the path to the directory of Lua C header files\n\nFor example, on a Debian system, to compile a file called program.fnl using\nLua 5.3, you would use this:\n\n $ %s --compile-binary program.fnl program \\\n /usr/lib/x86_64-linux-gnu/liblua5.3.a /usr/include/lua5.3\n\nThe program will be compiled to Lua, then compiled to C, then compiled to\nmachine code. You can set the CC environment variable to change the compiler\nused (default: cc) or set CC_OPTS to pass in compiler options. For example\nset CC_OPTS=-static to generate a binary with static linking.\n\nTo include C libraries that contain Lua modules, add --native-module path/to.so,\nand to include C libraries without modules, use --native-library path/to.so.\nThese options are unstable, barely tested, and even more likely to break.\n\nThis method is currently limited to programs do not transitively require Lua\nmodules. Requiring a Lua module directly will work, but requiring a Lua module\nwhich requires another will fail."):format(arg[0], arg[0])
2020-09-18 12:13:53 -07:00
return {compile = compile, help = help}
2018-10-17 18:32:39 -07:00
end
2021-09-12 22:29:05 -07:00
local fennel
2020-09-18 12:13:53 -07:00
package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...)
local utils = require("fennel.utils")
local parser = require("fennel.parser")
local compiler = require("fennel.compiler")
local specials = require("fennel.specials")
2021-09-12 22:29:05 -07:00
local unpack = (table.unpack or _G.unpack)
2020-09-18 12:13:53 -07:00
local function default_read_chunk(parser_state)
2021-09-12 22:29:05 -07:00
local function _481_()
2020-09-18 12:13:53 -07:00
if (0 < parser_state["stack-size"]) then
return ".."
else
return ">> "
end
end
2021-09-12 22:29:05 -07:00
io.write(_481_())
2020-09-18 12:13:53 -07:00
io.flush()
local input = io.read()
return (input and (input .. "\n"))
end
local function default_on_values(xs)
io.write(table.concat(xs, "\9"))
return io.write("\n")
end
local function default_on_error(errtype, err, lua_source)
2021-09-12 22:29:05 -07:00
local function _483_()
local _482_ = errtype
if (_482_ == "Lua Compile") then
2020-09-18 12:13:53 -07:00
return ("Bad code generated - likely a bug with the compiler:\n" .. "--- Generated Lua Start ---\n" .. lua_source .. "--- Generated Lua End ---\n")
2021-09-12 22:29:05 -07:00
elseif (_482_ == "Runtime") then
2021-02-01 17:09:15 -08:00
return (compiler.traceback(tostring(err), 4) .. "\n")
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
local _ = _482_
2020-09-18 12:13:53 -07:00
return ("%s error: %s\n"):format(errtype, tostring(err))
end
end
2021-09-12 22:29:05 -07:00
return io.write(_483_())
2020-09-18 12:13:53 -07:00
end
local save_source = table.concat({"local ___i___ = 1", "while true do", " local name, value = debug.getlocal(1, ___i___)", " if(name and name ~= \"___i___\") then", " ___replLocals___[name] = value", " ___i___ = ___i___ + 1", " else break end end"}, "\n")
local function splice_save_locals(env, lua_source)
env.___replLocals___ = (env.___replLocals___ or {})
local spliced_source = {}
local bind = "local %s = ___replLocals___['%s']"
for line in lua_source:gmatch("([^\n]+)\n?") do
table.insert(spliced_source, line)
end
for name in pairs(env.___replLocals___) do
table.insert(spliced_source, 1, bind:format(name, name))
end
if ((1 < #spliced_source) and (spliced_source[#spliced_source]):match("^ *return .*$")) then
table.insert(spliced_source, #spliced_source, save_source)
end
return table.concat(spliced_source, "\n")
end
2021-09-12 22:29:05 -07:00
local function completer(env, scope, text)
local matches = {}
local input_fragment = text:gsub(".*[%s)(]+", "")
local stop_looking_3f = false
local function add_partials(input, tbl, prefix, method_3f)
for k in utils.allpairs(tbl) do
local k0
if ((tbl == env) or (tbl == env.___replLocals___)) then
k0 = scope.unmanglings[k]
else
k0 = k
end
if ((#matches < 2000) and (type(k0) == "string") and (input == k0:sub(0, #input)) and (not method_3f or ("function" == type(tbl[k0])))) then
local function _487_()
if method_3f then
return (prefix .. ":" .. k0)
else
return (prefix .. k0)
end
end
table.insert(matches, _487_())
end
end
return nil
end
local function descend(input, tbl, prefix, add_matches, method_3f)
local splitter
if method_3f then
splitter = "^([^:]+):(.*)"
else
splitter = "^([^.]+)%.(.*)"
end
local head, tail = input:match(splitter)
local raw_head
if ((tbl == env) or (tbl == env.___replLocals___)) then
raw_head = scope.manglings[head]
else
raw_head = head
end
if (type(tbl[raw_head]) == "table") then
stop_looking_3f = true
if method_3f then
return add_partials(tail, tbl[raw_head], (prefix .. head), true)
else
return add_matches(tail, tbl[raw_head], (prefix .. head))
end
end
end
local function add_matches(input, tbl, prefix)
local prefix0
if prefix then
prefix0 = (prefix .. ".")
else
prefix0 = ""
end
if (not input:find("%.") and input:find(":")) then
return descend(input, tbl, prefix0, add_matches, true)
elseif not input:find("%.") then
return add_partials(input, tbl, prefix0)
else
return descend(input, tbl, prefix0, add_matches, false)
end
end
for _, source in ipairs({scope.specials, scope.macros, (env.___replLocals___ or {}), env, env._G}) do
add_matches(input_fragment, source)
if stop_looking_3f then
break
end
end
return matches
end
2020-12-23 10:33:09 -08:00
local commands = {}
local function command_3f(input)
return input:match("^%s*,")
end
2021-02-01 17:09:15 -08:00
local function command_docs()
2021-09-12 22:29:05 -07:00
local _496_
2021-02-01 17:09:15 -08:00
do
2021-09-12 22:29:05 -07:00
local tbl_13_auto = {}
2021-02-01 17:09:15 -08:00
for name, f in pairs(commands) do
2021-09-12 22:29:05 -07:00
tbl_13_auto[(#tbl_13_auto + 1)] = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented"))
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
_496_ = tbl_13_auto
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return table.concat(_496_, "\n")
2021-02-01 17:09:15 -08:00
end
2020-12-23 10:33:09 -08:00
commands.help = function(_, _0, on_values)
2021-02-01 17:09:15 -08:00
return on_values({("Welcome to Fennel.\nThis is the REPL where you can enter code to be evaluated.\nYou can also run these repl commands:\n\n" .. command_docs() .. "\n ,exit - Leave the repl.\n\nUse (doc something) to see descriptions for individual macros and special forms.\n\nFor more information about the language, see https://fennel-lang.org/reference")})
2020-12-23 10:33:09 -08:00
end
2021-02-01 17:09:15 -08:00
do end (compiler.metadata):set(commands.help, "fnl/docstring", "Show this message.")
2020-12-23 10:33:09 -08:00
local function reload(module_name, env, on_values, on_error)
2021-09-12 22:29:05 -07:00
local _497_, _498_ = pcall(specials["load-code"]("return require(...)", env), module_name)
if ((_497_ == true) and (nil ~= _498_)) then
local old = _498_
local _
2020-12-23 10:33:09 -08:00
package.loaded[module_name] = nil
_ = nil
local ok, new = pcall(require, module_name)
2021-09-12 22:29:05 -07:00
local new0
2020-12-23 10:33:09 -08:00
if not ok then
2021-02-01 17:09:15 -08:00
on_values({new})
2020-12-23 10:33:09 -08:00
new0 = old
else
new0 = new
end
if ((type(old) == "table") and (type(new0) == "table")) then
for k, v in pairs(new0) do
old[k] = v
end
for k in pairs(old) do
2021-09-12 22:29:05 -07:00
if (nil == (new0)[k]) then
2020-12-23 10:33:09 -08:00
old[k] = nil
end
end
package.loaded[module_name] = old
end
return on_values({"ok"})
2021-09-12 22:29:05 -07:00
elseif ((_497_ == false) and (nil ~= _498_)) then
local msg = _498_
local function _503_()
local _502_ = msg:gsub("\n.*", "")
return _502_
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
return on_error("Runtime", _503_())
end
end
local function run_command(read, on_error, f)
local _505_, _506_, _507_ = pcall(read)
if ((_505_ == true) and (_506_ == true) and (nil ~= _507_)) then
local val = _507_
return f(val)
elseif ((_505_ == false) and true and true) then
local _3fparse_ok = _506_
local _3ferr = _507_
return on_error("Parse", "Couldn't parse input.")
2020-12-23 10:33:09 -08:00
end
end
2021-02-01 17:09:15 -08:00
commands.reload = function(env, read, on_values, on_error)
2021-09-12 22:29:05 -07:00
local function _509_(_241)
return reload(tostring(_241), env, on_values, on_error)
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
return run_command(read, on_error, _509_)
2020-12-23 10:33:09 -08:00
end
2021-02-01 17:09:15 -08:00
do end (compiler.metadata):set(commands.reload, "fnl/docstring", "Reload the specified module.")
commands.reset = function(env, _, on_values)
2020-12-23 10:33:09 -08:00
env.___replLocals___ = {}
return on_values({"ok"})
end
2021-02-01 17:09:15 -08:00
do end (compiler.metadata):set(commands.reset, "fnl/docstring", "Erase all repl-local scope.")
2021-09-12 22:29:05 -07:00
commands.complete = function(env, read, on_values, on_error, scope, chars)
local function _510_()
return on_values(completer(env, scope, string.char(unpack(chars)):gsub(",complete +", ""):sub(1, -2)))
end
return run_command(read, on_error, _510_)
end
do end (compiler.metadata):set(commands.complete, "fnl/docstring", "Print all possible completions for a given input symbol.")
local function apropos_2a(pattern, module, prefix, seen, names)
for name, module0 in pairs(module) do
if (("string" == type(name)) and (package ~= module0)) then
local _511_ = type(module0)
if (_511_ == "function") then
if ((prefix .. name)):match(pattern) then
table.insert(names, (prefix .. name))
end
elseif (_511_ == "table") then
if not seen[module0] then
local _514_
do
local _513_ = seen
_513_[module0] = true
_514_ = _513_
end
apropos_2a(pattern, module0, (prefix .. name:gsub("%.", "/") .. "."), _514_, names)
end
end
end
end
return names
end
local function apropos(pattern)
local names = apropos_2a(pattern, package.loaded, "", {}, {})
local tbl_13_auto = {}
for _, name in ipairs(names) do
tbl_13_auto[(#tbl_13_auto + 1)] = name:gsub("^_G%.", "")
end
return tbl_13_auto
end
commands.apropos = function(env, read, on_values, on_error, scope)
local function _518_(_241)
return on_values(apropos(tostring(_241)))
end
return run_command(read, on_error, _518_)
end
do end (compiler.metadata):set(commands.apropos, "fnl/docstring", "Print all functions matching a pattern in all loaded modules.")
local function apropos_follow_path(path)
local paths
do
local tbl_13_auto = {}
for p in path:gmatch("[^%.]+") do
tbl_13_auto[(#tbl_13_auto + 1)] = p
end
paths = tbl_13_auto
end
local tgt = package.loaded
for _, path0 in ipairs(paths) do
local _520_
do
local _519_ = path0:gsub("%/", ".")
_520_ = _519_
end
tgt = tgt[_520_]
if (nil == tgt) then
break
end
end
return tgt
end
local function apropos_doc(pattern)
local names = {}
for _, path in ipairs(apropos(".*")) do
local tgt = apropos_follow_path(path)
if ("function" == type(tgt)) then
local _522_ = (compiler.metadata):get(tgt, "fnl/docstring")
if (nil ~= _522_) then
local docstr = _522_
if docstr:match(pattern) then
table.insert(names, path)
end
end
end
end
return names
end
commands["apropos-doc"] = function(env, read, on_values, on_error, scope)
local function _526_(_241)
return on_values(apropos_doc(tostring(_241)))
end
return run_command(read, on_error, _526_)
end
do end (compiler.metadata):set(commands["apropos-doc"], "fnl/docstring", "Print all functions that match the pattern in their docs")
local function apropos_show_docs(pattern)
for _, path in ipairs(apropos(pattern)) do
local tgt = apropos_follow_path(path)
if (("function" == type(tgt)) and (compiler.metadata):get(tgt, "fnl/docstring")) then
print(specials.doc(tgt, path))
print()
end
end
return nil
end
commands["apropos-show-docs"] = function(env, read, _, on_error, scope)
local function _528_(_241)
return apropos_show_docs(tostring(_241))
end
return run_command(read, on_error, _528_)
end
do end (compiler.metadata):set(commands["apropos-show-docs"], "fnl/docstring", "Print all documentations matching a pattern in function name")
2021-02-01 17:09:15 -08:00
local function load_plugin_commands()
if (utils.root and utils.root.options and utils.root.options.plugins) then
for _, plugin in ipairs(utils.root.options.plugins) do
for name, f in pairs(plugin) do
2021-09-12 22:29:05 -07:00
local _529_ = name:match("^repl%-command%-(.*)")
if (nil ~= _529_) then
local cmd_name = _529_
2021-02-01 17:09:15 -08:00
commands[cmd_name] = (commands[cmd_name] or f)
end
end
end
return nil
end
end
2021-09-12 22:29:05 -07:00
local function run_command_loop(input, read, loop, env, on_values, on_error, scope, chars)
2021-02-01 17:09:15 -08:00
load_plugin_commands()
2020-12-23 10:33:09 -08:00
local command_name = input:match(",([^%s/]+)")
do
2021-09-12 22:29:05 -07:00
local _532_ = commands[command_name]
if (nil ~= _532_) then
local command = _532_
command(env, read, on_values, on_error, scope, chars)
2020-12-23 10:33:09 -08:00
else
2021-09-12 22:29:05 -07:00
local _ = _532_
2020-12-23 10:33:09 -08:00
if ("exit" ~= command_name) then
on_values({"Unknown command", command_name})
end
end
end
if ("exit" ~= command_name) then
return loop()
end
end
2020-09-18 12:13:53 -07:00
local function repl(options)
local old_root_options = utils.root.options
2021-09-12 22:29:05 -07:00
local env
2020-09-18 12:13:53 -07:00
if options.env then
2020-10-13 23:23:38 -07:00
env = specials["wrap-env"](options.env)
2020-09-18 12:13:53 -07:00
else
2021-02-01 17:09:15 -08:00
env = setmetatable({}, {__index = (rawget(_G, "_ENV") or _G)})
2020-09-18 12:13:53 -07:00
end
local save_locals_3f = ((options.saveLocals ~= false) and env.debug and env.debug.getlocal)
2019-12-02 18:30:30 -08:00
local opts = {}
2021-09-12 22:29:05 -07:00
local _
2020-09-18 12:13:53 -07:00
for k, v in pairs(options) do
opts[k] = v
end
_ = nil
local read_chunk = (opts.readChunk or default_read_chunk)
local on_values = (opts.onValues or default_on_values)
local on_error = (opts.onError or default_on_error)
local pp = (opts.pp or tostring)
local byte_stream, clear_stream = parser.granulate(read_chunk)
local chars = {}
local read, reset = nil, nil
2021-09-12 22:29:05 -07:00
local function _537_(parser_state)
2020-09-18 12:13:53 -07:00
local c = byte_stream(parser_state)
2020-12-23 10:33:09 -08:00
table.insert(chars, c)
2020-09-18 12:13:53 -07:00
return c
end
2021-09-12 22:29:05 -07:00
read, reset = parser.parser(_537_)
2020-09-18 12:13:53 -07:00
local scope = compiler["make-scope"]()
opts.useMetadata = (options.useMetadata ~= false)
if (opts.allowedGlobals == nil) then
opts.allowedGlobals = specials["current-global-names"](opts.env)
end
if opts.registerCompleter then
2021-09-12 22:29:05 -07:00
local function _541_()
local _539_ = env
local _540_ = scope
local function _542_(...)
return completer(_539_, _540_, ...)
end
return _542_
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
opts.registerCompleter(_541_())
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
local function print_values(...)
local vals = {...}
local out = {}
env._, env.__ = vals[1], vals
for i = 1, select("#", ...) do
table.insert(out, pp(vals[i]))
end
return on_values(out)
end
2020-09-18 12:13:53 -07:00
local function loop()
for k in pairs(chars) do
chars[k] = nil
end
local ok, parse_ok_3f, x = pcall(read)
2021-09-12 22:29:05 -07:00
local src_string = string.char(unpack(chars))
reset()
2020-09-18 12:13:53 -07:00
utils.root.options = opts
if not ok then
on_error("Parse", parse_ok_3f)
clear_stream()
return loop()
2020-12-23 10:33:09 -08:00
elseif command_3f(src_string) then
2021-09-12 22:29:05 -07:00
return run_command_loop(src_string, read, loop, env, on_values, on_error, scope, chars)
2020-09-18 12:13:53 -07:00
else
if parse_ok_3f then
do
2021-09-12 22:29:05 -07:00
local _544_, _545_ = nil, nil
local function _547_()
local _546_ = opts
_546_["env"] = env
_546_["source"] = src_string
_546_["scope"] = scope
return _546_
end
_544_, _545_ = pcall(compiler.compile, x, _547_())
if ((_544_ == false) and (nil ~= _545_)) then
local msg = _545_
2020-09-18 12:13:53 -07:00
clear_stream()
on_error("Compile", msg)
2021-09-12 22:29:05 -07:00
elseif ((_544_ == true) and (nil ~= _545_)) then
local src = _545_
local src0
2020-09-18 12:13:53 -07:00
if save_locals_3f then
2020-12-23 10:33:09 -08:00
src0 = splice_save_locals(env, src)
2020-09-18 12:13:53 -07:00
else
2020-12-23 10:33:09 -08:00
src0 = src
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
local _549_, _550_ = pcall(specials["load-code"], src0, env)
if ((_549_ == false) and (nil ~= _550_)) then
local msg = _550_
2020-09-18 12:13:53 -07:00
clear_stream()
2020-12-23 10:33:09 -08:00
on_error("Lua Compile", msg, src0)
2021-09-12 22:29:05 -07:00
elseif (true and (nil ~= _550_)) then
local _0 = _549_
local chunk = _550_
local function _551_()
2020-12-23 10:33:09 -08:00
return print_values(chunk())
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
local function _552_()
local function _553_(...)
return on_error("Runtime", ...)
end
return _553_
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
xpcall(_551_, _552_())
2020-09-18 12:13:53 -07:00
end
end
end
utils.root.options = old_root_options
return loop()
end
end
end
return loop()
end
return repl
2019-12-02 18:30:30 -08:00
end
2021-09-12 22:29:05 -07:00
package.preload["fennel.specials"] = package.preload["fennel.specials"] or function(...)
local utils = require("fennel.utils")
local view = require("fennel.view")
local parser = require("fennel.parser")
local compiler = require("fennel.compiler")
local unpack = (table.unpack or _G.unpack)
local SPECIALS = compiler.scopes.global.specials
local function wrap_env(env)
local function _309_(_, key)
if (type(key) == "string") then
return env[compiler["global-unmangling"](key)]
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
return env[key]
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
local function _311_(_, key, value)
if (type(key) == "string") then
env[compiler["global-unmangling"](key)] = value
return nil
else
env[key] = value
return nil
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
local function _313_()
local function putenv(k, v)
local _314_
if (type(k) == "string") then
_314_ = compiler["global-unmangling"](k)
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
_314_ = k
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return _314_, v
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return next, utils.kvmap(env, putenv), nil
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return setmetatable({}, {__index = _309_, __newindex = _311_, __pairs = _313_})
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
local function current_global_names(env)
local mt
do
local _316_ = getmetatable(env)
local function _317_()
local __pairs = (_316_).__pairs
return __pairs
end
if (((_G.type(_316_) == "table") and true) and _317_()) then
local __pairs = (_316_).__pairs
local tbl_10_auto = {}
for k, v in __pairs(env) do
local _318_, _319_ = k, v
if ((nil ~= _318_) and (nil ~= _319_)) then
local k_11_auto = _318_
local v_12_auto = _319_
tbl_10_auto[k_11_auto] = v_12_auto
end
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
mt = tbl_10_auto
elseif (_316_ == nil) then
mt = (env or _G)
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
mt = nil
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
return (mt and utils.kvmap(mt, compiler["global-unmangling"]))
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
local function load_code(code, environment, filename)
local environment0 = (environment or rawget(_G, "_ENV") or _G)
if (rawget(_G, "setfenv") and rawget(_G, "loadstring")) then
local f = assert(_G.loadstring(code, filename))
_G.setfenv(f, environment0)
return f
else
return assert(load(code, filename, "t", environment0))
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
local function doc_2a(tgt, name)
if not tgt then
return (name .. " not found")
else
local docstring = (((compiler.metadata):get(tgt, "fnl/docstring") or "#<undocumented>")):gsub("\n$", ""):gsub("\n", "\n ")
local mt = getmetatable(tgt)
if ((type(tgt) == "function") or ((type(mt) == "table") and (type(mt.__call) == "function"))) then
local arglist = table.concat(((compiler.metadata):get(tgt, "fnl/arglist") or {"#<unknown-arguments>"}), " ")
local _323_
if (#arglist > 0) then
_323_ = " "
else
_323_ = ""
end
return string.format("(%s%s%s)\n %s", name, _323_, arglist, docstring)
else
return string.format("%s\n %s", name, docstring)
2021-02-01 17:09:15 -08:00
end
end
end
2021-09-12 22:29:05 -07:00
local function doc_special(name, arglist, docstring, body_form_3f)
compiler.metadata[SPECIALS[name]] = {["fnl/arglist"] = arglist, ["fnl/docstring"] = docstring, ["fnl/body-form?"] = body_form_3f}
return nil
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
local function compile_do(ast, scope, parent, start)
local start0 = (start or 2)
local len = #ast
local sub_scope = compiler["make-scope"](scope)
for i = start0, len do
compiler.compile1(ast[i], sub_scope, parent, {nval = 0})
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return nil
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
SPECIALS["do"] = function(ast, scope, parent, opts, start, chunk, sub_scope, pre_syms)
local start0 = (start or 2)
local sub_scope0 = (sub_scope or compiler["make-scope"](scope))
local chunk0 = (chunk or {})
local len = #ast
local retexprs = {returned = true}
local function compile_body(outer_target, outer_tail, outer_retexprs)
if (len < start0) then
compiler.compile1(nil, sub_scope0, chunk0, {tail = outer_tail, target = outer_target})
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
for i = start0, len do
local subopts = {nval = (((i ~= len) and 0) or opts.nval), tail = (((i == len) and outer_tail) or nil), target = (((i == len) and outer_target) or nil)}
local _ = utils["propagate-options"](opts, subopts)
local subexprs = compiler.compile1(ast[i], sub_scope0, chunk0, subopts)
if (i ~= len) then
compiler["keep-side-effects"](subexprs, parent, nil, ast[i])
end
end
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
compiler.emit(parent, chunk0, ast)
compiler.emit(parent, "end", ast)
return (outer_retexprs or retexprs)
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
if (opts.target or (opts.nval == 0) or opts.tail) then
compiler.emit(parent, "do", ast)
return compile_body(opts.target, opts.tail)
elseif opts.nval then
local syms = {}
for i = 1, opts.nval do
local s = ((pre_syms and pre_syms[i]) or compiler.gensym(scope))
do end (syms)[i] = s
retexprs[i] = utils.expr(s, "sym")
end
local outer_target = table.concat(syms, ", ")
compiler.emit(parent, string.format("local %s", outer_target), ast)
compiler.emit(parent, "do", ast)
return compile_body(outer_target, opts.tail)
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
local fname = compiler.gensym(scope)
local fargs
if scope.vararg then
fargs = "..."
else
fargs = ""
end
compiler.emit(parent, string.format("local function %s(%s)", fname, fargs), ast)
utils.hook("do", ast, sub_scope0)
return compile_body(nil, true, utils.expr((fname .. "(" .. fargs .. ")"), "statement"))
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
doc_special("do", {"..."}, "Evaluate multiple forms; return last value.", true)
SPECIALS.values = function(ast, scope, parent)
local len = #ast
local exprs = {}
for i = 2, len do
local subexprs = compiler.compile1(ast[i], scope, parent, {nval = ((i ~= len) and 1)})
table.insert(exprs, subexprs[1])
if (i == len) then
for j = 2, #subexprs do
table.insert(exprs, subexprs[j])
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
end
return exprs
end
doc_special("values", {"..."}, "Return multiple values from a function. Must be in tail position.")
local function deep_tostring(x, key_3f)
local elems = {}
if utils["sequence?"](x) then
local _332_
do
local tbl_13_auto = {}
for _, v in ipairs(x) do
tbl_13_auto[(#tbl_13_auto + 1)] = deep_tostring(v)
end
_332_ = tbl_13_auto
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return ("[" .. table.concat(_332_, " ") .. "]")
elseif utils["table?"](x) then
local _333_
2021-02-01 17:09:15 -08:00
do
2021-09-12 22:29:05 -07:00
local tbl_13_auto = {}
for k, v in pairs(x) do
tbl_13_auto[(#tbl_13_auto + 1)] = (deep_tostring(k, true) .. " " .. deep_tostring(v))
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
_333_ = tbl_13_auto
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return ("{" .. table.concat(_333_, " ") .. "}")
elseif (key_3f and (type(x) == "string") and x:find("^[-%w?\\^_!$%&*+./@:|<=>]+$")) then
return (":" .. x)
elseif (type(x) == "string") then
return string.format("%q", x):gsub("\\\"", "\\\\\""):gsub("\"", "\\\"")
else
return tostring(x)
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
local function set_fn_metadata(arg_list, docstring, parent, fn_name)
if utils.root.options.useMetadata then
local args
local function _335_(_241)
return ("\"%s\""):format(deep_tostring(_241))
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
args = utils.map(arg_list, _335_)
local meta_fields = {"\"fnl/arglist\"", ("{" .. table.concat(args, ", ") .. "}")}
if docstring then
table.insert(meta_fields, "\"fnl/docstring\"")
table.insert(meta_fields, ("\"" .. docstring:gsub("%s+$", ""):gsub("\\", "\\\\"):gsub("\n", "\\n"):gsub("\"", "\\\"") .. "\""))
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
local meta_str = ("require(\"%s\").metadata"):format((utils.root.options.moduleName or "fennel"))
return compiler.emit(parent, ("pcall(function() %s:setall(%s, %s) end)"):format(meta_str, fn_name, table.concat(meta_fields, ", ")))
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
local function get_fn_name(ast, scope, fn_name, multi)
if (fn_name and (fn_name[1] ~= "nil")) then
local _338_
if not multi then
_338_ = compiler["declare-local"](fn_name, {}, scope, ast)
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
_338_ = (compiler["symbol-to-expression"](fn_name, scope))[1]
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return _338_, not multi, 3
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
return nil, true, 2
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
local function compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, local_3f, arg_name_list, arg_list, docstring)
for i = (index + 1), #ast do
compiler.compile1(ast[i], f_scope, f_chunk, {nval = (((i ~= #ast) and 0) or nil), tail = (i == #ast)})
end
local _341_
if local_3f then
_341_ = "local function %s(%s)"
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
_341_ = "%s = function(%s)"
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
compiler.emit(parent, string.format(_341_, fn_name, table.concat(arg_name_list, ", ")), ast)
compiler.emit(parent, f_chunk, ast)
compiler.emit(parent, "end", ast)
set_fn_metadata(arg_list, docstring, parent, fn_name)
utils.hook("fn", ast, f_scope)
return utils.expr(fn_name, "sym")
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
local function compile_anonymous_fn(ast, f_scope, f_chunk, parent, index, arg_name_list, arg_list, docstring, scope)
local fn_name = compiler.gensym(scope)
return compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, true, arg_name_list, arg_list, docstring)
end
SPECIALS.fn = function(ast, scope, parent)
local f_scope
2021-02-01 17:09:15 -08:00
do
2021-09-12 22:29:05 -07:00
local _343_ = compiler["make-scope"](scope)
do end (_343_)["vararg"] = false
f_scope = _343_
end
local f_chunk = {}
local fn_sym = utils["sym?"](ast[2])
local multi = (fn_sym and utils["multi-sym?"](fn_sym[1]))
local fn_name, local_3f, index = get_fn_name(ast, scope, fn_sym, multi)
local arg_list = compiler.assert(utils["table?"](ast[index]), "expected parameters table", ast)
compiler.assert((not multi or not multi["multi-sym-method-call"]), ("unexpected multi symbol " .. tostring(fn_name)), fn_sym)
local function get_arg_name(arg)
if utils["varg?"](arg) then
compiler.assert((arg == arg_list[#arg_list]), "expected vararg as last parameter", ast)
f_scope.vararg = true
return "..."
elseif (utils["sym?"](arg) and (tostring(arg) ~= "nil") and not utils["multi-sym?"](tostring(arg))) then
return compiler["declare-local"](arg, {}, f_scope, ast)
elseif utils["table?"](arg) then
local raw = utils.sym(compiler.gensym(scope))
local declared = compiler["declare-local"](raw, {}, f_scope, ast)
compiler.destructure(arg, raw, ast, f_scope, f_chunk, {declaration = true, nomulti = true, symtype = "arg"})
return declared
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
return compiler.assert(false, ("expected symbol for function parameter: %s"):format(tostring(arg)), ast[2])
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
local arg_name_list = utils.map(arg_list, get_arg_name)
local index0, docstring = nil, nil
if ((type(ast[(index + 1)]) == "string") and ((index + 1) < #ast)) then
index0, docstring = (index + 1), ast[(index + 1)]
2021-04-12 16:52:31 -07:00
else
2021-09-12 22:29:05 -07:00
index0, docstring = index, nil
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
if fn_name then
return compile_named_fn(ast, f_scope, f_chunk, parent, index0, fn_name, local_3f, arg_name_list, arg_list, docstring)
else
return compile_anonymous_fn(ast, f_scope, f_chunk, parent, index0, arg_name_list, arg_list, docstring, scope)
2021-04-12 16:52:31 -07:00
end
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
doc_special("fn", {"name?", "args", "docstring?", "..."}, "Function syntax. May optionally include a name and docstring.\nIf a name is provided, the function will be bound in the current scope.\nWhen called with the wrong number of args, excess args will be discarded\nand lacking args will be nil, use lambda for arity-checked functions.", true)
SPECIALS.lua = function(ast, _, parent)
compiler.assert(((#ast == 2) or (#ast == 3)), "expected 1 or 2 arguments", ast)
local _348_
do
local _347_ = utils["sym?"](ast[2])
if _347_ then
_348_ = tostring(_347_)
else
_348_ = _347_
end
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
if ("nil" ~= _348_) then
table.insert(parent, {ast = ast, leaf = tostring(ast[2])})
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
local _352_
do
local _351_ = utils["sym?"](ast[3])
if _351_ then
_352_ = tostring(_351_)
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
_352_ = _351_
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
if ("nil" ~= _352_) then
return tostring(ast[3])
end
end
SPECIALS.doc = function(ast, scope, parent)
assert(utils.root.options.useMetadata, "can't look up doc with metadata disabled.")
compiler.assert((#ast == 2), "expected one argument", ast)
local target = tostring(ast[2])
local special_or_macro = (scope.specials[target] or scope.macros[target])
if special_or_macro then
return ("print(%q)"):format(doc_2a(special_or_macro, target))
2021-02-01 17:09:15 -08:00
else
2021-09-12 22:29:05 -07:00
local _let_355_ = compiler.compile1(ast[2], scope, parent, {nval = 1})
local value = _let_355_[1]
return ("print(require('%s').doc(%s, '%s'))"):format((utils.root.options.moduleName or "fennel"), tostring(value), tostring(ast[2]))
end
end
doc_special("doc", {"x"}, "Print the docstring and arglist for a function, macro, or special form.")
local function dot(ast, scope, parent)
compiler.assert((1 < #ast), "expected table argument", ast)
local len = #ast
local _let_357_ = compiler.compile1(ast[2], scope, parent, {nval = 1})
local lhs = _let_357_[1]
if (len == 2) then
return tostring(lhs)
else
local indices = {}
for i = 3, len do
local index = ast[i]
if ((type(index) == "string") and utils["valid-lua-identifier?"](index)) then
table.insert(indices, ("." .. index))
2021-04-12 16:52:31 -07:00
else
2021-09-12 22:29:05 -07:00
local _let_358_ = compiler.compile1(index, scope, parent, {nval = 1})
local index0 = _let_358_[1]
table.insert(indices, ("[" .. tostring(index0) .. "]"))
2021-04-12 16:52:31 -07:00
end
end
2021-09-12 22:29:05 -07:00
if (tostring(lhs):find("[{\"0-9]") or ("nil" == tostring(lhs))) then
return ("(" .. tostring(lhs) .. ")" .. table.concat(indices))
2021-04-12 16:52:31 -07:00
else
2021-09-12 22:29:05 -07:00
return (tostring(lhs) .. table.concat(indices))
2021-04-12 16:52:31 -07:00
end
2021-02-01 17:09:15 -08:00
end
end
2021-09-12 22:29:05 -07:00
SPECIALS["."] = dot
doc_special(".", {"tbl", "key1", "..."}, "Look up key1 in tbl table. If more args are provided, do a nested lookup.")
SPECIALS.global = function(ast, scope, parent)
compiler.assert((#ast == 3), "expected name and value", ast)
compiler.destructure(ast[2], ast[3], ast, scope, parent, {forceglobal = true, nomulti = true, symtype = "global"})
return nil
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
doc_special("global", {"name", "val"}, "Set name as a global with val.")
SPECIALS.set = function(ast, scope, parent)
compiler.assert((#ast == 3), "expected name and value", ast)
compiler.destructure(ast[2], ast[3], ast, scope, parent, {noundef = true, symtype = "set"})
return nil
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
doc_special("set", {"name", "val"}, "Set a local variable to a new value. Only works on locals using var.")
local function set_forcibly_21_2a(ast, scope, parent)
compiler.assert((#ast == 3), "expected name and value", ast)
compiler.destructure(ast[2], ast[3], ast, scope, parent, {forceset = true, symtype = "set"})
return nil
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
SPECIALS["set-forcibly!"] = set_forcibly_21_2a
local function local_2a(ast, scope, parent)
compiler.assert((#ast == 3), "expected name and value", ast)
compiler.destructure(ast[2], ast[3], ast, scope, parent, {declaration = true, nomulti = true, symtype = "local"})
return nil
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
SPECIALS["local"] = local_2a
doc_special("local", {"name", "val"}, "Introduce new top-level immutable local.")
SPECIALS.var = function(ast, scope, parent)
compiler.assert((#ast == 3), "expected name and value", ast)
compiler.destructure(ast[2], ast[3], ast, scope, parent, {declaration = true, isvar = true, nomulti = true, symtype = "var"})
return nil
end
doc_special("var", {"name", "val"}, "Introduce new mutable local.")
local function kv_3f(t)
local _362_
do
local tbl_13_auto = {}
for k in pairs(t) do
local _363_
if not ("number" == type(k)) then
_363_ = k
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
_363_ = nil
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
tbl_13_auto[(#tbl_13_auto + 1)] = _363_
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
_362_ = tbl_13_auto
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
return (_362_)[1]
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
SPECIALS.let = function(ast, scope, parent, opts)
local bindings = ast[2]
local pre_syms = {}
compiler.assert((utils["table?"](bindings) and not kv_3f(bindings)), "expected binding sequence", bindings)
compiler.assert(((#bindings % 2) == 0), "expected even number of name/value bindings", ast[2])
compiler.assert((#ast >= 3), "expected body expression", ast[1])
for _ = 1, (opts.nval or 0) do
table.insert(pre_syms, compiler.gensym(scope))
end
2020-09-18 12:13:53 -07:00
local sub_scope = compiler["make-scope"](scope)
2021-09-12 22:29:05 -07:00
local sub_chunk = {}
for i = 1, #bindings, 2 do
compiler.destructure(bindings[i], bindings[(i + 1)], ast, sub_scope, sub_chunk, {declaration = true, nomulti = true, symtype = "let"})
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
return SPECIALS["do"](ast, scope, parent, opts, 3, sub_chunk, sub_scope, pre_syms)
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
doc_special("let", {"[name1 val1 ... nameN valN]", "..."}, "Introduces a new scope in which a given set of local bindings are used.", true)
local function get_prev_line(parent)
if ("table" == type(parent)) then
return get_prev_line((parent.leaf or parent[#parent]))
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
return (parent or "")
2020-09-18 12:13:53 -07:00
end
end
2021-09-12 22:29:05 -07:00
local function disambiguate_3f(rootstr, parent)
local function _367_()
local _366_ = get_prev_line(parent)
if (nil ~= _366_) then
local prev_line = _366_
return prev_line:match("%)$")
2020-09-18 12:13:53 -07:00
end
end
2021-09-12 22:29:05 -07:00
return (rootstr:match("^{") or _367_())
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
SPECIALS.tset = function(ast, scope, parent)
compiler.assert((#ast > 3), "expected table, key, and value arguments", ast)
local root = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1]
local keys = {}
for i = 3, (#ast - 1) do
local _let_369_ = compiler.compile1(ast[i], scope, parent, {nval = 1})
local key = _let_369_[1]
table.insert(keys, tostring(key))
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
local value = (compiler.compile1(ast[#ast], scope, parent, {nval = 1}))[1]
local rootstr = tostring(root)
local fmtstr
if disambiguate_3f(rootstr, parent) then
fmtstr = "do end (%s)[%s] = %s"
else
fmtstr = "%s[%s] = %s"
2020-10-13 23:23:38 -07:00
end
2021-09-12 22:29:05 -07:00
return compiler.emit(parent, fmtstr:format(rootstr, table.concat(keys, "]["), tostring(value)), ast)
2020-10-13 23:23:38 -07:00
end
2021-09-12 22:29:05 -07:00
doc_special("tset", {"tbl", "key1", "...", "keyN", "val"}, "Set the value of a table field. Can take additional keys to set\nnested values, but all parents must contain an existing table.")
local function calculate_target(scope, opts)
if not (opts.tail or opts.target or opts.nval) then
return "iife", true, nil
elseif (opts.nval and (opts.nval ~= 0) and not opts.target) then
local accum = {}
local target_exprs = {}
for i = 1, opts.nval do
local s = compiler.gensym(scope)
do end (accum)[i] = s
target_exprs[i] = utils.expr(s, "sym")
2020-10-13 23:23:38 -07:00
end
2021-09-12 22:29:05 -07:00
return "target", opts.tail, table.concat(accum, ", "), target_exprs
2020-10-13 23:23:38 -07:00
else
2021-09-12 22:29:05 -07:00
return "none", opts.tail, opts.target
2021-04-12 16:52:31 -07:00
end
end
2021-09-12 22:29:05 -07:00
local function if_2a(ast, scope, parent, opts)
local do_scope = compiler["make-scope"](scope)
local branches = {}
local wrapper, inner_tail, inner_target, target_exprs = calculate_target(scope, opts)
local body_opts = {nval = opts.nval, tail = inner_tail, target = inner_target}
local function compile_body(i)
local chunk = {}
local cscope = compiler["make-scope"](do_scope)
compiler["keep-side-effects"](compiler.compile1(ast[i], cscope, chunk, body_opts), chunk, nil, ast[i])
return {chunk = chunk, scope = cscope}
2020-10-13 23:23:38 -07:00
end
2021-09-12 22:29:05 -07:00
for i = 2, (#ast - 1), 2 do
local condchunk = {}
local res = compiler.compile1(ast[i], do_scope, condchunk, {nval = 1})
local cond = res[1]
local branch = compile_body((i + 1))
branch.cond = cond
branch.condchunk = condchunk
branch.nested = ((i ~= 2) and (next(condchunk, nil) == nil))
table.insert(branches, branch)
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
local has_else_3f = ((#ast > 3) and ((#ast % 2) == 0))
local else_branch = (has_else_3f and compile_body(#ast))
2020-09-18 12:13:53 -07:00
local s = compiler.gensym(scope)
local buffer = {}
local last_buffer = buffer
for i = 1, #branches do
local branch = branches[i]
2021-09-12 22:29:05 -07:00
local fstr
2020-09-18 12:13:53 -07:00
if not branch.nested then
fstr = "if %s then"
else
fstr = "elseif %s then"
end
local cond = tostring(branch.cond)
2021-09-12 22:29:05 -07:00
local cond_line
2021-04-12 16:52:31 -07:00
if ((cond == "true") and branch.nested and (i == #branches) and not has_else_3f) then
2020-09-18 12:13:53 -07:00
cond_line = "else"
else
cond_line = fstr:format(cond)
end
if branch.nested then
compiler.emit(last_buffer, branch.condchunk, ast)
else
for _, v in ipairs(branch.condchunk) do
compiler.emit(last_buffer, v, ast)
end
end
compiler.emit(last_buffer, cond_line, ast)
compiler.emit(last_buffer, branch.chunk, ast)
if (i == #branches) then
2020-10-13 23:23:38 -07:00
if has_else_3f then
2020-09-18 12:13:53 -07:00
compiler.emit(last_buffer, "else", ast)
compiler.emit(last_buffer, else_branch.chunk, ast)
elseif (inner_target and (cond_line ~= "else")) then
compiler.emit(last_buffer, "else", ast)
compiler.emit(last_buffer, ("%s = nil"):format(inner_target), ast)
2020-03-07 17:41:37 -08:00
end
2020-09-18 12:13:53 -07:00
compiler.emit(last_buffer, "end", ast)
2021-09-12 22:29:05 -07:00
elseif not (branches[(i + 1)]).nested then
2020-09-18 12:13:53 -07:00
local next_buffer = {}
compiler.emit(last_buffer, "else", ast)
compiler.emit(last_buffer, next_buffer, ast)
compiler.emit(last_buffer, "end", ast)
last_buffer = next_buffer
end
end
if (wrapper == "iife") then
local iifeargs = ((scope.vararg and "...") or "")
compiler.emit(parent, ("local function %s(%s)"):format(tostring(s), iifeargs), ast)
compiler.emit(parent, buffer, ast)
compiler.emit(parent, "end", ast)
return utils.expr(("%s(%s)"):format(tostring(s), iifeargs), "statement")
elseif (wrapper == "none") then
2020-12-23 10:33:09 -08:00
for i = 1, #buffer do
2020-09-18 12:13:53 -07:00
compiler.emit(parent, buffer[i], ast)
end
return {returned = true}
else
compiler.emit(parent, ("local %s"):format(inner_target), ast)
2020-12-23 10:33:09 -08:00
for i = 1, #buffer do
2020-09-18 12:13:53 -07:00
compiler.emit(parent, buffer[i], ast)
end
return target_exprs
end
end
SPECIALS["if"] = if_2a
doc_special("if", {"cond1", "body1", "...", "condN", "bodyN"}, "Conditional form.\nTakes any number of condition/body pairs and evaluates the first body where\nthe condition evaluates to truthy. Similar to cond in other lisps.")
2021-04-12 16:52:31 -07:00
local function remove_until_condition(bindings)
if ("until" == bindings[(#bindings - 1)]) then
table.remove(bindings, (#bindings - 1))
return table.remove(bindings)
end
end
local function compile_until(condition, scope, chunk)
if condition then
2021-09-12 22:29:05 -07:00
local _let_379_ = compiler.compile1(condition, scope, chunk, {nval = 1})
local condition_lua = _let_379_[1]
return compiler.emit(chunk, ("if %s then break end"):format(tostring(condition_lua)), utils.expr(condition, "expression"))
2021-04-12 16:52:31 -07:00
end
end
2020-09-18 12:13:53 -07:00
SPECIALS.each = function(ast, scope, parent)
compiler.assert((#ast >= 3), "expected body expression", ast[1])
2020-10-13 23:23:38 -07:00
local binding = compiler.assert(utils["table?"](ast[2]), "expected binding table", ast)
2021-09-12 22:29:05 -07:00
local _ = compiler.assert((2 <= #binding), "expected binding and iterator", binding)
2021-04-12 16:52:31 -07:00
local until_condition = remove_until_condition(binding)
2020-09-18 12:13:53 -07:00
local iter = table.remove(binding, #binding)
local destructures = {}
local new_manglings = {}
local sub_scope = compiler["make-scope"](scope)
local function destructure_binding(v)
2021-09-12 22:29:05 -07:00
compiler.assert(("string" ~= type(v)), ("unexpected iterator clause " .. tostring(v)), binding)
2020-10-13 23:23:38 -07:00
if utils["sym?"](v) then
2020-09-18 12:13:53 -07:00
return compiler["declare-local"](v, {}, sub_scope, ast, new_manglings)
else
local raw = utils.sym(compiler.gensym(sub_scope))
2021-09-12 22:29:05 -07:00
do end (destructures)[raw] = v
2020-09-18 12:13:53 -07:00
return compiler["declare-local"](raw, {}, sub_scope, ast)
end
end
local bind_vars = utils.map(binding, destructure_binding)
local vals = compiler.compile1(iter, sub_scope, parent)
local val_names = utils.map(vals, tostring)
local chunk = {}
compiler.emit(parent, ("for %s in %s do"):format(table.concat(bind_vars, ", "), table.concat(val_names, ", ")), ast)
for raw, args in utils.stablepairs(destructures) do
2020-12-23 10:33:09 -08:00
compiler.destructure(args, raw, ast, sub_scope, chunk, {declaration = true, nomulti = true, symtype = "each"})
2020-09-18 12:13:53 -07:00
end
compiler["apply-manglings"](sub_scope, new_manglings, ast)
2021-04-12 16:52:31 -07:00
compile_until(until_condition, sub_scope, chunk)
2020-09-18 12:13:53 -07:00
compile_do(ast, sub_scope, chunk, 3)
compiler.emit(parent, chunk, ast)
return compiler.emit(parent, "end", ast)
end
2021-09-12 22:29:05 -07:00
doc_special("each", {"[key value (iterator)]", "..."}, "Runs the body once for each set of values provided by the given iterator.\nMost commonly used with ipairs for sequential tables or pairs for undefined\norder, but can be used with any iterator.", true)
2020-09-18 12:13:53 -07:00
local function while_2a(ast, scope, parent)
local len1 = #parent
2021-09-12 22:29:05 -07:00
local condition = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1]
2020-09-18 12:13:53 -07:00
local len2 = #parent
local sub_chunk = {}
if (len1 ~= len2) then
2020-12-23 10:33:09 -08:00
for i = (len1 + 1), len2 do
table.insert(sub_chunk, parent[i])
2021-09-12 22:29:05 -07:00
do end (parent)[i] = nil
2020-09-18 12:13:53 -07:00
end
compiler.emit(parent, "while true do", ast)
compiler.emit(sub_chunk, ("if not %s then break end"):format(condition[1]), ast)
else
compiler.emit(parent, ("while " .. tostring(condition) .. " do"), ast)
end
compile_do(ast, compiler["make-scope"](scope), sub_chunk, 3)
compiler.emit(parent, sub_chunk, ast)
return compiler.emit(parent, "end", ast)
end
SPECIALS["while"] = while_2a
2021-09-12 22:29:05 -07:00
doc_special("while", {"condition", "..."}, "The classic while loop. Evaluates body until a condition is non-truthy.", true)
2020-09-18 12:13:53 -07:00
local function for_2a(ast, scope, parent)
2020-10-13 23:23:38 -07:00
local ranges = compiler.assert(utils["table?"](ast[2]), "expected binding table", ast)
2021-04-12 16:52:31 -07:00
local until_condition = remove_until_condition(ast[2])
2020-09-18 12:13:53 -07:00
local binding_sym = table.remove(ast[2], 1)
local sub_scope = compiler["make-scope"](scope)
local range_args = {}
local chunk = {}
2020-10-13 23:23:38 -07:00
compiler.assert(utils["sym?"](binding_sym), ("unable to bind %s %s"):format(type(binding_sym), tostring(binding_sym)), ast[2])
2020-09-18 12:13:53 -07:00
compiler.assert((#ast >= 3), "expected body expression", ast[1])
2021-09-12 22:29:05 -07:00
compiler.assert((#ranges <= 3), "unexpected arguments", ranges[4])
2020-12-23 10:33:09 -08:00
for i = 1, math.min(#ranges, 3) do
2021-09-12 22:29:05 -07:00
range_args[i] = tostring((compiler.compile1(ranges[i], sub_scope, parent, {nval = 1}))[1])
2020-09-18 12:13:53 -07:00
end
compiler.emit(parent, ("for %s = %s do"):format(compiler["declare-local"](binding_sym, {}, sub_scope, ast), table.concat(range_args, ", ")), ast)
2021-04-12 16:52:31 -07:00
compile_until(until_condition, sub_scope, chunk)
2020-09-18 12:13:53 -07:00
compile_do(ast, sub_scope, chunk, 3)
compiler.emit(parent, chunk, ast)
return compiler.emit(parent, "end", ast)
end
SPECIALS["for"] = for_2a
2021-09-12 22:29:05 -07:00
doc_special("for", {"[index start stop step?]", "..."}, "Numeric loop construct.\nEvaluates body once for each value between start and stop (inclusive).", true)
2020-12-23 10:33:09 -08:00
local function native_method_call(ast, _scope, _parent, target, args)
2021-09-12 22:29:05 -07:00
local _let_383_ = ast
local _ = _let_383_[1]
local _0 = _let_383_[2]
local method_string = _let_383_[3]
local call_string
if ((target.type == "literal") or (target.type == "varg") or (target.type == "expression")) then
2020-09-18 12:13:53 -07:00
call_string = "(%s):%s(%s)"
else
call_string = "%s:%s(%s)"
end
return utils.expr(string.format(call_string, tostring(target), method_string, table.concat(args, ", ")), "statement")
end
local function nonnative_method_call(ast, scope, parent, target, args)
2021-09-12 22:29:05 -07:00
local method_string = tostring((compiler.compile1(ast[3], scope, parent, {nval = 1}))[1])
2020-10-13 23:23:38 -07:00
local args0 = {tostring(target), unpack(args)}
return utils.expr(string.format("%s[%s](%s)", tostring(target), method_string, table.concat(args0, ", ")), "statement")
2020-09-18 12:13:53 -07:00
end
local function double_eval_protected_method_call(ast, scope, parent, target, args)
2021-09-12 22:29:05 -07:00
local method_string = tostring((compiler.compile1(ast[3], scope, parent, {nval = 1}))[1])
2020-09-18 12:13:53 -07:00
local call = "(function(tgt, m, ...) return tgt[m](tgt, ...) end)(%s, %s)"
2020-10-13 23:23:38 -07:00
table.insert(args, 1, method_string)
2020-09-18 12:13:53 -07:00
return utils.expr(string.format(call, tostring(target), table.concat(args, ", ")), "statement")
end
local function method_call(ast, scope, parent)
compiler.assert((2 < #ast), "expected at least 2 arguments", ast)
2021-09-12 22:29:05 -07:00
local _let_385_ = compiler.compile1(ast[2], scope, parent, {nval = 1})
local target = _let_385_[1]
2020-09-18 12:13:53 -07:00
local args = {}
for i = 4, #ast do
2021-09-12 22:29:05 -07:00
local subexprs
local _386_
2020-09-18 12:13:53 -07:00
if (i ~= #ast) then
2021-09-12 22:29:05 -07:00
_386_ = 1
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
_386_ = nil
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
subexprs = compiler.compile1(ast[i], scope, parent, {nval = _386_})
2020-09-18 12:13:53 -07:00
utils.map(subexprs, tostring, args)
end
if ((type(ast[3]) == "string") and utils["valid-lua-identifier?"](ast[3])) then
return native_method_call(ast, scope, parent, target, args)
elseif (target.type == "sym") then
return nonnative_method_call(ast, scope, parent, target, args)
else
return double_eval_protected_method_call(ast, scope, parent, target, args)
end
end
SPECIALS[":"] = method_call
doc_special(":", {"tbl", "method-name", "..."}, "Call the named method on tbl with the provided args.\nMethod name doesn't have to be known at compile-time; if it is, use\n(tbl:method-name ...) instead.")
SPECIALS.comment = function(ast, _, parent)
local els = {}
2020-12-23 10:33:09 -08:00
for i = 2, #ast do
2021-09-12 22:29:05 -07:00
table.insert(els, view(ast[i], {["one-line?"] = true}))
2020-09-18 12:13:53 -07:00
end
return compiler.emit(parent, ("-- " .. table.concat(els, " ")), ast)
end
2021-09-12 22:29:05 -07:00
doc_special("comment", {"..."}, "Comment which will be emitted in Lua output.", true)
2020-10-13 23:23:38 -07:00
local function hashfn_max_used(f_scope, i, max)
2021-09-12 22:29:05 -07:00
local max0
2020-10-13 23:23:38 -07:00
if f_scope.symmeta[("$" .. i)].used then
max0 = i
else
max0 = max
end
if (i < 9) then
return hashfn_max_used(f_scope, (i + 1), max0)
else
return max0
end
end
2020-09-18 12:13:53 -07:00
SPECIALS.hashfn = function(ast, scope, parent)
compiler.assert((#ast == 2), "expected one argument", ast)
2021-09-12 22:29:05 -07:00
local f_scope
2020-09-18 12:13:53 -07:00
do
2021-09-12 22:29:05 -07:00
local _391_ = compiler["make-scope"](scope)
do end (_391_)["vararg"] = false
_391_["hashfn"] = true
f_scope = _391_
2020-09-18 12:13:53 -07:00
end
local f_chunk = {}
local name = compiler.gensym(scope)
local symbol = utils.sym(name)
local args = {}
2020-10-13 23:23:38 -07:00
compiler["declare-local"](symbol, {}, scope, ast)
2020-09-18 12:13:53 -07:00
for i = 1, 9 do
args[i] = compiler["declare-local"](utils.sym(("$" .. i)), {}, f_scope, ast)
end
local function walker(idx, node, parent_node)
2021-09-12 22:29:05 -07:00
if (utils["sym?"](node) and (tostring(node) == "$...")) then
2020-09-18 12:13:53 -07:00
parent_node[idx] = utils.varg()
f_scope.vararg = true
return nil
else
2020-10-13 23:23:38 -07:00
return (utils["list?"](node) or utils["table?"](node))
2020-09-18 12:13:53 -07:00
end
end
utils["walk-tree"](ast[2], walker)
compiler.compile1(ast[2], f_scope, f_chunk, {tail = true})
2020-10-13 23:23:38 -07:00
local max_used = hashfn_max_used(f_scope, 1, 0)
2020-09-18 12:13:53 -07:00
if f_scope.vararg then
compiler.assert((max_used == 0), "$ and $... in hashfn are mutually exclusive", ast)
end
2021-09-12 22:29:05 -07:00
local arg_str
2020-10-13 23:23:38 -07:00
if f_scope.vararg then
2021-09-12 22:29:05 -07:00
arg_str = tostring(utils.varg())
2020-10-13 23:23:38 -07:00
else
arg_str = table.concat(args, ", ", 1, max_used)
end
compiler.emit(parent, string.format("local function %s(%s)", name, arg_str), ast)
2020-09-18 12:13:53 -07:00
compiler.emit(parent, f_chunk, ast)
compiler.emit(parent, "end", ast)
return utils.expr(name, "sym")
end
doc_special("hashfn", {"..."}, "Function literal shorthand; args are either $... OR $1, $2, etc.")
2021-09-12 22:29:05 -07:00
local function arithmetic_special(name, zero_arity, unary_prefix, nval, ast, scope, parent)
2021-04-12 16:52:31 -07:00
local len = #ast
2021-09-12 22:29:05 -07:00
local operands = {}
local padded_op = (" " .. name .. " ")
for i = 2, len do
local subexprs
local _395_
if (i < len) then
_395_ = 1
else
_395_ = nil
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
subexprs = compiler.compile1(ast[i], scope, parent, {nval = _395_})
utils.map(subexprs, tostring, operands)
end
local _397_ = #operands
if (_397_ == 0) then
local _399_
do
local _398_ = zero_arity
compiler.assert(_398_, "Expected more than 0 arguments", ast)
_399_ = _398_
end
return utils.expr(_399_, "literal")
elseif (_397_ == 1) then
if unary_prefix then
return ("(" .. unary_prefix .. padded_op .. operands[1] .. ")")
2021-04-12 16:52:31 -07:00
else
2021-09-12 22:29:05 -07:00
return operands[1]
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
else
local _ = _397_
return ("(" .. table.concat(operands, padded_op) .. ")")
2020-09-18 12:13:53 -07:00
end
2021-04-12 16:52:31 -07:00
end
local function define_arithmetic_special(name, zero_arity, unary_prefix, lua_name)
2021-09-12 22:29:05 -07:00
local _405_
do
local _402_ = (lua_name or name)
local _403_ = zero_arity
local _404_ = unary_prefix
local function _406_(...)
return arithmetic_special(_402_, _403_, _404_, 1, ...)
end
_405_ = _406_
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
SPECIALS[name] = _405_
2020-09-18 12:13:53 -07:00
return doc_special(name, {"a", "b", "..."}, "Arithmetic operator; works the same as Lua but accepts more arguments.")
end
define_arithmetic_special("+", "0")
define_arithmetic_special("..", "''")
define_arithmetic_special("^")
define_arithmetic_special("-", nil, "")
define_arithmetic_special("*", "1")
define_arithmetic_special("%")
define_arithmetic_special("/", nil, "1")
define_arithmetic_special("//", nil, "1")
2021-09-12 22:29:05 -07:00
SPECIALS["or"] = function(ast, scope, parent)
return arithmetic_special("or", "false", nil, nil, ast, scope, parent)
end
SPECIALS["and"] = function(ast, scope, parent)
return arithmetic_special("and", "true", nil, nil, ast, scope, parent)
end
doc_special("and", {"a", "b", "..."}, "Boolean operator; works the same as Lua but accepts more arguments.")
doc_special("or", {"a", "b", "..."}, "Boolean operator; works the same as Lua but accepts more arguments.")
2021-04-12 16:52:31 -07:00
local function bitop_special(native_name, lib_name, zero_arity, unary_prefix, ast, scope, parent)
if (#ast == 1) then
return compiler.assert(zero_arity, "Expected more than 0 arguments.", ast)
else
local len = #ast
local operands = {}
local padded_native_name = (" " .. native_name .. " ")
local prefixed_lib_name = ("bit." .. lib_name)
for i = 2, len do
2021-09-12 22:29:05 -07:00
local subexprs
local _407_
2021-04-12 16:52:31 -07:00
if (i ~= len) then
2021-09-12 22:29:05 -07:00
_407_ = 1
2021-04-12 16:52:31 -07:00
else
2021-09-12 22:29:05 -07:00
_407_ = nil
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
subexprs = compiler.compile1(ast[i], scope, parent, {nval = _407_})
2021-04-12 16:52:31 -07:00
utils.map(subexprs, tostring, operands)
end
if (#operands == 1) then
if utils.root.options.useBitLib then
return (prefixed_lib_name .. "(" .. unary_prefix .. ", " .. operands[1] .. ")")
else
return ("(" .. unary_prefix .. padded_native_name .. operands[1] .. ")")
end
else
if utils.root.options.useBitLib then
return (prefixed_lib_name .. "(" .. table.concat(operands, ", ") .. ")")
else
return ("(" .. table.concat(operands, padded_native_name) .. ")")
end
end
end
end
local function define_bitop_special(name, zero_arity, unary_prefix, native)
2021-09-12 22:29:05 -07:00
local _417_
do
local _413_ = native
local _414_ = name
local _415_ = zero_arity
local _416_ = unary_prefix
local function _418_(...)
return bitop_special(_413_, _414_, _415_, _416_, ...)
end
_417_ = _418_
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
SPECIALS[name] = _417_
2021-04-12 16:52:31 -07:00
return nil
end
define_bitop_special("lshift", nil, "1", "<<")
define_bitop_special("rshift", nil, "1", ">>")
define_bitop_special("band", "0", "0", "&")
define_bitop_special("bor", "0", "0", "|")
define_bitop_special("bxor", "0", "0", "~")
doc_special("lshift", {"x", "n"}, "Bitwise logical left shift of x by n bits.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")
doc_special("rshift", {"x", "n"}, "Bitwise logical right shift of x by n bits.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")
doc_special("band", {"x1", "x2", "..."}, "Bitwise AND of any number of arguments.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")
doc_special("bor", {"x1", "x2", "..."}, "Bitwise OR of any number of arguments.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")
doc_special("bxor", {"x1", "x2", "..."}, "Bitwise XOR of any number of arguments.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")
2020-09-18 12:13:53 -07:00
doc_special("..", {"a", "b", "..."}, "String concatenation operator; works the same as Lua but accepts more arguments.")
2021-09-12 22:29:05 -07:00
local function native_comparator(op, _419_, scope, parent)
local _arg_420_ = _419_
local _ = _arg_420_[1]
local lhs_ast = _arg_420_[2]
local rhs_ast = _arg_420_[3]
local _let_421_ = compiler.compile1(lhs_ast, scope, parent, {nval = 1})
local lhs = _let_421_[1]
local _let_422_ = compiler.compile1(rhs_ast, scope, parent, {nval = 1})
local rhs = _let_422_[1]
2020-09-18 12:13:53 -07:00
return string.format("(%s %s %s)", tostring(lhs), op, tostring(rhs))
end
local function double_eval_protected_comparator(op, chain_op, ast, scope, parent)
local arglist = {}
local comparisons = {}
local vals = {}
local chain = string.format(" %s ", (chain_op or "and"))
for i = 2, #ast do
table.insert(arglist, tostring(compiler.gensym(scope)))
2021-09-12 22:29:05 -07:00
table.insert(vals, tostring((compiler.compile1(ast[i], scope, parent, {nval = 1}))[1]))
2018-10-17 18:32:39 -07:00
end
2020-09-18 12:13:53 -07:00
for i = 1, (#arglist - 1) do
table.insert(comparisons, string.format("(%s %s %s)", arglist[i], op, arglist[(i + 1)]))
2019-12-02 18:30:30 -08:00
end
2020-09-18 12:13:53 -07:00
return string.format("(function(%s) return %s end)(%s)", table.concat(arglist, ","), table.concat(comparisons, chain), table.concat(vals, ","))
end
local function define_comparator_special(name, lua_op, chain_op)
do
local op = (lua_op or name)
local function opfn(ast, scope, parent)
compiler.assert((2 < #ast), "expected at least two arguments", ast)
if (3 == #ast) then
return native_comparator(op, ast, scope, parent)
2019-12-02 18:30:30 -08:00
else
2020-09-18 12:13:53 -07:00
return double_eval_protected_comparator(op, chain_op, ast, scope, parent)
end
end
SPECIALS[name] = opfn
end
return doc_special(name, {"a", "b", "..."}, "Comparison operator; works the same as Lua but accepts more arguments.")
end
define_comparator_special(">")
define_comparator_special("<")
define_comparator_special(">=")
define_comparator_special("<=")
define_comparator_special("=", "==")
define_comparator_special("not=", "~=", "or")
local function define_unary_special(op, realop)
local function opfn(ast, scope, parent)
compiler.assert((#ast == 2), "expected one argument", ast)
local tail = compiler.compile1(ast[2], scope, parent, {nval = 1})
return ((realop or op) .. tostring(tail[1]))
end
SPECIALS[op] = opfn
return nil
end
define_unary_special("not", "not ")
doc_special("not", {"x"}, "Logical operator; works the same as Lua.")
define_unary_special("bnot", "~")
2021-04-12 16:52:31 -07:00
doc_special("bnot", {"x"}, "Bitwise negation; only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")
2020-09-18 12:13:53 -07:00
define_unary_special("length", "#")
doc_special("length", {"x"}, "Returns the length of a table or string.")
2021-09-12 22:29:05 -07:00
do end (SPECIALS)["~="] = SPECIALS["not="]
2020-09-18 12:13:53 -07:00
SPECIALS["#"] = SPECIALS.length
SPECIALS.quote = function(ast, scope, parent)
compiler.assert((#ast == 2), "expected one argument")
local runtime, this_scope = true, scope
while this_scope do
this_scope = this_scope.parent
if (this_scope == compiler.scopes.compiler) then
runtime = false
end
end
return compiler["do-quote"](ast[2], scope, parent, runtime)
end
doc_special("quote", {"x"}, "Quasiquote the following form. Only works in macro/compiler scope.")
2021-09-12 22:29:05 -07:00
local macro_loaded = {}
2021-04-12 16:52:31 -07:00
local function safe_getmetatable(tbl)
local mt = getmetatable(tbl)
assert((mt ~= getmetatable("")), "Illegal metatable access!")
return mt
end
local safe_require = nil
2021-09-12 22:29:05 -07:00
local function safe_compiler_env()
return {table = utils.copy(table), math = utils.copy(math), string = utils.copy(string), pairs = pairs, ipairs = ipairs, select = select, tostring = tostring, tonumber = tonumber, bit = rawget(_G, "bit"), pcall = pcall, xpcall = xpcall, next = next, print = print, type = type, assert = assert, error = error, setmetatable = setmetatable, getmetatable = safe_getmetatable, require = safe_require, rawlen = rawget(_G, "rawlen"), rawget = rawget, rawset = rawset, rawequal = rawequal}
end
local function combined_mt_pairs(env)
local combined = {}
local _let_425_ = getmetatable(env)
local __index = _let_425_["__index"]
if ("table" == type(__index)) then
for k, v in pairs(__index) do
combined[k] = v
end
end
for k, v in next, env, nil do
combined[k] = v
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
return next, combined, nil
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
local function make_compiler_env(ast, scope, parent, _3fopts)
local provided
do
local _427_ = (_3fopts or utils.root.options)
if ((_G.type(_427_) == "table") and ((_427_)["compiler-env"] == "strict")) then
provided = safe_compiler_env()
elseif ((_G.type(_427_) == "table") and (nil ~= (_427_).compilerEnv)) then
local compilerEnv = (_427_).compilerEnv
provided = compilerEnv
elseif ((_G.type(_427_) == "table") and (nil ~= (_427_)["compiler-env"])) then
local compiler_env = (_427_)["compiler-env"]
provided = compiler_env
else
local _ = _427_
provided = safe_compiler_env(false)
end
end
local env
local function _429_(base)
return utils.sym(compiler.gensym((compiler.scopes.macro or scope), base))
end
local function _430_()
2020-09-18 12:13:53 -07:00
return compiler.scopes.macro
end
2021-09-12 22:29:05 -07:00
local function _431_(symbol)
2020-09-18 12:13:53 -07:00
compiler.assert(compiler.scopes.macro, "must call from macro", ast)
return compiler.scopes.macro.manglings[tostring(symbol)]
end
2021-09-12 22:29:05 -07:00
local function _432_(form)
2020-09-18 12:13:53 -07:00
compiler.assert(compiler.scopes.macro, "must call from macro", ast)
return compiler.macroexpand(form, compiler.scopes.macro)
end
2021-09-12 22:29:05 -07:00
env = {_AST = ast, _CHUNK = parent, _IS_COMPILER = true, _SCOPE = scope, _SPECIALS = compiler.scopes.global.specials, _VARARG = utils.varg(), ["macro-loaded"] = macro_loaded, unpack = unpack, ["assert-compile"] = compiler.assert, list = utils.list, ["list?"] = utils["list?"], ["multi-sym?"] = utils["multi-sym?"], sequence = utils.sequence, ["sequence?"] = utils["sequence?"], sym = utils.sym, ["sym?"] = utils["sym?"], ["table?"] = utils["table?"], ["varg?"] = utils["varg?"], view = view, gensym = _429_, ["get-scope"] = _430_, ["in-scope?"] = _431_, macroexpand = _432_}
env._G = env
return setmetatable(env, {__index = provided, __newindex = provided, __pairs = combined_mt_pairs})
2020-09-18 12:13:53 -07:00
end
local cfg = string.gmatch(package.config, "([^\n]+)")
local dirsep, pathsep, pathmark = (cfg() or "/"), (cfg() or ";"), (cfg() or "?")
local pkg_config = {dirsep = dirsep, pathmark = pathmark, pathsep = pathsep}
local function escapepat(str)
return string.gsub(str, "[^%w]", "%%%1")
end
local function search_module(modulename, pathstring)
local pathsepesc = escapepat(pkg_config.pathsep)
local pattern = ("([^%s]*)%s"):format(pathsepesc, pathsepesc)
local no_dot_module = modulename:gsub("%.", pkg_config.dirsep)
local fullpath = ((pathstring or utils["fennel-module"].path) .. pkg_config.pathsep)
local function try_path(path)
local filename = path:gsub(escapepat(pkg_config.pathmark), no_dot_module)
local filename2 = path:gsub(escapepat(pkg_config.pathmark), modulename)
2021-09-12 22:29:05 -07:00
local _433_ = (io.open(filename) or io.open(filename2))
if (nil ~= _433_) then
local file = _433_
2020-09-18 12:13:53 -07:00
file:close()
return filename
end
end
local function find_in_path(start)
2021-09-12 22:29:05 -07:00
local _435_ = fullpath:match(pattern, start)
if (nil ~= _435_) then
local path = _435_
2020-09-18 12:13:53 -07:00
return (try_path(path) or find_in_path((start + #path + 1)))
end
end
return find_in_path(1)
end
local function make_searcher(options)
2021-09-12 22:29:05 -07:00
local function _437_(module_name)
2020-12-23 10:33:09 -08:00
local opts = utils.copy(utils.root.options)
for k, v in pairs((options or {})) do
opts[k] = v
end
opts["module-name"] = module_name
2021-09-12 22:29:05 -07:00
local _438_ = search_module(module_name)
if (nil ~= _438_) then
local filename = _438_
local _441_
do
local _439_ = filename
local _440_ = opts
local function _442_(...)
return utils["fennel-module"].dofile(_439_, _440_, ...)
end
_441_ = _442_
2019-12-02 18:30:30 -08:00
end
2021-09-12 22:29:05 -07:00
return _441_, filename
2020-09-18 12:13:53 -07:00
end
end
2021-09-12 22:29:05 -07:00
return _437_
2020-09-18 12:13:53 -07:00
end
local function macro_globals(env, globals)
local allowed = current_global_names(env)
for _, k in pairs((globals or {})) do
table.insert(allowed, k)
end
return allowed
end
2021-09-12 22:29:05 -07:00
local function fennel_macro_searcher(module_name)
local opts
do
local _444_ = utils.copy(utils.root.options)
do end (_444_)["env"] = "_COMPILER"
_444_["allowedGlobals"] = nil
opts = _444_
end
local _445_ = search_module(module_name, utils["fennel-module"]["macro-path"])
if (nil ~= _445_) then
local filename = _445_
local _448_
do
local _446_ = filename
local _447_ = opts
local function _449_(...)
return utils["fennel-module"].dofile(_446_, _447_, ...)
end
_448_ = _449_
end
return _448_, filename
end
end
local function lua_macro_searcher(module_name)
local _451_ = search_module(module_name, package.path)
if (nil ~= _451_) then
local filename = _451_
local code
do
local f = io.open(filename)
local function close_handlers_7_auto(ok_8_auto, ...)
f:close()
if ok_8_auto then
return ...
else
return error(..., 0)
end
end
local function _453_()
return assert(f:read("*a"))
end
code = close_handlers_7_auto(_G.xpcall(_453_, (package.loaded.fennel or debug).traceback))
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
local chunk = load_code(code, make_compiler_env(), filename)
return chunk, filename
2021-04-12 16:52:31 -07:00
end
end
2021-09-12 22:29:05 -07:00
local macro_searchers = {lua_macro_searcher, fennel_macro_searcher}
2021-04-12 16:52:31 -07:00
local function search_macro_module(modname, n)
2021-09-12 22:29:05 -07:00
local _455_ = macro_searchers[n]
if (nil ~= _455_) then
local f = _455_
local _456_, _457_ = f(modname)
if ((nil ~= _456_) and true) then
local loader = _456_
local _3ffilename = _457_
2021-04-12 16:52:31 -07:00
return loader, _3ffilename
else
2021-09-12 22:29:05 -07:00
local _ = _456_
2021-04-12 16:52:31 -07:00
return search_macro_module(modname, (n + 1))
end
end
2020-10-13 23:23:38 -07:00
end
local function metadata_only_fennel(modname)
if ((modname == "fennel.macros") or (package and package.loaded and ("table" == type(package.loaded[modname])) and (package.loaded[modname].metadata == compiler.metadata))) then
return {metadata = compiler.metadata}
end
end
2021-09-12 22:29:05 -07:00
local function _461_(modname)
local function _462_()
2021-04-12 16:52:31 -07:00
local loader, filename = search_macro_module(modname, 1)
compiler.assert(loader, (modname .. " module not found."))
2021-09-12 22:29:05 -07:00
do end (macro_loaded)[modname] = loader(modname, filename)
2021-04-12 16:52:31 -07:00
return macro_loaded[modname]
2020-10-13 23:23:38 -07:00
end
2021-09-12 22:29:05 -07:00
return (macro_loaded[modname] or metadata_only_fennel(modname) or _462_())
2020-10-13 23:23:38 -07:00
end
2021-09-12 22:29:05 -07:00
safe_require = _461_
2020-09-18 12:13:53 -07:00
local function add_macros(macros_2a, ast, scope)
2020-10-13 23:23:38 -07:00
compiler.assert(utils["table?"](macros_2a), "expected macros to be table", ast)
2020-09-18 12:13:53 -07:00
for k, v in pairs(macros_2a) do
compiler.assert((type(v) == "function"), "expected each macro to be function", ast)
2021-09-12 22:29:05 -07:00
do end (scope.macros)[k] = v
2020-09-18 12:13:53 -07:00
end
return nil
end
2021-09-12 22:29:05 -07:00
local function resolve_module_name(_463_, scope, parent, opts)
local _arg_464_ = _463_
local filename = _arg_464_["filename"]
local second = _arg_464_[2]
local filename0 = (filename or (utils["table?"](second) and second.filename))
local module_name = utils.root.options["module-name"]
local modexpr = compiler.compile(second, opts)
local modname_chunk = load_code(modexpr)
return modname_chunk(module_name, filename0)
end
2020-12-23 10:33:09 -08:00
SPECIALS["require-macros"] = function(ast, scope, parent, real_ast)
compiler.assert((#ast == 2), "Expected one module name argument", (real_ast or ast))
2021-09-12 22:29:05 -07:00
local modname = resolve_module_name(ast, scope, parent, {})
compiler.assert(("string" == type(modname)), "module name must compile to string", (real_ast or ast))
2020-09-18 12:13:53 -07:00
if not macro_loaded[modname] then
2021-09-12 22:29:05 -07:00
local loader, filename = search_macro_module(modname, 1)
2021-04-12 16:52:31 -07:00
compiler.assert(loader, (modname .. " module not found."), ast)
2021-09-12 22:29:05 -07:00
do end (macro_loaded)[modname] = loader(modname, filename)
2020-09-18 12:13:53 -07:00
end
return add_macros(macro_loaded[modname], ast, scope, parent)
end
doc_special("require-macros", {"macro-module-name"}, "Load given module and use its contents as macro definitions in current scope.\nMacro module should return a table of macro functions with string keys.\nConsider using import-macros instead as it is more flexible.")
2020-12-23 10:33:09 -08:00
local function emit_included_fennel(src, path, opts, sub_chunk)
2020-09-18 12:13:53 -07:00
local subscope = compiler["make-scope"](utils.root.scope.parent)
local forms = {}
if utils.root.options.requireAsInclude then
subscope.specials.require = compiler["require-include"]
end
for _, val in parser.parser(parser["string-stream"](src), path) do
table.insert(forms, val)
end
for i = 1, #forms do
2021-09-12 22:29:05 -07:00
local subopts
2020-09-18 12:13:53 -07:00
if (i == #forms) then
2020-12-23 10:33:09 -08:00
subopts = {tail = true}
2020-09-18 12:13:53 -07:00
else
subopts = {nval = 0}
end
utils["propagate-options"](opts, subopts)
compiler.compile1(forms[i], subscope, sub_chunk, subopts)
end
return nil
end
local function include_path(ast, opts, path, mod, fennel_3f)
utils.root.scope.includes[mod] = "fnl/loading"
2021-09-12 22:29:05 -07:00
local src
2020-09-18 12:13:53 -07:00
do
local f = assert(io.open(path))
2021-09-12 22:29:05 -07:00
local function close_handlers_7_auto(ok_8_auto, ...)
2018-10-17 18:32:39 -07:00
f:close()
2021-09-12 22:29:05 -07:00
if ok_8_auto then
2020-09-18 12:13:53 -07:00
return ...
else
return error(..., 0)
end
end
2021-09-12 22:29:05 -07:00
local function _469_()
2020-09-18 12:13:53 -07:00
return f:read("*all"):gsub("[\13\n]*$", "")
end
2021-09-12 22:29:05 -07:00
src = close_handlers_7_auto(_G.xpcall(_469_, (package.loaded.fennel or debug).traceback))
2020-09-18 12:13:53 -07:00
end
local ret = utils.expr(("require(\"" .. mod .. "\")"), "statement")
local target = ("package.preload[%q]"):format(mod)
local preload_str = (target .. " = " .. target .. " or function(...)")
local temp_chunk, sub_chunk = {}, {}
compiler.emit(temp_chunk, preload_str, ast)
compiler.emit(temp_chunk, sub_chunk)
compiler.emit(temp_chunk, "end", ast)
for i, v in ipairs(temp_chunk) do
table.insert(utils.root.chunk, i, v)
end
if fennel_3f then
2020-12-23 10:33:09 -08:00
emit_included_fennel(src, path, opts, sub_chunk)
2020-09-18 12:13:53 -07:00
else
compiler.emit(sub_chunk, src, ast)
end
utils.root.scope.includes[mod] = ret
return ret
end
local function include_circular_fallback(mod, modexpr, fallback, ast)
if (utils.root.scope.includes[mod] == "fnl/loading") then
compiler.assert(fallback, "circular include detected", ast)
return fallback(modexpr)
end
end
SPECIALS.include = function(ast, scope, parent, opts)
compiler.assert((#ast == 2), "expected one argument", ast)
2021-09-12 22:29:05 -07:00
local modexpr
do
local _472_, _473_ = pcall(resolve_module_name, ast, scope, parent, opts)
if ((_472_ == true) and (nil ~= _473_)) then
local modname = _473_
modexpr = utils.expr(string.format("%q", modname), "literal")
elseif (true and (nil ~= _473_)) then
local _ = _472_
local err = _473_
modexpr = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1]
else
modexpr = nil
end
end
2020-09-18 12:13:53 -07:00
if ((modexpr.type ~= "literal") or ((modexpr[1]):byte() ~= 34)) then
if opts.fallback then
return opts.fallback(modexpr)
else
return compiler.assert(false, "module name must be string literal", ast)
end
else
local mod = load_code(("return " .. modexpr[1]))()
2021-09-12 22:29:05 -07:00
local oldmod = utils.root.options["module-name"]
local _
utils.root.options["module-name"] = mod
_ = nil
local res
local function _477_()
local _476_ = search_module(mod)
if (nil ~= _476_) then
local fennel_path = _476_
2020-09-18 12:13:53 -07:00
return include_path(ast, opts, fennel_path, mod, true)
else
2021-09-12 22:29:05 -07:00
local _0 = _476_
2020-09-18 12:13:53 -07:00
local lua_path = search_module(mod, package.path)
if lua_path then
return include_path(ast, opts, lua_path, mod, false)
elseif opts.fallback then
return opts.fallback(modexpr)
else
return compiler.assert(false, ("module not found " .. mod), ast)
end
end
end
2021-09-12 22:29:05 -07:00
res = ((utils["member?"](mod, (utils.root.options.skipInclude or {})) and utils.expr("nil --[[SKIPPED INCLUDE]]--", "literal")) or include_circular_fallback(mod, modexpr, opts.fallback, ast) or utils.root.scope.includes[mod] or _477_())
utils.root.options["module-name"] = oldmod
return res
2020-09-18 12:13:53 -07:00
end
end
doc_special("include", {"module-name-literal"}, "Like require but load the target module during compilation and embed it in the\nLua output. The module must be a string literal and resolvable at compile time.")
local function eval_compiler_2a(ast, scope, parent)
2020-10-13 23:23:38 -07:00
local env = make_compiler_env(ast, scope, parent)
local opts = utils.copy(utils.root.options)
opts.scope = compiler["make-scope"](compiler.scopes.compiler)
opts.allowedGlobals = macro_globals(env, current_global_names())
2020-12-23 10:33:09 -08:00
return load_code(compiler.compile(ast, opts), wrap_env(env))(opts["module-name"], ast.filename)
2020-09-18 12:13:53 -07:00
end
SPECIALS.macros = function(ast, scope, parent)
compiler.assert((#ast == 2), "Expected one table argument", ast)
return add_macros(eval_compiler_2a(ast[2], scope, parent), ast, scope, parent)
end
doc_special("macros", {"{:macro-name-1 (fn [...] ...) ... :macro-name-N macro-body-N}"}, "Define all functions in the given table as macros local to the current scope.")
SPECIALS["eval-compiler"] = function(ast, scope, parent)
local old_first = ast[1]
ast[1] = utils.sym("do")
local val = eval_compiler_2a(ast, scope, parent)
2021-09-12 22:29:05 -07:00
do end (ast)[1] = old_first
2020-09-18 12:13:53 -07:00
return val
end
2021-09-12 22:29:05 -07:00
doc_special("eval-compiler", {"..."}, "Evaluate the body at compile-time. Use the macro system instead if possible.", true)
return {doc = doc_2a, ["current-global-names"] = current_global_names, ["load-code"] = load_code, ["macro-loaded"] = macro_loaded, ["macro-searchers"] = macro_searchers, ["make-compiler-env"] = make_compiler_env, ["search-module"] = search_module, ["make-searcher"] = make_searcher, ["wrap-env"] = wrap_env}
2020-09-18 12:13:53 -07:00
end
package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or function(...)
local utils = require("fennel.utils")
local parser = require("fennel.parser")
local friend = require("fennel.friend")
2021-02-01 17:09:15 -08:00
local unpack = (table.unpack or _G.unpack)
2020-09-18 12:13:53 -07:00
local scopes = {}
local function make_scope(parent)
local parent0 = (parent or scopes.global)
2021-09-12 22:29:05 -07:00
local _176_
2020-09-18 12:13:53 -07:00
if parent0 then
2021-09-12 22:29:05 -07:00
_176_ = ((parent0.depth or 0) + 1)
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
_176_ = 0
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
return {includes = setmetatable({}, {__index = (parent0 and parent0.includes)}), macros = setmetatable({}, {__index = (parent0 and parent0.macros)}), manglings = setmetatable({}, {__index = (parent0 and parent0.manglings)}), refedglobals = setmetatable({}, {__index = (parent0 and parent0.refedglobals)}), specials = setmetatable({}, {__index = (parent0 and parent0.specials)}), symmeta = setmetatable({}, {__index = (parent0 and parent0.symmeta)}), unmanglings = setmetatable({}, {__index = (parent0 and parent0.unmanglings)}), gensyms = setmetatable({}, {__index = (parent0 and parent0.gensyms)}), autogensyms = setmetatable({}, {__index = (parent0 and parent0.autogensyms)}), vararg = (parent0 and parent0.vararg), depth = _176_, hashfn = (parent0 and parent0.hashfn), parent = parent0}
2020-09-18 12:13:53 -07:00
end
2021-02-01 17:09:15 -08:00
local function assert_msg(ast, msg)
2021-09-12 22:29:05 -07:00
local ast_tbl
2021-02-01 17:09:15 -08:00
if ("table" == type(ast)) then
ast_tbl = ast
else
ast_tbl = {}
end
local m = getmetatable(ast)
local filename = ((m and m.filename) or ast_tbl.filename or "unknown")
local line = ((m and m.line) or ast_tbl.line or "?")
2021-09-12 22:29:05 -07:00
local target = tostring((utils["sym?"](ast_tbl[1]) or ast_tbl[1] or "()"))
return string.format("%s:%s: Compile error in '%s': %s", filename, line, target, msg)
2021-02-01 17:09:15 -08:00
end
2020-09-18 12:13:53 -07:00
local function assert_compile(condition, msg, ast)
if not condition then
2021-09-12 22:29:05 -07:00
local _let_179_ = (utils.root.options or {})
local source = _let_179_["source"]
local unfriendly = _let_179_["unfriendly"]
2020-09-18 12:13:53 -07:00
utils.root.reset()
2021-09-12 22:29:05 -07:00
if (unfriendly or not friend or not _G.io or not _G.io.read) then
2021-02-01 17:09:15 -08:00
error(assert_msg(ast, msg), 0)
2020-09-18 12:13:53 -07:00
else
friend["assert-compile"](condition, msg, ast, source)
end
end
return condition
end
scopes.global = make_scope()
scopes.global.vararg = true
scopes.compiler = make_scope(scopes.global)
scopes.macro = scopes.global
2021-09-12 22:29:05 -07:00
local serialize_subst = {["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\n"] = "n", ["\11"] = "\\v", ["\12"] = "\\f"}
2020-09-18 12:13:53 -07:00
local function serialize_string(str)
2021-09-12 22:29:05 -07:00
local function _182_(_241)
2020-09-18 12:13:53 -07:00
return ("\\" .. _241:byte())
end
2021-09-12 22:29:05 -07:00
return string.gsub(string.gsub(string.format("%q", str), ".", serialize_subst), "[\128-\255]", _182_)
2020-09-18 12:13:53 -07:00
end
local function global_mangling(str)
if utils["valid-lua-identifier?"](str) then
return str
else
2021-09-12 22:29:05 -07:00
local function _183_(_241)
2020-10-13 23:23:38 -07:00
return string.format("_%02x", _241:byte())
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
return ("__fnl_global__" .. str:gsub("[^%w]", _183_))
2020-09-18 12:13:53 -07:00
end
end
local function global_unmangling(identifier)
2021-09-12 22:29:05 -07:00
local _185_ = string.match(identifier, "^__fnl_global__(.*)$")
if (nil ~= _185_) then
local rest = _185_
local _186_
local function _187_(_241)
2020-09-18 12:13:53 -07:00
return string.char(tonumber(_241:sub(2), 16))
end
2021-09-12 22:29:05 -07:00
_186_ = string.gsub(rest, "_[%da-f][%da-f]", _187_)
return _186_
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
local _ = _185_
2020-09-18 12:13:53 -07:00
return identifier
end
end
local allowed_globals = nil
2021-09-12 22:29:05 -07:00
local function global_allowed_3f(name)
2020-12-23 10:33:09 -08:00
return (not allowed_globals or utils["member?"](name, allowed_globals))
2020-10-13 23:23:38 -07:00
end
local function unique_mangling(original, mangling, scope, append)
2021-09-12 22:29:05 -07:00
if (scope.unmanglings[mangling] and not scope.gensyms[mangling]) then
2020-10-13 23:23:38 -07:00
return unique_mangling(original, (original .. append), scope, (append + 1))
else
return mangling
2020-09-18 12:13:53 -07:00
end
end
local function local_mangling(str, scope, ast, temp_manglings)
2020-10-13 23:23:38 -07:00
assert_compile(not utils["multi-sym?"](str), ("unexpected multi symbol " .. str), ast)
2021-09-12 22:29:05 -07:00
local raw
if ((utils["lua-keywords"])[str] or str:match("^%d")) then
2020-10-13 23:23:38 -07:00
raw = ("_" .. str)
else
raw = str
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
local mangling
local function _191_(_241)
2020-10-13 23:23:38 -07:00
return string.format("_%02x", _241:byte())
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
mangling = string.gsub(string.gsub(raw, "-", "_"), "[^%w_]", _191_)
2020-10-13 23:23:38 -07:00
local unique = unique_mangling(mangling, mangling, scope, 0)
2021-09-12 22:29:05 -07:00
do end (scope.unmanglings)[unique] = str
2020-09-18 12:13:53 -07:00
do
local manglings = (temp_manglings or scope.manglings)
2021-09-12 22:29:05 -07:00
do end (manglings)[str] = unique
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
return unique
2020-09-18 12:13:53 -07:00
end
local function apply_manglings(scope, new_manglings, ast)
for raw, mangled in pairs(new_manglings) do
assert_compile(not scope.refedglobals[mangled], ("use of global " .. raw .. " is aliased by a local"), ast)
2021-09-12 22:29:05 -07:00
do end (scope.manglings)[raw] = mangled
2020-09-18 12:13:53 -07:00
end
return nil
end
local function combine_parts(parts, scope)
local ret = (scope.manglings[parts[1]] or global_mangling(parts[1]))
2020-12-23 10:33:09 -08:00
for i = 2, #parts do
2020-09-18 12:13:53 -07:00
if utils["valid-lua-identifier?"](parts[i]) then
if (parts["multi-sym-method-call"] and (i == #parts)) then
ret = (ret .. ":" .. parts[i])
else
ret = (ret .. "." .. parts[i])
end
else
ret = (ret .. "[" .. serialize_string(parts[i]) .. "]")
end
end
return ret
end
2021-09-12 22:29:05 -07:00
local function next_append()
utils.root.scope["gensym-append"] = ((utils.root.scope["gensym-append"] or 0) + 1)
return ("_" .. utils.root.scope["gensym-append"] .. "_")
end
local function gensym(scope, base, _3fsuffix)
local mangling = ((base or "") .. next_append() .. (_3fsuffix or ""))
2020-09-18 12:13:53 -07:00
while scope.unmanglings[mangling] do
2021-09-12 22:29:05 -07:00
mangling = ((base or "") .. next_append() .. (_3fsuffix or ""))
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
scope.unmanglings[mangling] = (base or true)
2021-09-12 22:29:05 -07:00
do end (scope.gensyms)[mangling] = true
2020-09-18 12:13:53 -07:00
return mangling
end
local function autogensym(base, scope)
2021-09-12 22:29:05 -07:00
local _194_ = utils["multi-sym?"](base)
if (nil ~= _194_) then
local parts = _194_
2020-09-18 12:13:53 -07:00
parts[1] = autogensym(parts[1], scope)
return table.concat(parts, ((parts["multi-sym-method-call"] and ":") or "."))
else
2021-09-12 22:29:05 -07:00
local _ = _194_
local function _195_()
local mangling = gensym(scope, base:sub(1, ( - 2)), "auto")
do end (scope.autogensyms)[base] = mangling
2020-09-18 12:13:53 -07:00
return mangling
end
2021-09-12 22:29:05 -07:00
return (scope.autogensyms[base] or _195_())
2020-09-18 12:13:53 -07:00
end
end
local function check_binding_valid(symbol, scope, ast)
2021-09-12 22:29:05 -07:00
local name = tostring(symbol)
assert_compile(not name:find("&"), "illegal character &")
2020-09-18 12:13:53 -07:00
assert_compile(not (scope.specials[name] or scope.macros[name]), ("local %s was overshadowed by a special form or macro"):format(name), ast)
2020-10-13 23:23:38 -07:00
return assert_compile(not utils["quoted?"](symbol), string.format("macro tried to bind %s without gensym", name), symbol)
2020-09-18 12:13:53 -07:00
end
local function declare_local(symbol, meta, scope, ast, temp_manglings)
check_binding_valid(symbol, scope, ast)
2021-09-12 22:29:05 -07:00
local name = tostring(symbol)
2020-10-13 23:23:38 -07:00
assert_compile(not utils["multi-sym?"](name), ("unexpected multi symbol " .. name), ast)
2021-09-12 22:29:05 -07:00
do end (scope.symmeta)[name] = meta
2020-09-18 12:13:53 -07:00
return local_mangling(name, scope, ast, temp_manglings)
end
2020-10-13 23:23:38 -07:00
local function hashfn_arg_name(name, multi_sym_parts, scope)
if not scope.hashfn then
return nil
elseif (name == "$") then
return "$1"
elseif multi_sym_parts then
if (multi_sym_parts and (multi_sym_parts[1] == "$")) then
multi_sym_parts[1] = "$1"
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
return table.concat(multi_sym_parts, ".")
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
end
local function symbol_to_expression(symbol, scope, reference_3f)
utils.hook("symbol-to-expression", symbol, scope, reference_3f)
local name = symbol[1]
local multi_sym_parts = utils["multi-sym?"](name)
local name0 = (hashfn_arg_name(name, multi_sym_parts, scope) or name)
local parts = (multi_sym_parts or {name0})
2020-09-18 12:13:53 -07:00
local etype = (((#parts > 1) and "expression") or "sym")
2020-10-13 23:23:38 -07:00
local local_3f = scope.manglings[parts[1]]
if (local_3f and scope.symmeta[parts[1]]) then
2020-09-18 12:13:53 -07:00
scope.symmeta[parts[1]]["used"] = true
end
2021-09-12 22:29:05 -07:00
assert_compile(not scope.macros[parts[1]], "tried to reference a macro at runtime", symbol)
assert_compile((not reference_3f or local_3f or ("_ENV" == parts[1]) or global_allowed_3f(parts[1])), ("unknown global in strict mode: " .. tostring(parts[1])), symbol)
2020-10-13 23:23:38 -07:00
if (allowed_globals and not local_3f) then
2020-09-18 12:13:53 -07:00
utils.root.scope.refedglobals[parts[1]] = true
end
return utils.expr(combine_parts(parts, scope), etype)
end
local function emit(chunk, out, ast)
if (type(out) == "table") then
return table.insert(chunk, out)
else
return table.insert(chunk, {ast = ast, leaf = out})
end
end
local function peephole(chunk)
if chunk.leaf then
return chunk
2021-09-12 22:29:05 -07:00
elseif ((#chunk >= 3) and ((chunk[(#chunk - 2)]).leaf == "do") and not (chunk[(#chunk - 1)]).leaf and (chunk[#chunk].leaf == "end")) then
2020-09-18 12:13:53 -07:00
local kid = peephole(chunk[(#chunk - 1)])
local new_chunk = {ast = chunk.ast}
2020-12-23 10:33:09 -08:00
for i = 1, (#chunk - 3) do
2020-09-18 12:13:53 -07:00
table.insert(new_chunk, peephole(chunk[i]))
end
2020-12-23 10:33:09 -08:00
for i = 1, #kid do
2020-09-18 12:13:53 -07:00
table.insert(new_chunk, kid[i])
end
return new_chunk
else
return utils.map(chunk, peephole)
end
end
2021-04-12 16:52:31 -07:00
local function ast_source(ast)
local m = getmetatable(ast)
return ((m and m.line and m) or (("table" == type(ast)) and ast) or {})
end
2021-09-12 22:29:05 -07:00
local function flatten_chunk_correlated(main_chunk, options)
2020-09-18 12:13:53 -07:00
local function flatten(chunk, out, last_line, file)
local last_line0 = last_line
if chunk.leaf then
out[last_line0] = ((out[last_line0] or "") .. " " .. chunk.leaf)
else
for _, subchunk in ipairs(chunk) do
if (subchunk.leaf or (#subchunk > 0)) then
2021-04-12 16:52:31 -07:00
local source = ast_source(subchunk.ast)
2021-09-12 22:29:05 -07:00
if (file == source.filename) then
2021-04-12 16:52:31 -07:00
last_line0 = math.max(last_line0, (source.line or 0))
2020-09-18 12:13:53 -07:00
end
last_line0 = flatten(subchunk, out, last_line0, file)
end
end
end
return last_line0
end
local out = {}
2021-09-12 22:29:05 -07:00
local last = flatten(main_chunk, out, 1, options.filename)
2020-09-18 12:13:53 -07:00
for i = 1, last do
if (out[i] == nil) then
out[i] = ""
end
end
return table.concat(out, "\n")
end
local function flatten_chunk(sm, chunk, tab, depth)
if chunk.leaf then
local code = chunk.leaf
local info = chunk.ast
if sm then
2021-04-12 16:52:31 -07:00
table.insert(sm, {(info and info.filename), (info and info.line)})
2020-09-18 12:13:53 -07:00
end
return code
else
2021-09-12 22:29:05 -07:00
local tab0
2020-09-18 12:13:53 -07:00
do
2021-09-12 22:29:05 -07:00
local _208_ = tab
if (_208_ == true) then
2020-09-18 12:13:53 -07:00
tab0 = " "
2021-09-12 22:29:05 -07:00
elseif (_208_ == false) then
2020-09-18 12:13:53 -07:00
tab0 = ""
2021-09-12 22:29:05 -07:00
elseif (_208_ == tab) then
2020-09-18 12:13:53 -07:00
tab0 = tab
2021-09-12 22:29:05 -07:00
elseif (_208_ == nil) then
2020-09-18 12:13:53 -07:00
tab0 = ""
else
tab0 = nil
end
end
local function parter(c)
if (c.leaf or (#c > 0)) then
local sub = flatten_chunk(sm, c, tab0, (depth + 1))
if (depth > 0) then
2020-10-13 23:23:38 -07:00
return (tab0 .. sub:gsub("\n", ("\n" .. tab0)))
else
return sub
2020-09-18 12:13:53 -07:00
end
end
end
return table.concat(utils.map(chunk, parter), "\n")
end
end
local fennel_sourcemap = {}
local function make_short_src(source)
local source0 = source:gsub("\n", " ")
if (#source0 <= 49) then
return ("[fennel \"" .. source0 .. "\"]")
else
return ("[fennel \"" .. source0:sub(1, 46) .. "...\"]")
end
end
local function flatten(chunk, options)
local chunk0 = peephole(chunk)
if options.correlate then
2021-09-12 22:29:05 -07:00
return flatten_chunk_correlated(chunk0, options), {}
2020-09-18 12:13:53 -07:00
else
local sm = {}
local ret = flatten_chunk(sm, chunk0, options.indent, 0)
if sm then
2021-04-12 16:52:31 -07:00
sm.short_src = (options.filename or make_short_src((options.source or ret)))
2020-09-18 12:13:53 -07:00
if options.filename then
2020-10-13 23:23:38 -07:00
sm.key = ("@" .. options.filename)
2020-09-18 12:13:53 -07:00
else
2020-10-13 23:23:38 -07:00
sm.key = ret
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
fennel_sourcemap[sm.key] = sm
2020-09-18 12:13:53 -07:00
end
return ret, sm
end
end
local function make_metadata()
2021-09-12 22:29:05 -07:00
local function _217_(self, tgt, key)
2020-09-18 12:13:53 -07:00
if self[tgt] then
return self[tgt][key]
end
end
2021-09-12 22:29:05 -07:00
local function _219_(self, tgt, key, value)
2020-09-18 12:13:53 -07:00
self[tgt] = (self[tgt] or {})
2021-09-12 22:29:05 -07:00
do end (self[tgt])[key] = value
2020-09-18 12:13:53 -07:00
return tgt
end
2021-09-12 22:29:05 -07:00
local function _220_(self, tgt, ...)
2020-09-18 12:13:53 -07:00
local kv_len = select("#", ...)
local kvs = {...}
if ((kv_len % 2) ~= 0) then
error("metadata:setall() expected even number of k/v pairs")
end
self[tgt] = (self[tgt] or {})
for i = 1, kv_len, 2 do
self[tgt][kvs[i]] = kvs[(i + 1)]
end
return tgt
end
2021-09-12 22:29:05 -07:00
return setmetatable({}, {__index = {get = _217_, set = _219_, setall = _220_}, __mode = "k"})
2020-09-18 12:13:53 -07:00
end
local function exprs1(exprs)
2021-09-12 22:29:05 -07:00
return table.concat(utils.map(exprs, tostring), ", ")
2021-04-12 16:52:31 -07:00
end
2020-09-18 12:13:53 -07:00
local function keep_side_effects(exprs, chunk, start, ast)
2021-09-12 22:29:05 -07:00
local start0 = (start or 1)
for j = start0, #exprs do
2020-09-18 12:13:53 -07:00
local se = exprs[j]
if ((se.type == "expression") and (se[1] ~= "nil")) then
2020-10-13 23:23:38 -07:00
emit(chunk, string.format("do local _ = %s end", tostring(se)), ast)
2020-09-18 12:13:53 -07:00
elseif (se.type == "statement") then
2021-09-12 22:29:05 -07:00
local code = tostring(se)
local disambiguated
if (code:byte() == 40) then
disambiguated = ("do end " .. code)
else
disambiguated = code
end
emit(chunk, disambiguated, ast)
2020-09-18 12:13:53 -07:00
end
end
return nil
end
local function handle_compile_opts(exprs, parent, opts, ast)
if opts.nval then
local n = opts.nval
local len = #exprs
if (n ~= len) then
if (len > n) then
keep_side_effects(exprs, parent, (n + 1), ast)
2020-12-23 10:33:09 -08:00
for i = (n + 1), len do
2020-09-18 12:13:53 -07:00
exprs[i] = nil
end
else
2020-12-23 10:33:09 -08:00
for i = (#exprs + 1), n do
2020-09-18 12:13:53 -07:00
exprs[i] = utils.expr("nil", "literal")
end
end
end
end
if opts.tail then
2020-10-13 23:23:38 -07:00
emit(parent, string.format("return %s", exprs1(exprs)), ast)
2020-09-18 12:13:53 -07:00
end
if opts.target then
local result = exprs1(exprs)
2021-09-12 22:29:05 -07:00
local function _228_()
2020-10-13 23:23:38 -07:00
if (result == "") then
return "nil"
else
return result
end
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
emit(parent, string.format("%s = %s", opts.target, _228_()), ast)
2020-09-18 12:13:53 -07:00
end
if (opts.tail or opts.target) then
2020-10-13 23:23:38 -07:00
return {returned = true}
else
2021-09-12 22:29:05 -07:00
local _230_ = exprs
_230_["returned"] = true
return _230_
2020-10-13 23:23:38 -07:00
end
end
local function find_macro(ast, scope, multi_sym_parts)
local function find_in_table(t, i)
if (i <= #multi_sym_parts) then
return find_in_table((utils["table?"](t) and t[multi_sym_parts[i]]), (i + 1))
else
return t
end
end
2021-09-12 22:29:05 -07:00
local macro_2a = (utils["sym?"](ast[1]) and scope.macros[tostring(ast[1])])
2020-10-13 23:23:38 -07:00
if (not macro_2a and multi_sym_parts) then
local nested_macro = find_in_table(scope.macros, 1)
assert_compile((not scope.macros[multi_sym_parts[1]] or (type(nested_macro) == "function")), "macro not found in imported macro module", ast)
return nested_macro
2020-09-18 12:13:53 -07:00
else
2020-10-13 23:23:38 -07:00
return macro_2a
2020-09-18 12:13:53 -07:00
end
end
local function macroexpand_2a(ast, scope, once)
2021-09-12 22:29:05 -07:00
local _234_
2021-04-12 16:52:31 -07:00
if utils["list?"](ast) then
2021-09-12 22:29:05 -07:00
_234_ = find_macro(ast, scope, utils["multi-sym?"](ast[1]))
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
_234_ = nil
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
if (_234_ == false) then
2021-04-12 16:52:31 -07:00
return ast
2021-09-12 22:29:05 -07:00
elseif (nil ~= _234_) then
local macro_2a = _234_
2021-04-12 16:52:31 -07:00
local old_scope = scopes.macro
2021-09-12 22:29:05 -07:00
local _
2021-04-12 16:52:31 -07:00
scopes.macro = scope
_ = nil
local ok, transformed = nil, nil
2021-09-12 22:29:05 -07:00
local function _236_()
2021-04-12 16:52:31 -07:00
return macro_2a(unpack(ast, 2))
end
2021-09-12 22:29:05 -07:00
ok, transformed = xpcall(_236_, debug.traceback)
2021-04-12 16:52:31 -07:00
scopes.macro = old_scope
assert_compile(ok, transformed, ast)
if (once or not transformed) then
return transformed
2020-09-18 12:13:53 -07:00
else
2021-04-12 16:52:31 -07:00
return macroexpand_2a(transformed, scope)
2020-09-18 12:13:53 -07:00
end
2021-04-12 16:52:31 -07:00
else
2021-09-12 22:29:05 -07:00
local _ = _234_
2021-04-12 16:52:31 -07:00
return ast
2020-09-18 12:13:53 -07:00
end
end
2020-10-13 23:23:38 -07:00
local function compile_special(ast, scope, parent, opts, special)
local exprs = (special(ast, scope, parent, opts) or utils.expr("nil", "literal"))
2021-09-12 22:29:05 -07:00
local exprs0
if ("table" ~= type(exprs)) then
2020-10-13 23:23:38 -07:00
exprs0 = utils.expr(exprs, "expression")
else
exprs0 = exprs
end
2021-09-12 22:29:05 -07:00
local exprs2
2020-10-13 23:23:38 -07:00
if utils["expr?"](exprs0) then
exprs2 = {exprs0}
else
exprs2 = exprs0
end
if not exprs2.returned then
return handle_compile_opts(exprs2, parent, opts, ast)
elseif (opts.tail or opts.target) then
return {returned = true}
else
return exprs2
end
end
2020-12-23 10:33:09 -08:00
local function compile_function_call(ast, scope, parent, opts, compile1, len)
local fargs = {}
2021-09-12 22:29:05 -07:00
local fcallee = (compile1(ast[1], scope, parent, {nval = 1}))[1]
assert_compile((("string" == type(ast[1])) or (fcallee.type ~= "literal")), ("cannot call literal value " .. tostring(ast[1])), ast)
2020-12-23 10:33:09 -08:00
for i = 2, len do
2021-09-12 22:29:05 -07:00
local subexprs
local _242_
2020-12-23 10:33:09 -08:00
if (i ~= len) then
2021-09-12 22:29:05 -07:00
_242_ = 1
2020-12-23 10:33:09 -08:00
else
2021-09-12 22:29:05 -07:00
_242_ = nil
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
subexprs = compile1(ast[i], scope, parent, {nval = _242_})
2020-12-23 10:33:09 -08:00
table.insert(fargs, (subexprs[1] or utils.expr("nil", "literal")))
if (i == len) then
for j = 2, #subexprs do
table.insert(fargs, subexprs[j])
end
else
keep_side_effects(subexprs, parent, 2, ast[i])
end
end
2021-09-12 22:29:05 -07:00
local pat
if ("string" == type(ast[1])) then
pat = "(%s)(%s)"
else
pat = "%s(%s)"
end
local call = string.format(pat, tostring(fcallee), exprs1(fargs))
2020-12-23 10:33:09 -08:00
return handle_compile_opts({utils.expr(call, "statement")}, parent, opts, ast)
end
2020-10-13 23:23:38 -07:00
local function compile_call(ast, scope, parent, opts, compile1)
utils.hook("call", ast, scope)
local len = #ast
local first = ast[1]
local multi_sym_parts = utils["multi-sym?"](first)
2021-09-12 22:29:05 -07:00
local special = (utils["sym?"](first) and scope.specials[tostring(first)])
2020-10-13 23:23:38 -07:00
assert_compile((len > 0), "expected a function, macro, or special to call", ast)
if special then
return compile_special(ast, scope, parent, opts, special)
elseif (multi_sym_parts and multi_sym_parts["multi-sym-method-call"]) then
local table_with_method = table.concat({unpack(multi_sym_parts, 1, (#multi_sym_parts - 1))}, ".")
local method_to_call = multi_sym_parts[#multi_sym_parts]
2021-04-12 16:52:31 -07:00
local new_ast = utils.list(utils.sym(":", nil, scope), utils.sym(table_with_method, nil, scope), method_to_call, select(2, unpack(ast)))
2020-10-13 23:23:38 -07:00
return compile1(new_ast, scope, parent, opts)
else
2020-12-23 10:33:09 -08:00
return compile_function_call(ast, scope, parent, opts, compile1, len)
2020-10-13 23:23:38 -07:00
end
end
local function compile_varg(ast, scope, parent, opts)
assert_compile(scope.vararg, "unexpected vararg", ast)
return handle_compile_opts({utils.expr("...", "varg")}, parent, opts, ast)
end
local function compile_sym(ast, scope, parent, opts)
local multi_sym_parts = utils["multi-sym?"](ast)
assert_compile(not (multi_sym_parts and multi_sym_parts["multi-sym-method-call"]), "multisym method calls may only be in call position", ast)
2021-09-12 22:29:05 -07:00
local e
2020-10-13 23:23:38 -07:00
if (ast[1] == "nil") then
e = utils.expr("nil", "literal")
else
e = symbol_to_expression(ast, scope, true)
end
return handle_compile_opts({e}, parent, opts, ast)
end
2021-02-01 17:09:15 -08:00
local function serialize_number(n)
2021-09-12 22:29:05 -07:00
local _248_ = string.gsub(tostring(n), ",", ".")
return _248_
2021-02-01 17:09:15 -08:00
end
2020-12-23 10:33:09 -08:00
local function compile_scalar(ast, _scope, parent, opts)
2021-09-12 22:29:05 -07:00
local serialize
2020-10-13 23:23:38 -07:00
do
2021-09-12 22:29:05 -07:00
local _249_ = type(ast)
if (_249_ == "nil") then
2020-10-13 23:23:38 -07:00
serialize = tostring
2021-09-12 22:29:05 -07:00
elseif (_249_ == "boolean") then
2020-10-13 23:23:38 -07:00
serialize = tostring
2021-09-12 22:29:05 -07:00
elseif (_249_ == "string") then
2020-10-13 23:23:38 -07:00
serialize = serialize_string
2021-09-12 22:29:05 -07:00
elseif (_249_ == "number") then
2021-02-01 17:09:15 -08:00
serialize = serialize_number
2020-09-18 12:13:53 -07:00
else
2020-10-13 23:23:38 -07:00
serialize = nil
end
end
return handle_compile_opts({utils.expr(serialize(ast), "literal")}, parent, opts)
end
local function compile_table(ast, scope, parent, opts, compile1)
local buffer = {}
2020-12-23 10:33:09 -08:00
for i = 1, #ast do
2020-10-13 23:23:38 -07:00
local nval = ((i ~= #ast) and 1)
2020-12-23 10:33:09 -08:00
table.insert(buffer, exprs1(compile1(ast[i], scope, parent, {nval = nval})))
2020-10-13 23:23:38 -07:00
end
local function write_other_values(k)
if ((type(k) ~= "number") or (math.floor(k) ~= k) or (k < 1) or (k > #ast)) then
if ((type(k) == "string") and utils["valid-lua-identifier?"](k)) then
return {k, k}
else
2021-09-12 22:29:05 -07:00
local _let_251_ = compile1(k, scope, parent, {nval = 1})
local compiled = _let_251_[1]
2020-10-13 23:23:38 -07:00
local kstr = ("[" .. tostring(compiled) .. "]")
return {kstr, k}
2020-09-18 12:13:53 -07:00
end
end
2020-10-13 23:23:38 -07:00
end
do
2021-09-12 22:29:05 -07:00
local keys
2020-09-18 12:13:53 -07:00
do
2021-09-12 22:29:05 -07:00
local tbl_13_auto = {}
for k, v in utils.stablepairs(ast) do
tbl_13_auto[(#tbl_13_auto + 1)] = write_other_values(k, v)
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
keys = tbl_13_auto
end
local function _256_(_254_)
local _arg_255_ = _254_
local k1 = _arg_255_[1]
local k2 = _arg_255_[2]
local _let_257_ = compile1(ast[k2], scope, parent, {nval = 1})
local v = _let_257_[1]
2021-04-12 16:52:31 -07:00
return string.format("%s = %s", k1, tostring(v))
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
utils.map(keys, _256_, buffer)
2020-10-13 23:23:38 -07:00
end
return handle_compile_opts({utils.expr(("{" .. table.concat(buffer, ", ") .. "}"), "expression")}, parent, opts, ast)
end
local function compile1(ast, scope, parent, opts)
local opts0 = (opts or {})
local ast0 = macroexpand_2a(ast, scope)
if utils["list?"](ast0) then
return compile_call(ast0, scope, parent, opts0, compile1)
elseif utils["varg?"](ast0) then
return compile_varg(ast0, scope, parent, opts0)
elseif utils["sym?"](ast0) then
return compile_sym(ast0, scope, parent, opts0)
elseif (type(ast0) == "table") then
return compile_table(ast0, scope, parent, opts0, compile1)
elseif ((type(ast0) == "nil") or (type(ast0) == "boolean") or (type(ast0) == "number") or (type(ast0) == "string")) then
return compile_scalar(ast0, scope, parent, opts0)
2020-09-18 12:13:53 -07:00
else
2020-10-13 23:23:38 -07:00
return assert_compile(false, ("could not compile value of type " .. type(ast0)), ast0)
2020-09-18 12:13:53 -07:00
end
end
local function destructure(to, from, ast, scope, parent, opts)
local opts0 = (opts or {})
2021-09-12 22:29:05 -07:00
local _let_259_ = opts0
local isvar = _let_259_["isvar"]
local declaration = _let_259_["declaration"]
local forceglobal = _let_259_["forceglobal"]
local forceset = _let_259_["forceset"]
local symtype = _let_259_["symtype"]
2020-12-23 10:33:09 -08:00
local symtype0 = ("_" .. (symtype or "dst"))
2021-09-12 22:29:05 -07:00
local setter
2020-09-18 12:13:53 -07:00
if declaration then
setter = "local %s = %s"
else
setter = "%s = %s"
end
local new_manglings = {}
local function getname(symbol, up1)
local raw = symbol[1]
2021-04-12 16:52:31 -07:00
assert_compile(not (opts0.nomulti and utils["multi-sym?"](raw)), ("unexpected multi symbol " .. raw), up1)
2020-09-18 12:13:53 -07:00
if declaration then
2020-12-23 10:33:09 -08:00
return declare_local(symbol, nil, scope, symbol, new_manglings)
2020-09-18 12:13:53 -07:00
else
2020-10-13 23:23:38 -07:00
local parts = (utils["multi-sym?"](raw) or {raw})
2020-09-18 12:13:53 -07:00
local meta = scope.symmeta[parts[1]]
2021-09-12 22:29:05 -07:00
assert_compile(not raw:find(":"), "cannot set method sym", symbol)
2020-09-18 12:13:53 -07:00
if ((#parts == 1) and not forceset) then
2020-10-13 23:23:38 -07:00
assert_compile(not (forceglobal and meta), string.format("global %s conflicts with local", tostring(symbol)), symbol)
2020-09-18 12:13:53 -07:00
assert_compile(not (meta and not meta.var), ("expected var " .. raw), symbol)
2021-04-12 16:52:31 -07:00
assert_compile((meta or not opts0.noundef), ("expected local " .. parts[1]), symbol)
2020-09-18 12:13:53 -07:00
end
if forceglobal then
assert_compile(not scope.symmeta[scope.unmanglings[raw]], ("global " .. raw .. " conflicts with local"), symbol)
2021-09-12 22:29:05 -07:00
do end (scope.manglings)[raw] = global_mangling(raw)
do end (scope.unmanglings)[global_mangling(raw)] = raw
2020-09-18 12:13:53 -07:00
if allowed_globals then
table.insert(allowed_globals, raw)
end
end
return symbol_to_expression(symbol, scope)[1]
end
end
local function compile_top_target(lvalues)
2021-09-12 22:29:05 -07:00
local inits
local function _265_(_241)
2020-09-18 12:13:53 -07:00
if scope.manglings[_241] then
return _241
else
return "nil"
end
end
2021-09-12 22:29:05 -07:00
inits = utils.map(lvalues, _265_)
2020-09-18 12:13:53 -07:00
local init = table.concat(inits, ", ")
local lvalue = table.concat(lvalues, ", ")
local plen, plast = #parent, parent[#parent]
local ret = compile1(from, scope, parent, {target = lvalue})
if declaration then
for pi = plen, #parent do
if (parent[pi] == plast) then
plen = pi
end
end
if ((#parent == (plen + 1)) and parent[#parent].leaf) then
parent[#parent]["leaf"] = ("local " .. parent[#parent].leaf)
2021-04-12 16:52:31 -07:00
elseif (init == "nil") then
table.insert(parent, (plen + 1), {ast = ast, leaf = ("local " .. lvalue)})
2020-09-18 12:13:53 -07:00
else
table.insert(parent, (plen + 1), {ast = ast, leaf = ("local " .. lvalue .. " = " .. init)})
end
end
return ret
end
2020-12-23 10:33:09 -08:00
local function destructure_sym(left, rightexprs, up1, top_3f)
local lname = getname(left, up1)
check_binding_valid(left, scope, left)
if top_3f then
compile_top_target({lname})
else
emit(parent, setter:format(lname, exprs1(rightexprs)), left)
end
if declaration then
2021-09-12 22:29:05 -07:00
scope.symmeta[tostring(left)] = {var = isvar}
2020-12-23 10:33:09 -08:00
return nil
end
end
local function destructure_table(left, rightexprs, top_3f, destructure1)
local s = gensym(scope, symtype0)
2021-09-12 22:29:05 -07:00
local right
2020-12-23 10:33:09 -08:00
do
2021-09-12 22:29:05 -07:00
local _272_
2020-12-23 10:33:09 -08:00
if top_3f then
2021-09-12 22:29:05 -07:00
_272_ = exprs1(compile1(from, scope, parent))
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
_272_ = exprs1(rightexprs)
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
if (_272_ == "") then
2020-09-18 12:13:53 -07:00
right = "nil"
2021-09-12 22:29:05 -07:00
elseif (nil ~= _272_) then
local right0 = _272_
2020-12-23 10:33:09 -08:00
right = right0
else
right = nil
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
end
emit(parent, string.format("local %s = %s", s, right), left)
for k, v in utils.stablepairs(left) do
if not (("number" == type(k)) and tostring(left[(k - 1)]):find("^&")) then
2021-09-12 22:29:05 -07:00
if (utils["sym?"](v) and (tostring(v) == "&")) then
2020-10-13 23:23:38 -07:00
local unpack_str = "{(table.unpack or unpack)(%s, %s)}"
local formatted = string.format(unpack_str, s, k)
2020-09-18 12:13:53 -07:00
local subexpr = utils.expr(formatted, "expression")
2020-12-23 10:33:09 -08:00
assert_compile((utils["sequence?"](left) and (nil == left[(k + 2)])), "expected rest argument before last parameter", left)
2020-09-18 12:13:53 -07:00
destructure1(left[(k + 1)], {subexpr}, left)
2021-09-12 22:29:05 -07:00
elseif (utils["sym?"](k) and (tostring(k) == "&as")) then
2020-12-23 10:33:09 -08:00
destructure_sym(v, {utils.expr(tostring(s))}, left)
2021-09-12 22:29:05 -07:00
elseif (utils["sequence?"](left) and (tostring(v) == "&as")) then
2020-12-23 10:33:09 -08:00
local _, next_sym, trailing = select(k, unpack(left))
assert_compile((nil == trailing), "expected &as argument before last parameter", left)
destructure_sym(next_sym, {utils.expr(tostring(s))}, left)
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
local key
2020-12-23 10:33:09 -08:00
if (type(k) == "string") then
key = serialize_string(k)
else
key = k
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
local subexpr = utils.expr(string.format("%s[%s]", s, key), "expression")
2020-09-18 12:13:53 -07:00
destructure1(v, {subexpr}, left)
end
end
2020-12-23 10:33:09 -08:00
end
return nil
end
local function destructure_values(left, up1, top_3f, destructure1)
local left_names, tables = {}, {}
for i, name in ipairs(left) do
if utils["sym?"](name) then
table.insert(left_names, getname(name, up1))
2020-09-18 12:13:53 -07:00
else
2020-12-23 10:33:09 -08:00
local symname = gensym(scope, symtype0)
table.insert(left_names, symname)
2021-09-12 22:29:05 -07:00
do end (tables)[i] = {name, utils.expr(symname, "sym")}
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
end
assert_compile(top_3f, "can't nest multi-value destructuring", left)
compile_top_target(left_names)
if declaration then
for _, sym in ipairs(left) do
2021-09-12 22:29:05 -07:00
if utils["sym?"](sym) then
scope.symmeta[tostring(sym)] = {var = isvar}
end
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
end
for _, pair in utils.stablepairs(tables) do
destructure1(pair[1], {pair[2]}, left)
end
return nil
end
local function destructure1(left, rightexprs, up1, top_3f)
if (utils["sym?"](left) and (left[1] ~= "nil")) then
destructure_sym(left, rightexprs, up1, top_3f)
elseif utils["table?"](left) then
destructure_table(left, rightexprs, top_3f, destructure1)
elseif utils["list?"](left) then
destructure_values(left, up1, top_3f, destructure1)
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
assert_compile(false, string.format("unable to bind %s %s", type(left), tostring(left)), (((type((up1)[2]) == "table") and (up1)[2]) or up1))
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
if top_3f then
2020-09-18 12:13:53 -07:00
return {returned = true}
end
end
local ret = destructure1(to, nil, ast, true)
2020-10-13 23:23:38 -07:00
utils.hook("destructure", from, to, scope)
2020-09-18 12:13:53 -07:00
apply_manglings(scope, new_manglings, ast)
return ret
end
local function require_include(ast, scope, parent, opts)
opts.fallback = function(e)
2020-10-13 23:23:38 -07:00
return utils.expr(string.format("require(%s)", tostring(e)), "statement")
2020-09-18 12:13:53 -07:00
end
return scopes.global.specials.include(ast, scope, parent, opts)
end
local function compile_stream(strm, options)
local opts = utils.copy(options)
local old_globals = allowed_globals
local scope = (opts.scope or make_scope(scopes.global))
local vals = {}
local chunk = {}
2021-09-12 22:29:05 -07:00
do end (function(tgt, m, ...) return tgt[m](tgt, ...) end)(utils.root, "set-reset")
2020-09-18 12:13:53 -07:00
allowed_globals = opts.allowedGlobals
if (opts.indent == nil) then
opts.indent = " "
end
if opts.requireAsInclude then
scope.specials.require = require_include
end
utils.root.chunk, utils.root.scope, utils.root.options = chunk, scope, opts
2020-12-23 10:33:09 -08:00
for _, val in parser.parser(strm, opts.filename, opts) do
table.insert(vals, val)
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
for i = 1, #vals do
2020-09-18 12:13:53 -07:00
local exprs = compile1(vals[i], scope, chunk, {nval = (((i < #vals) and 0) or nil), tail = (i == #vals)})
keep_side_effects(exprs, chunk, nil, vals[i])
end
allowed_globals = old_globals
utils.root.reset()
return flatten(chunk, opts)
end
local function compile_string(str, opts)
return compile_stream(parser["string-stream"](str), (opts or {}))
end
local function compile(ast, opts)
local opts0 = utils.copy(opts)
local old_globals = allowed_globals
local chunk = {}
local scope = (opts0.scope or make_scope(scopes.global))
2021-09-12 22:29:05 -07:00
do end (function(tgt, m, ...) return tgt[m](tgt, ...) end)(utils.root, "set-reset")
2020-09-18 12:13:53 -07:00
allowed_globals = opts0.allowedGlobals
if (opts0.indent == nil) then
opts0.indent = " "
end
if opts0.requireAsInclude then
scope.specials.require = require_include
end
utils.root.chunk, utils.root.scope, utils.root.options = chunk, scope, opts0
local exprs = compile1(ast, scope, chunk, {tail = true})
keep_side_effects(exprs, chunk, nil, ast)
allowed_globals = old_globals
utils.root.reset()
return flatten(chunk, opts0)
end
local function traceback_frame(info)
if ((info.what == "C") and info.name) then
2020-10-13 23:23:38 -07:00
return string.format(" [C]: in function '%s'", info.name)
2020-09-18 12:13:53 -07:00
elseif (info.what == "C") then
return " [C]: in ?"
else
local remap = fennel_sourcemap[info.source]
if (remap and remap[info.currentline]) then
2021-04-12 16:52:31 -07:00
if remap[info.currentline][1] then
info.short_src = fennel_sourcemap[("@" .. remap[info.currentline][1])].short_src
else
info.short_src = remap.short_src
end
info.currentline = (remap[info.currentline][2] or -1)
2020-09-18 12:13:53 -07:00
end
if (info.what == "Lua") then
2021-09-12 22:29:05 -07:00
local function _289_()
2020-09-18 12:13:53 -07:00
if info.name then
return ("'" .. info.name .. "'")
else
return "?"
end
end
2021-09-12 22:29:05 -07:00
return string.format(" %s:%d: in function %s", info.short_src, info.currentline, _289_())
2021-04-12 16:52:31 -07:00
elseif (info.short_src == "(tail call)") then
2020-09-18 12:13:53 -07:00
return " (tail call)"
else
return string.format(" %s:%d: in main chunk", info.short_src, info.currentline)
end
end
end
local function traceback(msg, start)
2021-09-12 22:29:05 -07:00
local msg0 = tostring((msg or ""))
2020-10-13 23:23:38 -07:00
if ((msg0:find("^Compile error") or msg0:find("^Parse error")) and not utils["debug-on?"]("trace")) then
2020-09-18 12:13:53 -07:00
return msg0
else
local lines = {}
2021-09-12 22:29:05 -07:00
if (msg0:find(":%d+: Compile error") or msg0:find(":%d+: Parse error")) then
2020-09-18 12:13:53 -07:00
table.insert(lines, msg0)
else
local newmsg = msg0:gsub("^[^:]*:%d+:%s+", "runtime error: ")
table.insert(lines, newmsg)
end
table.insert(lines, "stack traceback:")
local done_3f, level = false, (start or 2)
while not done_3f do
do
2021-09-12 22:29:05 -07:00
local _293_ = debug.getinfo(level, "Sln")
if (_293_ == nil) then
2020-09-18 12:13:53 -07:00
done_3f = true
2021-09-12 22:29:05 -07:00
elseif (nil ~= _293_) then
local info = _293_
2020-09-18 12:13:53 -07:00
table.insert(lines, traceback_frame(info))
end
end
level = (level + 1)
end
return table.concat(lines, "\n")
end
end
local function entry_transform(fk, fv)
2021-09-12 22:29:05 -07:00
local function _296_(k, v)
2020-09-18 12:13:53 -07:00
if (type(k) == "number") then
return k, fv(v)
else
return fk(k), fv(v)
end
end
2021-09-12 22:29:05 -07:00
return _296_
2020-09-18 12:13:53 -07:00
end
local function mixed_concat(t, joiner)
local seen = {}
local ret, s = "", ""
for k, v in ipairs(t) do
table.insert(seen, k)
ret = (ret .. s .. v)
s = joiner
end
for k, v in utils.stablepairs(t) do
if not seen[k] then
ret = (ret .. s .. "[" .. k .. "]" .. "=" .. v)
s = joiner
end
end
return ret
end
2020-10-13 23:23:38 -07:00
local function do_quote(form, scope, parent, runtime_3f)
2020-09-18 12:13:53 -07:00
local function q(x)
2020-10-13 23:23:38 -07:00
return do_quote(x, scope, parent, runtime_3f)
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
if utils["varg?"](form) then
assert_compile(not runtime_3f, "quoted ... may only be used at compile time", form)
2020-09-18 12:13:53 -07:00
return "_VARARG"
2020-10-13 23:23:38 -07:00
elseif utils["sym?"](form) then
2021-09-12 22:29:05 -07:00
local filename
2020-09-18 12:13:53 -07:00
if form.filename then
2020-10-13 23:23:38 -07:00
filename = string.format("%q", form.filename)
2020-09-18 12:13:53 -07:00
else
filename = "nil"
end
2021-09-12 22:29:05 -07:00
local symstr = tostring(form)
2020-10-13 23:23:38 -07:00
assert_compile(not runtime_3f, "symbols may only be used at compile time", form)
2020-09-18 12:13:53 -07:00
if (symstr:find("#$") or symstr:find("#[:.]")) then
2021-04-12 16:52:31 -07:00
return string.format("sym('%s', {filename=%s, line=%s})", autogensym(symstr, scope), filename, (form.line or "nil"))
2020-09-18 12:13:53 -07:00
else
2021-04-12 16:52:31 -07:00
return string.format("sym('%s', {quoted=true, filename=%s, line=%s})", symstr, filename, (form.line or "nil"))
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
elseif (utils["list?"](form) and utils["sym?"](form[1]) and (tostring(form[1]) == "unquote")) then
2020-09-18 12:13:53 -07:00
local payload = form[2]
local res = unpack(compile1(payload, scope, parent))
return res[1]
2020-10-13 23:23:38 -07:00
elseif utils["list?"](form) then
2021-09-12 22:29:05 -07:00
local mapped
local function _301_()
2021-04-12 16:52:31 -07:00
return nil
end
2021-09-12 22:29:05 -07:00
mapped = utils.kvmap(form, entry_transform(_301_, q))
local filename
2020-09-18 12:13:53 -07:00
if form.filename then
2020-10-13 23:23:38 -07:00
filename = string.format("%q", form.filename)
2020-09-18 12:13:53 -07:00
else
filename = "nil"
end
2020-10-13 23:23:38 -07:00
assert_compile(not runtime_3f, "lists may only be used at compile time", form)
return string.format(("setmetatable({filename=%s, line=%s, bytestart=%s, %s}" .. ", getmetatable(list()))"), filename, (form.line or "nil"), (form.bytestart or "nil"), mixed_concat(mapped, ", "))
2021-04-12 16:52:31 -07:00
elseif utils["sequence?"](form) then
local mapped = utils.kvmap(form, entry_transform(q, q))
local source = getmetatable(form)
2021-09-12 22:29:05 -07:00
local filename
2021-04-12 16:52:31 -07:00
if source.filename then
filename = string.format("%q", source.filename)
else
filename = "nil"
end
2021-09-12 22:29:05 -07:00
local _304_
2021-04-12 16:52:31 -07:00
if source then
2021-09-12 22:29:05 -07:00
_304_ = source.line
2021-04-12 16:52:31 -07:00
else
2021-09-12 22:29:05 -07:00
_304_ = "nil"
2021-04-12 16:52:31 -07:00
end
2021-09-12 22:29:05 -07:00
return string.format("setmetatable({%s}, {filename=%s, line=%s, sequence=%s})", mixed_concat(mapped, ", "), filename, _304_, "(getmetatable(sequence()))['sequence']")
2020-09-18 12:13:53 -07:00
elseif (type(form) == "table") then
local mapped = utils.kvmap(form, entry_transform(q, q))
local source = getmetatable(form)
2021-09-12 22:29:05 -07:00
local filename
2020-09-18 12:13:53 -07:00
if source.filename then
2020-10-13 23:23:38 -07:00
filename = string.format("%q", source.filename)
2020-09-18 12:13:53 -07:00
else
filename = "nil"
end
2021-09-12 22:29:05 -07:00
local function _307_()
2020-09-18 12:13:53 -07:00
if source then
return source.line
else
return "nil"
end
end
2021-09-12 22:29:05 -07:00
return string.format("setmetatable({%s}, {filename=%s, line=%s})", mixed_concat(mapped, ", "), filename, _307_())
2020-09-18 12:13:53 -07:00
elseif (type(form) == "string") then
return serialize_string(form)
else
return tostring(form)
end
end
2021-09-12 22:29:05 -07:00
return {compile = compile, compile1 = compile1, ["compile-stream"] = compile_stream, ["compile-string"] = compile_string, emit = emit, destructure = destructure, ["require-include"] = require_include, autogensym = autogensym, gensym = gensym, ["do-quote"] = do_quote, ["global-mangling"] = global_mangling, ["global-unmangling"] = global_unmangling, ["apply-manglings"] = apply_manglings, macroexpand = macroexpand_2a, ["declare-local"] = declare_local, ["make-scope"] = make_scope, ["keep-side-effects"] = keep_side_effects, ["symbol-to-expression"] = symbol_to_expression, assert = assert_compile, scopes = scopes, traceback = traceback, metadata = make_metadata()}
2020-09-18 12:13:53 -07:00
end
package.preload["fennel.friend"] = package.preload["fennel.friend"] or function(...)
local function ast_source(ast)
local m = getmetatable(ast)
2021-02-01 17:09:15 -08:00
return ((m and m.line and m) or (("table" == type(ast)) and ast) or {})
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
local suggestions = {["unexpected multi symbol (.*)"] = {"removing periods or colons from %s"}, ["use of global (.*) is aliased by a local"] = {"renaming local %s", "refer to the global using _G.%s instead of directly"}, ["local (.*) was overshadowed by a special form or macro"] = {"renaming local %s"}, ["global (.*) conflicts with local"] = {"renaming local %s"}, ["expected var (.*)"] = {"declaring %s using var instead of let/local", "introducing a new local instead of changing the value of %s"}, ["expected macros to be table"] = {"ensuring your macro definitions return a table"}, ["expected each macro to be function"] = {"ensuring that the value for each key in your macros table contains a function", "avoid defining nested macro tables"}, ["macro not found in macro module"] = {"checking the keys of the imported macro module's returned table"}, ["macro tried to bind (.*) without gensym"] = {"changing to %s# when introducing identifiers inside macros"}, ["unknown global in strict mode: (.*)"] = {"looking to see if there's a typo", "using the _G table instead, eg. _G.%s if you really want a global", "moving this code to somewhere that %s is in scope", "binding %s as a local in the scope of this code"}, ["expected a function.* to call"] = {"removing the empty parentheses", "using square brackets if you want an empty table"}, ["cannot call literal value"] = {"checking for typos", "checking for a missing function name"}, ["unexpected vararg"] = {"putting \"...\" at the end of the fn parameters if the vararg was intended"}, ["multisym method calls may only be in call position"] = {"using a period instead of a colon to reference a table's fields", "putting parens around this"}, ["unused local (.*)"] = {"fixing a typo so %s is used", "renaming the local to _%s"}, ["expected parameters"] = {"adding function parameters as a list of identifiers in brackets"}, ["unable to bind (.*)"] = {"replacing the %s with an identifier"}, ["expected rest argument before last parameter"] = {"moving & to right before the final identifier when destructuring"}, ["expected vararg as last parameter"] = {"moving the \"...\" to the end of the parameter list"}, ["expected symbol for function parameter: (.*)"] = {"changing %s to an identifier instead of a literal value"}, ["could not compile value of type "] = {"debugging the macro you're calling to return a list or table"}, ["expected local"] = {"looking for a typo", "looking for a local which is used out of its scope"}, ["expected body expression"] = {"putting some code in the body of this form after the bindings"}, ["expected binding and iterator"] = {"making sure you haven't omitted a local name or iterator"}, ["expected binding sequence"] = {"placing a table here in square brackets containing identifiers to bind"}, ["expected even number of name/value bindings"] = {"finding where the identifier or value is missing"}, ["may only be used at compile time"] = {"moving this to inside a macro if you need to manipulate symbols/lists", "using square brackets instead of parens to construct a table"}, ["unexpected closing delimiter (.)"] = {"deleting %s", "adding matching opening delimiter earlier"}, ["mismatched closing delimiter (.), expected (.)"] = {"replacing %s with %s", "deleting %s", "adding matching opening delimiter earlier"}, ["expected even number of values in table literal"] = {"removing a key", "adding a value"}, ["expected whitespace before opening delimiter"] = {"adding whitespace"}, ["illegal character: (.)"] = {"deleting or replacing %s", "avoiding reserved characters like \", \\, ', ~, ;, @, `, and comma"}, ["could not read number (.*)"] = {"removing the non-digit character", "beginning the identifier with a non-digit if it is not meant to be a number"}, ["can't start multisym segment with a digit"] = {"removing the digit", "adding a non-digit before the digit"}, ["malformed multisym"] = {"ensuring each period or colon is not followed by another period or colon"}, ["method must be last component"] = {"using a period instead of a colon for field access", "removing segments after the colon
2021-02-01 17:09:15 -08:00
local unpack = (table.unpack or _G.unpack)
2020-09-18 12:13:53 -07:00
local function suggest(msg)
local suggestion = nil
for pat, sug in pairs(suggestions) do
local matches = {msg:match(pat)}
if (0 < #matches) then
if ("table" == type(sug)) then
local out = {}
for _, s in ipairs(sug) do
table.insert(out, s:format(unpack(matches)))
end
suggestion = out
else
suggestion = sug(matches)
end
end
end
return suggestion
end
local function read_line_from_file(filename, line)
local bytes = 0
local f = assert(io.open(filename))
2021-09-12 22:29:05 -07:00
local _
2020-09-18 12:13:53 -07:00
for _0 = 1, (line - 1) do
bytes = (bytes + 1 + #f:read())
end
_ = nil
local codeline = f:read()
f:close()
return codeline, bytes
end
2021-04-12 16:52:31 -07:00
local function read_line_from_string(matcher, target_line, _3fcurrent_line, _3fbytes)
local this_line, newline = matcher()
local current_line = (_3fcurrent_line or 1)
local bytes = ((_3fbytes or 0) + #this_line + #newline)
if (target_line == current_line) then
2021-09-12 22:29:05 -07:00
return this_line, (bytes - #this_line - 1)
2021-04-12 16:52:31 -07:00
elseif this_line then
return read_line_from_string(matcher, target_line, (current_line + 1), bytes)
2020-09-18 12:13:53 -07:00
end
end
local function read_line(filename, line, source)
if source then
2021-04-12 16:52:31 -07:00
return read_line_from_string(string.gmatch((source .. "\n"), "(.-)(\13?\n)"), line)
2020-09-18 12:13:53 -07:00
else
return read_line_from_file(filename, line)
end
end
2021-09-12 22:29:05 -07:00
local function friendly_msg(msg, _116_, source)
local _arg_117_ = _116_
local filename = _arg_117_["filename"]
local line = _arg_117_["line"]
local bytestart = _arg_117_["bytestart"]
local byteend = _arg_117_["byteend"]
2020-12-23 10:33:09 -08:00
local ok, codeline, bol = pcall(read_line, filename, line, source)
2020-09-18 12:13:53 -07:00
local suggestions0 = suggest(msg)
local out = {msg, ""}
if (ok and codeline) then
table.insert(out, codeline)
end
if (ok and codeline and bytestart and byteend) then
table.insert(out, (string.rep(" ", (bytestart - bol - 1)) .. "^" .. string.rep("^", math.min((byteend - bytestart), ((bol + #codeline) - bytestart)))))
end
if (ok and codeline and bytestart and not byteend) then
table.insert(out, (string.rep("-", (bytestart - bol - 1)) .. "^"))
table.insert(out, "")
end
if suggestions0 then
for _, suggestion in ipairs(suggestions0) do
table.insert(out, ("* Try %s."):format(suggestion))
end
end
return table.concat(out, "\n")
end
local function assert_compile(condition, msg, ast, source)
if not condition then
2021-09-12 22:29:05 -07:00
local _let_122_ = ast_source(ast)
local filename = _let_122_["filename"]
local line = _let_122_["line"]
2020-09-18 12:13:53 -07:00
error(friendly_msg(("Compile error in %s:%s\n %s"):format((filename or "unknown"), (line or "?"), msg), ast_source(ast), source), 0)
end
return condition
end
local function parse_error(msg, filename, line, bytestart, source)
2021-09-12 22:29:05 -07:00
return error(friendly_msg(("Parse error in %s:%s\n %s"):format(filename, line, msg), {filename = filename, line = line, bytestart = bytestart}, source), 0)
2020-09-18 12:13:53 -07:00
end
return {["assert-compile"] = assert_compile, ["parse-error"] = parse_error}
end
package.preload["fennel.parser"] = package.preload["fennel.parser"] or function(...)
local utils = require("fennel.utils")
local friend = require("fennel.friend")
2021-02-01 17:09:15 -08:00
local unpack = (table.unpack or _G.unpack)
2020-09-18 12:13:53 -07:00
local function granulate(getchunk)
2020-10-13 23:23:38 -07:00
local c, index, done_3f = "", 1, false
2021-09-12 22:29:05 -07:00
local function _124_(parser_state)
2020-10-13 23:23:38 -07:00
if not done_3f then
2020-09-18 12:13:53 -07:00
if (index <= #c) then
local b = c:byte(index)
index = (index + 1)
return b
else
2021-09-12 22:29:05 -07:00
local _125_ = getchunk(parser_state)
local function _126_()
local char = _125_
return (char ~= "")
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
if ((nil ~= _125_) and _126_()) then
local char = _125_
2020-12-23 10:33:09 -08:00
c = char
index = 2
return c:byte()
else
2021-09-12 22:29:05 -07:00
local _ = _125_
2020-10-13 23:23:38 -07:00
done_3f = true
2020-09-18 12:13:53 -07:00
return nil
end
end
end
end
2021-09-12 22:29:05 -07:00
local function _130_()
2020-09-18 12:13:53 -07:00
c = ""
return nil
end
2021-09-12 22:29:05 -07:00
return _124_, _130_
2020-09-18 12:13:53 -07:00
end
local function string_stream(str)
2020-12-23 10:33:09 -08:00
local str0 = str:gsub("^#!", ";;")
2020-09-18 12:13:53 -07:00
local index = 1
2021-09-12 22:29:05 -07:00
local function _131_()
2020-09-18 12:13:53 -07:00
local r = str0:byte(index)
index = (index + 1)
return r
end
2021-09-12 22:29:05 -07:00
return _131_
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
local delims = {[40] = 41, [41] = true, [91] = 93, [93] = true, [123] = 125, [125] = true}
2020-10-13 23:23:38 -07:00
local function whitespace_3f(b)
2020-09-18 12:13:53 -07:00
return ((b == 32) or ((b >= 9) and (b <= 13)))
end
2021-02-01 17:09:15 -08:00
local function sym_char_3f(b)
2021-09-12 22:29:05 -07:00
local b0
2021-02-01 17:09:15 -08:00
if ("number" == type(b)) then
b0 = b
else
b0 = string.byte(b)
end
return ((b0 > 32) and not delims[b0] and (b0 ~= 127) and (b0 ~= 34) and (b0 ~= 39) and (b0 ~= 126) and (b0 ~= 59) and (b0 ~= 44) and (b0 ~= 64) and (b0 ~= 96))
2020-09-18 12:13:53 -07:00
end
local prefixes = {[35] = "hashfn", [39] = "quote", [44] = "unquote", [96] = "quote"}
local function parser(getbyte, filename, options)
local stack = {}
local line = 1
local byteindex = 0
local lastb = nil
local function ungetb(ub)
if (ub == 10) then
line = (line - 1)
end
byteindex = (byteindex - 1)
lastb = ub
return nil
end
local function getb()
local r = nil
if lastb then
r, lastb = lastb, nil
else
r = getbyte({["stack-size"] = #stack})
end
byteindex = (byteindex + 1)
if (r == 10) then
line = (line + 1)
end
return r
end
2021-04-12 16:52:31 -07:00
assert(((nil == filename) or ("string" == type(filename))), "expected filename as second argument to parser")
2020-12-23 10:33:09 -08:00
local function parse_error(msg, byteindex_override)
2021-09-12 22:29:05 -07:00
local _let_136_ = (options or utils.root.options or {})
local source = _let_136_["source"]
local unfriendly = _let_136_["unfriendly"]
2020-09-18 12:13:53 -07:00
utils.root.reset()
2021-09-12 22:29:05 -07:00
if (unfriendly or not friend or not _G.io or not _G.io.read) then
return error(string.format("%s:%s: Parse error: %s", (filename or "unknown"), (line or "?"), msg), 0)
2020-09-18 12:13:53 -07:00
else
2020-12-23 10:33:09 -08:00
return friend["parse-error"](msg, (filename or "unknown"), (line or "?"), (byteindex_override or byteindex), source)
2020-09-18 12:13:53 -07:00
end
end
local function parse_stream()
2020-10-13 23:23:38 -07:00
local whitespace_since_dispatch, done_3f, retval = true
2020-09-18 12:13:53 -07:00
local function dispatch(v)
2021-09-12 22:29:05 -07:00
local _138_ = stack[#stack]
if (_138_ == nil) then
2020-10-13 23:23:38 -07:00
retval, done_3f, whitespace_since_dispatch = v, true, false
2020-09-18 12:13:53 -07:00
return nil
2021-09-12 22:29:05 -07:00
elseif ((_G.type(_138_) == "table") and (nil ~= (_138_).prefix)) then
local prefix = (_138_).prefix
local source
2021-04-12 16:52:31 -07:00
do
2021-09-12 22:29:05 -07:00
local _139_ = table.remove(stack)
do end (_139_)["byteend"] = byteindex
source = _139_
2021-04-12 16:52:31 -07:00
end
local list = utils.list(utils.sym(prefix, source), v)
for k, v0 in pairs(source) do
list[k] = v0
end
return dispatch(list)
2021-09-12 22:29:05 -07:00
elseif (nil ~= _138_) then
local top = _138_
2020-09-18 12:13:53 -07:00
whitespace_since_dispatch = false
2020-12-23 10:33:09 -08:00
return table.insert(top, v)
2020-09-18 12:13:53 -07:00
end
end
local function badend()
local accum = utils.map(stack, "closer")
2021-09-12 22:29:05 -07:00
local _141_
2020-12-23 10:33:09 -08:00
if (#stack == 1) then
2021-09-12 22:29:05 -07:00
_141_ = ""
2020-12-23 10:33:09 -08:00
else
2021-09-12 22:29:05 -07:00
_141_ = "s"
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
return parse_error(string.format("expected closing delimiter%s %s", _141_, string.char(unpack(accum))))
2020-12-23 10:33:09 -08:00
end
local function skip_whitespace(b)
if (b and whitespace_3f(b)) then
whitespace_since_dispatch = true
return skip_whitespace(getb())
elseif (not b and (#stack > 0)) then
return badend()
else
return b
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
end
2021-02-01 17:09:15 -08:00
local function parse_comment(b, contents)
2020-12-23 10:33:09 -08:00
if (b and (10 ~= b)) then
2021-09-12 22:29:05 -07:00
local function _145_()
local _144_ = contents
table.insert(_144_, string.char(b))
return _144_
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
return parse_comment(getb(), _145_())
2021-02-01 17:09:15 -08:00
elseif (options and options.comments) then
2021-09-12 22:29:05 -07:00
return dispatch(utils.comment(table.concat(contents), {line = (line - 1), filename = filename}))
2020-12-23 10:33:09 -08:00
else
return b
end
end
local function open_table(b)
if not whitespace_since_dispatch then
parse_error(("expected whitespace before opening delimiter " .. string.char(b)))
end
return table.insert(stack, {bytestart = byteindex, closer = delims[b], filename = filename, line = line})
end
local function close_list(list)
return dispatch(setmetatable(list, getmetatable(utils.list())))
end
local function close_sequence(tbl)
local val = utils.sequence(unpack(tbl))
for k, v in pairs(tbl) do
getmetatable(val)[k] = v
end
return dispatch(val)
end
2021-04-12 16:52:31 -07:00
local function add_comment_at(comments, index, node)
2021-09-12 22:29:05 -07:00
local _148_ = comments[index]
if (nil ~= _148_) then
local existing = _148_
2021-04-12 16:52:31 -07:00
return table.insert(existing, node)
else
2021-09-12 22:29:05 -07:00
local _ = _148_
2021-04-12 16:52:31 -07:00
comments[index] = {node}
return nil
end
end
local function next_noncomment(tbl, i)
if utils["comment?"](tbl[i]) then
return next_noncomment(tbl, (i + 1))
else
return tbl[i]
end
end
local function extract_comments(tbl)
2021-09-12 22:29:05 -07:00
local comments = {keys = {}, values = {}, last = {}}
2021-04-12 16:52:31 -07:00
while utils["comment?"](tbl[#tbl]) do
table.insert(comments.last, 1, table.remove(tbl))
end
local last_key_3f = false
for i, node in ipairs(tbl) do
if not utils["comment?"](node) then
last_key_3f = not last_key_3f
elseif last_key_3f then
add_comment_at(comments.values, next_noncomment(tbl, i), node)
else
add_comment_at(comments.keys, next_noncomment(tbl, i), node)
end
end
for i = #tbl, 1, -1 do
if utils["comment?"](tbl[i]) then
table.remove(tbl, i)
end
end
return comments
end
2020-12-23 10:33:09 -08:00
local function close_curly_table(tbl)
2021-04-12 16:52:31 -07:00
local comments = extract_comments(tbl)
local keys = {}
2020-12-23 10:33:09 -08:00
local val = {}
if ((#tbl % 2) ~= 0) then
byteindex = (byteindex - 1)
parse_error("expected even number of values in table literal")
end
setmetatable(val, tbl)
for i = 1, #tbl, 2 do
if ((tostring(tbl[i]) == ":") and utils["sym?"](tbl[(i + 1)]) and utils["sym?"](tbl[i])) then
tbl[i] = tostring(tbl[(i + 1)])
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
val[tbl[i]] = tbl[(i + 1)]
2021-04-12 16:52:31 -07:00
table.insert(keys, tbl[i])
2020-12-23 10:33:09 -08:00
end
2021-04-12 16:52:31 -07:00
tbl.comments = comments
tbl.keys = keys
2020-12-23 10:33:09 -08:00
return dispatch(val)
end
local function close_table(b)
local top = table.remove(stack)
if (top == nil) then
parse_error(("unexpected closing delimiter " .. string.char(b)))
end
2021-04-12 16:52:31 -07:00
if (top.closer and (top.closer ~= b)) then
2020-12-23 10:33:09 -08:00
parse_error(("mismatched closing delimiter " .. string.char(b) .. ", expected " .. string.char(top.closer)))
end
top.byteend = byteindex
if (b == 41) then
return close_list(top)
elseif (b == 93) then
return close_sequence(top)
else
return close_curly_table(top)
end
end
local function parse_string_loop(chars, b, state)
table.insert(chars, b)
2021-09-12 22:29:05 -07:00
local state0
2020-12-23 10:33:09 -08:00
do
2021-09-12 22:29:05 -07:00
local _158_ = {state, b}
if ((_G.type(_158_) == "table") and ((_158_)[1] == "base") and ((_158_)[2] == 92)) then
2020-12-23 10:33:09 -08:00
state0 = "backslash"
2021-09-12 22:29:05 -07:00
elseif ((_G.type(_158_) == "table") and ((_158_)[1] == "base") and ((_158_)[2] == 34)) then
2020-12-23 10:33:09 -08:00
state0 = "done"
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
local _ = _158_
2020-12-23 10:33:09 -08:00
state0 = "base"
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
end
if (b and (state0 ~= "done")) then
return parse_string_loop(chars, getb(), state0)
else
return b
end
end
2021-09-12 22:29:05 -07:00
local function escape_char(c)
return ({[7] = "\\a", [8] = "\\b", [9] = "\\t", [10] = "\\n", [11] = "\\v", [12] = "\\f", [13] = "\\r"})[c:byte()]
end
local function parse_string()
table.insert(stack, {closer = 34})
local chars = {34}
if not parse_string_loop(chars, getb(), "base") then
badend()
end
table.remove(stack)
local raw = string.char(unpack(chars))
local formatted = raw:gsub("[\7-\13]", escape_char)
local _162_ = (rawget(_G, "loadstring") or load)(("return " .. formatted))
if (nil ~= _162_) then
local load_fn = _162_
return dispatch(load_fn())
elseif (_162_ == nil) then
return parse_error(("Invalid string: " .. raw))
end
end
local function parse_prefix(b)
table.insert(stack, {prefix = prefixes[b], filename = filename, line = line, bytestart = byteindex})
local nextb = getb()
if (whitespace_3f(nextb) or (true == delims[nextb])) then
if (b ~= 35) then
parse_error("invalid whitespace after quoting prefix")
end
table.remove(stack)
dispatch(utils.sym("#"))
end
return ungetb(nextb)
end
local function parse_sym_loop(chars, b)
if (b and sym_char_3f(b)) then
table.insert(chars, b)
return parse_sym_loop(chars, getb())
else
if b then
ungetb(b)
end
return chars
end
end
local function parse_number(rawstr)
local number_with_stripped_underscores = (not rawstr:find("^_") and rawstr:gsub("_", ""))
if rawstr:match("^%d") then
dispatch((tonumber(number_with_stripped_underscores) or parse_error(("could not read number \"" .. rawstr .. "\""))))
return true
else
local _168_ = tonumber(number_with_stripped_underscores)
if (nil ~= _168_) then
local x = _168_
dispatch(x)
return true
else
local _ = _168_
return false
end
end
end
local function check_malformed_sym(rawstr)
if (rawstr:match("^~") and (rawstr ~= "~=")) then
return parse_error("illegal character: ~")
elseif rawstr:match("%.[0-9]") then
return parse_error(("can't start multisym segment with a digit: " .. rawstr), (((byteindex - #rawstr) + rawstr:find("%.[0-9]")) + 1))
elseif (rawstr:match("[%.:][%.:]") and (rawstr ~= "..") and (rawstr ~= "$...")) then
return parse_error(("malformed multisym: " .. rawstr), ((byteindex - #rawstr) + 1 + rawstr:find("[%.:][%.:]")))
elseif ((rawstr ~= ":") and rawstr:match(":$")) then
return parse_error(("malformed multisym: " .. rawstr), ((byteindex - #rawstr) + 1 + rawstr:find(":$")))
elseif rawstr:match(":.+[%.:]") then
return parse_error(("method must be last component of multisym: " .. rawstr), ((byteindex - #rawstr) + rawstr:find(":.+[%.:]")))
else
return rawstr
end
end
local function parse_sym(b)
local bytestart = byteindex
local rawstr = string.char(unpack(parse_sym_loop({b}, getb())))
if (rawstr == "true") then
return dispatch(true)
elseif (rawstr == "false") then
return dispatch(false)
elseif (rawstr == "...") then
return dispatch(utils.varg())
elseif rawstr:match("^:.+$") then
return dispatch(rawstr:sub(2))
elseif not parse_number(rawstr) then
return dispatch(utils.sym(check_malformed_sym(rawstr), {byteend = byteindex, bytestart = bytestart, filename = filename, line = line}))
end
end
local function parse_loop(b)
if not b then
elseif (b == 59) then
parse_comment(getb(), {";"})
elseif (type(delims[b]) == "number") then
open_table(b)
elseif delims[b] then
close_table(b)
elseif (b == 34) then
parse_string(b)
elseif prefixes[b] then
parse_prefix(b)
elseif (sym_char_3f(b) or (b == string.byte("~"))) then
parse_sym(b)
elseif not utils.hook("illegal-char", b, getb, ungetb, dispatch) then
parse_error(("illegal character: " .. string.char(b)))
end
if not b then
return nil
elseif done_3f then
return true, retval
else
return parse_loop(skip_whitespace(getb()))
end
end
return parse_loop(skip_whitespace(getb()))
end
local function _175_()
stack, line, byteindex = {}, 1, 0
return nil
end
return parse_stream, _175_
end
return {granulate = granulate, parser = parser, ["string-stream"] = string_stream, ["sym-char?"] = sym_char_3f}
end
package.preload["fennel.view"] = package.preload["fennel.view"] or function(...)
local type_order = {number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7}
local function sort_keys(_1_, _3_)
local _arg_2_ = _1_
local a = _arg_2_[1]
local _arg_4_ = _3_
local b = _arg_4_[1]
local ta = type(a)
local tb = type(b)
if ((ta == tb) and ((ta == "string") or (ta == "number"))) then
return (a < b)
else
local dta = type_order[ta]
local dtb = type_order[tb]
if (dta and dtb) then
return (dta < dtb)
elseif dta then
return true
elseif dtb then
return false
else
return (ta < tb)
end
end
end
local function max_index_gap(kv)
local gap = 0
if (#kv > 0) then
local i = 0
for _, _7_ in ipairs(kv) do
local _each_8_ = _7_
local k = _each_8_[1]
if ((k - i) > gap) then
gap = (k - i)
end
i = k
end
end
return gap
end
local function fill_gaps(kv)
local missing_indexes = {}
local i = 0
for _, _11_ in ipairs(kv) do
local _each_12_ = _11_
local j = _each_12_[1]
i = (i + 1)
while (i < j) do
table.insert(missing_indexes, i)
i = (i + 1)
end
end
for _, k in ipairs(missing_indexes) do
table.insert(kv, k, {k})
end
return nil
end
local function table_kv_pairs(t, options)
local assoc_3f = false
local kv = {}
local insert = table.insert
for k, v in pairs(t) do
if (type(k) ~= "number") then
assoc_3f = true
end
insert(kv, {k, v})
end
table.sort(kv, sort_keys)
if not assoc_3f then
local gap = max_index_gap(kv)
if (max_index_gap(kv) > options["max-sparse-gap"]) then
assoc_3f = true
else
fill_gaps(kv)
end
end
if (#kv == 0) then
return kv, "empty"
else
local function _16_()
if assoc_3f then
return "table"
else
return "seq"
end
end
return kv, _16_()
end
end
local function count_table_appearances(t, appearances)
if (type(t) == "table") then
if not appearances[t] then
appearances[t] = 1
for k, v in pairs(t) do
count_table_appearances(k, appearances)
count_table_appearances(v, appearances)
end
else
appearances[t] = ((appearances[t] or 0) + 1)
end
end
return appearances
end
local function save_table(t, seen)
local seen0 = (seen or {len = 0})
local id = (seen0.len + 1)
if not (seen0)[t] then
seen0[t] = id
seen0.len = id
end
return seen0
end
local function detect_cycle(t, seen, _3fk)
if ("table" == type(t)) then
seen[t] = true
local _21_, _22_ = next(t, _3fk)
if ((nil ~= _21_) and (nil ~= _22_)) then
local k = _21_
local v = _22_
return (seen[k] or detect_cycle(k, seen) or seen[v] or detect_cycle(v, seen) or detect_cycle(t, seen, k))
end
end
end
local function visible_cycle_3f(t, options)
return (options["detect-cycles?"] and detect_cycle(t, {}) and save_table(t, options.seen) and (1 < (options.appearances[t] or 0)))
end
local function table_indent(t, indent, id)
local opener_length
if id then
opener_length = (#tostring(id) + 2)
else
opener_length = 1
end
return (indent + opener_length)
end
local pp = nil
local function concat_table_lines(elements, options, multiline_3f, indent, table_type, prefix)
local indent_str = ("\n" .. string.rep(" ", indent))
local open
local _26_
if ("seq" == table_type) then
_26_ = "["
else
_26_ = "{"
end
open = ((prefix or "") .. _26_)
local close
if ("seq" == table_type) then
close = "]"
else
close = "}"
end
local oneline = (open .. table.concat(elements, " ") .. close)
if (not options["one-line?"] and (multiline_3f or ((indent + #oneline) > options["line-length"]))) then
return (open .. table.concat(elements, indent_str) .. close)
else
return oneline
end
end
local function pp_associative(t, kv, options, indent, key_3f)
local multiline_3f = false
local id = options.seen[t]
if (options.level >= options.depth) then
return "{...}"
elseif (id and options["detect-cycles?"]) then
return ("@" .. id .. "{...}")
else
local visible_cycle_3f0 = visible_cycle_3f(t, options)
local id0 = (visible_cycle_3f0 and options.seen[t])
local indent0 = table_indent(t, indent, id0)
local slength
local function _31_()
local _30_ = rawget(_G, "utf8")
if _30_ then
return (_30_).len
else
return _30_
end
end
local function _33_(_241)
return #_241
end
slength = ((options["utf8?"] and _31_()) or _33_)
local prefix
if visible_cycle_3f0 then
prefix = ("@" .. id0)
else
prefix = ""
end
local items
do
local tbl_13_auto = {}
for _, _35_ in pairs(kv) do
local _each_36_ = _35_
local k = _each_36_[1]
local v = _each_36_[2]
local _37_
do
local k0 = pp(k, options, (indent0 + 1), true)
local v0 = pp(v, options, (indent0 + slength(k0) + 1))
multiline_3f = (multiline_3f or k0:find("\n") or v0:find("\n"))
_37_ = (k0 .. " " .. v0)
end
tbl_13_auto[(#tbl_13_auto + 1)] = _37_
end
items = tbl_13_auto
end
return concat_table_lines(items, options, multiline_3f, indent0, "table", prefix)
end
end
local function pp_sequence(t, kv, options, indent)
local multiline_3f = false
local id = options.seen[t]
if (options.level >= options.depth) then
return "[...]"
elseif (id and options["detect-cycles?"]) then
return ("@" .. id .. "[...]")
else
local visible_cycle_3f0 = visible_cycle_3f(t, options)
local id0 = (visible_cycle_3f0 and options.seen[t])
local indent0 = table_indent(t, indent, id0)
local prefix
if visible_cycle_3f0 then
prefix = ("@" .. id0)
else
prefix = ""
end
local items
do
local tbl_13_auto = {}
for _, _40_ in pairs(kv) do
local _each_41_ = _40_
local _0 = _each_41_[1]
local v = _each_41_[2]
local _42_
do
local v0 = pp(v, options, indent0)
multiline_3f = (multiline_3f or v0:find("\n"))
_42_ = v0
end
tbl_13_auto[(#tbl_13_auto + 1)] = _42_
end
items = tbl_13_auto
end
return concat_table_lines(items, options, multiline_3f, indent0, "seq", prefix)
end
end
local function concat_lines(lines, options, indent, force_multi_line_3f)
if (#lines == 0) then
if options["empty-as-sequence?"] then
return "[]"
else
return "{}"
2021-02-01 17:09:15 -08:00
end
2021-09-12 22:29:05 -07:00
else
local oneline
local _45_
do
local tbl_13_auto = {}
for _, line in ipairs(lines) do
tbl_13_auto[(#tbl_13_auto + 1)] = line:gsub("^%s+", "")
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
_45_ = tbl_13_auto
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
oneline = table.concat(_45_, " ")
if (not options["one-line?"] and (force_multi_line_3f or oneline:find("\n") or ((indent + #oneline) > options["line-length"]))) then
return table.concat(lines, ("\n" .. string.rep(" ", indent)))
else
return oneline
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
end
end
local function pp_metamethod(t, metamethod, options, indent)
if (options.level >= options.depth) then
if options["empty-as-sequence?"] then
return "[...]"
else
return "{...}"
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
else
local _
local function _49_(_241)
return visible_cycle_3f(_241, options)
end
options["visible-cycle?"] = _49_
_ = nil
local lines, force_multi_line_3f = metamethod(t, pp, options, indent)
options["visible-cycle?"] = nil
local _50_ = type(lines)
if (_50_ == "string") then
return lines
elseif (_50_ == "table") then
return concat_lines(lines, options, indent, force_multi_line_3f)
else
local _0 = _50_
return error("__fennelview metamethod must return a table of lines")
end
end
end
local function pp_table(x, options, indent)
options.level = (options.level + 1)
local x0
do
local _53_
if options["metamethod?"] then
local _54_ = x
if _54_ then
local _55_ = getmetatable(_54_)
if _55_ then
_53_ = (_55_).__fennelview
2020-12-23 10:33:09 -08:00
else
2021-09-12 22:29:05 -07:00
_53_ = _55_
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
else
_53_ = _54_
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
else
_53_ = nil
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
if (nil ~= _53_) then
local metamethod = _53_
x0 = pp_metamethod(x, metamethod, options, indent)
else
local _ = _53_
local _59_, _60_ = table_kv_pairs(x, options)
if (true and (_60_ == "empty")) then
local _0 = _59_
if options["empty-as-sequence?"] then
x0 = "[]"
else
x0 = "{}"
end
elseif ((nil ~= _59_) and (_60_ == "table")) then
local kv = _59_
x0 = pp_associative(x, kv, options, indent)
elseif ((nil ~= _59_) and (_60_ == "seq")) then
local kv = _59_
x0 = pp_sequence(x, kv, options, indent)
2021-04-12 16:52:31 -07:00
else
2021-09-12 22:29:05 -07:00
x0 = nil
2020-12-23 10:33:09 -08:00
end
end
2021-09-12 22:29:05 -07:00
end
options.level = (options.level - 1)
return x0
end
local function number__3estring(n)
local _64_ = string.gsub(tostring(n), ",", ".")
return _64_
end
local function colon_string_3f(s)
return s:find("^[-%w?^_!$%&*+./@|<=>]+$")
end
local function pp_string(str, options, indent)
local escs
local _65_
if (options["escape-newlines?"] and (#str < (options["line-length"] - indent))) then
_65_ = "\\n"
else
_65_ = "\n"
end
local function _67_(_241, _242)
return ("\\%03d"):format(_242:byte())
end
escs = setmetatable({["\7"] = "\\a", ["\8"] = "\\b", ["\12"] = "\\f", ["\11"] = "\\v", ["\13"] = "\\r", ["\9"] = "\\t", ["\\"] = "\\\\", ["\""] = "\\\"", ["\n"] = _65_}, {__index = _67_})
return ("\"" .. str:gsub("[%c\\\"]", escs) .. "\"")
end
local function make_options(t, options)
local defaults = {["line-length"] = 80, ["one-line?"] = false, depth = 128, ["detect-cycles?"] = true, ["empty-as-sequence?"] = false, ["metamethod?"] = true, ["prefer-colon?"] = false, ["escape-newlines?"] = false, ["utf8?"] = true, ["max-sparse-gap"] = 10}
local overrides = {level = 0, appearances = count_table_appearances(t, {}), seen = {len = 0}}
for k, v in pairs((options or {})) do
defaults[k] = v
end
for k, v in pairs(overrides) do
defaults[k] = v
end
return defaults
end
local function _68_(x, options, indent, colon_3f)
local indent0 = (indent or 0)
local options0 = (options or make_options(x))
local x0
if options0.preprocess then
x0 = options0.preprocess(x, options0)
else
x0 = x
end
local tv = type(x0)
local function _71_()
local _70_ = getmetatable(x0)
if _70_ then
return (_70_).__fennelview
else
return _70_
2020-12-23 10:33:09 -08:00
end
2021-09-12 22:29:05 -07:00
end
if ((tv == "table") or ((tv == "userdata") and _71_())) then
return pp_table(x0, options0, indent0)
elseif (tv == "number") then
return number__3estring(x0)
else
local function _73_()
if (colon_3f ~= nil) then
return colon_3f
elseif ("function" == type(options0["prefer-colon?"])) then
return options0["prefer-colon?"](x0)
2020-12-23 10:33:09 -08:00
else
2021-09-12 22:29:05 -07:00
return options0["prefer-colon?"]
2020-09-18 12:13:53 -07:00
end
end
2021-09-12 22:29:05 -07:00
if ((tv == "string") and colon_string_3f(x0) and _73_()) then
return (":" .. x0)
elseif (tv == "string") then
return pp_string(x0, options0, indent0)
elseif ((tv == "boolean") or (tv == "nil")) then
return tostring(x0)
else
return ("#<" .. tostring(x0) .. ">")
end
2020-09-18 12:13:53 -07:00
end
end
2021-09-12 22:29:05 -07:00
pp = _68_
local function view(x, options)
return pp(x, make_options(x, options), 0)
end
return view
2020-09-18 12:13:53 -07:00
end
package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(...)
2021-09-12 22:29:05 -07:00
local view = require("fennel.view")
2020-09-18 12:13:53 -07:00
local function stablepairs(t)
local keys = {}
2021-09-12 22:29:05 -07:00
local used_keys = {}
2020-09-18 12:13:53 -07:00
local succ = {}
2021-09-12 22:29:05 -07:00
if (getmetatable(t) and getmetatable(t).keys) then
for _, k in ipairs(getmetatable(t).keys) do
if used_keys[k] then
for i = #keys, 1, -1 do
if (keys[i] == k) then
table.remove(keys, i)
end
end
end
used_keys[k] = true
table.insert(keys, k)
end
else
for k in pairs(t) do
table.insert(keys, k)
end
local function _77_(_241, _242)
return (tostring(_241) < tostring(_242))
end
table.sort(keys, _77_)
2020-09-18 12:13:53 -07:00
end
for i, k in ipairs(keys) do
succ[k] = keys[(i + 1)]
end
local function stablenext(tbl, idx)
2021-09-12 22:29:05 -07:00
local key
2020-09-18 12:13:53 -07:00
if (idx == nil) then
2021-04-12 16:52:31 -07:00
key = keys[1]
2020-09-18 12:13:53 -07:00
else
2021-04-12 16:52:31 -07:00
key = succ[idx]
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
local value
2021-04-12 16:52:31 -07:00
if (key == nil) then
value = nil
else
value = tbl[key]
end
return key, value
2020-09-18 12:13:53 -07:00
end
return stablenext, t, nil
end
local function map(t, f, out)
local out0 = (out or {})
2021-09-12 22:29:05 -07:00
local f0
2020-09-18 12:13:53 -07:00
if (type(f) == "function") then
f0 = f
else
2021-09-12 22:29:05 -07:00
local function _81_(_241)
return (_241)[f]
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
f0 = _81_
2020-09-18 12:13:53 -07:00
end
for _, x in ipairs(t) do
2021-09-12 22:29:05 -07:00
local _83_ = f0(x)
if (nil ~= _83_) then
local v = _83_
2020-09-18 12:13:53 -07:00
table.insert(out0, v)
end
end
return out0
end
local function kvmap(t, f, out)
local out0 = (out or {})
2021-09-12 22:29:05 -07:00
local f0
2020-09-18 12:13:53 -07:00
if (type(f) == "function") then
f0 = f
else
2021-09-12 22:29:05 -07:00
local function _85_(_241)
return (_241)[f]
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
f0 = _85_
2020-09-18 12:13:53 -07:00
end
for k, x in stablepairs(t) do
2021-09-12 22:29:05 -07:00
local _87_, _88_ = f0(k, x)
if ((nil ~= _87_) and (nil ~= _88_)) then
local key = _87_
local value = _88_
2020-12-23 10:33:09 -08:00
out0[key] = value
2021-09-12 22:29:05 -07:00
elseif (nil ~= _87_) then
local value = _87_
2020-12-23 10:33:09 -08:00
table.insert(out0, value)
2020-09-18 12:13:53 -07:00
end
end
return out0
end
2020-10-13 23:23:38 -07:00
local function copy(from, to)
local to0 = (to or {})
2020-09-18 12:13:53 -07:00
for k, v in pairs((from or {})) do
2020-10-13 23:23:38 -07:00
to0[k] = v
end
return to0
end
local function member_3f(x, tbl, n)
2021-09-12 22:29:05 -07:00
local _90_ = tbl[(n or 1)]
if (_90_ == x) then
2020-10-13 23:23:38 -07:00
return true
2021-09-12 22:29:05 -07:00
elseif (_90_ == nil) then
return nil
2020-10-13 23:23:38 -07:00
else
2021-09-12 22:29:05 -07:00
local _ = _90_
2020-10-13 23:23:38 -07:00
return member_3f(x, tbl, ((n or 1) + 1))
2020-09-18 12:13:53 -07:00
end
end
local function allpairs(tbl)
assert((type(tbl) == "table"), "allpairs expects a table")
local t = tbl
local seen = {}
local function allpairs_next(_, state)
local next_state, value = next(t, state)
if seen[next_state] then
return allpairs_next(nil, next_state)
elseif next_state then
seen[next_state] = true
return next_state, value
else
2021-09-12 22:29:05 -07:00
local _92_ = getmetatable(t)
if ((_G.type(_92_) == "table") and true) then
local __index = (_92_).__index
if ("table" == type(__index)) then
t = __index
return allpairs_next(t)
end
2020-09-18 12:13:53 -07:00
end
end
end
return allpairs_next
end
local function deref(self)
return self[1]
end
local nil_sym = nil
2020-10-13 23:23:38 -07:00
local function list__3estring(self, tostring2)
2020-09-18 12:13:53 -07:00
local safe, max = {}, 0
for k in pairs(self) do
if ((type(k) == "number") and (k > max)) then
max = k
end
end
2020-12-23 10:33:09 -08:00
for i = 1, max do
2020-09-18 12:13:53 -07:00
safe[i] = (((self[i] == nil) and nil_sym) or self[i])
end
2021-09-12 22:29:05 -07:00
return ("(" .. table.concat(map(safe, (tostring2 or view)), " ", 1, max) .. ")")
2020-09-18 12:13:53 -07:00
end
2021-04-12 16:52:31 -07:00
local function comment_view(c)
return c, true
end
local function sym_3d(a, b)
return ((deref(a) == deref(b)) and (getmetatable(a) == getmetatable(b)))
end
local function sym_3c(a, b)
return (a[1] < tostring(b))
end
2021-09-12 22:29:05 -07:00
local symbol_mt = {"SYMBOL", __fennelview = deref, __tostring = deref, __eq = sym_3d, __lt = sym_3c}
local expr_mt
local function _97_(x)
return tostring(deref(x))
end
expr_mt = {"EXPR", __tostring = _97_}
2020-10-13 23:23:38 -07:00
local list_mt = {"LIST", __fennelview = list__3estring, __tostring = list__3estring}
2021-09-12 22:29:05 -07:00
local comment_mt = {"COMMENT", __fennelview = comment_view, __tostring = deref, __eq = sym_3d, __lt = sym_3c}
2020-10-13 23:23:38 -07:00
local sequence_marker = {"SEQUENCE"}
local vararg = setmetatable({"..."}, {"VARARG", __fennelview = deref, __tostring = deref})
2021-09-12 22:29:05 -07:00
local getenv
local function _98_()
2020-09-18 12:13:53 -07:00
return nil
end
2021-09-12 22:29:05 -07:00
getenv = ((os and os.getenv) or _98_)
2020-10-13 23:23:38 -07:00
local function debug_on_3f(flag)
2020-09-18 12:13:53 -07:00
local level = (getenv("FENNEL_DEBUG") or "")
return ((level == "all") or level:find(flag))
end
local function list(...)
2020-10-13 23:23:38 -07:00
return setmetatable({...}, list_mt)
2020-09-18 12:13:53 -07:00
end
2021-04-12 16:52:31 -07:00
local function sym(str, _3fsource, _3fscope)
local s = {str, ["?scope"] = _3fscope}
for k, v in pairs((_3fsource or {})) do
2020-09-18 12:13:53 -07:00
if (type(k) == "string") then
s[k] = v
end
end
2020-10-13 23:23:38 -07:00
return setmetatable(s, symbol_mt)
2020-09-18 12:13:53 -07:00
end
nil_sym = sym("nil")
local function sequence(...)
2020-10-13 23:23:38 -07:00
return setmetatable({...}, {sequence = sequence_marker})
2020-09-18 12:13:53 -07:00
end
local function expr(strcode, etype)
2020-10-13 23:23:38 -07:00
return setmetatable({strcode, type = etype}, expr_mt)
2020-09-18 12:13:53 -07:00
end
2021-04-12 16:52:31 -07:00
local function comment_2a(contents, _3fsource)
2021-09-12 22:29:05 -07:00
local _let_100_ = (_3fsource or {})
local filename = _let_100_["filename"]
local line = _let_100_["line"]
2021-04-12 16:52:31 -07:00
return setmetatable({contents, filename = filename, line = line}, comment_mt)
2021-02-01 17:09:15 -08:00
end
2020-09-18 12:13:53 -07:00
local function varg()
2020-10-13 23:23:38 -07:00
return vararg
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
local function expr_3f(x)
return ((type(x) == "table") and (getmetatable(x) == expr_mt) and x)
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
local function varg_3f(x)
return ((x == vararg) and x)
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
local function list_3f(x)
return ((type(x) == "table") and (getmetatable(x) == list_mt) and x)
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
local function sym_3f(x)
return ((type(x) == "table") and (getmetatable(x) == symbol_mt) and x)
2020-09-18 12:13:53 -07:00
end
2020-10-13 23:23:38 -07:00
local function sequence_3f(x)
2020-09-18 12:13:53 -07:00
local mt = ((type(x) == "table") and getmetatable(x))
2020-10-13 23:23:38 -07:00
return (mt and (mt.sequence == sequence_marker) and x)
2020-09-18 12:13:53 -07:00
end
2021-02-01 17:09:15 -08:00
local function comment_3f(x)
return ((type(x) == "table") and (getmetatable(x) == comment_mt) and x)
end
2021-04-12 16:52:31 -07:00
local function table_3f(x)
return ((type(x) == "table") and (x ~= vararg) and (getmetatable(x) ~= list_mt) and (getmetatable(x) ~= symbol_mt) and not comment_3f(x) and x)
end
2020-10-13 23:23:38 -07:00
local function multi_sym_3f(str)
if sym_3f(str) then
return multi_sym_3f(tostring(str))
2020-09-18 12:13:53 -07:00
elseif (type(str) ~= "string") then
return false
else
local parts = {}
for part in str:gmatch("[^%.%:]+[%.%:]?") do
local last_char = part:sub(( - 1))
if (last_char == ":") then
parts["multi-sym-method-call"] = true
end
if ((last_char == ":") or (last_char == ".")) then
parts[(#parts + 1)] = part:sub(1, ( - 2))
else
parts[(#parts + 1)] = part
end
end
return ((#parts > 0) and (str:match("%.") or str:match(":")) and not str:match("%.%.") and (str:byte() ~= string.byte(".")) and (str:byte(( - 1)) ~= string.byte(".")) and parts)
end
end
2020-10-13 23:23:38 -07:00
local function quoted_3f(symbol)
2020-09-18 12:13:53 -07:00
return symbol.quoted
end
local function walk_tree(root, f, custom_iterator)
local function walk(iterfn, parent, idx, node)
if f(idx, node, parent) then
for k, v in iterfn(node) do
walk(iterfn, node, k, v)
end
return nil
end
end
walk((custom_iterator or pairs), nil, nil, root)
return root
end
2020-12-23 10:33:09 -08:00
local lua_keywords = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", "goto"}
2020-09-18 12:13:53 -07:00
for i, v in ipairs(lua_keywords) do
lua_keywords[v] = i
end
local function valid_lua_identifier_3f(str)
return (str:match("^[%a_][%w_]*$") and not lua_keywords[str])
end
2021-02-01 17:09:15 -08:00
local propagated_options = {"allowedGlobals", "indent", "correlate", "useMetadata", "env", "compiler-env", "compilerEnv"}
2020-09-18 12:13:53 -07:00
local function propagate_options(options, subopts)
for _, name in ipairs(propagated_options) do
subopts[name] = options[name]
end
return subopts
end
2021-09-12 22:29:05 -07:00
local root
local function _105_()
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
root = {chunk = nil, scope = nil, options = nil, reset = _105_}
root["set-reset"] = function(_106_)
local _arg_107_ = _106_
local chunk = _arg_107_["chunk"]
local scope = _arg_107_["scope"]
local options = _arg_107_["options"]
local reset = _arg_107_["reset"]
2020-09-18 12:13:53 -07:00
root.reset = function()
2020-10-13 23:23:38 -07:00
root.chunk, root.scope, root.options, root.reset = chunk, scope, options, reset
2020-09-18 12:13:53 -07:00
return nil
end
return root.reset
end
2020-10-13 23:23:38 -07:00
local function hook(event, ...)
2021-09-12 22:29:05 -07:00
local result = nil
2020-10-13 23:23:38 -07:00
if (root.options and root.options.plugins) then
for _, plugin in ipairs(root.options.plugins) do
2021-09-12 22:29:05 -07:00
do
local _108_ = plugin[event]
if (nil ~= _108_) then
local f = _108_
result = f(...)
end
end
if (nil ~= result) then
return result
2020-10-13 23:23:38 -07:00
end
end
return nil
end
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
return {allpairs = allpairs, stablepairs = stablepairs, copy = copy, kvmap = kvmap, map = map, ["walk-tree"] = walk_tree, ["member?"] = member_3f, list = list, sequence = sequence, sym = sym, varg = varg, expr = expr, comment = comment_2a, ["comment?"] = comment_3f, ["expr?"] = expr_3f, ["list?"] = list_3f, ["multi-sym?"] = multi_sym_3f, ["sequence?"] = sequence_3f, ["sym?"] = sym_3f, ["table?"] = table_3f, ["varg?"] = varg_3f, ["quoted?"] = quoted_3f, ["valid-lua-identifier?"] = valid_lua_identifier_3f, ["lua-keywords"] = lua_keywords, hook = hook, ["propagate-options"] = propagate_options, root = root, ["debug-on?"] = debug_on_3f, path = table.concat({"./?.fnl", "./?/init.fnl", getenv("FENNEL_PATH")}, ";"), ["macro-path"] = table.concat({"./?.fnl", "./?/init-macros.fnl", "./?/init.fnl", getenv("FENNEL_MACRO_PATH")}, ";")}
2020-09-18 12:13:53 -07:00
end
package.preload["fennel"] = package.preload["fennel"] or function(...)
local utils = require("fennel.utils")
local parser = require("fennel.parser")
local compiler = require("fennel.compiler")
local specials = require("fennel.specials")
local repl = require("fennel.repl")
2021-02-01 17:09:15 -08:00
local view = require("fennel.view")
2021-09-12 22:29:05 -07:00
local function eval_env(env, opts)
2020-12-23 10:33:09 -08:00
if (env == "_COMPILER") then
2021-09-12 22:29:05 -07:00
local env0 = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}, opts)
if (opts.allowedGlobals == nil) then
opts.allowedGlobals = specials["current-global-names"](env0)
end
2020-12-23 10:33:09 -08:00
return specials["wrap-env"](env0)
else
return (env and specials["wrap-env"](env))
end
end
2021-04-12 16:52:31 -07:00
local function eval_opts(options, str)
2020-09-18 12:13:53 -07:00
local opts = utils.copy(options)
2021-09-12 22:29:05 -07:00
if (opts.allowedGlobals == nil) then
2020-09-18 12:13:53 -07:00
opts.allowedGlobals = specials["current-global-names"](opts.env)
end
2021-04-12 16:52:31 -07:00
if (not opts.filename and not opts.source) then
opts.source = str
end
if (opts.env == "_COMPILER") then
opts.scope = compiler["make-scope"](compiler.scopes.compiler)
end
return opts
end
local function eval(str, options, ...)
local opts = eval_opts(options, str)
2021-09-12 22:29:05 -07:00
local env = eval_env(opts.env, opts)
2020-09-18 12:13:53 -07:00
local lua_source = compiler["compile-string"](str, opts)
2021-09-12 22:29:05 -07:00
local loader
local function _563_(...)
2020-09-18 12:13:53 -07:00
if opts.filename then
return ("@" .. opts.filename)
else
return str
end
end
2021-09-12 22:29:05 -07:00
loader = specials["load-code"](lua_source, env, _563_(...))
2020-09-18 12:13:53 -07:00
opts.filename = nil
return loader(...)
end
local function dofile_2a(filename, options, ...)
local opts = utils.copy(options)
local f = assert(io.open(filename, "rb"))
2020-10-13 23:23:38 -07:00
local source = assert(f:read("*all"), ("Could not read " .. filename))
2020-09-18 12:13:53 -07:00
f:close()
opts.filename = filename
return eval(source, opts, ...)
end
2021-09-12 22:29:05 -07:00
local function syntax()
local body_3f = {"when", "with-open", "collect", "icollect", "lambda", "\206\187", "macro", "match", "accumulate"}
local binding_3f = {"collect", "icollect", "each", "for", "let", "with-open", "accumulate"}
local define_3f = {"fn", "lambda", "\206\187", "var", "local", "macro", "macros", "global"}
local out = {}
for k, v in pairs(compiler.scopes.global.specials) do
local metadata = (compiler.metadata[v] or {})
do end (out)[k] = {["special?"] = true, ["body-form?"] = metadata["fnl/body-form?"], ["binding-form?"] = utils["member?"](k, binding_3f), ["define?"] = utils["member?"](k, define_3f)}
end
for k, v in pairs(compiler.scopes.global.macros) do
out[k] = {["macro?"] = true, ["body-form?"] = utils["member?"](k, body_3f), ["binding-form?"] = utils["member?"](k, binding_3f), ["define?"] = utils["member?"](k, define_3f)}
end
for k, v in pairs(_G) do
local _564_ = type(v)
if (_564_ == "function") then
out[k] = {["global?"] = true, ["function?"] = true}
elseif (_564_ == "table") then
for k2, v2 in pairs(v) do
if (("function" == type(v2)) and (k ~= "_G")) then
out[(k .. "." .. k2)] = {["function?"] = true, ["global?"] = true}
end
end
out[k] = {["global?"] = true}
end
end
return out
end
local mod = {list = utils.list, ["list?"] = utils["list?"], sym = utils.sym, ["sym?"] = utils["sym?"], sequence = utils.sequence, ["sequence?"] = utils["sequence?"], comment = utils.comment, ["comment?"] = utils["comment?"], varg = utils.varg, path = utils.path, ["macro-path"] = utils["macro-path"], ["sym-char?"] = parser["sym-char?"], parser = parser.parser, granulate = parser.granulate, ["string-stream"] = parser["string-stream"], compile = compiler.compile, ["compile-string"] = compiler["compile-string"], ["compile-stream"] = compiler["compile-stream"], compile1 = compiler.compile1, traceback = compiler.traceback, mangle = compiler["global-mangling"], unmangle = compiler["global-unmangling"], metadata = compiler.metadata, scope = compiler["make-scope"], gensym = compiler.gensym, ["load-code"] = specials["load-code"], ["macro-loaded"] = specials["macro-loaded"], ["macro-searchers"] = specials["macro-searchers"], ["search-module"] = specials["search-module"], ["make-searcher"] = specials["make-searcher"], makeSearcher = specials["make-searcher"], searcher = specials["make-searcher"](), doc = specials.doc, view = view, eval = eval, dofile = dofile_2a, version = "1.0.0-dev", repl = repl, syntax = syntax, loadCode = specials["load-code"], make_searcher = specials["make-searcher"], searchModule = specials["search-module"], macroLoaded = specials["macro-loaded"], compileStream = compiler["compile-stream"], compileString = compiler["compile-string"], stringStream = parser["string-stream"]}
2020-09-18 12:13:53 -07:00
utils["fennel-module"] = mod
do
2020-10-13 23:23:38 -07:00
local builtin_macros = [===[;; This module contains all the built-in Fennel macros. Unlike all the other
;; modules that are loaded by the old bootstrap compiler, this runs in the
;; compiler scope of the version of the compiler being defined.
;; The code for these macros is somewhat idiosyncratic because it cannot use any
2020-09-18 12:13:53 -07:00
;; macros which have not yet been defined.
2020-12-23 10:33:09 -08:00
;; TODO: some of these macros modify their arguments; we should stop doing that,
;; but in a way that preserves file/line metadata.
2021-04-12 16:52:31 -07:00
(fn ->* [val ...]
2020-09-18 12:13:53 -07:00
"Thread-first macro.
Take the first value and splice it into the second form as its first argument.
The value of the second form is spliced into the first arg of the third, etc."
(var x val)
(each [_ e (ipairs [...])]
(let [elt (if (list? e) e (list e))]
(table.insert elt 2 x)
(set x elt)))
x)
2021-04-12 16:52:31 -07:00
(fn ->>* [val ...]
2020-09-18 12:13:53 -07:00
"Thread-last macro.
Same as ->, except splices the value into the last position of each form
rather than the first."
(var x val)
(each [_ e (pairs [...])]
(let [elt (if (list? e) e (list e))]
(table.insert elt x)
(set x elt)))
x)
2021-04-12 16:52:31 -07:00
(fn -?>* [val ...]
2020-09-18 12:13:53 -07:00
"Nil-safe thread-first macro.
Same as -> except will short-circuit with nil when it encounters a nil value."
(if (= 0 (select "#" ...))
val
(let [els [...]
e (table.remove els 1)
el (if (list? e) e (list e))
tmp (gensym)]
(table.insert el 2 tmp)
`(let [,tmp ,val]
(if ,tmp
(-?> ,el ,(unpack els))
,tmp)))))
2021-04-12 16:52:31 -07:00
(fn -?>>* [val ...]
2020-09-18 12:13:53 -07:00
"Nil-safe thread-last macro.
Same as ->> except will short-circuit with nil when it encounters a nil value."
(if (= 0 (select "#" ...))
val
(let [els [...]
e (table.remove els 1)
el (if (list? e) e (list e))
tmp (gensym)]
(table.insert el tmp)
`(let [,tmp ,val]
(if ,tmp
(-?>> ,el ,(unpack els))
,tmp)))))
2021-09-12 22:29:05 -07:00
(fn ?dot [tbl ...]
2021-04-12 16:52:31 -07:00
"Nil-safe table look up.
Same as . (dot), except will short-circuit with nil when it encounters
a nil value in any of subsequent keys."
2021-09-12 22:29:05 -07:00
(let [head (gensym :t)
lookups `(do (var ,head ,tbl) ,head)]
(each [_ k (ipairs [...])]
;; Kinda gnarly to reassign in place like this, but it emits the best lua.
;; With this impl, it emits a flat, concise, and readable set of if blocks.
(table.insert lookups (# lookups) `(if (not= nil ,head)
(set ,head (. ,head ,k)))))
lookups))
2021-04-12 16:52:31 -07:00
(fn doto* [val ...]
2020-09-18 12:13:53 -07:00
"Evaluates val and splices it into the first argument of subsequent forms."
(let [name (gensym)
form `(let [,name ,val])]
(each [_ elt (pairs [...])]
(table.insert elt 2 name)
(table.insert form elt))
(table.insert form name)
form))
2021-04-12 16:52:31 -07:00
(fn when* [condition body1 ...]
2020-09-18 12:13:53 -07:00
"Evaluate body for side-effects only when condition is truthy."
(assert body1 "expected body")
`(if ,condition
2021-04-12 16:52:31 -07:00
(do
,body1
,...)))
2020-09-18 12:13:53 -07:00
2021-04-12 16:52:31 -07:00
(fn with-open* [closable-bindings ...]
2020-09-18 12:13:53 -07:00
"Like `let`, but invokes (v:close) on each binding after evaluating the body.
The body is evaluated inside `xpcall` so that bound values will be closed upon
encountering an error before propagating it."
2021-04-12 16:52:31 -07:00
(let [bodyfn `(fn []
,...)
closer `(fn close-handlers# [ok# ...]
(if ok# ... (error ... 0)))
2020-09-18 12:13:53 -07:00
traceback `(. (or package.loaded.fennel debug) :traceback)]
2021-04-12 16:52:31 -07:00
(for [i 1 (length closable-bindings) 2]
2020-09-18 12:13:53 -07:00
(assert (sym? (. closable-bindings i))
"with-open only allows symbols in bindings")
(table.insert closer 4 `(: ,(. closable-bindings i) :close)))
2021-04-12 16:52:31 -07:00
`(let ,closable-bindings
,closer
2021-09-12 22:29:05 -07:00
(close-handlers# (_G.xpcall ,bodyfn ,traceback)))))
(fn into-val [iter-tbl]
(var into nil)
(for [i (length iter-tbl) 2 -1]
(if (= :into (. iter-tbl i))
(do (set into (table.remove iter-tbl (+ i 1)))
(table.remove iter-tbl i))))
(assert (or (not into) (table? into)) "expected table in :into clause")
(or into []))
2020-09-18 12:13:53 -07:00
2021-04-12 16:52:31 -07:00
(fn collect* [iter-tbl key-value-expr ...]
2020-12-23 10:33:09 -08:00
"Returns a table made by running an iterator and evaluating an expression
that returns key-value pairs to be inserted sequentially into the table.
This can be thought of as a \"table comprehension\". The provided key-value
expression must return either 2 values, or nil.
For example,
(collect [k v (pairs {:apple \"red\" :orange \"orange\"})]
(values v k))
returns
2021-09-12 22:29:05 -07:00
{:red \"apple\" :orange \"orange\"}
Supports an :into clause after the iterator to put results in an existing table.
Supports early termination with an :until clause."
2020-12-23 10:33:09 -08:00
(assert (and (sequence? iter-tbl) (>= (length iter-tbl) 2))
"expected iterator binding table")
2021-04-12 16:52:31 -07:00
(assert (not= nil key-value-expr) "expected key-value expression")
2021-02-01 17:09:15 -08:00
(assert (= nil ...)
"expected exactly one body expression. Wrap multiple expressions with do")
2021-09-12 22:29:05 -07:00
`(let [tbl# ,(into-val iter-tbl)]
2020-12-23 10:33:09 -08:00
(each ,iter-tbl
(match ,key-value-expr
(k# v#) (tset tbl# k# v#)))
tbl#))
2021-04-12 16:52:31 -07:00
(fn icollect* [iter-tbl value-expr ...]
2020-12-23 10:33:09 -08:00
"Returns a sequential table made by running an iterator and evaluating an
expression that returns values to be inserted sequentially into the table.
This can be thought of as a \"list comprehension\".
For example,
(icollect [_ v (ipairs [1 2 3 4 5])] (when (> v 2) (* v v)))
returns
2021-09-12 22:29:05 -07:00
[9 16 25]
Supports an :into clause after the iterator to put results in an existing table.
Supports early termination with an :until clause."
2020-12-23 10:33:09 -08:00
(assert (and (sequence? iter-tbl) (>= (length iter-tbl) 2))
"expected iterator binding table")
2021-04-12 16:52:31 -07:00
(assert (not= nil value-expr) "expected table value expression")
2021-02-01 17:09:15 -08:00
(assert (= nil ...)
"expected exactly one body expression. Wrap multiple expressions with do")
2021-09-12 22:29:05 -07:00
`(let [tbl# ,(into-val iter-tbl)]
2020-12-23 10:33:09 -08:00
(each ,iter-tbl
(tset tbl# (+ (length tbl#) 1) ,value-expr))
tbl#))
2021-09-12 22:29:05 -07:00
(fn accumulate* [iter-tbl accum-expr ...]
"Accumulation macro.
It takes a binding table and an expression as its arguments.
In the binding table, the first symbol is bound to the second value, being an
initial accumulator variable. The rest are an iterator binding table in the
format `each` takes.
It runs through the iterator in each step of which the given expression is
evaluated, and its returned value updates the accumulator variable.
It eventually returns the final value of the accumulator variable.
For example,
(accumulate [total 0
_ n (pairs {:apple 2 :orange 3})]
(+ total n))
returns
5"
(assert (and (sequence? iter-tbl) (>= (length iter-tbl) 4))
"expected initial value and iterator binding table")
(assert (not= nil accum-expr) "expected accumulating expression")
(assert (= nil ...)
"expected exactly one body expression. Wrap multiple expressions with do")
(let [accum-var (table.remove iter-tbl 1)
accum-init (table.remove iter-tbl 1)]
`(do (var ,accum-var ,accum-init)
(each ,iter-tbl
(set ,accum-var ,accum-expr))
,accum-var)))
2021-04-12 16:52:31 -07:00
(fn partial* [f ...]
2020-09-18 12:13:53 -07:00
"Returns a function with all arguments partially applied to f."
2021-04-12 16:52:31 -07:00
(assert f "expected a function to partially apply")
2021-09-12 22:29:05 -07:00
(let [bindings []
args []]
(each [_ arg (ipairs [...])]
(if (or (= :number (type arg))
(= :string (type arg))
(= :boolean (type arg))
(= `nil arg))
(table.insert args arg)
(let [name (gensym)]
(table.insert bindings name)
(table.insert bindings arg)
(table.insert args name))))
(let [body (list f (unpack args))]
(table.insert body _VARARG)
`(let ,bindings
(fn [,_VARARG]
,body)))))
2020-09-18 12:13:53 -07:00
2021-04-12 16:52:31 -07:00
(fn pick-args* [n f]
2020-09-18 12:13:53 -07:00
"Creates a function of arity n that applies its arguments to f.
For example,
(pick-args 2 func)
expands to
(fn [_0_ _1_] (func _0_ _1_))"
2021-09-12 22:29:05 -07:00
(if (and _G.io _G.io.stderr)
(_G.io.stderr:write
"-- WARNING: pick-args is deprecated and will be removed in the future.\n"))
2020-09-18 12:13:53 -07:00
(assert (and (= (type n) :number) (= n (math.floor n)) (>= n 0))
2021-04-12 16:52:31 -07:00
(.. "Expected n to be an integer literal >= 0, got " (tostring n)))
2020-09-18 12:13:53 -07:00
(let [bindings []]
2021-04-12 16:52:31 -07:00
(for [i 1 n]
(tset bindings i (gensym)))
`(fn ,bindings
(,f ,(unpack bindings)))))
2020-09-18 12:13:53 -07:00
2021-04-12 16:52:31 -07:00
(fn pick-values* [n ...]
2020-09-18 12:13:53 -07:00
"Like the `values` special, but emits exactly n values.
For example,
(pick-values 2 ...)
expands to
(let [(_0_ _1_) ...]
(values _0_ _1_))"
(assert (and (= :number (type n)) (>= n 0) (= n (math.floor n)))
2021-04-12 16:52:31 -07:00
(.. "Expected n to be an integer >= 0, got " (tostring n)))
(let [let-syms (list)
let-values (if (= 1 (select "#" ...)) ... `(values ,...))]
(for [i 1 n]
(table.insert let-syms (gensym)))
2020-09-18 12:13:53 -07:00
(if (= n 0) `(values)
2021-04-12 16:52:31 -07:00
`(let [,let-syms ,let-values]
(values ,(unpack let-syms))))))
2020-09-18 12:13:53 -07:00
2021-04-12 16:52:31 -07:00
(fn lambda* [...]
2021-09-12 22:29:05 -07:00
"Function literal with nil-checked arguments.
Like `fn`, but will throw an exception if a declared argument is passed in as
nil, unless that argument's name begins with a question mark."
2020-09-18 12:13:53 -07:00
(let [args [...]
has-internal-name? (sym? (. args 1))
arglist (if has-internal-name? (. args 2) (. args 1))
docstring-position (if has-internal-name? 3 2)
2021-04-12 16:52:31 -07:00
has-docstring? (and (> (length args) docstring-position)
2020-09-18 12:13:53 -07:00
(= :string (type (. args docstring-position))))
arity-check-position (- 4 (if has-internal-name? 0 1)
(if has-docstring? 0 1))
2021-04-12 16:52:31 -07:00
empty-body? (< (length args) arity-check-position)]
2020-09-18 12:13:53 -07:00
(fn check! [a]
(if (table? a)
(each [_ a (pairs a)]
(check! a))
2020-12-23 10:33:09 -08:00
(let [as (tostring a)]
2021-04-12 16:52:31 -07:00
(and (not (as:match "^?")) (not= as "&") (not= as "_")
2021-09-12 22:29:05 -07:00
(not= as "...") (not= as "&as")))
2020-09-18 12:13:53 -07:00
(table.insert args arity-check-position
2021-09-12 22:29:05 -07:00
`(_G.assert (not= nil ,a)
,(: "Missing argument %s on %s:%s" :format
(tostring a)
(or a.filename :unknown)
(or a.line "?"))))))
2021-04-12 16:52:31 -07:00
2020-09-18 12:13:53 -07:00
(assert (= :table (type arglist)) "expected arg list")
(each [_ a (ipairs arglist)]
(check! a))
(if empty-body?
(table.insert args (sym :nil)))
`(fn ,(unpack args))))
2021-04-12 16:52:31 -07:00
(fn macro* [name ...]
2020-09-18 12:13:53 -07:00
"Define a single macro."
(assert (sym? name) "expected symbol for macro name")
(local args [...])
2021-04-12 16:52:31 -07:00
`(macros {,(tostring name) (fn ,(unpack args))}))
2020-09-18 12:13:53 -07:00
2021-04-12 16:52:31 -07:00
(fn macrodebug* [form return?]
2020-09-18 12:13:53 -07:00
"Print the resulting form after performing macroexpansion.
With a second argument, returns expanded form as a string instead of printing."
2021-02-01 17:09:15 -08:00
(let [handle (if return? `do `print)]
`(,handle ,(view (macroexpand form _SCOPE)))))
2020-09-18 12:13:53 -07:00
2021-04-12 16:52:31 -07:00
(fn import-macros* [binding1 module-name1 ...]
2020-09-18 12:13:53 -07:00
"Binds a table of macros from each macro module according to a binding form.
Each binding form can be either a symbol or a k/v destructuring table.
Example:
(import-macros mymacros :my-macros ; bind to symbol
{:macro1 alias : macro2} :proj.macros) ; import by name"
2021-04-12 16:52:31 -07:00
(assert (and binding1 module-name1 (= 0 (% (select "#" ...) 2)))
2020-09-18 12:13:53 -07:00
"expected even number of binding/modulename pairs")
2021-04-12 16:52:31 -07:00
(for [i 1 (select "#" binding1 module-name1 ...) 2]
2020-12-23 10:33:09 -08:00
(let [(binding modname) (select i binding1 module-name1 ...)
;; generate a subscope of current scope, use require-macros
;; to bring in macro module. after that, we just copy the
;; macros from subscope to scope.
scope (get-scope)
subscope (fennel.scope scope)]
(_SPECIALS.require-macros `(require-macros ,modname) subscope {} ast)
(if (sym? binding)
;; bind whole table of macros to table bound to symbol
2021-09-12 22:29:05 -07:00
(tset scope.macros (. binding 1) (. macro-loaded modname))
2020-12-23 10:33:09 -08:00
;; 1-level table destructuring for importing individual macros
(table? binding)
(each [macro-name [import-key] (pairs binding)]
(assert (= :function (type (. subscope.macros macro-name)))
(.. "macro " macro-name " not found in module "
(tostring modname)))
(tset scope.macros import-key (. subscope.macros macro-name))))))
2020-09-18 12:13:53 -07:00
nil)
;;; Pattern matching
2020-12-23 10:33:09 -08:00
(fn match-values [vals pattern unifications match-pattern]
(let [condition `(and)
bindings []]
(each [i pat (ipairs pattern)]
(let [(subcondition subbindings) (match-pattern [(. vals i)] pat
unifications)]
(table.insert condition subcondition)
(each [_ b (ipairs subbindings)]
(table.insert bindings b))))
(values condition bindings)))
(fn match-table [val pattern unifications match-pattern]
2021-09-12 22:29:05 -07:00
(let [condition `(and (= (_G.type ,val) :table))
2020-12-23 10:33:09 -08:00
bindings []]
(each [k pat (pairs pattern)]
2021-04-12 16:52:31 -07:00
(if (= pat `&)
(do
(assert (= nil (. pattern (+ k 2)))
"expected & rest argument before last parameter")
(table.insert bindings (. pattern (+ k 1)))
(table.insert bindings
[`(select ,k ((or table.unpack _G.unpack) ,val))]))
(= k `&as)
(do
(table.insert bindings pat)
(table.insert bindings val))
(and (= :number (type k)) (= `&as pat))
(do
(assert (= nil (. pattern (+ k 2)))
"expected &as argument before last parameter")
(table.insert bindings (. pattern (+ k 1)))
(table.insert bindings val))
;; don't process the pattern right after &/&as; already got it
(or (not= :number (type k)) (and (not= `&as (. pattern (- k 1)))
(not= `& (. pattern (- k 1)))))
2020-12-23 10:33:09 -08:00
(let [subval `(. ,val ,k)
(subcondition subbindings) (match-pattern [subval] pat
unifications)]
(table.insert condition subcondition)
(each [_ b (ipairs subbindings)]
(table.insert bindings b)))))
(values condition bindings)))
2020-09-18 12:13:53 -07:00
(fn match-pattern [vals pattern unifications]
"Takes the AST of values and a single pattern and returns a condition
to determine if it matches as well as a list of bindings to
introduce for the duration of the body if it does match."
;; we have to assume we're matching against multiple values here until we
;; know we're either in a multi-valued clause (in which case we know the #
;; of vals) or we're not, in which case we only care about the first one.
(let [[val] vals]
(if (or (and (sym? pattern) ; unification with outer locals (or nil)
2021-04-12 16:52:31 -07:00
(not= "_" (tostring pattern)) ; never unify _
(or (in-scope? pattern) (= :nil (tostring pattern))))
(and (multi-sym? pattern) (in-scope? (. (multi-sym? pattern) 1))))
2020-09-18 12:13:53 -07:00
(values `(= ,val ,pattern) [])
;; unify a local we've seen already
2020-12-23 10:33:09 -08:00
(and (sym? pattern) (. unifications (tostring pattern)))
2020-09-18 12:13:53 -07:00
(values `(= ,(. unifications (tostring pattern)) ,val) [])
;; bind a fresh local
(sym? pattern)
2020-12-23 10:33:09 -08:00
(let [wildcard? (: (tostring pattern) :find "^_")]
2020-09-18 12:13:53 -07:00
(if (not wildcard?) (tset unifications (tostring pattern) val))
2021-04-12 16:52:31 -07:00
(values (if (or wildcard? (string.find (tostring pattern) "^?")) true
`(not= ,(sym :nil) ,val)) [pattern val]))
2020-09-18 12:13:53 -07:00
;; guard clause
2021-04-12 16:52:31 -07:00
(and (list? pattern) (= (. pattern 2) `?))
2020-09-18 12:13:53 -07:00
(let [(pcondition bindings) (match-pattern vals (. pattern 1)
unifications)
2021-09-12 22:29:05 -07:00
condition `(and ,(unpack pattern 3))]
(values `(and ,pcondition
(let ,bindings
,condition)) bindings))
2020-09-18 12:13:53 -07:00
;; multi-valued patterns (represented as lists)
(list? pattern)
2020-12-23 10:33:09 -08:00
(match-values vals pattern unifications match-pattern)
2020-09-18 12:13:53 -07:00
;; table patterns
(= (type pattern) :table)
2020-12-23 10:33:09 -08:00
(match-table val pattern unifications match-pattern)
2020-09-18 12:13:53 -07:00
;; literal value
(values `(= ,val ,pattern) []))))
(fn match-condition [vals clauses]
"Construct the actual `if` AST for the given match values and clauses."
(if (not= 0 (% (length clauses) 2)) ; treat odd final clause as default
2021-04-12 16:52:31 -07:00
(table.insert clauses (length clauses) (sym "_")))
2020-09-18 12:13:53 -07:00
(let [out `(if)]
(for [i 1 (length clauses) 2]
(let [pattern (. clauses i)
body (. clauses (+ i 1))
(condition bindings) (match-pattern vals pattern {})]
(table.insert out condition)
2021-04-12 16:52:31 -07:00
(table.insert out `(let ,bindings
,body))))
2020-09-18 12:13:53 -07:00
out))
(fn match-val-syms [clauses]
"How many multi-valued clauses are there? return a list of that many gensyms."
(let [syms (list (gensym))]
(for [i 1 (length clauses) 2]
2021-09-12 22:29:05 -07:00
(let [clause (if (and (list? (. clauses i)) (= `? (. clauses i 2)))
(. clauses i 1)
(. clauses i))]
(if (list? clause)
(each [valnum (ipairs clause)]
(if (not (. syms valnum))
(tset syms valnum (gensym)))))))
2020-09-18 12:13:53 -07:00
syms))
2021-04-12 16:52:31 -07:00
(fn match* [val ...]
;; Old implementation of match macro, which doesn't directly support
;; `where' and `or'. New syntax is implemented in `match-where',
;; which simply generates old syntax and feeds it to `match*'.
2020-09-18 12:13:53 -07:00
(let [clauses [...]
vals (match-val-syms clauses)]
2021-09-12 22:29:05 -07:00
(assert (= 0 (math.fmod (length clauses) 2))
"expected even number of pattern/body pairs")
2020-09-18 12:13:53 -07:00
;; protect against multiple evaluation of the value, bind against as
;; many values as we ever match against in the clauses.
2021-04-12 16:52:31 -07:00
(list `let [vals val] (match-condition vals clauses))))
;; Construction of old match syntax from new syntax
(fn partition-2 [seq]
;; Partition `seq` by 2.
;; If `seq` has odd amount of elements, the last one is dropped.
;;
;; Input: [1 2 3 4 5]
;; Output: [[1 2] [3 4]]
(let [firsts []
seconds []
res []]
(for [i 1 (length seq) 2]
(let [first (. seq i)
second (. seq (+ i 1))]
(table.insert firsts (if (not= nil first) first `nil))
(table.insert seconds (if (not= nil second) second `nil))))
(each [i v1 (ipairs firsts)]
(let [v2 (. seconds i)]
(if (not= nil v2)
(table.insert res [v1 v2]))))
res))
2020-09-18 12:13:53 -07:00
2021-04-12 16:52:31 -07:00
(fn transform-or [[_ & pats] guards]
;; Transforms `(or pat pats*)` lists into match `guard` patterns.
;;
;; (or pat1 pat2), guard => [(pat1 ? guard) (pat2 ? guard)]
(let [res []]
(each [_ pat (ipairs pats)]
(table.insert res (list pat `? (unpack guards))))
res))
(fn transform-cond [cond]
;; Transforms `where` cond into sequence of `match` guards.
;;
;; pat => [pat]
;; (where pat guard) => [(pat ? guard)]
;; (where (or pat1 pat2) guard) => [(pat1 ? guard) (pat2 ? guard)]
(if (and (list? cond) (= (. cond 1) `where))
(let [second (. cond 2)]
(if (and (list? second) (= (. second 1) `or))
(transform-or second [(unpack cond 3)])
:else
[(list second `? (unpack cond 3))]))
:else
[cond]))
(fn match-where [val ...]
"Perform pattern matching on val. See reference for details.
Syntax:
(match data-expression
pattern body
(where pattern guard guards*) body
(where (or pattern patterns*) guard guards*) body)"
(let [conds-bodies (partition-2 [...])
else-branch (if (not= 0 (% (select "#" ...) 2))
(select (select "#" ...) ...))
match-body []]
(each [_ [cond body] (ipairs conds-bodies)]
(each [_ cond (ipairs (transform-cond cond))]
(table.insert match-body cond)
(table.insert match-body body)))
(if else-branch
(table.insert match-body else-branch))
(match* val (unpack match-body))))
{:-> ->*
:->> ->>*
:-?> -?>*
:-?>> -?>>*
:?. ?dot
:doto doto*
:when when*
:with-open with-open*
:collect collect*
:icollect icollect*
2021-09-12 22:29:05 -07:00
:accumulate accumulate*
2021-04-12 16:52:31 -07:00
:partial partial*
:lambda lambda*
:pick-args pick-args*
:pick-values pick-values*
:macro macro*
:macrodebug macrodebug*
:import-macros import-macros*
:match match-where}
2020-09-18 12:13:53 -07:00
]===]
local module_name = "fennel.macros"
2021-09-12 22:29:05 -07:00
local _
local function _567_()
2020-09-18 12:13:53 -07:00
return mod
end
2021-09-12 22:29:05 -07:00
package.preload[module_name] = _567_
2020-09-18 12:13:53 -07:00
_ = nil
2021-09-12 22:29:05 -07:00
local env
2020-10-13 23:23:38 -07:00
do
2021-09-12 22:29:05 -07:00
local _568_ = specials["make-compiler-env"](nil, compiler.scopes.compiler, {})
do end (_568_)["utils"] = utils
_568_["fennel"] = mod
env = _568_
2020-10-13 23:23:38 -07:00
end
2021-09-12 22:29:05 -07:00
local built_ins = eval(builtin_macros, {env = env, scope = compiler.scopes.compiler, allowedGlobals = false, useMetadata = true, filename = "src/fennel/macros.fnl", moduleName = module_name})
2020-09-18 12:13:53 -07:00
for k, v in pairs(built_ins) do
compiler.scopes.global.macros[k] = v
end
compiler.scopes.global.macros["\206\187"] = compiler.scopes.global.macros.lambda
package.preload[module_name] = nil
end
return mod
end
fennel = require("fennel")
2021-02-01 17:09:15 -08:00
local unpack = (table.unpack or _G.unpack)
2021-09-12 22:29:05 -07:00
local help = "\nUsage: fennel [FLAG] [FILE]\n\nRun fennel, a lisp programming language for the Lua runtime.\n\n --repl : Command to launch an interactive repl session\n --compile FILES (-c) : Command to AOT compile files, writing Lua to stdout\n --eval SOURCE (-e) : Command to evaluate source code and print the result\n\n --no-searcher : Skip installing package.searchers entry\n --indent VAL : Indent compiler output with VAL\n --add-package-path PATH : Add PATH to package.path for finding Lua modules\n --add-fennel-path PATH : Add PATH to fennel.path for finding Fennel modules\n --globals G1[,G2...] : Allow these globals in addition to standard ones\n --globals-only G1[,G2] : Same as above, but exclude standard ones\n --require-as-include : Inline required modules in the output\n --skip-include M1[,M2] : Omit certain modules from output when included\n --use-bit-lib : Use LuaJITs bit library instead of operators\n --metadata : Enable function metadata, even in compiled output\n --no-metadata : Disable function metadata, even in REPL\n --correlate : Make Lua output line numbers match Fennel input\n --load FILE (-l) : Load the specified FILE before executing the command\n --lua LUA_EXE : Run in a child process with LUA_EXE\n --no-fennelrc : Skip loading ~/.fennelrc when launching repl\n --raw-errors : Disable friendly compile error reporting\n --plugin FILE : Activate the compiler plugin in FILE\n --compile-binary FILE\n OUT LUA_LIB LUA_DIR : Compile FILE to standalone binary OUT\n --compile-binary --help : Display further help for compiling binaries\n --no-compiler-sandbox : Do not limit compiler environment to minimal sandbox\n\n --help (-h) : Display this text\n --version (-v) : Show version\n\nGlobals are not checked when doing AOT (ahead-of-time) compilation unless\nthe --globals-only or --globals flag is provided. Use --globals \"*\" to disable\nstrict globals checking in other contexts.\n\nMetadata is typically considered a development feature and is not recommended\nfor production. It is used for docstrings and enabled by default in the REPL.\n\nWhen not given a command, runs the file given as the first argument.\nWhen given neither command nor file, launches a repl.\n\nIf ~/.fennelrc exists, it will be loaded before launching a repl."
2020-10-13 23:23:38 -07:00
local options = {plugins = {}}
2020-09-18 12:13:53 -07:00
local function dosafely(f, ...)
local args = {...}
2021-09-12 22:29:05 -07:00
local _569_, _570_ = nil, nil
local function _571_()
2020-09-18 12:13:53 -07:00
return f(unpack(args))
end
2021-09-12 22:29:05 -07:00
_569_, _570_ = xpcall(_571_, fennel.traceback)
if ((_569_ == true) and (nil ~= _570_)) then
local val = _570_
return val
elseif (true and (nil ~= _570_)) then
local _ = _569_
local msg = _570_
do end (io.stderr):write((msg .. "\n"))
return os.exit(1)
2020-09-18 12:13:53 -07:00
end
end
2021-09-12 22:29:05 -07:00
local function allow_globals(global_names, globals)
if (global_names == "*") then
options.allowedGlobals = false
return nil
else
do
local tbl_13_auto = {}
for g in global_names:gmatch("([^,]+),?") do
tbl_13_auto[(#tbl_13_auto + 1)] = g
end
options.allowedGlobals = tbl_13_auto
end
for global_name in pairs(globals) do
table.insert(options.allowedGlobals, global_name)
end
return nil
2020-09-18 12:13:53 -07:00
end
end
local function handle_load(i)
local file = table.remove(arg, (i + 1))
dosafely(fennel.dofile, file, options)
return table.remove(arg, i)
end
2020-10-13 23:23:38 -07:00
local function handle_lua(i)
table.remove(arg, i)
local tgt_lua = table.remove(arg, i)
local cmd = {string.format("%s %s", tgt_lua, arg[0])}
for i0 = 1, #arg do
table.insert(cmd, string.format("%q", arg[i0]))
end
local ok = os.execute(table.concat(cmd, " "))
2021-09-12 22:29:05 -07:00
local _574_
2020-10-13 23:23:38 -07:00
if ok then
2021-09-12 22:29:05 -07:00
_574_ = 0
2020-10-13 23:23:38 -07:00
else
2021-09-12 22:29:05 -07:00
_574_ = 1
2020-10-13 23:23:38 -07:00
end
2021-09-12 22:29:05 -07:00
return os.exit(_574_, true)
2020-10-13 23:23:38 -07:00
end
for i = #arg, 1, -1 do
2021-09-12 22:29:05 -07:00
local _576_ = arg[i]
if (_576_ == "--lua") then
2020-10-13 23:23:38 -07:00
handle_lua(i)
end
end
2020-09-18 12:13:53 -07:00
for i = #arg, 1, -1 do
2021-09-12 22:29:05 -07:00
local _578_ = arg[i]
if (_578_ == "--no-searcher") then
2020-12-23 10:33:09 -08:00
options["no-searcher"] = true
2020-09-18 12:13:53 -07:00
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--indent") then
2020-09-18 12:13:53 -07:00
options.indent = table.remove(arg, (i + 1))
if (options.indent == "false") then
options.indent = false
end
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--add-package-path") then
2020-09-18 12:13:53 -07:00
local entry = table.remove(arg, (i + 1))
package.path = (entry .. ";" .. package.path)
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--add-fennel-path") then
2020-09-18 12:13:53 -07:00
local entry = table.remove(arg, (i + 1))
fennel.path = (entry .. ";" .. fennel.path)
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--load") then
2020-09-18 12:13:53 -07:00
handle_load(i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "-l") then
2020-09-18 12:13:53 -07:00
handle_load(i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--no-fennelrc") then
2020-09-18 12:13:53 -07:00
options.fennelrc = false
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--correlate") then
2020-09-18 12:13:53 -07:00
options.correlate = true
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--check-unused-locals") then
2020-09-18 12:13:53 -07:00
options.checkUnusedLocals = true
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--globals") then
allow_globals(table.remove(arg, (i + 1)), _G)
2020-09-18 12:13:53 -07:00
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--globals-only") then
allow_globals(table.remove(arg, (i + 1)), {})
2020-09-18 12:13:53 -07:00
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--require-as-include") then
2020-09-18 12:13:53 -07:00
options.requireAsInclude = true
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--skip-include") then
local skip_names = table.remove(arg, (i + 1))
local skip
do
local tbl_13_auto = {}
for m in skip_names:gmatch("([^,]+)") do
tbl_13_auto[(#tbl_13_auto + 1)] = m
end
skip = tbl_13_auto
end
options.skipInclude = skip
table.remove(arg, i)
elseif (_578_ == "--use-bit-lib") then
2021-04-12 16:52:31 -07:00
options.useBitLib = true
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--metadata") then
2020-09-18 12:13:53 -07:00
options.useMetadata = true
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--no-metadata") then
2020-09-18 12:13:53 -07:00
options.useMetadata = false
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--no-compiler-sandbox") then
2020-10-13 23:23:38 -07:00
options["compiler-env"] = _G
table.remove(arg, i)
2021-09-12 22:29:05 -07:00
elseif (_578_ == "--raw-errors") then
options.unfriendly = true
table.remove(arg, i)
elseif (_578_ == "--plugin") then
local opts = {env = "_COMPILER", useMetadata = true, ["compiler-env"] = _G}
local plugin = fennel.dofile(table.remove(arg, (i + 1)), opts)
2020-10-13 23:23:38 -07:00
table.insert(options.plugins, 1, plugin)
table.remove(arg, i)
2020-09-18 12:13:53 -07:00
end
end
2020-12-23 10:33:09 -08:00
local searcher_opts = {}
if not options["no-searcher"] then
2020-09-18 12:13:53 -07:00
for k, v in pairs(options) do
2020-12-23 10:33:09 -08:00
searcher_opts[k] = v
2020-09-18 12:13:53 -07:00
end
2020-12-23 10:33:09 -08:00
table.insert((package.loaders or package.searchers), fennel["make-searcher"](searcher_opts))
2020-09-18 12:13:53 -07:00
end
local function try_readline(ok, readline)
if ok then
if readline.set_readline_name then
readline.set_readline_name("fennel")
end
2021-09-12 22:29:05 -07:00
readline.set_options({keeplines = 1000, histfile = ""})
2020-09-18 12:13:53 -07:00
options.readChunk = function(parser_state)
2021-09-12 22:29:05 -07:00
local prompt
2020-09-18 12:13:53 -07:00
if (0 < parser_state["stack-size"]) then
prompt = ".. "
else
prompt = ">> "
end
local str = readline.readline(prompt)
if str then
return (str .. "\n")
end
end
local completer = nil
options.registerCompleter = function(repl_completer)
completer = repl_completer
return nil
end
local function repl_completer(text, from, to)
if completer then
readline.set_completion_append_character("")
return completer(text:sub(from, to))
else
return {}
end
end
readline.set_complete_function(repl_completer)
return readline
end
end
local function load_initfile()
local home = (os.getenv("HOME") or "/")
local xdg_config_home = (os.getenv("XDG_CONFIG_HOME") or (home .. "/.config"))
local xdg_initfile = (xdg_config_home .. "/fennel/fennelrc")
local home_initfile = (home .. "/.fennelrc")
local init = io.open(xdg_initfile, "rb")
2021-09-12 22:29:05 -07:00
local init_filename
2020-09-18 12:13:53 -07:00
if init then
init_filename = xdg_initfile
else
init_filename = home_initfile
end
local init0 = (init or io.open(home_initfile, "rb"))
if init0 then
init0:close()
return dosafely(fennel.dofile, init_filename, options, options, fennel)
end
end
local function repl()
2021-09-12 22:29:05 -07:00
local readline = (("dumb" ~= os.getenv("TERM")) and try_readline(pcall(require, "readline")))
2020-12-23 10:33:09 -08:00
searcher_opts.useMetadata = (false ~= options.useMetadata)
2021-02-01 17:09:15 -08:00
options.pp = require("fennel.view")
2020-09-18 12:13:53 -07:00
if (false ~= options.fennelrc) then
load_initfile()
end
print(("Welcome to Fennel " .. fennel.version .. " on " .. _VERSION .. "!"))
2020-12-23 10:33:09 -08:00
print("Use ,help to see available commands.")
2021-09-12 22:29:05 -07:00
if (not readline and ("dumb" ~= os.getenv("TERM"))) then
2020-09-18 12:13:53 -07:00
print("Try installing readline via luarocks for a better repl experience.")
end
fennel.repl(options)
if readline then
return readline.save_history()
end
end
local function eval(form)
2021-09-12 22:29:05 -07:00
local _592_
2020-09-18 12:13:53 -07:00
if (form == "-") then
2021-09-12 22:29:05 -07:00
_592_ = (io.stdin):read("*a")
2020-09-18 12:13:53 -07:00
else
2021-09-12 22:29:05 -07:00
_592_ = form
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
return print(dosafely(fennel.eval, _592_, options))
2020-09-18 12:13:53 -07:00
end
2021-09-12 22:29:05 -07:00
local function compile(files)
2020-09-18 12:13:53 -07:00
for _, filename in ipairs(files) do
options.filename = filename
2021-09-12 22:29:05 -07:00
local f
2020-09-18 12:13:53 -07:00
if (filename == "-") then
f = io.stdin
else
f = assert(io.open(filename, "rb"))
end
2021-09-12 22:29:05 -07:00
do
local _595_, _596_ = nil, nil
local function _597_()
return fennel["compile-string"](f:read("*a"), options)
end
_595_, _596_ = xpcall(_597_, fennel.traceback)
if ((_595_ == true) and (nil ~= _596_)) then
local val = _596_
print(val)
elseif (true and (nil ~= _596_)) then
local _0 = _595_
local msg = _596_
do end (io.stderr):write((msg .. "\n"))
os.exit(1)
end
2018-10-17 18:32:39 -07:00
end
2020-09-18 12:13:53 -07:00
f:close()
end
return nil
2021-09-12 22:29:05 -07:00
end
local _599_ = arg
local function _600_(...)
return (0 == #arg)
end
if ((_G.type(_599_) == "table") and _600_(...)) then
return repl()
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--repl")) then
return repl()
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--compile")) then
local files = {select(2, (table.unpack or _G.unpack)(_599_))}
return compile(files)
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "-c")) then
local files = {select(2, (table.unpack or _G.unpack)(_599_))}
return compile(files)
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--compile-binary") and (nil ~= (_599_)[2]) and (nil ~= (_599_)[3]) and (nil ~= (_599_)[4]) and (nil ~= (_599_)[5])) then
local filename = (_599_)[2]
local out = (_599_)[3]
local static_lua = (_599_)[4]
local lua_include_dir = (_599_)[5]
local args = {select(6, (table.unpack or _G.unpack)(_599_))}
2020-09-18 12:13:53 -07:00
local bin = require("fennel.binary")
options.filename = filename
options.requireAsInclude = true
return bin.compile(filename, out, static_lua, lua_include_dir, options, args)
2021-09-12 22:29:05 -07:00
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--compile-binary")) then
return print((require("fennel.binary")).help)
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--eval") and (nil ~= (_599_)[2])) then
local form = (_599_)[2]
2020-09-18 12:13:53 -07:00
return eval(form)
2021-09-12 22:29:05 -07:00
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "-e") and (nil ~= (_599_)[2])) then
local form = (_599_)[2]
2020-09-18 12:13:53 -07:00
return eval(form)
2021-09-12 22:29:05 -07:00
else
local function _620_(...)
local a = (_599_)[1]
return ((a == "-v") or (a == "--version"))
end
if (((_G.type(_599_) == "table") and (nil ~= (_599_)[1])) and _620_(...)) then
local a = (_599_)[1]
return print(("Fennel " .. fennel.version .. " on " .. _VERSION))
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--help")) then
return print(help)
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "-h")) then
return print(help)
elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "-")) then
local args = {select(2, (table.unpack or _G.unpack)(_599_))}
return dosafely(fennel.eval, (io.stdin):read("*a"))
elseif ((_G.type(_599_) == "table") and (nil ~= (_599_)[1])) then
local filename = (_599_)[1]
local args = {select(2, (table.unpack or _G.unpack)(_599_))}
arg[-2] = arg[-1]
arg[-1] = arg[0]
arg[0] = table.remove(arg, 1)
return dosafely(fennel.dofile, filename, options, unpack(args))
end
2018-10-17 18:32:39 -07:00
end