@@ 0,0 1,6344 @@
+#!/usr/bin/env lua
+package.preload["fennel.binary"] = package.preload["fennel.binary"] or function(...)
+ local fennel = require("fennel")
+ local _local_767_ = require("fennel.utils")
+ local warn = _local_767_["warn"]
+ local copy = _local_767_["copy"]
+ local function shellout(command)
+ local f = io.popen(command)
+ local stdout = f:read("*all")
+ return (f:close() and stdout)
+ end
+ local function execute(cmd)
+ local _768_ = os.execute(cmd)
+ if (_768_ == 0) then
+ return true
+ elseif (_768_ == true) then
+ return true
+ else
+ return nil
+ end
+ 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)
+ local f
+ 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 module_name(open, rename, used_renames)
+ local require_name
+ do
+ local _771_ = rename[open]
+ if (nil ~= _771_) then
+ local renamed = _771_
+ used_renames[open] = true
+ require_name = renamed
+ elseif true then
+ local _ = _771_
+ require_name = open
+ else
+ require_name = nil
+ end
+ end
+ return (require_name:sub(1, 1) .. require_name:sub(2):gsub("_", "."))
+ end
+ local function native_loader(native, _3foptions)
+ local opts = (_3foptions or {["rename-modules"] = {}})
+ local rename = (opts["rename-modules"] or {})
+ local used_renames = {}
+ local nm = (os.getenv("NM") or "nm")
+ local out = {" /* native libraries */"}
+ for _, path in ipairs(native) do
+ local opens = {}
+ for open in shellout((nm .. " " .. path)):gmatch("[^dDt] _?luaopen_([%a%p%d]+)") do
+ table.insert(opens, open)
+ end
+ if (0 == #opens) then
+ warn((("Native module %s did not contain any luaopen_* symbols. " .. "Did you mean to use --native-library instead of --native-module?")):format(path))
+ else
+ end
+ for _0, open in ipairs(opens) 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(module_name(open, rename, used_renames)))
+ end
+ end
+ for key, val in pairs(rename) do
+ if not used_renames[key] then
+ warn((("unused --rename-native-module %s %s argument. " .. "Did you mean to include a native module?")):format(key, val))
+ else
+ 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)
+ local fennel_loader
+ local _775_
+ do
+ _775_ = "(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)))"
+ end
+ fennel_loader = _775_:format(dotpath_noextension)
+ local lua_loader = fennel["compile-string"](fennel_loader)
+ local _let_776_ = options
+ local rename_modules = _let_776_["rename-modules"]
+ 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, {["rename-modules"] = rename_modules}))
+ 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
+ local _778_
+ do
+ local _777_ = shellout((cc .. " -dumpmachine"))
+ if (nil ~= _777_) then
+ _778_ = _777_:match("mingw")
+ else
+ _778_ = _777_
+ end
+ end
+ if _778_ then
+ rdynamic, bin_extension, ldl_3f = "", ".exe", false
+ else
+ rdynamic, bin_extension, ldl_3f = "-rdynamic", "", true
+ end
+ local compile_command
+ local _781_
+ if ldl_3f then
+ _781_ = "-ldl"
+ else
+ _781_ = ""
+ end
+ compile_command = {cc, "-Os", lua_c_path, table.concat(native, " "), static_lua, rdynamic, "-lm", _781_, "-o", (executable_name .. bin_extension), "-I", lua_include_dir, os.getenv("CC_OPTS")}
+ if os.getenv("FENNEL_DEBUG") then
+ print("Compiling with", table.concat(compile_command, " "))
+ else
+ end
+ if not execute(table.concat(compile_command, " ")) then
+ print("failed:", table.concat(compile_command, " "))
+ os.exit(1)
+ else
+ end
+ if not os.getenv("FENNEL_DEBUG") then
+ os.remove(lua_c_path)
+ else
+ end
+ return os.exit(0)
+ end
+ local function native_path_3f(path)
+ local extension, version_extension = path:match("%.(%a+)(%.?%d*)$")
+ if (version_extension and (version_extension ~= "") and not version_extension:match("%.%d+")) then
+ return false
+ else
+ local _786_ = extension
+ if (_786_ == "a") then
+ return path
+ elseif (_786_ == "o") then
+ return path
+ elseif (_786_ == "so") then
+ return path
+ elseif (_786_ == "dylib") then
+ return path
+ elseif true then
+ local _ = _786_
+ return false
+ else
+ return nil
+ end
+ end
+ end
+ local function extract_native_args(args)
+ local native = {modules = {}, libraries = {}, ["rename-modules"] = {}}
+ 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)
+ else
+ 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)
+ else
+ end
+ if ("--rename-native-module" == args[i]) then
+ local original = table.remove(args, (i + 1))
+ local new = table.remove(args, (i + 1))
+ do end (native["rename-modules"])[original] = new
+ table.remove(args, i)
+ else
+ end
+ end
+ if (0 < #args) then
+ print(table.concat(args, " "))
+ error(("Unknown args: " .. table.concat(args, " ")))
+ else
+ end
+ return native
+ end
+ local function compile(filename, executable_name, static_lua, lua_include_dir, options, args)
+ local _let_793_ = extract_native_args(args)
+ local modules = _let_793_["modules"]
+ local libraries = _let_793_["libraries"]
+ local rename_modules = _let_793_["rename-modules"]
+ local opts = {["rename-modules"] = rename_modules}
+ copy(options, opts)
+ return compile_binary(write_c(filename, modules, opts), executable_name, static_lua, lua_include_dir, libraries)
+ end
+ 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\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.\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\nIf you need to change the require name that a given native module is referenced\nas, you can use the --rename-native-module ORIGINAL NEW. ORIGINAL should be the\nsuffix of the luaopen_* symbol in the native module. NEW should be the string\nyou wish to pass to require to require the given native module. This can be used\nto handle cases where the name of an object file does not match the name of the\nluaopen_* symbol(s) within it. For example, the Lua readline bindings include a\nreadline.lua file which is usually required as \"readline\", and a C-readline.so\nfile which is required in the Lua half of the bindings like so:\n\n require 'C-readline'\n\nHowever, the symbol within the C-readline.so file is named luaopen_readline, so\nby default --compile-binary will make it so you can require it as \"readline\",\nwhich collides with the name of the readline.lua file and doesn't match the\nrequire call within readline.lua. In order to include the module within your\ncompiled binary and have it get picked up by readline.lua correctly, you can\nspecify the name used to refer to it in a require call by compiling it like\nso (this is assuming that program.fnl requires the Lua bindings):\n\n $ %s --compile-binary program.fnl program \\\n /usr/lib/x86_64-linux-gnu/liblua5.3.a /usr/include/lua5.3 \\\n --native-module C-readline.so \\\n --rename-native-module readline C-readline\n"):format(arg[0], arg[0], arg[0])
+ return {compile = compile, help = help}
+end
+local fennel
+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")
+ local view = require("fennel.view")
+ local unpack = (table.unpack or _G.unpack)
+ local function default_read_chunk(parser_state)
+ local function _616_()
+ if (0 < parser_state["stack-size"]) then
+ return ".."
+ else
+ return ">> "
+ end
+ end
+ io.write(_616_())
+ 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)
+ local function _618_()
+ local _617_ = errtype
+ if (_617_ == "Lua Compile") then
+ return ("Bad code generated - likely a bug with the compiler:\n" .. "--- Generated Lua Start ---\n" .. lua_source .. "--- Generated Lua End ---\n")
+ elseif (_617_ == "Runtime") then
+ return (compiler.traceback(tostring(err), 4) .. "\n")
+ elseif true then
+ local _ = _617_
+ return ("%s error: %s\n"):format(errtype, tostring(err))
+ else
+ return nil
+ end
+ end
+ return io.write(_618_())
+ 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)
+ 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)
+ else
+ end
+ return table.concat(spliced_source, "\n")
+ end
+ local function completer(env, scope, text)
+ local max_items = 2000
+ local seen = {}
+ local matches = {}
+ local input_fragment = text:gsub(".*[%s)(]+", "")
+ local stop_looking_3f = false
+ local function add_partials(input, tbl, prefix)
+ local scope_first_3f = ((tbl == env) or (tbl == env.___replLocals___))
+ local tbl_14_auto = matches
+ local i_15_auto = #tbl_14_auto
+ local function _621_()
+ if scope_first_3f then
+ return scope.manglings
+ else
+ return tbl
+ end
+ end
+ for k, is_mangled in utils.allpairs(_621_()) do
+ if (max_items <= #matches) then break end
+ local val_16_auto
+ do
+ local lookup_k
+ if scope_first_3f then
+ lookup_k = is_mangled
+ else
+ lookup_k = k
+ end
+ if ((type(k) == "string") and (input == k:sub(0, #input)) and not seen[k] and ((":" ~= prefix:sub(-1)) or ("function" == type(tbl[lookup_k])))) then
+ seen[k] = true
+ val_16_auto = (prefix .. k)
+ else
+ val_16_auto = nil
+ end
+ end
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ return tbl_14_auto
+ 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 = (scope.manglings[head] or head)
+ if (type(tbl[raw_head]) == "table") then
+ stop_looking_3f = true
+ if method_3f then
+ return add_partials(tail, tbl[raw_head], (prefix .. head .. ":"))
+ else
+ return add_matches(tail, tbl[raw_head], (prefix .. head))
+ end
+ else
+ return nil
+ 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
+ if stop_looking_3f then break end
+ add_matches(input_fragment, source)
+ end
+ return matches
+ end
+ local commands = {}
+ local function command_3f(input)
+ return input:match("^%s*,")
+ end
+ local function command_docs()
+ local _630_
+ do
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for name, f in pairs(commands) do
+ local val_16_auto = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented"))
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ _630_ = tbl_14_auto
+ end
+ return table.concat(_630_, "\n")
+ end
+ commands.help = function(_, _0, on_values)
+ 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")})
+ end
+ do end (compiler.metadata):set(commands.help, "fnl/docstring", "Show this message.")
+ local function reload(module_name, env, on_values, on_error)
+ local _632_, _633_ = pcall(specials["load-code"]("return require(...)", env), module_name)
+ if ((_632_ == true) and (nil ~= _633_)) then
+ local old = _633_
+ local _
+ package.loaded[module_name] = nil
+ _ = nil
+ local ok, new = pcall(require, module_name)
+ local new0
+ if not ok then
+ on_values({new})
+ new0 = old
+ else
+ new0 = new
+ end
+ specials["macro-loaded"][module_name] = nil
+ 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
+ if (nil == (new0)[k]) then
+ old[k] = nil
+ else
+ end
+ end
+ package.loaded[module_name] = old
+ else
+ end
+ return on_values({"ok"})
+ elseif ((_632_ == false) and (nil ~= _633_)) then
+ local msg = _633_
+ if (specials["macro-loaded"])[module_name] then
+ specials["macro-loaded"][module_name] = nil
+ return nil
+ else
+ local function _638_()
+ local _637_ = msg:gsub("\n.*", "")
+ return _637_
+ end
+ return on_error("Runtime", _638_())
+ end
+ else
+ return nil
+ end
+ end
+ local function run_command(read, on_error, f)
+ local _641_, _642_, _643_ = pcall(read)
+ if ((_641_ == true) and (_642_ == true) and (nil ~= _643_)) then
+ local val = _643_
+ return f(val)
+ elseif (_641_ == false) then
+ return on_error("Parse", "Couldn't parse input.")
+ else
+ return nil
+ end
+ end
+ commands.reload = function(env, read, on_values, on_error)
+ local function _645_(_241)
+ return reload(tostring(_241), env, on_values, on_error)
+ end
+ return run_command(read, on_error, _645_)
+ end
+ do end (compiler.metadata):set(commands.reload, "fnl/docstring", "Reload the specified module.")
+ commands.reset = function(env, _, on_values)
+ env.___replLocals___ = {}
+ return on_values({"ok"})
+ end
+ do end (compiler.metadata):set(commands.reset, "fnl/docstring", "Erase all repl-local scope.")
+ commands.complete = function(env, read, on_values, on_error, scope, chars)
+ local function _646_()
+ return on_values(completer(env, scope, string.char(unpack(chars)):gsub(",complete +", ""):sub(1, -2)))
+ end
+ return run_command(read, on_error, _646_)
+ end
+ do end (compiler.metadata):set(commands.complete, "fnl/docstring", "Print all possible completions for a given input symbol.")
+ local function apropos_2a(pattern, tbl, prefix, seen, names)
+ for name, subtbl in pairs(tbl) do
+ if (("string" == type(name)) and (package ~= subtbl)) then
+ local _647_ = type(subtbl)
+ if (_647_ == "function") then
+ if ((prefix .. name)):match(pattern) then
+ table.insert(names, (prefix .. name))
+ else
+ end
+ elseif (_647_ == "table") then
+ if not seen[subtbl] then
+ local _650_
+ do
+ local _649_ = seen
+ _649_[subtbl] = true
+ _650_ = _649_
+ end
+ apropos_2a(pattern, subtbl, (prefix .. name:gsub("%.", "/") .. "."), _650_, names)
+ else
+ end
+ else
+ end
+ else
+ end
+ end
+ return names
+ end
+ local function apropos(pattern)
+ local names = apropos_2a(pattern, package.loaded, "", {}, {})
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for _, name in ipairs(names) do
+ local val_16_auto = name:gsub("^_G%.", "")
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ return tbl_14_auto
+ end
+ commands.apropos = function(_env, read, on_values, on_error, _scope)
+ local function _655_(_241)
+ return on_values(apropos(tostring(_241)))
+ end
+ return run_command(read, on_error, _655_)
+ 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_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for p in path:gmatch("[^%.]+") do
+ local val_16_auto = p
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ paths = tbl_14_auto
+ end
+ local tgt = package.loaded
+ for _, path0 in ipairs(paths) do
+ if (nil == tgt) then break end
+ local _658_
+ do
+ local _657_ = path0:gsub("%/", ".")
+ _658_ = _657_
+ end
+ tgt = tgt[_658_]
+ end
+ return tgt
+ end
+ local function apropos_doc(pattern)
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for _, path in ipairs(apropos(".*")) do
+ local val_16_auto
+ do
+ local tgt = apropos_follow_path(path)
+ if ("function" == type(tgt)) then
+ local _659_ = (compiler.metadata):get(tgt, "fnl/docstring")
+ if (nil ~= _659_) then
+ local docstr = _659_
+ val_16_auto = (docstr:match(pattern) and path)
+ else
+ val_16_auto = nil
+ end
+ else
+ val_16_auto = nil
+ end
+ end
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ return tbl_14_auto
+ end
+ commands["apropos-doc"] = function(_env, read, on_values, on_error, _scope)
+ local function _663_(_241)
+ return on_values(apropos_doc(tostring(_241)))
+ end
+ return run_command(read, on_error, _663_)
+ 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(on_values, 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
+ on_values(specials.doc(tgt, path))
+ on_values()
+ else
+ end
+ end
+ return nil
+ end
+ commands["apropos-show-docs"] = function(_env, read, on_values, on_error)
+ local function _665_(_241)
+ return apropos_show_docs(on_values, tostring(_241))
+ end
+ return run_command(read, on_error, _665_)
+ end
+ do end (compiler.metadata):set(commands["apropos-show-docs"], "fnl/docstring", "Print all documentations matching a pattern in function name")
+ local function resolve(identifier, _666_, scope)
+ local _arg_667_ = _666_
+ local ___replLocals___ = _arg_667_["___replLocals___"]
+ local env = _arg_667_
+ local e
+ local function _668_(_241, _242)
+ return (___replLocals___[_242] or env[_242])
+ end
+ e = setmetatable({}, {__index = _668_})
+ local _669_, _670_ = pcall(compiler["compile-string"], tostring(identifier), {scope = scope})
+ if ((_669_ == true) and (nil ~= _670_)) then
+ local code = _670_
+ local _671_ = specials["load-code"](code, e)()
+ local function _672_()
+ local x = _671_
+ return (type(x) == "function")
+ end
+ if ((nil ~= _671_) and _672_()) then
+ local x = _671_
+ return x
+ else
+ return nil
+ end
+ else
+ return nil
+ end
+ end
+ commands.find = function(env, read, on_values, on_error, scope)
+ local function _675_(_241)
+ local _676_
+ do
+ local _677_ = utils["sym?"](_241)
+ if (nil ~= _677_) then
+ local _678_ = resolve(_677_, env, scope)
+ if (nil ~= _678_) then
+ _676_ = debug.getinfo(_678_)
+ else
+ _676_ = _678_
+ end
+ else
+ _676_ = _677_
+ end
+ end
+ if ((_G.type(_676_) == "table") and ((_676_).what == "Lua") and (nil ~= (_676_).linedefined) and (nil ~= (_676_).source) and (nil ~= (_676_).short_src)) then
+ local line = (_676_).linedefined
+ local source = (_676_).source
+ local src = (_676_).short_src
+ local fnlsrc
+ do
+ local t_681_ = compiler.sourcemap
+ if (nil ~= t_681_) then
+ t_681_ = (t_681_)[source]
+ else
+ end
+ if (nil ~= t_681_) then
+ t_681_ = (t_681_)[line]
+ else
+ end
+ if (nil ~= t_681_) then
+ t_681_ = (t_681_)[2]
+ else
+ end
+ fnlsrc = t_681_
+ end
+ return on_values({string.format("%s:%s", src, (fnlsrc or line))})
+ elseif (_676_ == nil) then
+ return on_error("Repl", "Unknown value")
+ elseif true then
+ local _ = _676_
+ return on_error("Repl", "No source info")
+ else
+ return nil
+ end
+ end
+ return run_command(read, on_error, _675_)
+ end
+ do end (compiler.metadata):set(commands.find, "fnl/docstring", "Print the filename and line number for a given function")
+ commands.doc = function(env, read, on_values, on_error, scope)
+ local function _686_(_241)
+ local name = tostring(_241)
+ local path = (utils["multi-sym?"](name) or {name})
+ local is_ok, target = nil, nil
+ local function _687_()
+ return (utils["get-in"](scope.specials, path) or utils["get-in"](scope.macros, path) or resolve(name, env, scope))
+ end
+ is_ok, target = pcall(_687_)
+ if is_ok then
+ return on_values({specials.doc(target, name)})
+ else
+ return on_error("Repl", "Could not resolve value for docstring lookup")
+ end
+ end
+ return run_command(read, on_error, _686_)
+ end
+ do end (compiler.metadata):set(commands.doc, "fnl/docstring", "Print the docstring and arglist for a function, macro, or special form.")
+ local function load_plugin_commands(plugins)
+ for _, plugin in ipairs((plugins or {})) do
+ for name, f in pairs(plugin) do
+ local _689_ = name:match("^repl%-command%-(.*)")
+ if (nil ~= _689_) then
+ local cmd_name = _689_
+ commands[cmd_name] = (commands[cmd_name] or f)
+ else
+ end
+ end
+ end
+ return nil
+ end
+ local function run_command_loop(input, read, loop, env, on_values, on_error, scope, chars)
+ local command_name = input:match(",([^%s/]+)")
+ do
+ local _691_ = commands[command_name]
+ if (nil ~= _691_) then
+ local command = _691_
+ command(env, read, on_values, on_error, scope, chars)
+ elseif true then
+ local _ = _691_
+ if ("exit" ~= command_name) then
+ on_values({"Unknown command", command_name})
+ else
+ end
+ else
+ end
+ end
+ if ("exit" ~= command_name) then
+ return loop()
+ else
+ return nil
+ end
+ end
+ local function try_readline_21(opts, ok, readline)
+ if ok then
+ if readline.set_readline_name then
+ readline.set_readline_name("fennel")
+ else
+ end
+ do
+ local rl_opts
+ do
+ local tbl_11_auto = {keeplines = 1000, histfile = ""}
+ for k, v in pairs(readline.set_options({})) do
+ local _696_, _697_ = k, v
+ if ((nil ~= _696_) and (nil ~= _697_)) then
+ local k_12_auto = _696_
+ local v_13_auto = _697_
+ tbl_11_auto[k_12_auto] = v_13_auto
+ else
+ end
+ end
+ rl_opts = tbl_11_auto
+ end
+ readline.set_options(rl_opts)
+ end
+ opts.readChunk = function(parser_state)
+ local prompt
+ if (0 < parser_state["stack-size"]) then
+ prompt = ".. "
+ else
+ prompt = ">> "
+ end
+ local str = readline.readline(prompt)
+ if str then
+ return (str .. "\n")
+ else
+ return nil
+ end
+ end
+ local completer0 = nil
+ opts.registerCompleter = function(repl_completer)
+ completer0 = repl_completer
+ return nil
+ end
+ local function repl_completer(text, from, to)
+ if completer0 then
+ readline.set_completion_append_character("")
+ return completer0(text:sub(from, to))
+ else
+ return {}
+ end
+ end
+ readline.set_complete_function(repl_completer)
+ return readline
+ else
+ return nil
+ end
+ end
+ local function should_use_readline_3f(opts)
+ return (("dumb" ~= os.getenv("TERM")) and not opts.readChunk and not opts.registerCompleter)
+ end
+ local function repl(_3foptions)
+ local old_root_options = utils.root.options
+ local opts = ((_3foptions and utils.copy(_3foptions)) or {})
+ local readline = (should_use_readline_3f(opts) and try_readline_21(opts, pcall(require, "readline")))
+ local env = specials["wrap-env"]((opts.env or rawget(_G, "_ENV") or _G))
+ local save_locals_3f = ((opts.saveLocals ~= false) and env.debug and env.debug.getlocal)
+ 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 view)
+ local byte_stream, clear_stream = parser.granulate(read_chunk)
+ local chars = {}
+ local read, reset = nil, nil
+ local function _703_(parser_state)
+ local c = byte_stream(parser_state)
+ table.insert(chars, c)
+ return c
+ end
+ read, reset = parser.parser(_703_)
+ opts.env, opts.scope = env, compiler["make-scope"]()
+ opts.useMetadata = (opts.useMetadata ~= false)
+ if (opts.allowedGlobals == nil) then
+ opts.allowedGlobals = specials["current-global-names"](env)
+ else
+ end
+ if opts.registerCompleter then
+ local function _707_()
+ local _705_ = env
+ local _706_ = opts.scope
+ local function _708_(...)
+ return completer(_705_, _706_, ...)
+ end
+ return _708_
+ end
+ opts.registerCompleter(_707_())
+ else
+ end
+ load_plugin_commands(opts.plugins)
+ if save_locals_3f then
+ local function newindex(t, k, v)
+ if opts.scope.unmanglings[k] then
+ return rawset(t, k, v)
+ else
+ return nil
+ end
+ end
+ env.___replLocals___ = setmetatable({}, {__newindex = newindex})
+ else
+ end
+ 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
+ local function loop()
+ for k in pairs(chars) do
+ chars[k] = nil
+ end
+ reset()
+ local ok, not_eof_3f, x = pcall(read)
+ local src_string = string.char(unpack(chars))
+ if not ok then
+ on_error("Parse", not_eof_3f)
+ clear_stream()
+ return loop()
+ elseif command_3f(src_string) then
+ return run_command_loop(src_string, read, loop, env, on_values, on_error, opts.scope, chars)
+ else
+ if not_eof_3f then
+ do
+ local _712_, _713_ = nil, nil
+ local function _715_()
+ local _714_ = opts
+ _714_["source"] = src_string
+ return _714_
+ end
+ _712_, _713_ = pcall(compiler.compile, x, _715_())
+ if ((_712_ == false) and (nil ~= _713_)) then
+ local msg = _713_
+ clear_stream()
+ on_error("Compile", msg)
+ elseif ((_712_ == true) and (nil ~= _713_)) then
+ local src = _713_
+ local src0
+ if save_locals_3f then
+ src0 = splice_save_locals(env, src, opts.scope)
+ else
+ src0 = src
+ end
+ local _717_, _718_ = pcall(specials["load-code"], src0, env)
+ if ((_717_ == false) and (nil ~= _718_)) then
+ local msg = _718_
+ clear_stream()
+ on_error("Lua Compile", msg, src0)
+ elseif (true and (nil ~= _718_)) then
+ local _ = _717_
+ local chunk = _718_
+ local function _719_()
+ return print_values(chunk())
+ end
+ local function _720_()
+ local function _721_(...)
+ return on_error("Runtime", ...)
+ end
+ return _721_
+ end
+ xpcall(_719_, _720_())
+ else
+ end
+ else
+ end
+ end
+ utils.root.options = old_root_options
+ return loop()
+ else
+ return nil
+ end
+ end
+ end
+ loop()
+ if readline then
+ return readline.save_history()
+ else
+ return nil
+ end
+ end
+ return repl
+end
+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 _411_(_, key)
+ if utils["string?"](key) then
+ return env[compiler["global-unmangling"](key)]
+ else
+ return env[key]
+ end
+ end
+ local function _413_(_, key, value)
+ if utils["string?"](key) then
+ env[compiler["global-unmangling"](key)] = value
+ return nil
+ else
+ env[key] = value
+ return nil
+ end
+ end
+ local function _415_()
+ local function putenv(k, v)
+ local _416_
+ if utils["string?"](k) then
+ _416_ = compiler["global-unmangling"](k)
+ else
+ _416_ = k
+ end
+ return _416_, v
+ end
+ return next, utils.kvmap(env, putenv), nil
+ end
+ return setmetatable({}, {__index = _411_, __newindex = _413_, __pairs = _415_})
+ end
+ local function current_global_names(_3fenv)
+ local mt
+ do
+ local _418_ = getmetatable(_3fenv)
+ if ((_G.type(_418_) == "table") and (nil ~= (_418_).__pairs)) then
+ local mtpairs = (_418_).__pairs
+ local tbl_11_auto = {}
+ for k, v in mtpairs(_3fenv) do
+ local _419_, _420_ = k, v
+ if ((nil ~= _419_) and (nil ~= _420_)) then
+ local k_12_auto = _419_
+ local v_13_auto = _420_
+ tbl_11_auto[k_12_auto] = v_13_auto
+ else
+ end
+ end
+ mt = tbl_11_auto
+ elseif (_418_ == nil) then
+ mt = (_3fenv or _G)
+ else
+ mt = nil
+ end
+ end
+ return (mt and utils.kvmap(mt, compiler["global-unmangling"]))
+ end
+ local function load_code(code, _3fenv, _3ffilename)
+ local env = (_3fenv or rawget(_G, "_ENV") or _G)
+ local _423_, _424_ = rawget(_G, "setfenv"), rawget(_G, "loadstring")
+ if ((nil ~= _423_) and (nil ~= _424_)) then
+ local setfenv = _423_
+ local loadstring = _424_
+ local f = assert(loadstring(code, _3ffilename))
+ local _425_ = f
+ setfenv(_425_, env)
+ return _425_
+ elseif true then
+ local _ = _423_
+ return assert(load(code, _3ffilename, "t", env))
+ else
+ return nil
+ end
+ end
+ 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 _427_
+ if (0 < #arglist) then
+ _427_ = " "
+ else
+ _427_ = ""
+ end
+ return string.format("(%s%s%s)\n %s", name, _427_, arglist, docstring)
+ else
+ return string.format("%s\n %s", name, docstring)
+ end
+ end
+ end
+ 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
+ end
+ local function compile_do(ast, scope, parent, _3fstart)
+ local start = (_3fstart or 2)
+ local len = #ast
+ local sub_scope = compiler["make-scope"](scope)
+ for i = start, len do
+ compiler.compile1(ast[i], sub_scope, parent, {nval = 0})
+ end
+ return nil
+ end
+ SPECIALS["do"] = function(ast, scope, parent, opts, _3fstart, _3fchunk, _3fsub_scope, _3fpre_syms)
+ local start = (_3fstart or 2)
+ local sub_scope = (_3fsub_scope or compiler["make-scope"](scope))
+ local chunk = (_3fchunk or {})
+ local len = #ast
+ local retexprs = {returned = true}
+ local function compile_body(outer_target, outer_tail, outer_retexprs)
+ if (len < start) then
+ compiler.compile1(nil, sub_scope, chunk, {tail = outer_tail, target = outer_target})
+ else
+ for i = start, 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_scope, chunk, subopts)
+ if (i ~= len) then
+ compiler["keep-side-effects"](subexprs, parent, nil, ast[i])
+ else
+ end
+ end
+ end
+ compiler.emit(parent, chunk, ast)
+ compiler.emit(parent, "end", ast)
+ utils.hook("do", ast, sub_scope)
+ return (outer_retexprs or retexprs)
+ end
+ 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 = ((_3fpre_syms and (_3fpre_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)
+ else
+ 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)
+ return compile_body(nil, true, utils.expr((fname .. "(" .. fargs .. ")"), "statement"))
+ end
+ end
+ 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])
+ end
+ else
+ end
+ 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)
+ if utils["list?"](x) then
+ local _436_
+ do
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for _, v in ipairs(x) do
+ local val_16_auto = deep_tostring(v)
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ _436_ = tbl_14_auto
+ end
+ return ("(" .. table.concat(_436_, " ") .. ")")
+ elseif utils["sequence?"](x) then
+ local _438_
+ do
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for _, v in ipairs(x) do
+ local val_16_auto = deep_tostring(v)
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ _438_ = tbl_14_auto
+ end
+ return ("[" .. table.concat(_438_, " ") .. "]")
+ elseif utils["table?"](x) then
+ local _440_
+ do
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for k, v in pairs(x) do
+ local val_16_auto = (deep_tostring(k, true) .. " " .. deep_tostring(v))
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ _440_ = tbl_14_auto
+ end
+ return ("{" .. table.concat(_440_, " ") .. "}")
+ elseif (key_3f and utils["string?"](x) and x:find("^[-%w?\\^_!$%&*+./@:|<=>]+$")) then
+ return (":" .. x)
+ elseif utils["string?"](x) then
+ return string.format("%q", x):gsub("\\\"", "\\\\\""):gsub("\"", "\\\"")
+ else
+ return tostring(x)
+ end
+ end
+ local function set_fn_metadata(arg_list, docstring, parent, fn_name)
+ if utils.root.options.useMetadata then
+ local args
+ local function _443_(_241)
+ return ("\"%s\""):format(deep_tostring(_241))
+ end
+ args = utils.map(arg_list, _443_)
+ 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("\"", "\\\"") .. "\""))
+ else
+ end
+ 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, ", ")))
+ else
+ return nil
+ end
+ end
+ local function get_fn_name(ast, scope, fn_name, multi)
+ if (fn_name and (fn_name[1] ~= "nil")) then
+ local _446_
+ if not multi then
+ _446_ = compiler["declare-local"](fn_name, {}, scope, ast)
+ else
+ _446_ = (compiler["symbol-to-expression"](fn_name, scope))[1]
+ end
+ return _446_, not multi, 3
+ else
+ return nil, true, 2
+ end
+ end
+ local function compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, local_3f, arg_name_list, f_metadata)
+ 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 _449_
+ if local_3f then
+ _449_ = "local function %s(%s)"
+ else
+ _449_ = "%s = function(%s)"
+ end
+ compiler.emit(parent, string.format(_449_, fn_name, table.concat(arg_name_list, ", ")), ast)
+ compiler.emit(parent, f_chunk, ast)
+ compiler.emit(parent, "end", ast)
+ set_fn_metadata(f_metadata["fnl/arglist"], f_metadata["fnl/docstring"], parent, fn_name)
+ utils.hook("fn", ast, f_scope)
+ return utils.expr(fn_name, "sym")
+ end
+ local function compile_anonymous_fn(ast, f_scope, f_chunk, parent, index, arg_name_list, f_metadata, scope)
+ local fn_name = compiler.gensym(scope)
+ return compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, true, arg_name_list, f_metadata)
+ end
+ local function get_function_metadata(ast, arg_list, index)
+ local f_metadata = {["fnl/arglist"] = arg_list}
+ local index_2a = (index + 1)
+ local expr = ast[index_2a]
+ if (utils["string?"](expr) and (index_2a < #ast)) then
+ local _452_
+ do
+ local _451_ = f_metadata
+ _451_["fnl/docstring"] = expr
+ _452_ = _451_
+ end
+ return _452_, index_2a
+ elseif (utils["table?"](expr) and (index_2a < #ast)) then
+ local _453_
+ do
+ local tbl_11_auto = f_metadata
+ for k, v in pairs(expr) do
+ local _454_, _455_ = k, v
+ if ((nil ~= _454_) and (nil ~= _455_)) then
+ local k_12_auto = _454_
+ local v_13_auto = _455_
+ tbl_11_auto[k_12_auto] = v_13_auto
+ else
+ end
+ end
+ _453_ = tbl_11_auto
+ end
+ return _453_, index_2a
+ else
+ return f_metadata, index
+ end
+ end
+ SPECIALS.fn = function(ast, scope, parent)
+ local f_scope
+ do
+ local _458_ = compiler["make-scope"](scope)
+ do end (_458_)["vararg"] = false
+ f_scope = _458_
+ 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
+ else
+ return compiler.assert(false, ("expected symbol for function parameter: %s"):format(tostring(arg)), ast[index])
+ end
+ end
+ local arg_name_list = utils.map(arg_list, get_arg_name)
+ local f_metadata, index0 = get_function_metadata(ast, arg_list, index)
+ if fn_name then
+ return compile_named_fn(ast, f_scope, f_chunk, parent, index0, fn_name, local_3f, arg_name_list, f_metadata)
+ else
+ return compile_anonymous_fn(ast, f_scope, f_chunk, parent, index0, arg_name_list, f_metadata, scope)
+ end
+ end
+ doc_special("fn", {"name?", "args", "docstring?", "..."}, "Function syntax. May optionally include a name and docstring or a metadata table.\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 _462_
+ do
+ local _461_ = utils["sym?"](ast[2])
+ if (nil ~= _461_) then
+ _462_ = tostring(_461_)
+ else
+ _462_ = _461_
+ end
+ end
+ if ("nil" ~= _462_) then
+ table.insert(parent, {ast = ast, leaf = tostring(ast[2])})
+ else
+ end
+ local _466_
+ do
+ local _465_ = utils["sym?"](ast[3])
+ if (nil ~= _465_) then
+ _466_ = tostring(_465_)
+ else
+ _466_ = _465_
+ end
+ end
+ if ("nil" ~= _466_) then
+ return tostring(ast[3])
+ else
+ return nil
+ end
+ end
+ local function dot(ast, scope, parent)
+ compiler.assert((1 < #ast), "expected table argument", ast)
+ local len = #ast
+ local _let_469_ = compiler.compile1(ast[2], scope, parent, {nval = 1})
+ local lhs = _let_469_[1]
+ if (len == 2) then
+ return tostring(lhs)
+ else
+ local indices = {}
+ for i = 3, len do
+ local index = ast[i]
+ if (utils["string?"](index) and utils["valid-lua-identifier?"](index)) then
+ table.insert(indices, ("." .. index))
+ else
+ local _let_470_ = compiler.compile1(index, scope, parent, {nval = 1})
+ local index0 = _let_470_[1]
+ table.insert(indices, ("[" .. tostring(index0) .. "]"))
+ end
+ end
+ if (tostring(lhs):find("[{\"0-9]") or ("nil" == tostring(lhs))) then
+ return ("(" .. tostring(lhs) .. ")" .. table.concat(indices))
+ else
+ return (tostring(lhs) .. table.concat(indices))
+ end
+ end
+ end
+ 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
+ end
+ 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
+ end
+ 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
+ end
+ 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
+ end
+ 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 _474_
+ do
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for k in pairs(t) do
+ local val_16_auto
+ if ("number" ~= type(k)) then
+ val_16_auto = k
+ else
+ val_16_auto = nil
+ end
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ _474_ = tbl_14_auto
+ end
+ return (_474_)[1]
+ end
+ 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((3 <= #ast), "expected body expression", ast[1])
+ for _ = 1, (opts.nval or 0) do
+ table.insert(pre_syms, compiler.gensym(scope))
+ end
+ local sub_scope = compiler["make-scope"](scope)
+ 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"})
+ end
+ return SPECIALS["do"](ast, scope, parent, opts, 3, sub_chunk, sub_scope, pre_syms)
+ end
+ 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]))
+ else
+ return (parent or "")
+ end
+ end
+ local function disambiguate_3f(rootstr, parent)
+ local function _479_()
+ local _478_ = get_prev_line(parent)
+ if (nil ~= _478_) then
+ local prev_line = _478_
+ return prev_line:match("%)$")
+ else
+ return nil
+ end
+ end
+ return (rootstr:match("^{") or _479_())
+ end
+ SPECIALS.tset = function(ast, scope, parent)
+ compiler.assert((3 < #ast), "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_481_ = compiler.compile1(ast[i], scope, parent, {nval = 1})
+ local key = _let_481_[1]
+ table.insert(keys, tostring(key))
+ end
+ 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"
+ end
+ return compiler.emit(parent, fmtstr:format(rootstr, table.concat(keys, "]["), tostring(value)), ast)
+ end
+ 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")
+ end
+ return "target", opts.tail, table.concat(accum, ", "), target_exprs
+ else
+ return "none", opts.tail, opts.target
+ end
+ end
+ local function if_2a(ast, scope, parent, opts)
+ compiler.assert((2 < #ast), "expected condition and body", ast)
+ 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}
+ end
+ if (1 == (#ast % 2)) then
+ table.insert(ast, utils.sym("nil"))
+ else
+ end
+ 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)
+ end
+ local else_branch = compile_body(#ast)
+ local s = compiler.gensym(scope)
+ local buffer = {}
+ local last_buffer = buffer
+ for i = 1, #branches do
+ local branch = branches[i]
+ local fstr
+ if not branch.nested then
+ fstr = "if %s then"
+ else
+ fstr = "elseif %s then"
+ end
+ local cond = tostring(branch.cond)
+ local cond_line = fstr:format(cond)
+ 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
+ compiler.emit(last_buffer, "else", ast)
+ compiler.emit(last_buffer, else_branch.chunk, ast)
+ compiler.emit(last_buffer, "end", ast)
+ elseif not (branches[(i + 1)]).nested then
+ 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
+ else
+ 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
+ for i = 1, #buffer do
+ compiler.emit(parent, buffer[i], ast)
+ end
+ return {returned = true}
+ else
+ compiler.emit(parent, ("local %s"):format(inner_target), ast)
+ for i = 1, #buffer do
+ 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.")
+ local function remove_until_condition(bindings)
+ local last_item = bindings[(#bindings - 1)]
+ if ((utils["sym?"](last_item) and (tostring(last_item) == "&until")) or ("until" == last_item)) then
+ table.remove(bindings, (#bindings - 1))
+ return table.remove(bindings)
+ else
+ return nil
+ end
+ end
+ local function compile_until(condition, scope, chunk)
+ if condition then
+ local _let_490_ = compiler.compile1(condition, scope, chunk, {nval = 1})
+ local condition_lua = _let_490_[1]
+ return compiler.emit(chunk, ("if %s then break end"):format(tostring(condition_lua)), utils.expr(condition, "expression"))
+ else
+ return nil
+ end
+ end
+ SPECIALS.each = function(ast, scope, parent)
+ compiler.assert((3 <= #ast), "expected body expression", ast[1])
+ local binding = compiler.assert(utils["table?"](ast[2]), "expected binding table", ast)
+ local _ = compiler.assert((2 <= #binding), "expected binding and iterator", binding)
+ local until_condition = remove_until_condition(binding)
+ local iter = table.remove(binding, #binding)
+ local destructures = {}
+ local new_manglings = {}
+ local sub_scope = compiler["make-scope"](scope)
+ local function destructure_binding(v)
+ compiler.assert(not utils["string?"](v), ("unexpected iterator clause " .. tostring(v)), binding)
+ if utils["sym?"](v) then
+ return compiler["declare-local"](v, {}, sub_scope, ast, new_manglings)
+ else
+ local raw = utils.sym(compiler.gensym(sub_scope))
+ do end (destructures)[raw] = v
+ return compiler["declare-local"](raw, {}, sub_scope, ast)
+ end
+ end
+ local bind_vars = utils.map(binding, destructure_binding)
+ local vals = compiler.compile1(iter, 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
+ compiler.destructure(args, raw, ast, sub_scope, chunk, {declaration = true, nomulti = true, symtype = "each"})
+ end
+ compiler["apply-manglings"](sub_scope, new_manglings, ast)
+ compile_until(until_condition, sub_scope, chunk)
+ compile_do(ast, sub_scope, chunk, 3)
+ compiler.emit(parent, chunk, ast)
+ return compiler.emit(parent, "end", ast)
+ end
+ 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)
+ local function while_2a(ast, scope, parent)
+ local len1 = #parent
+ local condition = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1]
+ local len2 = #parent
+ local sub_chunk = {}
+ if (len1 ~= len2) then
+ for i = (len1 + 1), len2 do
+ table.insert(sub_chunk, parent[i])
+ do end (parent)[i] = nil
+ 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
+ doc_special("while", {"condition", "..."}, "The classic while loop. Evaluates body until a condition is non-truthy.", true)
+ local function for_2a(ast, scope, parent)
+ local ranges = compiler.assert(utils["table?"](ast[2]), "expected binding table", ast)
+ local until_condition = remove_until_condition(ast[2])
+ local binding_sym = table.remove(ast[2], 1)
+ local sub_scope = compiler["make-scope"](scope)
+ local range_args = {}
+ local chunk = {}
+ compiler.assert(utils["sym?"](binding_sym), ("unable to bind %s %s"):format(type(binding_sym), tostring(binding_sym)), ast[2])
+ compiler.assert((3 <= #ast), "expected body expression", ast[1])
+ compiler.assert((#ranges <= 3), "unexpected arguments", ranges[4])
+ for i = 1, math.min(#ranges, 3) do
+ range_args[i] = tostring((compiler.compile1(ranges[i], scope, parent, {nval = 1}))[1])
+ end
+ compiler.emit(parent, ("for %s = %s do"):format(compiler["declare-local"](binding_sym, {}, sub_scope, ast), table.concat(range_args, ", ")), ast)
+ compile_until(until_condition, sub_scope, chunk)
+ compile_do(ast, sub_scope, chunk, 3)
+ compiler.emit(parent, chunk, ast)
+ return compiler.emit(parent, "end", ast)
+ end
+ SPECIALS["for"] = for_2a
+ doc_special("for", {"[index start stop step?]", "..."}, "Numeric loop construct.\nEvaluates body once for each value between start and stop (inclusive).", true)
+ local function native_method_call(ast, _scope, _parent, target, args)
+ local _let_494_ = ast
+ local _ = _let_494_[1]
+ local _0 = _let_494_[2]
+ local method_string = _let_494_[3]
+ local call_string
+ if ((target.type == "literal") or (target.type == "varg") or (target.type == "expression")) then
+ 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)
+ local method_string = tostring((compiler.compile1(ast[3], scope, parent, {nval = 1}))[1])
+ local args0 = {tostring(target), unpack(args)}
+ return utils.expr(string.format("%s[%s](%s)", tostring(target), method_string, table.concat(args0, ", ")), "statement")
+ end
+ local function double_eval_protected_method_call(ast, scope, parent, target, args)
+ local method_string = tostring((compiler.compile1(ast[3], scope, parent, {nval = 1}))[1])
+ local call = "(function(tgt, m, ...) return tgt[m](tgt, ...) end)(%s, %s)"
+ table.insert(args, 1, method_string)
+ 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)
+ local _let_496_ = compiler.compile1(ast[2], scope, parent, {nval = 1})
+ local target = _let_496_[1]
+ local args = {}
+ for i = 4, #ast do
+ local subexprs
+ local _497_
+ if (i ~= #ast) then
+ _497_ = 1
+ else
+ _497_ = nil
+ end
+ subexprs = compiler.compile1(ast[i], scope, parent, {nval = _497_})
+ utils.map(subexprs, tostring, args)
+ end
+ if (utils["string?"](ast[3]) 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 = {}
+ for i = 2, #ast do
+ table.insert(els, view(ast[i], {["one-line?"] = true}))
+ end
+ return compiler.emit(parent, ("--[[ " .. table.concat(els, " ") .. " ]]"), ast)
+ end
+ doc_special("comment", {"..."}, "Comment which will be emitted in Lua output.", true)
+ local function hashfn_max_used(f_scope, i, max)
+ local max0
+ 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
+ SPECIALS.hashfn = function(ast, scope, parent)
+ compiler.assert((#ast == 2), "expected one argument", ast)
+ local f_scope
+ do
+ local _502_ = compiler["make-scope"](scope)
+ do end (_502_)["vararg"] = false
+ _502_["hashfn"] = true
+ f_scope = _502_
+ end
+ local f_chunk = {}
+ local name = compiler.gensym(scope)
+ local symbol = utils.sym(name)
+ local args = {}
+ compiler["declare-local"](symbol, {}, scope, ast)
+ for i = 1, 9 do
+ args[i] = compiler["declare-local"](utils.sym(("$" .. i)), {}, f_scope, ast)
+ end
+ local function walker(idx, node, parent_node)
+ if (utils["sym?"](node) and (tostring(node) == "$...")) then
+ parent_node[idx] = utils.varg()
+ f_scope.vararg = true
+ return nil
+ else
+ return (utils["list?"](node) or utils["table?"](node))
+ end
+ end
+ utils["walk-tree"](ast[2], walker)
+ compiler.compile1(ast[2], f_scope, f_chunk, {tail = true})
+ local max_used = hashfn_max_used(f_scope, 1, 0)
+ if f_scope.vararg then
+ compiler.assert((max_used == 0), "$ and $... in hashfn are mutually exclusive", ast)
+ else
+ end
+ local arg_str
+ if f_scope.vararg then
+ arg_str = tostring(utils.varg())
+ else
+ arg_str = table.concat(args, ", ", 1, max_used)
+ end
+ compiler.emit(parent, string.format("local function %s(%s)", name, arg_str), ast)
+ 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.")
+ local function maybe_short_circuit_protect(ast, i, name, _506_)
+ local _arg_507_ = _506_
+ local mac = _arg_507_["macros"]
+ local call = (utils["list?"](ast) and tostring(ast[1]))
+ if ((("or" == name) or ("and" == name)) and (1 < i) and (mac[call] or ("set" == call) or ("tset" == call) or ("global" == call))) then
+ return utils.list(utils.sym("do"), ast)
+ else
+ return ast
+ end
+ end
+ local function arithmetic_special(name, zero_arity, unary_prefix, ast, scope, parent)
+ local len = #ast
+ local operands = {}
+ local padded_op = (" " .. name .. " ")
+ for i = 2, len do
+ local subast = maybe_short_circuit_protect(ast[i], i, name, scope)
+ local subexprs = compiler.compile1(subast, scope, parent)
+ if (i == len) then
+ utils.map(subexprs, tostring, operands)
+ else
+ table.insert(operands, tostring(subexprs[1]))
+ end
+ end
+ local _510_ = #operands
+ if (_510_ == 0) then
+ local _512_
+ do
+ local _511_ = zero_arity
+ compiler.assert(_511_, "Expected more than 0 arguments", ast)
+ _512_ = _511_
+ end
+ return utils.expr(_512_, "literal")
+ elseif (_510_ == 1) then
+ if unary_prefix then
+ return ("(" .. unary_prefix .. padded_op .. operands[1] .. ")")
+ else
+ return operands[1]
+ end
+ elseif true then
+ local _ = _510_
+ return ("(" .. table.concat(operands, padded_op) .. ")")
+ else
+ return nil
+ end
+ end
+ local function define_arithmetic_special(name, zero_arity, unary_prefix, _3flua_name)
+ local _518_
+ do
+ local _515_ = (_3flua_name or name)
+ local _516_ = zero_arity
+ local _517_ = unary_prefix
+ local function _519_(...)
+ return arithmetic_special(_515_, _516_, _517_, ...)
+ end
+ _518_ = _519_
+ end
+ SPECIALS[name] = _518_
+ 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")
+ SPECIALS["or"] = function(ast, scope, parent)
+ return arithmetic_special("or", "false", nil, ast, scope, parent)
+ end
+ SPECIALS["and"] = function(ast, scope, parent)
+ return arithmetic_special("and", "true", 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.")
+ 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
+ local subexprs
+ local _520_
+ if (i ~= len) then
+ _520_ = 1
+ else
+ _520_ = nil
+ end
+ subexprs = compiler.compile1(ast[i], scope, parent, {nval = _520_})
+ 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)
+ local _530_
+ do
+ local _526_ = native
+ local _527_ = name
+ local _528_ = zero_arity
+ local _529_ = unary_prefix
+ local function _531_(...)
+ return bitop_special(_526_, _527_, _528_, _529_, ...)
+ end
+ _530_ = _531_
+ end
+ SPECIALS[name] = _530_
+ 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.")
+ doc_special("..", {"a", "b", "..."}, "String concatenation operator; works the same as Lua but accepts more arguments.")
+ local function native_comparator(op, _532_, scope, parent)
+ local _arg_533_ = _532_
+ local _ = _arg_533_[1]
+ local lhs_ast = _arg_533_[2]
+ local rhs_ast = _arg_533_[3]
+ local _let_534_ = compiler.compile1(lhs_ast, scope, parent, {nval = 1})
+ local lhs = _let_534_[1]
+ local _let_535_ = compiler.compile1(rhs_ast, scope, parent, {nval = 1})
+ local rhs = _let_535_[1]
+ 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)))
+ table.insert(vals, tostring((compiler.compile1(ast[i], scope, parent, {nval = 1}))[1]))
+ end
+ for i = 1, (#arglist - 1) do
+ table.insert(comparisons, string.format("(%s %s %s)", arglist[i], op, arglist[(i + 1)]))
+ end
+ 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, _3flua_op, _3fchain_op)
+ do
+ local op = (_3flua_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)
+ else
+ return double_eval_protected_comparator(op, _3fchain_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, _3frealop)
+ 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 ((_3frealop 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", "~")
+ doc_special("bnot", {"x"}, "Bitwise negation; only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.")
+ define_unary_special("length", "#")
+ doc_special("length", {"x"}, "Returns the length of a table or string.")
+ do end (SPECIALS)["~="] = SPECIALS["not="]
+ SPECIALS["#"] = SPECIALS.length
+ SPECIALS.quote = function(ast, scope, parent)
+ compiler.assert((#ast == 2), "expected one argument", ast)
+ local runtime, this_scope = true, scope
+ while this_scope do
+ this_scope = this_scope.parent
+ if (this_scope == compiler.scopes.compiler) then
+ runtime = false
+ else
+ 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.")
+ local macro_loaded = {}
+ local function safe_getmetatable(tbl)
+ local mt = getmetatable(tbl)
+ assert((mt ~= getmetatable("")), "Illegal metatable access!")
+ return mt
+ end
+ local safe_require = nil
+ local function safe_compiler_env()
+ local _539_
+ do
+ local _538_ = rawget(_G, "utf8")
+ if (nil ~= _538_) then
+ _539_ = utils.copy(_538_)
+ else
+ _539_ = _538_
+ end
+ end
+ 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, _VERSION = _VERSION, utf8 = _539_}
+ end
+ local function combined_mt_pairs(env)
+ local combined = {}
+ local _let_541_ = getmetatable(env)
+ local __index = _let_541_["__index"]
+ if ("table" == type(__index)) then
+ for k, v in pairs(__index) do
+ combined[k] = v
+ end
+ else
+ end
+ for k, v in next, env, nil do
+ combined[k] = v
+ end
+ return next, combined, nil
+ end
+ local function make_compiler_env(ast, scope, parent, _3fopts)
+ local provided
+ do
+ local _543_ = (_3fopts or utils.root.options)
+ if ((_G.type(_543_) == "table") and ((_543_)["compiler-env"] == "strict")) then
+ provided = safe_compiler_env()
+ elseif ((_G.type(_543_) == "table") and (nil ~= (_543_).compilerEnv)) then
+ local compilerEnv = (_543_).compilerEnv
+ provided = compilerEnv
+ elseif ((_G.type(_543_) == "table") and (nil ~= (_543_)["compiler-env"])) then
+ local compiler_env = (_543_)["compiler-env"]
+ provided = compiler_env
+ elseif true then
+ local _ = _543_
+ provided = safe_compiler_env(false)
+ else
+ provided = nil
+ end
+ end
+ local env
+ local function _545_(base)
+ return utils.sym(compiler.gensym((compiler.scopes.macro or scope), base))
+ end
+ local function _546_()
+ return compiler.scopes.macro
+ end
+ local function _547_(symbol)
+ compiler.assert(compiler.scopes.macro, "must call from macro", ast)
+ return compiler.scopes.macro.manglings[tostring(symbol)]
+ end
+ local function _548_(form)
+ compiler.assert(compiler.scopes.macro, "must call from macro", ast)
+ return compiler.macroexpand(form, compiler.scopes.macro)
+ end
+ 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, view = view, version = utils.version, metadata = compiler.metadata, ["ast-source"] = utils["ast-source"], list = utils.list, ["list?"] = utils["list?"], ["table?"] = utils["table?"], sequence = utils.sequence, ["sequence?"] = utils["sequence?"], sym = utils.sym, ["sym?"] = utils["sym?"], ["multi-sym?"] = utils["multi-sym?"], comment = utils.comment, ["comment?"] = utils["comment?"], ["varg?"] = utils["varg?"], gensym = _545_, ["get-scope"] = _546_, ["in-scope?"] = _547_, macroexpand = _548_}
+ env._G = env
+ return setmetatable(env, {__index = provided, __newindex = provided, __pairs = combined_mt_pairs})
+ end
+ local function _550_(...)
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for c in string.gmatch((package.config or ""), "([^\n]+)") do
+ local val_16_auto = c
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ return tbl_14_auto
+ end
+ local _local_549_ = _550_(...)
+ local dirsep = _local_549_[1]
+ local pathsep = _local_549_[2]
+ local pathmark = _local_549_[3]
+ local pkg_config = {dirsep = (dirsep or "/"), pathmark = (pathmark or ";"), pathsep = (pathsep or "?")}
+ local function escapepat(str)
+ return string.gsub(str, "[^%w]", "%%%1")
+ end
+ local function search_module(modulename, _3fpathstring)
+ local pathsepesc = escapepat(pkg_config.pathsep)
+ local pattern = ("([^%s]*)%s"):format(pathsepesc, pathsepesc)
+ local no_dot_module = modulename:gsub("%.", pkg_config.dirsep)
+ local fullpath = ((_3fpathstring 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)
+ local _552_ = (io.open(filename) or io.open(filename2))
+ if (nil ~= _552_) then
+ local file = _552_
+ file:close()
+ return filename
+ elseif true then
+ local _ = _552_
+ return nil, ("no file '" .. filename .. "'")
+ else
+ return nil
+ end
+ end
+ local function find_in_path(start, _3ftried_paths)
+ local _554_ = fullpath:match(pattern, start)
+ if (nil ~= _554_) then
+ local path = _554_
+ local _555_, _556_ = try_path(path)
+ if (nil ~= _555_) then
+ local filename = _555_
+ return filename
+ elseif ((_555_ == nil) and (nil ~= _556_)) then
+ local error = _556_
+ local function _558_()
+ local _557_ = (_3ftried_paths or {})
+ table.insert(_557_, error)
+ return _557_
+ end
+ return find_in_path((start + #path + 1), _558_())
+ else
+ return nil
+ end
+ elseif true then
+ local _ = _554_
+ local function _560_()
+ local tried_paths = table.concat((_3ftried_paths or {}), "\n\9")
+ if (_VERSION < "Lua 5.4") then
+ return ("\n\9" .. tried_paths)
+ else
+ return tried_paths
+ end
+ end
+ return nil, _560_()
+ else
+ return nil
+ end
+ end
+ return find_in_path(1)
+ end
+ local function make_searcher(_3foptions)
+ local function _563_(module_name)
+ local opts = utils.copy(utils.root.options)
+ for k, v in pairs((_3foptions or {})) do
+ opts[k] = v
+ end
+ opts["module-name"] = module_name
+ local _564_, _565_ = search_module(module_name)
+ if (nil ~= _564_) then
+ local filename = _564_
+ local _568_
+ do
+ local _566_ = filename
+ local _567_ = opts
+ local function _569_(...)
+ return utils["fennel-module"].dofile(_566_, _567_, ...)
+ end
+ _568_ = _569_
+ end
+ return _568_, filename
+ elseif ((_564_ == nil) and (nil ~= _565_)) then
+ local error = _565_
+ return error
+ else
+ return nil
+ end
+ end
+ return _563_
+ end
+ local function dofile_with_searcher(fennel_macro_searcher, filename, opts, ...)
+ local searchers = (package.loaders or package.searchers or {})
+ local _ = table.insert(searchers, 1, fennel_macro_searcher)
+ local m = utils["fennel-module"].dofile(filename, opts, ...)
+ table.remove(searchers, 1)
+ return m
+ end
+ local function fennel_macro_searcher(module_name)
+ local opts
+ do
+ local _571_ = utils.copy(utils.root.options)
+ do end (_571_)["module-name"] = module_name
+ _571_["env"] = "_COMPILER"
+ _571_["requireAsInclude"] = false
+ _571_["allowedGlobals"] = nil
+ opts = _571_
+ end
+ local _572_ = search_module(module_name, utils["fennel-module"]["macro-path"])
+ if (nil ~= _572_) then
+ local filename = _572_
+ local _573_
+ if (opts["compiler-env"] == _G) then
+ local _574_ = fennel_macro_searcher
+ local _575_ = filename
+ local _576_ = opts
+ local function _578_(...)
+ return dofile_with_searcher(_574_, _575_, _576_, ...)
+ end
+ _573_ = _578_
+ else
+ local _579_ = filename
+ local _580_ = opts
+ local function _582_(...)
+ return utils["fennel-module"].dofile(_579_, _580_, ...)
+ end
+ _573_ = _582_
+ end
+ return _573_, filename
+ else
+ return nil
+ end
+ end
+ local function lua_macro_searcher(module_name)
+ local _585_ = search_module(module_name, package.path)
+ if (nil ~= _585_) then
+ local filename = _585_
+ local code
+ do
+ local f = io.open(filename)
+ local function close_handlers_8_auto(ok_9_auto, ...)
+ f:close()
+ if ok_9_auto then
+ return ...
+ else
+ return error(..., 0)
+ end
+ end
+ local function _587_()
+ return assert(f:read("*a"))
+ end
+ code = close_handlers_8_auto(_G.xpcall(_587_, (package.loaded.fennel or debug).traceback))
+ end
+ local chunk = load_code(code, make_compiler_env(), filename)
+ return chunk, filename
+ else
+ return nil
+ end
+ end
+ local macro_searchers = {fennel_macro_searcher, lua_macro_searcher}
+ local function search_macro_module(modname, n)
+ local _589_ = macro_searchers[n]
+ if (nil ~= _589_) then
+ local f = _589_
+ local _590_, _591_ = f(modname)
+ if ((nil ~= _590_) and true) then
+ local loader = _590_
+ local _3ffilename = _591_
+ return loader, _3ffilename
+ elseif true then
+ local _ = _590_
+ return search_macro_module(modname, (n + 1))
+ else
+ return nil
+ end
+ else
+ return nil
+ end
+ end
+ local function sandbox_fennel_module(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, view = view}
+ else
+ return nil
+ end
+ end
+ local function _595_(modname)
+ local function _596_()
+ local loader, filename = search_macro_module(modname, 1)
+ compiler.assert(loader, (modname .. " module not found."))
+ do end (macro_loaded)[modname] = loader(modname, filename)
+ return macro_loaded[modname]
+ end
+ return (macro_loaded[modname] or sandbox_fennel_module(modname) or _596_())
+ end
+ safe_require = _595_
+ local function add_macros(macros_2a, ast, scope)
+ compiler.assert(utils["table?"](macros_2a), "expected macros to be table", ast)
+ for k, v in pairs(macros_2a) do
+ compiler.assert((type(v) == "function"), "expected each macro to be function", ast)
+ compiler["check-binding-valid"](utils.sym(k), scope, ast)
+ do end (scope.macros)[k] = v
+ end
+ return nil
+ end
+ local function resolve_module_name(_597_, _scope, _parent, opts)
+ local _arg_598_ = _597_
+ local filename = _arg_598_["filename"]
+ local second = _arg_598_[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
+ SPECIALS["require-macros"] = function(ast, scope, parent, _3freal_ast)
+ compiler.assert((#ast == 2), "Expected one module name argument", (_3freal_ast or ast))
+ local modname = resolve_module_name(ast, scope, parent, {})
+ compiler.assert(utils["string?"](modname), "module name must compile to string", (_3freal_ast or ast))
+ if not macro_loaded[modname] then
+ local loader, filename = search_macro_module(modname, 1)
+ compiler.assert(loader, (modname .. " module not found."), ast)
+ do end (macro_loaded)[modname] = compiler.assert(utils["table?"](loader(modname, filename)), "expected macros to be table", (_3freal_ast or ast))
+ else
+ end
+ if ("import-macros" == tostring(ast[1])) then
+ return macro_loaded[modname]
+ else
+ return add_macros(macro_loaded[modname], ast, scope, parent)
+ end
+ 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.")
+ local function emit_included_fennel(src, path, opts, sub_chunk)
+ local subscope = compiler["make-scope"](utils.root.scope.parent)
+ local forms = {}
+ if utils.root.options.requireAsInclude then
+ subscope.specials.require = compiler["require-include"]
+ else
+ end
+ for _, val in parser.parser(parser["string-stream"](src), path) do
+ table.insert(forms, val)
+ end
+ for i = 1, #forms do
+ local subopts
+ if (i == #forms) then
+ subopts = {tail = true}
+ 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"
+ local src
+ do
+ local f = assert(io.open(path))
+ local function close_handlers_8_auto(ok_9_auto, ...)
+ f:close()
+ if ok_9_auto then
+ return ...
+ else
+ return error(..., 0)
+ end
+ end
+ local function _604_()
+ return assert(f:read("*all")):gsub("[\13\n]*$", "")
+ end
+ src = close_handlers_8_auto(_G.xpcall(_604_, (package.loaded.fennel or debug).traceback))
+ 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 _, v in ipairs(temp_chunk) do
+ table.insert(utils.root.chunk, v)
+ end
+ if fennel_3f then
+ emit_included_fennel(src, path, opts, sub_chunk)
+ 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)
+ else
+ return nil
+ end
+ end
+ SPECIALS.include = function(ast, scope, parent, opts)
+ compiler.assert((#ast == 2), "expected one argument", ast)
+ local modexpr
+ do
+ local _607_, _608_ = pcall(resolve_module_name, ast, scope, parent, opts)
+ if ((_607_ == true) and (nil ~= _608_)) then
+ local modname = _608_
+ modexpr = utils.expr(string.format("%q", modname), "literal")
+ elseif true then
+ local _ = _607_
+ modexpr = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1]
+ else
+ modexpr = nil
+ end
+ end
+ 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]))()
+ local oldmod = utils.root.options["module-name"]
+ local _
+ utils.root.options["module-name"] = mod
+ _ = nil
+ local res
+ local function _612_()
+ local _611_ = search_module(mod)
+ if (nil ~= _611_) then
+ local fennel_path = _611_
+ return include_path(ast, opts, fennel_path, mod, true)
+ elseif true then
+ local _0 = _611_
+ 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
+ else
+ return nil
+ end
+ end
+ res = ((utils["member?"](mod, (utils.root.options.skipInclude or {})) and opts.fallback(modexpr, true)) or include_circular_fallback(mod, modexpr, opts.fallback, ast) or utils.root.scope.includes[mod] or _612_())
+ utils.root.options["module-name"] = oldmod
+ return res
+ 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)
+ 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 = current_global_names(env)
+ return load_code(compiler.compile(ast, opts), wrap_env(env))(opts["module-name"], ast.filename)
+ 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)
+ do end (ast)[1] = old_first
+ return val
+ end
+ 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}
+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")
+ local unpack = (table.unpack or _G.unpack)
+ local scopes = {}
+ local function make_scope(_3fparent)
+ local parent = (_3fparent or scopes.global)
+ local _254_
+ if parent then
+ _254_ = ((parent.depth or 0) + 1)
+ else
+ _254_ = 0
+ end
+ return {includes = setmetatable({}, {__index = (parent and parent.includes)}), macros = setmetatable({}, {__index = (parent and parent.macros)}), manglings = setmetatable({}, {__index = (parent and parent.manglings)}), specials = setmetatable({}, {__index = (parent and parent.specials)}), symmeta = setmetatable({}, {__index = (parent and parent.symmeta)}), unmanglings = setmetatable({}, {__index = (parent and parent.unmanglings)}), gensyms = setmetatable({}, {__index = (parent and parent.gensyms)}), autogensyms = setmetatable({}, {__index = (parent and parent.autogensyms)}), vararg = (parent and parent.vararg), depth = _254_, hashfn = (parent and parent.hashfn), refedglobals = {}, parent = parent}
+ end
+ local function assert_msg(ast, msg)
+ local ast_tbl
+ 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 "?")
+ local col = ((m and m.col) or ast_tbl.col or "?")
+ local target = tostring((utils["sym?"](ast_tbl[1]) or ast_tbl[1] or "()"))
+ return string.format("%s:%s:%s Compile error in '%s': %s", filename, line, col, target, msg)
+ end
+ local function assert_compile(condition, msg, ast)
+ if not condition then
+ local _let_257_ = (utils.root.options or {})
+ local source = _let_257_["source"]
+ local unfriendly = _let_257_["unfriendly"]
+ if (nil == utils.hook("assert-compile", condition, msg, ast, utils.root.reset)) then
+ utils.root.reset()
+ if (unfriendly or not friend or not _G.io or not _G.io.read) then
+ error(assert_msg(ast, msg), 0)
+ else
+ friend["assert-compile"](condition, msg, ast, source)
+ end
+ else
+ end
+ else
+ end
+ return condition
+ end
+ scopes.global = make_scope()
+ scopes.global.vararg = true
+ scopes.compiler = make_scope(scopes.global)
+ scopes.macro = scopes.global
+ local serialize_subst = {["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\n"] = "n", ["\11"] = "\\v", ["\12"] = "\\f"}
+ local function serialize_string(str)
+ local function _261_(_241)
+ return ("\\" .. _241:byte())
+ end
+ return string.gsub(string.gsub(string.format("%q", str), ".", serialize_subst), "[\128-\255]", _261_)
+ end
+ local function global_mangling(str)
+ if utils["valid-lua-identifier?"](str) then
+ return str
+ else
+ local function _262_(_241)
+ return string.format("_%02x", _241:byte())
+ end
+ return ("__fnl_global__" .. str:gsub("[^%w]", _262_))
+ end
+ end
+ local function global_unmangling(identifier)
+ local _264_ = string.match(identifier, "^__fnl_global__(.*)$")
+ if (nil ~= _264_) then
+ local rest = _264_
+ local _265_
+ local function _266_(_241)
+ return string.char(tonumber(_241:sub(2), 16))
+ end
+ _265_ = string.gsub(rest, "_[%da-f][%da-f]", _266_)
+ return _265_
+ elseif true then
+ local _ = _264_
+ return identifier
+ else
+ return nil
+ end
+ end
+ local allowed_globals = nil
+ local function global_allowed_3f(name)
+ return (not allowed_globals or utils["member?"](name, allowed_globals))
+ end
+ local function unique_mangling(original, mangling, scope, append)
+ if (scope.unmanglings[mangling] and not scope.gensyms[mangling]) then
+ return unique_mangling(original, (original .. append), scope, (append + 1))
+ else
+ return mangling
+ end
+ end
+ local function local_mangling(str, scope, ast, _3ftemp_manglings)
+ assert_compile(not utils["multi-sym?"](str), ("unexpected multi symbol " .. str), ast)
+ local raw
+ if ((utils["lua-keywords"])[str] or str:match("^%d")) then
+ raw = ("_" .. str)
+ else
+ raw = str
+ end
+ local mangling
+ local function _270_(_241)
+ return string.format("_%02x", _241:byte())
+ end
+ mangling = string.gsub(string.gsub(raw, "-", "_"), "[^%w_]", _270_)
+ local unique = unique_mangling(mangling, mangling, scope, 0)
+ do end (scope.unmanglings)[unique] = str
+ do
+ local manglings = (_3ftemp_manglings or scope.manglings)
+ do end (manglings)[str] = unique
+ end
+ return unique
+ 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)
+ do end (scope.manglings)[raw] = mangled
+ end
+ return nil
+ end
+ local function combine_parts(parts, scope)
+ local ret = (scope.manglings[parts[1]] or global_mangling(parts[1]))
+ for i = 2, #parts do
+ 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
+ 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, _3fbase, _3fsuffix)
+ local mangling = ((_3fbase or "") .. next_append() .. (_3fsuffix or ""))
+ while scope.unmanglings[mangling] do
+ mangling = ((_3fbase or "") .. next_append() .. (_3fsuffix or ""))
+ end
+ scope.unmanglings[mangling] = (_3fbase or true)
+ do end (scope.gensyms)[mangling] = true
+ return mangling
+ end
+ local function combine_auto_gensym(parts, first)
+ parts[1] = first
+ local last = table.remove(parts)
+ local last2 = table.remove(parts)
+ local last_joiner = ((parts["multi-sym-method-call"] and ":") or ".")
+ table.insert(parts, (last2 .. last_joiner .. last))
+ return table.concat(parts, ".")
+ end
+ local function autogensym(base, scope)
+ local _273_ = utils["multi-sym?"](base)
+ if (nil ~= _273_) then
+ local parts = _273_
+ return combine_auto_gensym(parts, autogensym(parts[1], scope))
+ elseif true then
+ local _ = _273_
+ local function _274_()
+ local mangling = gensym(scope, base:sub(1, ( - 2)), "auto")
+ do end (scope.autogensyms)[base] = mangling
+ return mangling
+ end
+ return (scope.autogensyms[base] or _274_())
+ else
+ return nil
+ end
+ end
+ local function check_binding_valid(symbol, scope, ast)
+ local name = tostring(symbol)
+ assert_compile(not name:find("&"), "invalid character: &")
+ assert_compile(not name:find("^%."), "invalid character: .")
+ assert_compile(not (scope.specials[name] or scope.macros[name]), ("local %s was overshadowed by a special form or macro"):format(name), ast)
+ return assert_compile(not utils["quoted?"](symbol), string.format("macro tried to bind %s without gensym", name), symbol)
+ end
+ local function declare_local(symbol, meta, scope, ast, _3ftemp_manglings)
+ check_binding_valid(symbol, scope, ast)
+ local name = tostring(symbol)
+ assert_compile(not utils["multi-sym?"](name), ("unexpected multi symbol " .. name), ast)
+ do end (scope.symmeta)[name] = meta
+ return local_mangling(name, scope, ast, _3ftemp_manglings)
+ end
+ 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"
+ else
+ end
+ return table.concat(multi_sym_parts, ".")
+ else
+ return nil
+ end
+ end
+ local function symbol_to_expression(symbol, scope, _3freference_3f)
+ utils.hook("symbol-to-expression", symbol, scope, _3freference_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})
+ local etype = (((1 < #parts) and "expression") or "sym")
+ local local_3f = scope.manglings[parts[1]]
+ if (local_3f and scope.symmeta[parts[1]]) then
+ scope.symmeta[parts[1]]["used"] = true
+ else
+ end
+ assert_compile(not scope.macros[parts[1]], "tried to reference a macro at runtime", symbol)
+ assert_compile((not scope.specials[parts[1]] or ("require" == parts[1])), "tried to reference a special form at runtime", symbol)
+ assert_compile((not _3freference_3f or local_3f or ("_ENV" == parts[1]) or global_allowed_3f(parts[1])), ("unknown identifier in strict mode: " .. tostring(parts[1])), symbol)
+ if (allowed_globals and not local_3f and scope.parent) then
+ scope.parent.refedglobals[parts[1]] = true
+ else
+ end
+ return utils.expr(combine_parts(parts, scope), etype)
+ end
+ local function emit(chunk, out, _3fast)
+ if (type(out) == "table") then
+ return table.insert(chunk, out)
+ else
+ return table.insert(chunk, {ast = _3fast, leaf = out})
+ end
+ end
+ local function peephole(chunk)
+ if chunk.leaf then
+ return chunk
+ elseif ((3 <= #chunk) and (chunk[(#chunk - 2)].leaf == "do") and not chunk[(#chunk - 1)].leaf and (chunk[#chunk].leaf == "end")) then
+ local kid = peephole(chunk[(#chunk - 1)])
+ local new_chunk = {ast = chunk.ast}
+ for i = 1, (#chunk - 3) do
+ table.insert(new_chunk, peephole(chunk[i]))
+ end
+ for i = 1, #kid do
+ table.insert(new_chunk, kid[i])
+ end
+ return new_chunk
+ else
+ return utils.map(chunk, peephole)
+ end
+ end
+ local function flatten_chunk_correlated(main_chunk, options)
+ 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 (0 < #subchunk)) then
+ local source = utils["ast-source"](subchunk.ast)
+ if (file == source.filename) then
+ last_line0 = math.max(last_line0, (source.line or 0))
+ else
+ end
+ last_line0 = flatten(subchunk, out, last_line0, file)
+ else
+ end
+ end
+ end
+ return last_line0
+ end
+ local out = {}
+ local last = flatten(main_chunk, out, 1, options.filename)
+ for i = 1, last do
+ if (out[i] == nil) then
+ out[i] = ""
+ else
+ 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
+ table.insert(sm, {(info and info.filename), (info and info.line)})
+ else
+ end
+ return code
+ else
+ local tab0
+ do
+ local _287_ = tab
+ if (_287_ == true) then
+ tab0 = " "
+ elseif (_287_ == false) then
+ tab0 = ""
+ elseif (_287_ == tab) then
+ tab0 = tab
+ elseif (_287_ == nil) then
+ tab0 = ""
+ else
+ tab0 = nil
+ end
+ end
+ local function parter(c)
+ if (c.leaf or (0 < #c)) then
+ local sub = flatten_chunk(sm, c, tab0, (depth + 1))
+ if (0 < depth) then
+ return (tab0 .. sub:gsub("\n", ("\n" .. tab0)))
+ else
+ return sub
+ end
+ else
+ return nil
+ end
+ end
+ return table.concat(utils.map(chunk, parter), "\n")
+ end
+ end
+ local 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
+ return flatten_chunk_correlated(chunk0, options), {}
+ else
+ local sm = {}
+ local ret = flatten_chunk(sm, chunk0, options.indent, 0)
+ if sm then
+ sm.short_src = (options.filename or make_short_src((options.source or ret)))
+ if options.filename then
+ sm.key = ("@" .. options.filename)
+ else
+ sm.key = ret
+ end
+ sourcemap[sm.key] = sm
+ else
+ end
+ return ret, sm
+ end
+ end
+ local function make_metadata()
+ local function _296_(self, tgt, key)
+ if self[tgt] then
+ return self[tgt][key]
+ else
+ return nil
+ end
+ end
+ local function _298_(self, tgt, key, value)
+ self[tgt] = (self[tgt] or {})
+ do end (self[tgt])[key] = value
+ return tgt
+ end
+ local function _299_(self, tgt, ...)
+ local kv_len = select("#", ...)
+ local kvs = {...}
+ if ((kv_len % 2) ~= 0) then
+ error("metadata:setall() expected even number of k/v pairs")
+ else
+ end
+ self[tgt] = (self[tgt] or {})
+ for i = 1, kv_len, 2 do
+ self[tgt][kvs[i]] = kvs[(i + 1)]
+ end
+ return tgt
+ end
+ return setmetatable({}, {__index = {get = _296_, set = _298_, setall = _299_}, __mode = "k"})
+ end
+ local function exprs1(exprs)
+ return table.concat(utils.map(exprs, tostring), ", ")
+ end
+ local function keep_side_effects(exprs, chunk, start, ast)
+ local start0 = (start or 1)
+ for j = start0, #exprs do
+ local se = exprs[j]
+ if ((se.type == "expression") and (se[1] ~= "nil")) then
+ emit(chunk, string.format("do local _ = %s end", tostring(se)), ast)
+ elseif (se.type == "statement") then
+ local code = tostring(se)
+ local disambiguated
+ if (code:byte() == 40) then
+ disambiguated = ("do end " .. code)
+ else
+ disambiguated = code
+ end
+ emit(chunk, disambiguated, ast)
+ else
+ 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 (n < len) then
+ keep_side_effects(exprs, parent, (n + 1), ast)
+ for i = (n + 1), len do
+ exprs[i] = nil
+ end
+ else
+ for i = (#exprs + 1), n do
+ exprs[i] = utils.expr("nil", "literal")
+ end
+ end
+ else
+ end
+ else
+ end
+ if opts.tail then
+ emit(parent, string.format("return %s", exprs1(exprs)), ast)
+ else
+ end
+ if opts.target then
+ local result = exprs1(exprs)
+ local function _307_()
+ if (result == "") then
+ return "nil"
+ else
+ return result
+ end
+ end
+ emit(parent, string.format("%s = %s", opts.target, _307_()), ast)
+ else
+ end
+ if (opts.tail or opts.target) then
+ return {returned = true}
+ else
+ local _309_ = exprs
+ _309_["returned"] = true
+ return _309_
+ end
+ end
+ local function find_macro(ast, scope)
+ local macro_2a
+ do
+ local _311_ = utils["sym?"](ast[1])
+ if (_311_ ~= nil) then
+ local _312_ = tostring(_311_)
+ if (_312_ ~= nil) then
+ macro_2a = scope.macros[_312_]
+ else
+ macro_2a = _312_
+ end
+ else
+ macro_2a = _311_
+ end
+ end
+ local multi_sym_parts = utils["multi-sym?"](ast[1])
+ if (not macro_2a and multi_sym_parts) then
+ local nested_macro = utils["get-in"](scope.macros, multi_sym_parts)
+ 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
+ else
+ return macro_2a
+ end
+ end
+ local function propagate_trace_info(_316_, _index, node)
+ local _arg_317_ = _316_
+ local filename = _arg_317_["filename"]
+ local line = _arg_317_["line"]
+ local bytestart = _arg_317_["bytestart"]
+ local byteend = _arg_317_["byteend"]
+ do
+ local src = utils["ast-source"](node)
+ if (("table" == type(node)) and (filename ~= src.filename)) then
+ src.filename, src.line, src["from-macro?"] = filename, line, true
+ src.bytestart, src.byteend = bytestart, byteend
+ else
+ end
+ end
+ return ("table" == type(node))
+ end
+ local function max_n(t)
+ local n = 0
+ for k in pairs(t) do
+ if ("number" == type(k)) then
+ n = math.max(k, n)
+ else
+ end
+ end
+ return n
+ end
+ local function quote_literal_nils(index, node, parent)
+ if (parent and utils["list?"](parent)) then
+ for i = 1, max_n(parent) do
+ local _320_ = parent[i]
+ if (_320_ == nil) then
+ parent[i] = utils.sym("nil")
+ else
+ end
+ end
+ else
+ end
+ return index, node, parent
+ end
+ local function comp(f, g)
+ local function _323_(...)
+ return f(g(...))
+ end
+ return _323_
+ end
+ local function built_in_3f(m)
+ local found_3f = false
+ for _, f in pairs(scopes.global.macros) do
+ if found_3f then break end
+ found_3f = (f == m)
+ end
+ return found_3f
+ end
+ local function macroexpand_2a(ast, scope, _3fonce)
+ local _324_
+ if utils["list?"](ast) then
+ _324_ = find_macro(ast, scope)
+ else
+ _324_ = nil
+ end
+ if (_324_ == false) then
+ return ast
+ elseif (nil ~= _324_) then
+ local macro_2a = _324_
+ local old_scope = scopes.macro
+ local _
+ scopes.macro = scope
+ _ = nil
+ local ok, transformed = nil, nil
+ local function _326_()
+ return macro_2a(unpack(ast, 2))
+ end
+ local function _327_()
+ if built_in_3f(macro_2a) then
+ return tostring
+ else
+ return debug.traceback
+ end
+ end
+ ok, transformed = xpcall(_326_, _327_())
+ local _329_
+ do
+ local _328_ = ast
+ local function _330_(...)
+ return propagate_trace_info(_328_, ...)
+ end
+ _329_ = _330_
+ end
+ utils["walk-tree"](transformed, comp(_329_, quote_literal_nils))
+ scopes.macro = old_scope
+ assert_compile(ok, transformed, ast)
+ if (_3fonce or not transformed) then
+ return transformed
+ else
+ return macroexpand_2a(transformed, scope)
+ end
+ elseif true then
+ local _ = _324_
+ return ast
+ else
+ return nil
+ end
+ end
+ local function compile_special(ast, scope, parent, opts, special)
+ local exprs = (special(ast, scope, parent, opts) or utils.expr("nil", "literal"))
+ local exprs0
+ if ("table" ~= type(exprs)) then
+ exprs0 = utils.expr(exprs, "expression")
+ else
+ exprs0 = exprs
+ end
+ local exprs2
+ 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
+ local function compile_function_call(ast, scope, parent, opts, compile1, len)
+ local fargs = {}
+ local fcallee = (compile1(ast[1], scope, parent, {nval = 1}))[1]
+ assert_compile((utils["sym?"](ast[1]) or utils["list?"](ast[1]) or ("string" == type(ast[1]))), ("cannot call literal value " .. tostring(ast[1])), ast)
+ for i = 2, len do
+ local subexprs
+ local _336_
+ if (i ~= len) then
+ _336_ = 1
+ else
+ _336_ = nil
+ end
+ subexprs = compile1(ast[i], scope, parent, {nval = _336_})
+ 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
+ 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))
+ return handle_compile_opts({utils.expr(call, "statement")}, parent, opts, ast)
+ end
+ 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)
+ local special = (utils["sym?"](first) and scope.specials[tostring(first)])
+ assert_compile((0 < len), "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]
+ local new_ast = utils.list(utils.sym(":", ast), utils.sym(table_with_method, ast), method_to_call, select(2, unpack(ast)))
+ return compile1(new_ast, scope, parent, opts)
+ else
+ return compile_function_call(ast, scope, parent, opts, compile1, len)
+ end
+ end
+ local function compile_varg(ast, scope, parent, opts)
+ local _341_
+ if scope.hashfn then
+ _341_ = "use $... in hashfn"
+ else
+ _341_ = "unexpected vararg"
+ end
+ assert_compile(scope.vararg, _341_, 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)
+ local e
+ 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
+ local function serialize_number(n)
+ local _344_ = string.gsub(tostring(n), ",", ".")
+ return _344_
+ end
+ local function compile_scalar(ast, _scope, parent, opts)
+ local serialize
+ do
+ local _345_ = type(ast)
+ if (_345_ == "nil") then
+ serialize = tostring
+ elseif (_345_ == "boolean") then
+ serialize = tostring
+ elseif (_345_ == "string") then
+ serialize = serialize_string
+ elseif (_345_ == "number") then
+ serialize = serialize_number
+ else
+ 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 = {}
+ local function write_other_values(k)
+ if ((type(k) ~= "number") or (math.floor(k) ~= k) or (k < 1) or (#ast < k)) then
+ if ((type(k) == "string") and utils["valid-lua-identifier?"](k)) then
+ return {k, k}
+ else
+ local _let_347_ = compile1(k, scope, parent, {nval = 1})
+ local compiled = _let_347_[1]
+ local kstr = ("[" .. tostring(compiled) .. "]")
+ return {kstr, k}
+ end
+ else
+ return nil
+ end
+ end
+ do
+ local keys
+ do
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for k, v in utils.stablepairs(ast) do
+ local val_16_auto = write_other_values(k, v)
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ keys = tbl_14_auto
+ end
+ local function _353_(_351_)
+ local _arg_352_ = _351_
+ local k1 = _arg_352_[1]
+ local k2 = _arg_352_[2]
+ local _let_354_ = compile1(ast[k2], scope, parent, {nval = 1})
+ local v = _let_354_[1]
+ return string.format("%s = %s", k1, tostring(v))
+ end
+ utils.map(keys, _353_, buffer)
+ end
+ for i = 1, #ast do
+ local nval = ((i ~= #ast) and 1)
+ table.insert(buffer, exprs1(compile1(ast[i], scope, parent, {nval = nval})))
+ end
+ return handle_compile_opts({utils.expr(("{" .. table.concat(buffer, ", ") .. "}"), "expression")}, parent, opts, ast)
+ end
+ local function compile1(ast, scope, parent, _3fopts)
+ local opts = (_3fopts or {})
+ local ast0 = macroexpand_2a(ast, scope)
+ if utils["list?"](ast0) then
+ return compile_call(ast0, scope, parent, opts, compile1)
+ elseif utils["varg?"](ast0) then
+ return compile_varg(ast0, scope, parent, opts)
+ elseif utils["sym?"](ast0) then
+ return compile_sym(ast0, scope, parent, opts)
+ elseif (type(ast0) == "table") then
+ return compile_table(ast0, scope, parent, opts, compile1)
+ elseif ((type(ast0) == "nil") or (type(ast0) == "boolean") or (type(ast0) == "number") or (type(ast0) == "string")) then
+ return compile_scalar(ast0, scope, parent, opts)
+ else
+ return assert_compile(false, ("could not compile value of type " .. type(ast0)), ast0)
+ end
+ end
+ local function destructure(to, from, ast, scope, parent, opts)
+ local opts0 = (opts or {})
+ local _let_356_ = opts0
+ local isvar = _let_356_["isvar"]
+ local declaration = _let_356_["declaration"]
+ local forceglobal = _let_356_["forceglobal"]
+ local forceset = _let_356_["forceset"]
+ local symtype = _let_356_["symtype"]
+ local symtype0 = ("_" .. (symtype or "dst"))
+ local setter
+ if declaration then
+ setter = "local %s = %s"
+ else
+ setter = "%s = %s"
+ end
+ local new_manglings = {}
+ local function getname(symbol, up1)
+ local raw = symbol[1]
+ assert_compile(not (opts0.nomulti and utils["multi-sym?"](raw)), ("unexpected multi symbol " .. raw), up1)
+ if declaration then
+ return declare_local(symbol, nil, scope, symbol, new_manglings)
+ else
+ local parts = (utils["multi-sym?"](raw) or {raw})
+ local meta = scope.symmeta[parts[1]]
+ assert_compile(not raw:find(":"), "cannot set method sym", symbol)
+ if ((#parts == 1) and not forceset) then
+ assert_compile(not (forceglobal and meta), string.format("global %s conflicts with local", tostring(symbol)), symbol)
+ assert_compile(not (meta and not meta.var), ("expected var " .. raw), symbol)
+ assert_compile((meta or not opts0.noundef), ("expected local " .. parts[1]), symbol)
+ else
+ end
+ if forceglobal then
+ assert_compile(not scope.symmeta[scope.unmanglings[raw]], ("global " .. raw .. " conflicts with local"), symbol)
+ do end (scope.manglings)[raw] = global_mangling(raw)
+ do end (scope.unmanglings)[global_mangling(raw)] = raw
+ if allowed_globals then
+ table.insert(allowed_globals, raw)
+ else
+ end
+ else
+ end
+ return symbol_to_expression(symbol, scope)[1]
+ end
+ end
+ local function compile_top_target(lvalues)
+ local inits
+ local function _362_(_241)
+ if scope.manglings[_241] then
+ return _241
+ else
+ return "nil"
+ end
+ end
+ inits = utils.map(lvalues, _362_)
+ local init = table.concat(inits, ", ")
+ local lvalue = table.concat(lvalues, ", ")
+ local plast = parent[#parent]
+ local plen = #parent
+ local ret = compile1(from, scope, parent, {target = lvalue})
+ if declaration then
+ for pi = plen, #parent do
+ if (parent[pi] == plast) then
+ plen = pi
+ else
+ end
+ end
+ if ((#parent == (plen + 1)) and parent[#parent].leaf) then
+ parent[#parent]["leaf"] = ("local " .. parent[#parent].leaf)
+ elseif (init == "nil") then
+ table.insert(parent, (plen + 1), {ast = ast, leaf = ("local " .. lvalue)})
+ else
+ table.insert(parent, (plen + 1), {ast = ast, leaf = ("local " .. lvalue .. " = " .. init)})
+ end
+ else
+ end
+ return ret
+ end
+ 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
+ scope.symmeta[tostring(left)] = {var = isvar}
+ return nil
+ else
+ return nil
+ end
+ end
+ local unpack_fn = "function (t, k, e)\n local mt = getmetatable(t)\n if 'table' == type(mt) and mt.__fennelrest then\n return mt.__fennelrest(t, k)\n elseif e then\n local rest = {}\n for k, v in pairs(t) do\n if not e[k] then rest[k] = v end\n end\n return rest\n else\n return {(table.unpack or unpack)(t, k)}\n end\n end"
+ local function destructure_kv_rest(s, v, left, excluded_keys, destructure1)
+ local exclude_str
+ local _369_
+ do
+ local tbl_14_auto = {}
+ local i_15_auto = #tbl_14_auto
+ for _, k in ipairs(excluded_keys) do
+ local val_16_auto = string.format("[%s] = true", serialize_string(k))
+ if (nil ~= val_16_auto) then
+ i_15_auto = (i_15_auto + 1)
+ do end (tbl_14_auto)[i_15_auto] = val_16_auto
+ else
+ end
+ end
+ _369_ = tbl_14_auto
+ end
+ exclude_str = table.concat(_369_, ", ")
+ local subexpr = utils.expr(string.format(string.gsub(("(" .. unpack_fn .. ")(%s, %s, {%s})"), "\n%s*", " "), s, tostring(v), exclude_str), "expression")
+ return destructure1(v, {subexpr}, left)
+ end
+ local function destructure_rest(s, k, left, destructure1)
+ local unpack_str = ("(" .. unpack_fn .. ")(%s, %s)")
+ local formatted = string.format(string.gsub(unpack_str, "\n%s*", " "), s, k)
+ local subexpr = utils.expr(formatted, "expression")
+ assert_compile((utils["sequence?"](left) and (nil == left[(k + 2)])), "expected rest argument before last parameter", left)
+ return destructure1(left[(k + 1)], {subexpr}, left)
+ end
+ local function destructure_table(left, rightexprs, top_3f, destructure1)
+ local s = gensym(scope, symtype0)
+ local right
+ do
+ local _371_
+ if top_3f then
+ _371_ = exprs1(compile1(from, scope, parent))
+ else
+ _371_ = exprs1(rightexprs)
+ end
+ if (_371_ == "") then
+ right = "nil"
+ elseif (nil ~= _371_) then
+ local right0 = _371_
+ right = right0
+ else
+ right = nil
+ end
+ end
+ local excluded_keys = {}
+ 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
+ if (utils["sym?"](k) and (tostring(k) == "&")) then
+ destructure_kv_rest(s, v, left, excluded_keys, destructure1)
+ elseif (utils["sym?"](v) and (tostring(v) == "&")) then
+ destructure_rest(s, k, left, destructure1)
+ elseif (utils["sym?"](k) and (tostring(k) == "&as")) then
+ destructure_sym(v, {utils.expr(tostring(s))}, left)
+ elseif (utils["sequence?"](left) and (tostring(v) == "&as")) then
+ 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)
+ else
+ local key
+ if (type(k) == "string") then
+ key = serialize_string(k)
+ else
+ key = k
+ end
+ local subexpr = utils.expr(string.format("%s[%s]", s, key), "expression")
+ if (type(k) == "string") then
+ table.insert(excluded_keys, k)
+ else
+ end
+ destructure1(v, {subexpr}, left)
+ end
+ else
+ end
+ 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))
+ else
+ local symname = gensym(scope, symtype0)
+ table.insert(left_names, symname)
+ do end (tables)[i] = {name, utils.expr(symname, "sym")}
+ end
+ end
+ assert_compile(left[1], "must provide at least one value", left)
+ 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
+ if utils["sym?"](sym) then
+ scope.symmeta[tostring(sym)] = {var = isvar}
+ else
+ end
+ end
+ else
+ 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)
+ else
+ assert_compile(false, string.format("unable to bind %s %s", type(left), tostring(left)), (((type((up1)[2]) == "table") and (up1)[2]) or up1))
+ end
+ if top_3f then
+ return {returned = true}
+ else
+ return nil
+ end
+ end
+ local ret = destructure1(to, nil, ast, true)
+ utils.hook("destructure", from, to, scope, opts0)
+ apply_manglings(scope, new_manglings, ast)
+ return ret
+ end
+ local function require_include(ast, scope, parent, opts)
+ opts.fallback = function(e, no_warn)
+ if (not no_warn and ("literal" == e.type)) then
+ utils.warn(("include module not found, falling back to require: %s"):format(tostring(e)))
+ else
+ end
+ return utils.expr(string.format("require(%s)", tostring(e)), "statement")
+ 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 = {}
+ do end (function(tgt, m, ...) return tgt[m](tgt, ...) end)(utils.root, "set-reset")
+ allowed_globals = opts.allowedGlobals
+ if (opts.indent == nil) then
+ opts.indent = " "
+ else
+ end
+ if opts.requireAsInclude then
+ scope.specials.require = require_include
+ else
+ end
+ utils.root.chunk, utils.root.scope, utils.root.options = chunk, scope, opts
+ for _, val in parser.parser(strm, opts.filename, opts) do
+ table.insert(vals, val)
+ end
+ for i = 1, #vals do
+ 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])
+ if (i == #vals) then
+ utils.hook("chunk", vals[i], scope)
+ else
+ end
+ 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))
+ do end (function(tgt, m, ...) return tgt[m](tgt, ...) end)(utils.root, "set-reset")
+ allowed_globals = opts0.allowedGlobals
+ if (opts0.indent == nil) then
+ opts0.indent = " "
+ else
+ end
+ if opts0.requireAsInclude then
+ scope.specials.require = require_include
+ else
+ 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)
+ utils.hook("chunk", ast, scope)
+ 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
+ return string.format(" [C]: in function '%s'", info.name)
+ elseif (info.what == "C") then
+ return " [C]: in ?"
+ else
+ local remap = sourcemap[info.source]
+ if (remap and remap[info.currentline]) then
+ if ((remap[info.currentline][1] or "unknown") ~= "unknown") then
+ info.short_src = sourcemap[("@" .. remap[info.currentline][1])].short_src
+ else
+ info.short_src = remap.short_src
+ end
+ info.currentline = (remap[info.currentline][2] or -1)
+ else
+ end
+ if (info.what == "Lua") then
+ local function _391_()
+ if info.name then
+ return ("'" .. info.name .. "'")
+ else
+ return "?"
+ end
+ end
+ return string.format(" %s:%d: in function %s", info.short_src, info.currentline, _391_())
+ elseif (info.short_src == "(tail call)") then
+ return " (tail call)"
+ else
+ return string.format(" %s:%d: in main chunk", info.short_src, info.currentline)
+ end
+ end
+ end
+ local function traceback(_3fmsg, _3fstart)
+ local msg = tostring((_3fmsg or ""))
+ if ((msg:find("^Compile error") or msg:find("^Parse error")) and not utils["debug-on?"]("trace")) then
+ return msg
+ else
+ local lines = {}
+ if (msg:find(":%d+: Compile error") or msg:find(":%d+: Parse error")) then
+ table.insert(lines, msg)
+ else
+ local newmsg = msg:gsub("^[^:]*:%d+:%s+", "runtime error: ")
+ table.insert(lines, newmsg)
+ end
+ table.insert(lines, "stack traceback:")
+ local done_3f, level = false, (_3fstart or 2)
+ while not done_3f do
+ do
+ local _395_ = debug.getinfo(level, "Sln")
+ if (_395_ == nil) then
+ done_3f = true
+ elseif (nil ~= _395_) then
+ local info = _395_
+ table.insert(lines, traceback_frame(info))
+ else
+ end
+ end
+ level = (level + 1)
+ end
+ return table.concat(lines, "\n")
+ end
+ end
+ local function entry_transform(fk, fv)
+ local function _398_(k, v)
+ if (type(k) == "number") then
+ return k, fv(v)
+ else
+ return fk(k), fv(v)
+ end
+ end
+ return _398_
+ 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
+ else
+ end
+ end
+ return ret
+ end
+ local function do_quote(form, scope, parent, runtime_3f)
+ local function q(x)
+ return do_quote(x, scope, parent, runtime_3f)
+ end
+ if utils["varg?"](form) then
+ assert_compile(not runtime_3f, "quoted ... may only be used at compile time", form)
+ return "_VARARG"
+ elseif utils["sym?"](form) then
+ local filename
+ if form.filename then
+ filename = string.format("%q", form.filename)
+ else
+ filename = "nil"
+ end
+ local symstr = tostring(form)
+ assert_compile(not runtime_3f, "symbols may only be used at compile time", form)
+ if (symstr:find("#$") or symstr:find("#[:.]")) then
+ return string.format("sym('%s', {filename=%s, line=%s})", autogensym(symstr, scope), filename, (form.line or "nil"))
+ else
+ return string.format("sym('%s', {quoted=true, filename=%s, line=%s})", symstr, filename, (form.line or "nil"))
+ end
+ elseif (utils["list?"](form) and utils["sym?"](form[1]) and (tostring(form[1]) == "unquote")) then
+ local payload = form[2]
+ local res = unpack(compile1(payload, scope, parent))
+ return res[1]
+ elseif utils["list?"](form) then
+ local mapped
+ local function _403_()
+ return nil
+ end
+ mapped = utils.kvmap(form, entry_transform(_403_, q))
+ local filename
+ if form.filename then
+ filename = string.format("%q", form.filename)
+ else
+ filename = "nil"
+ end
+ 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, ", "))
+ elseif utils["sequence?"](form) then
+ local mapped = utils.kvmap(form, entry_transform(q, q))
+ local source = getmetatable(form)
+ local filename
+ if source.filename then
+ filename = string.format("%q", source.filename)
+ else
+ filename = "nil"
+ end
+ local _406_
+ if source then
+ _406_ = source.line
+ else
+ _406_ = "nil"
+ end
+ return string.format("setmetatable({%s}, {filename=%s, line=%s, sequence=%s})", mixed_concat(mapped, ", "), filename, _406_, "(getmetatable(sequence()))['sequence']")
+ elseif (type(form) == "table") then
+ local mapped = utils.kvmap(form, entry_transform(q, q))
+ local source = getmetatable(form)
+ local filename
+ if source.filename then
+ filename = string.format("%q", source.filename)
+ else
+ filename = "nil"
+ end
+ local function _409_()
+ if source then
+ return source.line
+ else
+ return "nil"
+ end
+ end
+ return string.format("setmetatable({%s}, {filename=%s, line=%s})", mixed_concat(mapped, ", "), filename, _409_())
+ elseif (type(form) == "string") then
+ return serialize_string(form)
+ else
+ return tostring(form)
+ end
+ end
+ return {compile = compile, compile1 = compile1, ["compile-stream"] = compile_stream, ["compile-string"] = compile_string, ["check-binding-valid"] = check_binding_valid, 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(), sourcemap = sourcemap}
+end
+package.preload["fennel.friend"] = package.preload["fennel.friend"] or function(...)
+ local utils = require("fennel.utils")
+ local utf8_ok_3f, utf8 = pcall(require, "utf8")
+ 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 identifier 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 (.*)"] = {"renaming the local to _%s if it is meant to be unused", "fixing a typo so %s is used", "disabling the linter which checks for unused locals"}, ["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"}, ["invalid 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", "making the method call, then looking up the field on the result"}, ["$ and $... in hashfn are mutually exclusive"] = {"modifying the hashfn so it only contains $... or $, $1, $2, $3, etc"}, ["tried to reference a macro at runtime"] = {"renaming the macro so as not to conflict with locals"}, ["tried to reference a special form at runtime"] = {"wrapping the special in a function if you need it to be first class"}, ["missing subject"] = {"adding an item to operate on"}, ["expected even number of pattern/body pairs"] = {"checking that every pattern has a body to go with it", "adding _ before the final body"}, ["expected at least one pattern/body pair"] = {"adding a pattern and a body to execute when the pattern matches"}, ["unexpected arguments"] = {"removing an argument", "checking for typos"}, ["unexpected iterator clause"] = {"removing an argument", "checking for typos"}}
+ local unpack = (table.unpack or _G.unpack)
+ 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
+ else
+ end
+ end
+ return suggestion
+ end
+ local function read_line(filename, line, _3fsource)
+ if _3fsource then
+ local matcher = string.gmatch((_3fsource .. "\n"), "(.-)(\13?\n)")
+ for _ = 2, line do
+ matcher()
+ end
+ return matcher()
+ else
+ local f = assert(io.open(filename))
+ local function close_handlers_8_auto(ok_9_auto, ...)
+ f:close()
+ if ok_9_auto then
+ return ...
+ else
+ return error(..., 0)
+ end
+ end
+ local function _178_()
+ for _ = 2, line do
+ f:read()
+ end
+ return f:read()
+ end
+ return close_handlers_8_auto(_G.xpcall(_178_, (package.loaded.fennel or debug).traceback))
+ end
+ end
+ local function sub(str, start, _end)
+ if (_end < start) then
+ return ""
+ elseif utf8_ok_3f then
+ return string.sub(str, utf8.offset(str, start), ((utf8.offset(str, (_end + 1)) or (utf8.len(str) + 1)) - 1))
+ else
+ return string.sub(str, start, math.min(_end, str:len()))
+ end
+ end
+ local function highlight_line(codeline, col, _3fendcol)
+ local endcol = (_3fendcol or col)
+ local eol
+ if utf8_ok_3f then
+ eol = utf8.len(codeline)
+ else
+ eol = string.len(codeline)
+ end
+ return (sub(codeline, 1, col) .. "\27[7m" .. sub(codeline, (col + 1), (endcol + 1)) .. "\27[0m" .. sub(codeline, (endcol + 2), eol))
+ end
+ local function friendly_msg(msg, _182_, source)
+ local _arg_183_ = _182_
+ local filename = _arg_183_["filename"]
+ local line = _arg_183_["line"]
+ local col = _arg_183_["col"]
+ local endcol = _arg_183_["endcol"]
+ local ok, codeline = pcall(read_line, filename, line, source)
+ local out = {msg, ""}
+ if (ok and codeline) then
+ if col then
+ table.insert(out, highlight_line(codeline, col, endcol))
+ else
+ table.insert(out, codeline)
+ end
+ else
+ end
+ for _, suggestion in ipairs((suggest(msg) or {})) do
+ table.insert(out, ("* Try %s."):format(suggestion))
+ end
+ return table.concat(out, "\n")
+ end
+ local function assert_compile(condition, msg, ast, source)
+ if not condition then
+