From 11087a53dfa25527bde725275f04da83366edcf8 Mon Sep 17 00:00:00 2001 From: Alexander Griffith Date: Mon, 13 Sep 2021 01:29:05 -0400 Subject: [PATCH] Bumped Fennel Version to 0.10.0 --- lib/fennel | 3096 ++++++++++++++++++++++++++++-------------------- lib/fennel.lua | 2790 +++++++++++++++++++++++++------------------ 2 files changed, 3470 insertions(+), 2416 deletions(-) diff --git a/lib/fennel b/lib/fennel index 8520268..f72b948 100755 --- a/lib/fennel +++ b/lib/fennel @@ -7,10 +7,10 @@ package.preload["fennel.binary"] = package.preload["fennel.binary"] or function( return (f:close() and stdout) end local function execute(cmd) - local _0_0 = os.execute(cmd) - if (_0_0 == 0) then + local _601_ = os.execute(cmd) + if (_601_ == 0) then return true - elseif (_0_0 == true) then + elseif (_601_ == true) then return true end end @@ -23,7 +23,7 @@ package.preload["fennel.binary"] = package.preload["fennel.binary"] or function( end local c_shim = "#ifdef __cplusplus\nextern \"C\" {\n#endif\n#include \n#include \n#include \n#ifdef __cplusplus\n}\n#endif\n#include \n#include \n#include \n#include \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 = nil + local f if (filename == "-") then f = io.stdin else @@ -50,12 +50,12 @@ package.preload["fennel.binary"] = package.preload["fennel.binary"] or function( local basename_noextension = (basename:match("(.+)%.") or basename) local dotpath = filename:gsub("^%.%/", ""):gsub("[\\/]", ".") local dotpath_noextension = (dotpath:match("(.+)%.") or dotpath) - local fennel_loader = nil - local _0_ + local fennel_loader + local _604_ do - _0_ = "(do (local bundle_0_ ...) (fn loader_0_ [name_0_] (match (or (. bundle_0_ name_0_) (. bundle_0_ (.. name_0_ \".init\"))) (mod_0_ ? (= \"function\" (type mod_0_))) mod_0_ (mod_0_ ? (= \"string\" (type mod_0_))) (assert (if (= _VERSION \"Lua 5.1\") (loadstring mod_0_ name_0_) (load mod_0_ name_0_))) nil (values nil (: \"\n\\tmodule '%%s' not found in fennel bundle\" \"format\" name_0_)))) (table.insert (or package.loaders package.searchers) 2 loader_0_) ((assert (loader_0_ \"%s\")) ((or unpack table.unpack) arg)))" + _604_ = "(do (local bundle_2_auto ...) (fn loader_3_auto [name_4_auto] (match (or (. bundle_2_auto name_4_auto) (. bundle_2_auto (.. name_4_auto \".init\"))) (mod_5_auto ? (= \"function\" (type mod_5_auto))) mod_5_auto (mod_5_auto ? (= \"string\" (type mod_5_auto))) (assert (if (= _VERSION \"Lua 5.1\") (loadstring mod_5_auto name_4_auto) (load mod_5_auto name_4_auto))) nil (values nil (: \"\n\\tmodule '%%s' not found in fennel bundle\" \"format\" name_4_auto)))) (table.insert (or package.loaders package.searchers) 2 loader_3_auto) ((assert (loader_3_auto \"%s\")) ((or unpack table.unpack) arg)))" end - fennel_loader = _0_:format(dotpath_noextension) + fennel_loader = _604_:format(dotpath_noextension) local lua_loader = fennel["compile-string"](fennel_loader) return c_shim:format(string__3ec_hex_literal(lua_loader), basename_noextension, string__3ec_hex_literal(compile_fennel(filename, options)), dotpath_noextension, native_loader(native)) end @@ -69,19 +69,28 @@ package.preload["fennel.binary"] = package.preload["fennel.binary"] or function( 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 - if shellout((cc .. " -dumpmachine")):match("mingw") then + local _606_ + do + local _605_ = shellout((cc .. " -dumpmachine")) + if _605_ then + _606_ = _605_:match("mingw") + else + _606_ = _605_ + end + end + if _606_ then rdynamic, bin_extension, ldl_3f = "", ".exe", false else rdynamic, bin_extension, ldl_3f = "-rdynamic", "", true end - local compile_command = nil - local _1_ + local compile_command + local _609_ if ldl_3f then - _1_ = "-ldl" + _609_ = "-ldl" else - _1_ = "" + _609_ = "" end - compile_command = {cc, "-Os", lua_c_path, table.concat(native, " "), static_lua, rdynamic, "-lm", _1_, "-o", (executable_name .. bin_extension), "-I", lua_include_dir, os.getenv("CC_OPTS")} + compile_command = {cc, "-Os", lua_c_path, table.concat(native, " "), static_lua, rdynamic, "-lm", _609_, "-o", (executable_name .. bin_extension), "-I", lua_include_dir, os.getenv("CC_OPTS")} if os.getenv("FENNEL_DEBUG") then print("Compiling with", table.concat(compile_command, " ")) end @@ -95,22 +104,22 @@ package.preload["fennel.binary"] = package.preload["fennel.binary"] or function( return os.exit(0) end local function native_path_3f(path) - local _0_0 = path:match("%.(%a+)$") - if (_0_0 == "a") then + local _614_ = path:match("%.(%a+)$") + if (_614_ == "a") then return path - elseif (_0_0 == "o") then + elseif (_614_ == "o") then return path - elseif (_0_0 == "so") then + elseif (_614_ == "so") then return path - elseif (_0_0 == "dylib") then + elseif (_614_ == "dylib") then return path else - local _ = _0_0 + local _ = _614_ return false end end local function extract_native_args(args) - local native = {libraries = {}, modules = {}} + local native = {modules = {}, libraries = {}} for i = #args, 1, -1 do if ("--native-module" == args[i]) then local path = assert(native_path_3f(table.remove(args, (i + 1)))) @@ -130,29 +139,30 @@ package.preload["fennel.binary"] = package.preload["fennel.binary"] or function( return native end local function compile(filename, executable_name, static_lua, lua_include_dir, options, args) - local _0_ = extract_native_args(args) - local libraries = _0_["libraries"] - local modules = _0_["modules"] + local _let_619_ = extract_native_args(args) + local modules = _let_619_["modules"] + local libraries = _let_619_["libraries"] return compile_binary(write_c(filename, modules, options), 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\nTo include C libraries that contain Lua modules, add --native-module path/to.so,\nand to include C libraries without modules, use --native-library path/to.so.\nThese options are unstable, barely tested, and even more likely to break.\n\nThis method is currently limited to programs do not transitively require Lua\nmodules. Requiring a Lua module directly will work, but requiring a Lua module\nwhich requires another will fail."):format(arg[0], arg[0]) return {compile = compile, help = help} end -local fennel = nil +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 unpack = (table.unpack or _G.unpack) local function default_read_chunk(parser_state) - local function _0_() + local function _481_() if (0 < parser_state["stack-size"]) then return ".." else return ">> " end end - io.write(_0_()) + io.write(_481_()) io.flush() local input = io.read() return (input and (input .. "\n")) @@ -162,18 +172,18 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) return io.write("\n") end local function default_on_error(errtype, err, lua_source) - local function _1_() - local _0_0 = errtype - if (_0_0 == "Lua Compile") then + local function _483_() + local _482_ = errtype + if (_482_ == "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 (_0_0 == "Runtime") then + elseif (_482_ == "Runtime") then return (compiler.traceback(tostring(err), 4) .. "\n") else - local _ = _0_0 + local _ = _482_ return ("%s error: %s\n"):format(errtype, tostring(err)) end end - return io.write(_1_()) + return io.write(_483_()) 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) @@ -191,34 +201,105 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) end return table.concat(spliced_source, "\n") end + local function completer(env, scope, text) + local matches = {} + local input_fragment = text:gsub(".*[%s)(]+", "") + local stop_looking_3f = false + local function add_partials(input, tbl, prefix, method_3f) + for k in utils.allpairs(tbl) do + local k0 + if ((tbl == env) or (tbl == env.___replLocals___)) then + k0 = scope.unmanglings[k] + else + k0 = k + end + if ((#matches < 2000) and (type(k0) == "string") and (input == k0:sub(0, #input)) and (not method_3f or ("function" == type(tbl[k0])))) then + local function _487_() + if method_3f then + return (prefix .. ":" .. k0) + else + return (prefix .. k0) + end + end + table.insert(matches, _487_()) + end + end + return nil + end + local function descend(input, tbl, prefix, add_matches, method_3f) + local splitter + if method_3f then + splitter = "^([^:]+):(.*)" + else + splitter = "^([^.]+)%.(.*)" + end + local head, tail = input:match(splitter) + local raw_head + if ((tbl == env) or (tbl == env.___replLocals___)) then + raw_head = scope.manglings[head] + else + raw_head = head + end + if (type(tbl[raw_head]) == "table") then + stop_looking_3f = true + if method_3f then + return add_partials(tail, tbl[raw_head], (prefix .. head), true) + else + return add_matches(tail, tbl[raw_head], (prefix .. head)) + end + end + end + local function add_matches(input, tbl, prefix) + local prefix0 + if prefix then + prefix0 = (prefix .. ".") + else + prefix0 = "" + end + if (not input:find("%.") and input:find(":")) then + return descend(input, tbl, prefix0, add_matches, true) + elseif not input:find("%.") then + return add_partials(input, tbl, prefix0) + else + return descend(input, tbl, prefix0, add_matches, false) + end + end + for _, source in ipairs({scope.specials, scope.macros, (env.___replLocals___ or {}), env, env._G}) do + add_matches(input_fragment, source) + if stop_looking_3f then + break + end + end + return matches + end local commands = {} local function command_3f(input) return input:match("^%s*,") end local function command_docs() - local _0_ + local _496_ do - local tbl_0_ = {} + local tbl_13_auto = {} for name, f in pairs(commands) do - tbl_0_[(#tbl_0_ + 1)] = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented")) + tbl_13_auto[(#tbl_13_auto + 1)] = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented")) end - _0_ = tbl_0_ + _496_ = tbl_13_auto end - return table.concat(_0_, "\n") + return table.concat(_496_, "\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 _0_0, _1_0 = pcall(specials["load-code"]("return require(...)", env), module_name) - if ((_0_0 == true) and (nil ~= _1_0)) then - local old = _1_0 - local _ = nil + local _497_, _498_ = pcall(specials["load-code"]("return require(...)", env), module_name) + if ((_497_ == true) and (nil ~= _498_)) then + local old = _498_ + local _ package.loaded[module_name] = nil _ = nil local ok, new = pcall(require, module_name) - local new0 = nil + local new0 if not ok then on_values({new}) new0 = old @@ -230,32 +311,38 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) old[k] = v end for k in pairs(old) do - if (nil == new0[k]) then + if (nil == (new0)[k]) then old[k] = nil end end package.loaded[module_name] = old end return on_values({"ok"}) - elseif ((_0_0 == false) and (nil ~= _1_0)) then - local msg = _1_0 - local function _3_() - local _2_0 = msg:gsub("\n.*", "") - return _2_0 + elseif ((_497_ == false) and (nil ~= _498_)) then + local msg = _498_ + local function _503_() + local _502_ = msg:gsub("\n.*", "") + return _502_ end - return on_error("Runtime", _3_()) + return on_error("Runtime", _503_()) + end + end + local function run_command(read, on_error, f) + local _505_, _506_, _507_ = pcall(read) + if ((_505_ == true) and (_506_ == true) and (nil ~= _507_)) then + local val = _507_ + return f(val) + elseif ((_505_ == false) and true and true) then + local _3fparse_ok = _506_ + local _3ferr = _507_ + return on_error("Parse", "Couldn't parse input.") end end commands.reload = function(env, read, on_values, on_error) - local _0_0, _1_0, _2_0 = pcall(read) - if ((_0_0 == true) and (_1_0 == true) and (nil ~= _2_0)) then - local module_sym = _2_0 - return reload(tostring(module_sym), env, on_values, on_error) - elseif ((_0_0 == false) and true and true) then - local _3fparse_ok = _1_0 - local _3fmsg = _2_0 - return on_error("Parse", (_3fmsg or _3fparse_ok)) + local function _509_(_241) + return reload(tostring(_241), env, on_values, on_error) end + return run_command(read, on_error, _509_) end do end (compiler.metadata):set(commands.reload, "fnl/docstring", "Reload the specified module.") commands.reset = function(env, _, on_values) @@ -263,13 +350,121 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) 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 _510_() + return on_values(completer(env, scope, string.char(unpack(chars)):gsub(",complete +", ""):sub(1, -2))) + end + return run_command(read, on_error, _510_) + end + do end (compiler.metadata):set(commands.complete, "fnl/docstring", "Print all possible completions for a given input symbol.") + local function apropos_2a(pattern, module, prefix, seen, names) + for name, module0 in pairs(module) do + if (("string" == type(name)) and (package ~= module0)) then + local _511_ = type(module0) + if (_511_ == "function") then + if ((prefix .. name)):match(pattern) then + table.insert(names, (prefix .. name)) + end + elseif (_511_ == "table") then + if not seen[module0] then + local _514_ + do + local _513_ = seen + _513_[module0] = true + _514_ = _513_ + end + apropos_2a(pattern, module0, (prefix .. name:gsub("%.", "/") .. "."), _514_, names) + end + end + end + end + return names + end + local function apropos(pattern) + local names = apropos_2a(pattern, package.loaded, "", {}, {}) + local tbl_13_auto = {} + for _, name in ipairs(names) do + tbl_13_auto[(#tbl_13_auto + 1)] = name:gsub("^_G%.", "") + end + return tbl_13_auto + end + commands.apropos = function(env, read, on_values, on_error, scope) + local function _518_(_241) + return on_values(apropos(tostring(_241))) + end + return run_command(read, on_error, _518_) + end + do end (compiler.metadata):set(commands.apropos, "fnl/docstring", "Print all functions matching a pattern in all loaded modules.") + local function apropos_follow_path(path) + local paths + do + local tbl_13_auto = {} + for p in path:gmatch("[^%.]+") do + tbl_13_auto[(#tbl_13_auto + 1)] = p + end + paths = tbl_13_auto + end + local tgt = package.loaded + for _, path0 in ipairs(paths) do + local _520_ + do + local _519_ = path0:gsub("%/", ".") + _520_ = _519_ + end + tgt = tgt[_520_] + if (nil == tgt) then + break + end + end + return tgt + end + local function apropos_doc(pattern) + local names = {} + for _, path in ipairs(apropos(".*")) do + local tgt = apropos_follow_path(path) + if ("function" == type(tgt)) then + local _522_ = (compiler.metadata):get(tgt, "fnl/docstring") + if (nil ~= _522_) then + local docstr = _522_ + if docstr:match(pattern) then + table.insert(names, path) + end + end + end + end + return names + end + commands["apropos-doc"] = function(env, read, on_values, on_error, scope) + local function _526_(_241) + return on_values(apropos_doc(tostring(_241))) + end + return run_command(read, on_error, _526_) + end + do end (compiler.metadata):set(commands["apropos-doc"], "fnl/docstring", "Print all functions that match the pattern in their docs") + local function apropos_show_docs(pattern) + for _, path in ipairs(apropos(pattern)) do + local tgt = apropos_follow_path(path) + if (("function" == type(tgt)) and (compiler.metadata):get(tgt, "fnl/docstring")) then + print(specials.doc(tgt, path)) + print() + end + end + return nil + end + commands["apropos-show-docs"] = function(env, read, _, on_error, scope) + local function _528_(_241) + return apropos_show_docs(tostring(_241)) + end + return run_command(read, on_error, _528_) + end + do end (compiler.metadata):set(commands["apropos-show-docs"], "fnl/docstring", "Print all documentations matching a pattern in function name") local function load_plugin_commands() if (utils.root and utils.root.options and utils.root.options.plugins) then for _, plugin in ipairs(utils.root.options.plugins) do for name, f in pairs(plugin) do - local _0_0 = name:match("^repl%-command%-(.*)") - if (nil ~= _0_0) then - local cmd_name = _0_0 + local _529_ = name:match("^repl%-command%-(.*)") + if (nil ~= _529_) then + local cmd_name = _529_ commands[cmd_name] = (commands[cmd_name] or f) end end @@ -277,16 +472,16 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) return nil end end - local function run_command(input, read, loop, env, on_values, on_error) + local function run_command_loop(input, read, loop, env, on_values, on_error, scope, chars) load_plugin_commands() local command_name = input:match(",([^%s/]+)") do - local _0_0 = commands[command_name] - if (nil ~= _0_0) then - local command = _0_0 - command(env, read, on_values, on_error) + local _532_ = commands[command_name] + if (nil ~= _532_) then + local command = _532_ + command(env, read, on_values, on_error, scope, chars) else - local _ = _0_0 + local _ = _532_ if ("exit" ~= command_name) then on_values({"Unknown command", command_name}) end @@ -296,55 +491,9 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) return loop() end end - local function completer(env, scope, text) - local matches = {} - local input_fragment = text:gsub(".*[%s)(]+", "") - local function add_partials(input, tbl, prefix) - for k in utils.allpairs(tbl) do - local k0 = nil - if ((tbl == env) or (tbl == env.___replLocals___)) then - k0 = scope.unmanglings[k] - else - k0 = k - end - if ((#matches < 2000) and (type(k0) == "string") and (input == k0:sub(0, #input))) then - table.insert(matches, (prefix .. k0)) - end - end - return nil - end - local function add_matches(input, tbl, prefix) - local prefix0 = nil - if prefix then - prefix0 = (prefix .. ".") - else - prefix0 = "" - end - if not input:find("%.") then - return add_partials(input, tbl, prefix0) - else - local head, tail = input:match("^([^.]+)%.(.*)") - local raw_head = nil - if ((tbl == env) or (tbl == env.___replLocals___)) then - raw_head = scope.manglings[head] - else - raw_head = head - end - if (type(tbl[raw_head]) == "table") then - return add_matches(tail, tbl[raw_head], (prefix0 .. head)) - end - end - end - add_matches(input_fragment, (scope.specials or {})) - add_matches(input_fragment, (scope.macros or {})) - add_matches(input_fragment, (env.___replLocals___ or {})) - add_matches(input_fragment, env) - add_matches(input_fragment, (env._ENV or env._G or {})) - return matches - end local function repl(options) local old_root_options = utils.root.options - local env = nil + local env if options.env then env = specials["wrap-env"](options.env) else @@ -352,7 +501,7 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) end local save_locals_3f = ((options.saveLocals ~= false) and env.debug and env.debug.getlocal) local opts = {} - local _ = nil + local _ for k, v in pairs(options) do opts[k] = v end @@ -364,22 +513,27 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) local byte_stream, clear_stream = parser.granulate(read_chunk) local chars = {} local read, reset = nil, nil - local function _1_(parser_state) + local function _537_(parser_state) local c = byte_stream(parser_state) table.insert(chars, c) return c end - read, reset = parser.parser(_1_) + read, reset = parser.parser(_537_) local scope = compiler["make-scope"]() opts.useMetadata = (options.useMetadata ~= false) if (opts.allowedGlobals == nil) then opts.allowedGlobals = specials["current-global-names"](opts.env) end if opts.registerCompleter then - local function _3_(...) - return completer(env, scope, ...) + local function _541_() + local _539_ = env + local _540_ = scope + local function _542_(...) + return completer(_539_, _540_, ...) + end + return _542_ end - opts.registerCompleter(_3_) + opts.registerCompleter(_541_()) end local function print_values(...) local vals = {...} @@ -395,46 +549,57 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) chars[k] = nil end local ok, parse_ok_3f, x = pcall(read) - local src_string = string.char((table.unpack or _G.unpack)(chars)) + local src_string = string.char(unpack(chars)) + reset() utils.root.options = opts if not ok then on_error("Parse", parse_ok_3f) clear_stream() - reset() return loop() elseif command_3f(src_string) then - return run_command(src_string, read, loop, env, on_values, on_error) + return run_command_loop(src_string, read, loop, env, on_values, on_error, scope, chars) else if parse_ok_3f then do - local _4_0, _5_0 = pcall(compiler.compile, x, {["assert-compile"] = opts["assert-compile"], ["parse-error"] = opts["parse-error"], correlate = opts.correlate, moduleName = opts.moduleName, scope = scope, source = src_string, useMetadata = opts.useMetadata}) - if ((_4_0 == false) and (nil ~= _5_0)) then - local msg = _5_0 + local _544_, _545_ = nil, nil + local function _547_() + local _546_ = opts + _546_["env"] = env + _546_["source"] = src_string + _546_["scope"] = scope + return _546_ + end + _544_, _545_ = pcall(compiler.compile, x, _547_()) + if ((_544_ == false) and (nil ~= _545_)) then + local msg = _545_ clear_stream() on_error("Compile", msg) - elseif ((_4_0 == true) and (nil ~= _5_0)) then - local src = _5_0 - local src0 = nil + elseif ((_544_ == true) and (nil ~= _545_)) then + local src = _545_ + local src0 if save_locals_3f then src0 = splice_save_locals(env, src) else src0 = src end - local _7_0, _8_0 = pcall(specials["load-code"], src0, env) - if ((_7_0 == false) and (nil ~= _8_0)) then - local msg = _8_0 + local _549_, _550_ = pcall(specials["load-code"], src0, env) + if ((_549_ == false) and (nil ~= _550_)) then + local msg = _550_ clear_stream() on_error("Lua Compile", msg, src0) - elseif (true and (nil ~= _8_0)) then - local _0 = _7_0 - local chunk = _8_0 - local function _9_() + elseif (true and (nil ~= _550_)) then + local _0 = _549_ + local chunk = _550_ + local function _551_() return print_values(chunk()) end - local function _10_(...) - return on_error("Runtime", ...) + local function _552_() + local function _553_(...) + return on_error("Runtime", ...) + end + return _553_ end - xpcall(_9_, _10_) + xpcall(_551_, _552_()) end end end @@ -447,390 +612,6 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) end return repl end -package.preload["fennel.view"] = package.preload["fennel.view"] or function(...) - local type_order = {["function"] = 5, boolean = 2, number = 1, string = 3, table = 4, thread = 7, userdata = 6} - local function sort_keys(_0_0, _1_0) - local _1_ = _0_0 - local a = _1_[1] - local _2_ = _1_0 - local b = _2_[1] - local ta = type(a) - local tb = type(b) - if ((ta == tb) and ((ta == "string") or (ta == "number"))) then - return (a < b) - else - local dta = type_order[ta] - local dtb = type_order[tb] - if (dta and dtb) then - return (dta < dtb) - elseif dta then - return true - elseif dtb then - return false - else - return (ta < tb) - end - end - end - local function table_kv_pairs(t) - local assoc_3f = false - local i = 1 - local kv = {} - local insert = table.insert - for k, v in pairs(t) do - if ((type(k) ~= "number") or (k ~= i)) then - assoc_3f = true - end - i = (i + 1) - insert(kv, {k, v}) - end - table.sort(kv, sort_keys) - if (#kv == 0) then - return kv, "empty" - else - local function _2_() - if assoc_3f then - return "table" - else - return "seq" - end - end - return kv, _2_() - end - end - local function count_table_appearances(t, appearances) - if (type(t) == "table") then - if not appearances[t] then - appearances[t] = 1 - for k, v in pairs(t) do - count_table_appearances(k, appearances) - count_table_appearances(v, appearances) - end - else - appearances[t] = ((appearances[t] or 0) + 1) - end - end - return appearances - end - local function save_table(t, seen) - local seen0 = (seen or {len = 0}) - local id = (seen0.len + 1) - if not seen0[t] then - seen0[t] = id - seen0.len = id - end - return seen0 - end - local function detect_cycle(t, seen, _3fk) - if ("table" == type(t)) then - seen[t] = true - local _2_0, _3_0 = next(t, _3fk) - if ((nil ~= _2_0) and (nil ~= _3_0)) then - local k = _2_0 - local v = _3_0 - return (seen[k] or detect_cycle(k, seen) or seen[v] or detect_cycle(v, seen) or detect_cycle(t, seen, k)) - end - end - end - local function visible_cycle_3f(t, options) - return (options["detect-cycles?"] and detect_cycle(t, {}) and save_table(t, options.seen) and (1 < (options.appearances[t] or 0))) - end - local function table_indent(t, indent, id) - local opener_length = nil - if id then - opener_length = (#tostring(id) + 2) - else - opener_length = 1 - end - return (indent + opener_length) - end - local pp = nil - local function concat_table_lines(elements, options, multiline_3f, indent, table_type, prefix) - local indent_str = ("\n" .. string.rep(" ", indent)) - local open = nil - local function _2_() - if ("seq" == table_type) then - return "[" - else - return "{" - end - end - open = ((prefix or "") .. _2_()) - local close = nil - if ("seq" == table_type) then - close = "]" - else - close = "}" - end - local oneline = (open .. table.concat(elements, " ") .. close) - if (not options["one-line?"] and (multiline_3f or ((indent + #oneline) > options["line-length"]))) then - return (open .. table.concat(elements, indent_str) .. close) - else - return oneline - end - end - local function pp_associative(t, kv, options, indent, key_3f) - local multiline_3f = false - local id = options.seen[t] - if (options.level >= options.depth) then - return "{...}" - elseif (id and options["detect-cycles?"]) then - return ("@" .. id .. "{...}") - else - local visible_cycle_3f0 = visible_cycle_3f(t, options) - local id0 = (visible_cycle_3f0 and options.seen[t]) - local indent0 = table_indent(t, indent, id0) - local slength = nil - local function _3_() - local _2_0 = rawget(_G, "utf8") - if _2_0 then - return _2_0.len - else - return _2_0 - end - end - local function _4_(_241) - return #_241 - end - slength = ((options["utf8?"] and _3_()) or _4_) - local prefix = nil - if visible_cycle_3f0 then - prefix = ("@" .. id0) - else - prefix = "" - end - local items = nil - do - local tbl_0_ = {} - for _, _6_0 in pairs(kv) do - local _7_ = _6_0 - local k = _7_[1] - local v = _7_[2] - local _8_ - do - local k0 = pp(k, options, (indent0 + 1), true) - local v0 = pp(v, options, (indent0 + slength(k0) + 1)) - multiline_3f = (multiline_3f or k0:find("\n") or v0:find("\n")) - _8_ = (k0 .. " " .. v0) - end - tbl_0_[(#tbl_0_ + 1)] = _8_ - end - items = tbl_0_ - end - return concat_table_lines(items, options, multiline_3f, indent0, "table", prefix) - end - end - local function pp_sequence(t, kv, options, indent) - local multiline_3f = false - local id = options.seen[t] - if (options.level >= options.depth) then - return "[...]" - elseif (id and options["detect-cycles?"]) then - return ("@" .. id .. "[...]") - else - local visible_cycle_3f0 = visible_cycle_3f(t, options) - local id0 = (visible_cycle_3f0 and options.seen[t]) - local indent0 = table_indent(t, indent, id0) - local prefix = nil - if visible_cycle_3f0 then - prefix = ("@" .. id0) - else - prefix = "" - end - local items = nil - do - local tbl_0_ = {} - for _, _3_0 in pairs(kv) do - local _4_ = _3_0 - local _0 = _4_[1] - local v = _4_[2] - local _5_ - do - local v0 = pp(v, options, indent0) - multiline_3f = (multiline_3f or v0:find("\n")) - _5_ = v0 - end - tbl_0_[(#tbl_0_ + 1)] = _5_ - end - items = tbl_0_ - end - return concat_table_lines(items, options, multiline_3f, indent0, "seq", prefix) - end - end - local function concat_lines(lines, options, indent, force_multi_line_3f) - if (#lines == 0) then - if options["empty-as-sequence?"] then - return "[]" - else - return "{}" - end - else - local oneline = nil - local _2_ - do - local tbl_0_ = {} - for _, line in ipairs(lines) do - tbl_0_[(#tbl_0_ + 1)] = line:gsub("^%s+", "") - end - _2_ = tbl_0_ - end - oneline = table.concat(_2_, " ") - if (not options["one-line?"] and (force_multi_line_3f or oneline:find("\n") or ((indent + #oneline) > options["line-length"]))) then - return table.concat(lines, ("\n" .. string.rep(" ", indent))) - else - return oneline - end - end - end - local function pp_metamethod(t, metamethod, options, indent) - if (options.level >= options.depth) then - if options["empty-as-sequence?"] then - return "[...]" - else - return "{...}" - end - else - local _ = nil - local function _2_(_241) - return visible_cycle_3f(_241, options) - end - options["visible-cycle?"] = _2_ - _ = nil - local lines, force_multi_line_3f = metamethod(t, pp, options, indent) - options["visible-cycle?"] = nil - local _3_0 = type(lines) - if (_3_0 == "string") then - return lines - elseif (_3_0 == "table") then - return concat_lines(lines, options, indent, force_multi_line_3f) - else - local _0 = _3_0 - return error("__fennelview metamethod must return a table of lines") - end - end - end - local function pp_table(x, options, indent) - options.level = (options.level + 1) - local x0 = nil - do - local _2_0 = nil - if options["metamethod?"] then - local _3_0 = x - if _3_0 then - local _4_0 = getmetatable(_3_0) - if _4_0 then - _2_0 = _4_0.__fennelview - else - _2_0 = _4_0 - end - else - _2_0 = _3_0 - end - else - _2_0 = nil - end - if (nil ~= _2_0) then - local metamethod = _2_0 - x0 = pp_metamethod(x, metamethod, options, indent) - else - local _ = _2_0 - local _4_0, _5_0 = table_kv_pairs(x) - if (true and (_5_0 == "empty")) then - local _0 = _4_0 - if options["empty-as-sequence?"] then - x0 = "[]" - else - x0 = "{}" - end - elseif ((nil ~= _4_0) and (_5_0 == "table")) then - local kv = _4_0 - x0 = pp_associative(x, kv, options, indent) - elseif ((nil ~= _4_0) and (_5_0 == "seq")) then - local kv = _4_0 - x0 = pp_sequence(x, kv, options, indent) - else - x0 = nil - end - end - end - options.level = (options.level - 1) - return x0 - end - local function number__3estring(n) - local _2_0 = string.gsub(tostring(n), ",", ".") - return _2_0 - end - local function colon_string_3f(s) - return s:find("^[-%w?^_!$%&*+./@|<=>]+$") - end - local function pp_string(str, options, indent) - local escs = nil - local _2_ - if (options["escape-newlines?"] and (#str < (options["line-length"] - indent))) then - _2_ = "\\n" - else - _2_ = "\n" - end - local function _4_(_241, _242) - return ("\\%03d"):format(_242:byte()) - end - escs = setmetatable({["\""] = "\\\"", ["\11"] = "\\v", ["\12"] = "\\f", ["\13"] = "\\r", ["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\\"] = "\\\\", ["\n"] = _2_}, {__index = _4_}) - return ("\"" .. str:gsub("[%c\\\"]", escs) .. "\"") - end - local function make_options(t, options) - local defaults = {["detect-cycles?"] = true, ["empty-as-sequence?"] = false, ["escape-newlines?"] = false, ["line-length"] = 80, ["metamethod?"] = true, ["one-line?"] = false, ["prefer-colon?"] = false, ["utf8?"] = true, depth = 128} - local overrides = {appearances = count_table_appearances(t, {}), level = 0, seen = {len = 0}} - for k, v in pairs((options or {})) do - defaults[k] = v - end - for k, v in pairs(overrides) do - defaults[k] = v - end - return defaults - end - local function _2_(x, options, indent, colon_3f) - local indent0 = (indent or 0) - local options0 = (options or make_options(x)) - local tv = type(x) - local function _4_() - local _3_0 = getmetatable(x) - if _3_0 then - return _3_0.__fennelview - else - return _3_0 - end - end - if ((tv == "table") or ((tv == "userdata") and _4_())) then - return pp_table(x, options0, indent0) - elseif (tv == "number") then - return number__3estring(x) - else - local function _5_() - if (colon_3f ~= nil) then - return colon_3f - elseif ("function" == type(options0["prefer-colon?"])) then - return options0["prefer-colon?"](x) - else - return options0["prefer-colon?"] - end - end - if ((tv == "string") and colon_string_3f(x) and _5_()) then - return (":" .. x) - elseif (tv == "string") then - return pp_string(x, options0, indent0) - elseif ((tv == "boolean") or (tv == "nil")) then - return tostring(x) - else - return ("#<" .. tostring(x) .. ">") - end - end - end - pp = _2_ - local function view(x, options) - return pp(x, make_options(x, options), 0) - end - return view -end package.preload["fennel.specials"] = package.preload["fennel.specials"] or function(...) local utils = require("fennel.utils") local view = require("fennel.view") @@ -839,14 +620,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local unpack = (table.unpack or _G.unpack) local SPECIALS = compiler.scopes.global.specials local function wrap_env(env) - local function _0_(_, key) + local function _309_(_, key) if (type(key) == "string") then return env[compiler["global-unmangling"](key)] else return env[key] end end - local function _1_(_, key, value) + local function _311_(_, key, value) if (type(key) == "string") then env[compiler["global-unmangling"](key)] = value return nil @@ -855,22 +636,47 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return nil end end - local function _2_() + local function _313_() local function putenv(k, v) - local _3_ + local _314_ if (type(k) == "string") then - _3_ = compiler["global-unmangling"](k) + _314_ = compiler["global-unmangling"](k) else - _3_ = k + _314_ = k end - return _3_, v + return _314_, v end return next, utils.kvmap(env, putenv), nil end - return setmetatable({}, {__index = _0_, __newindex = _1_, __pairs = _2_}) + return setmetatable({}, {__index = _309_, __newindex = _311_, __pairs = _313_}) end local function current_global_names(env) - return utils.kvmap((env or _G), compiler["global-unmangling"]) + local mt + do + local _316_ = getmetatable(env) + local function _317_() + local __pairs = (_316_).__pairs + return __pairs + end + if (((_G.type(_316_) == "table") and true) and _317_()) then + local __pairs = (_316_).__pairs + local tbl_10_auto = {} + for k, v in __pairs(env) do + local _318_, _319_ = k, v + if ((nil ~= _318_) and (nil ~= _319_)) then + local k_11_auto = _318_ + local v_12_auto = _319_ + tbl_10_auto[k_11_auto] = v_12_auto + end + end + mt = tbl_10_auto + elseif (_316_ == nil) then + mt = (env or _G) + else + mt = nil + end + end + return (mt and utils.kvmap(mt, compiler["global-unmangling"])) end local function load_code(code, environment, filename) local environment0 = (environment or rawget(_G, "_ENV") or _G) @@ -890,20 +696,20 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 {"#"}), " ") - local _0_ + local _323_ if (#arglist > 0) then - _0_ = " " + _323_ = " " else - _0_ = "" + _323_ = "" end - return string.format("(%s%s%s)\n %s", name, _0_, arglist, docstring) + return string.format("(%s%s%s)\n %s", name, _323_, arglist, docstring) else return string.format("%s\n %s", name, docstring) end end end - local function doc_special(name, arglist, docstring) - compiler.metadata[SPECIALS[name]] = {["fnl/arglist"] = arglist, ["fnl/docstring"] = docstring} + 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, start) @@ -945,7 +751,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local syms = {} for i = 1, opts.nval do local s = ((pre_syms and pre_syms[i]) or compiler.gensym(scope)) - syms[i] = s + do end (syms)[i] = s retexprs[i] = utils.expr(s, "sym") end local outer_target = table.concat(syms, ", ") @@ -954,7 +760,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return compile_body(outer_target, opts.tail) else local fname = compiler.gensym(scope) - local fargs = nil + local fargs if scope.vararg then fargs = "..." else @@ -965,7 +771,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return compile_body(nil, true, utils.expr((fname .. "(" .. fargs .. ")"), "statement")) end end - doc_special("do", {"..."}, "Evaluate multiple forms; return last value.") + doc_special("do", {"..."}, "Evaluate multiple forms; return last value.", true) SPECIALS.values = function(ast, scope, parent) local len = #ast local exprs = {} @@ -984,25 +790,25 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local function deep_tostring(x, key_3f) local elems = {} if utils["sequence?"](x) then - local _0_ + local _332_ do - local tbl_0_ = {} + local tbl_13_auto = {} for _, v in ipairs(x) do - tbl_0_[(#tbl_0_ + 1)] = deep_tostring(v) + tbl_13_auto[(#tbl_13_auto + 1)] = deep_tostring(v) end - _0_ = tbl_0_ + _332_ = tbl_13_auto end - return ("[" .. table.concat(_0_, " ") .. "]") + return ("[" .. table.concat(_332_, " ") .. "]") elseif utils["table?"](x) then - local _0_ + local _333_ do - local tbl_0_ = {} + local tbl_13_auto = {} for k, v in pairs(x) do - tbl_0_[(#tbl_0_ + 1)] = (deep_tostring(k, true) .. " " .. deep_tostring(v)) + tbl_13_auto[(#tbl_13_auto + 1)] = (deep_tostring(k, true) .. " " .. deep_tostring(v)) end - _0_ = tbl_0_ + _333_ = tbl_13_auto end - return ("{" .. table.concat(_0_, " ") .. "}") + return ("{" .. table.concat(_333_, " ") .. "}") elseif (key_3f and (type(x) == "string") and x:find("^[-%w?\\^_!$%&*+./@:|<=>]+$")) then return (":" .. x) elseif (type(x) == "string") then @@ -1013,11 +819,11 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end local function set_fn_metadata(arg_list, docstring, parent, fn_name) if utils.root.options.useMetadata then - local args = nil - local function _0_(_241) + local args + local function _335_(_241) return ("\"%s\""):format(deep_tostring(_241)) end - args = utils.map(arg_list, _0_) + args = utils.map(arg_list, _335_) local meta_fields = {"\"fnl/arglist\"", ("{" .. table.concat(args, ", ") .. "}")} if docstring then table.insert(meta_fields, "\"fnl/docstring\"") @@ -1029,13 +835,13 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end local function get_fn_name(ast, scope, fn_name, multi) if (fn_name and (fn_name[1] ~= "nil")) then - local _0_ + local _338_ if not multi then - _0_ = compiler["declare-local"](fn_name, {}, scope, ast) + _338_ = compiler["declare-local"](fn_name, {}, scope, ast) else - _0_ = compiler["symbol-to-expression"](fn_name, scope)[1] + _338_ = (compiler["symbol-to-expression"](fn_name, scope))[1] end - return _0_, not multi, 3 + return _338_, not multi, 3 else return nil, true, 2 end @@ -1044,13 +850,13 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 _0_ + local _341_ if local_3f then - _0_ = "local function %s(%s)" + _341_ = "local function %s(%s)" else - _0_ = "%s = function(%s)" + _341_ = "%s = function(%s)" end - compiler.emit(parent, string.format(_0_, fn_name, table.concat(arg_name_list, ", ")), ast) + compiler.emit(parent, string.format(_341_, fn_name, table.concat(arg_name_list, ", ")), ast) compiler.emit(parent, f_chunk, ast) compiler.emit(parent, "end", ast) set_fn_metadata(arg_list, docstring, parent, fn_name) @@ -1062,11 +868,11 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, true, arg_name_list, arg_list, docstring) end SPECIALS.fn = function(ast, scope, parent) - local f_scope = nil + local f_scope do - local _0_0 = compiler["make-scope"](scope) - _0_0["vararg"] = false - f_scope = _0_0 + local _343_ = compiler["make-scope"](scope) + do end (_343_)["vararg"] = false + f_scope = _343_ end local f_chunk = {} local fn_sym = utils["sym?"](ast[2]) @@ -1079,7 +885,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct compiler.assert((arg == arg_list[#arg_list]), "expected vararg as last parameter", ast) f_scope.vararg = true return "..." - elseif (utils["sym?"](arg) and (utils.deref(arg) ~= "nil") and not utils["multi-sym?"](utils.deref(arg))) then + 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)) @@ -1103,26 +909,44 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return compile_anonymous_fn(ast, f_scope, f_chunk, parent, index0, arg_name_list, arg_list, docstring, scope) end end - doc_special("fn", {"name?", "args", "docstring?", "..."}, "Function syntax. May optionally include a name and docstring.\nIf a name is provided, the function will be bound in the current scope.\nWhen called with the wrong number of args, excess args will be discarded\nand lacking args will be nil, use lambda for arity-checked functions.") + doc_special("fn", {"name?", "args", "docstring?", "..."}, "Function syntax. May optionally include a name and docstring.\nIf a name is provided, the function will be bound in the current scope.\nWhen called with the wrong number of args, excess args will be discarded\nand lacking args will be nil, use lambda for arity-checked functions.", true) SPECIALS.lua = function(ast, _, parent) compiler.assert(((#ast == 2) or (#ast == 3)), "expected 1 or 2 arguments", ast) - if (ast[2] ~= nil) then + local _348_ + do + local _347_ = utils["sym?"](ast[2]) + if _347_ then + _348_ = tostring(_347_) + else + _348_ = _347_ + end + end + if ("nil" ~= _348_) then table.insert(parent, {ast = ast, leaf = tostring(ast[2])}) end - if (ast[3] ~= nil) then + local _352_ + do + local _351_ = utils["sym?"](ast[3]) + if _351_ then + _352_ = tostring(_351_) + else + _352_ = _351_ + end + end + if ("nil" ~= _352_) then return tostring(ast[3]) end end SPECIALS.doc = function(ast, scope, parent) assert(utils.root.options.useMetadata, "can't look up doc with metadata disabled.") compiler.assert((#ast == 2), "expected one argument", ast) - local target = utils.deref(ast[2]) + local target = tostring(ast[2]) local special_or_macro = (scope.specials[target] or scope.macros[target]) if special_or_macro then return ("print(%q)"):format(doc_2a(special_or_macro, target)) else - local _0_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) - local value = _0_[1] + local _let_355_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) + local value = _let_355_[1] return ("print(require('%s').doc(%s, '%s'))"):format((utils.root.options.moduleName or "fennel"), tostring(value), tostring(ast[2])) end end @@ -1130,8 +954,8 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local function dot(ast, scope, parent) compiler.assert((1 < #ast), "expected table argument", ast) local len = #ast - local _0_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) - local lhs = _0_[1] + local _let_357_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) + local lhs = _let_357_[1] if (len == 2) then return tostring(lhs) else @@ -1141,8 +965,8 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct if ((type(index) == "string") and utils["valid-lua-identifier?"](index)) then table.insert(indices, ("." .. index)) else - local _1_ = compiler.compile1(index, scope, parent, {nval = 1}) - local index0 = _1_[1] + local _let_358_ = compiler.compile1(index, scope, parent, {nval = 1}) + local index0 = _let_358_[1] table.insert(indices, ("[" .. tostring(index0) .. "]")) end end @@ -1186,10 +1010,27 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return nil end doc_special("var", {"name", "val"}, "Introduce new mutable local.") + local function kv_3f(t) + local _362_ + do + local tbl_13_auto = {} + for k in pairs(t) do + local _363_ + if not ("number" == type(k)) then + _363_ = k + else + _363_ = nil + end + tbl_13_auto[(#tbl_13_auto + 1)] = _363_ + end + _362_ = tbl_13_auto + end + return (_362_)[1] + end SPECIALS.let = function(ast, scope, parent, opts) local bindings = ast[2] local pre_syms = {} - compiler.assert((utils["list?"](bindings) or utils["table?"](bindings)), "expected binding table", ast) + compiler.assert((utils["table?"](bindings) and not kv_3f(bindings)), "expected binding sequence", bindings) compiler.assert(((#bindings % 2) == 0), "expected even number of name/value bindings", ast[2]) compiler.assert((#ast >= 3), "expected body expression", ast[1]) for _ = 1, (opts.nval or 0) do @@ -1202,25 +1043,42 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") + 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 _367_() + local _366_ = get_prev_line(parent) + if (nil ~= _366_) then + local prev_line = _366_ + return prev_line:match("%)$") + end + end + return (rootstr:match("^{") or _367_()) + end SPECIALS.tset = function(ast, scope, parent) compiler.assert((#ast > 3), "expected table, key, and value arguments", ast) - local root = compiler.compile1(ast[2], scope, parent, {nval = 1})[1] + local root = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1] local keys = {} for i = 3, (#ast - 1) do - local _0_ = compiler.compile1(ast[i], scope, parent, {nval = 1}) - local key = _0_[1] + local _let_369_ = compiler.compile1(ast[i], scope, parent, {nval = 1}) + local key = _let_369_[1] table.insert(keys, tostring(key)) end - local value = compiler.compile1(ast[#ast], scope, parent, {nval = 1})[1] + local value = (compiler.compile1(ast[#ast], scope, parent, {nval = 1}))[1] local rootstr = tostring(root) - local fmtstr = nil - if rootstr:match("^{") then + 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(tostring(root), table.concat(keys, "]["), tostring(value)), ast) + 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) @@ -1231,7 +1089,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local target_exprs = {} for i = 1, opts.nval do local s = compiler.gensym(scope) - accum[i] = s + do end (accum)[i] = s target_exprs[i] = utils.expr(s, "sym") end return "target", opts.tail, table.concat(accum, ", "), target_exprs @@ -1267,14 +1125,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local last_buffer = buffer for i = 1, #branches do local branch = branches[i] - local fstr = nil + 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 = nil + local cond_line if ((cond == "true") and branch.nested and (i == #branches) and not has_else_3f) then cond_line = "else" else @@ -1298,7 +1156,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct compiler.emit(last_buffer, ("%s = nil"):format(inner_target), ast) end compiler.emit(last_buffer, "end", ast) - elseif not branches[(i + 1)].nested then + elseif not (branches[(i + 1)]).nested then local next_buffer = {} compiler.emit(last_buffer, "else", ast) compiler.emit(last_buffer, next_buffer, ast) @@ -1335,25 +1193,27 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end local function compile_until(condition, scope, chunk) if condition then - local _0_ = compiler.compile1(condition, scope, chunk, {nval = 1}) - local condition_lua = _0_[1] - return compiler.emit(chunk, ("if %s then break end"):format(tostring(condition_lua)), condition) + local _let_379_ = compiler.compile1(condition, scope, chunk, {nval = 1}) + local condition_lua = _let_379_[1] + return compiler.emit(chunk, ("if %s then break end"):format(tostring(condition_lua)), utils.expr(condition, "expression")) end end SPECIALS.each = function(ast, scope, parent) compiler.assert((#ast >= 3), "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(("string" ~= type(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)) - destructures[raw] = v + do end (destructures)[raw] = v return compiler["declare-local"](raw, {}, sub_scope, ast) end end @@ -1371,16 +1231,16 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") + 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 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]) - parent[i] = nil + 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) @@ -1392,7 +1252,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") + 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]) @@ -1402,8 +1262,9 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local chunk = {} compiler.assert(utils["sym?"](binding_sym), ("unable to bind %s %s"):format(type(binding_sym), tostring(binding_sym)), ast[2]) compiler.assert((#ast >= 3), "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], sub_scope, parent, {nval = 1})[1]) + range_args[i] = tostring((compiler.compile1(ranges[i], sub_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) @@ -1412,14 +1273,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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).") + 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 _0_ = ast - local _ = _0_[1] - local _0 = _0_[2] - local method_string = _0_[3] - local call_string = nil - if ((target.type == "literal") or (target.type == "expression")) then + local _let_383_ = ast + local _ = _let_383_[1] + local _0 = _let_383_[2] + local method_string = _let_383_[3] + local call_string + if ((target.type == "literal") or (target.type == "varg") or (target.type == "expression")) then call_string = "(%s):%s(%s)" else call_string = "%s:%s(%s)" @@ -1427,30 +1288,30 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 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 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 _0_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) - local target = _0_[1] + local _let_385_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) + local target = _let_385_[1] local args = {} for i = 4, #ast do - local subexprs = nil - local _1_ + local subexprs + local _386_ if (i ~= #ast) then - _1_ = 1 + _386_ = 1 else - _1_ = nil + _386_ = nil end - subexprs = compiler.compile1(ast[i], scope, parent, {nval = _1_}) + subexprs = compiler.compile1(ast[i], scope, parent, {nval = _386_}) utils.map(subexprs, tostring, args) end if ((type(ast[3]) == "string") and utils["valid-lua-identifier?"](ast[3])) then @@ -1466,17 +1327,13 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct SPECIALS.comment = function(ast, _, parent) local els = {} for i = 2, #ast do - local function _1_() - local _0_0 = tostring(ast[i]):gsub("\n", " ") - return _0_0 - end - table.insert(els, _1_()) + 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.") + doc_special("comment", {"..."}, "Comment which will be emitted in Lua output.", true) local function hashfn_max_used(f_scope, i, max) - local max0 = nil + local max0 if f_scope.symmeta[("$" .. i)].used then max0 = i else @@ -1490,12 +1347,12 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end SPECIALS.hashfn = function(ast, scope, parent) compiler.assert((#ast == 2), "expected one argument", ast) - local f_scope = nil + local f_scope do - local _0_0 = compiler["make-scope"](scope) - _0_0["vararg"] = false - _0_0["hashfn"] = true - f_scope = _0_0 + local _391_ = compiler["make-scope"](scope) + do end (_391_)["vararg"] = false + _391_["hashfn"] = true + f_scope = _391_ end local f_chunk = {} local name = compiler.gensym(scope) @@ -1506,7 +1363,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct args[i] = compiler["declare-local"](utils.sym(("$" .. i)), {}, f_scope, ast) end local function walker(idx, node, parent_node) - if (utils["sym?"](node) and (utils.deref(node) == "$...")) then + if (utils["sym?"](node) and (tostring(node) == "$...")) then parent_node[idx] = utils.varg() f_scope.vararg = true return nil @@ -1520,9 +1377,9 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct if f_scope.vararg then compiler.assert((max_used == 0), "$ and $... in hashfn are mutually exclusive", ast) end - local arg_str = nil + local arg_str if f_scope.vararg then - arg_str = utils.deref(utils.varg()) + arg_str = tostring(utils.varg()) else arg_str = table.concat(args, ", ", 1, max_used) end @@ -1532,41 +1389,53 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return utils.expr(name, "sym") end doc_special("hashfn", {"..."}, "Function literal shorthand; args are either $... OR $1, $2, etc.") - local function arithmetic_special(name, zero_arity, unary_prefix, ast, scope, parent) + local function arithmetic_special(name, zero_arity, unary_prefix, nval, ast, scope, parent) local len = #ast - if (len == 1) then - compiler.assert(zero_arity, "Expected more than 0 arguments", ast) - return utils.expr(zero_arity, "literal") - else - local operands = {} - local padded_op = (" " .. name .. " ") - for i = 2, len do - local subexprs = nil - local _0_ - if (i ~= len) then - _0_ = 1 - else - _0_ = nil - end - subexprs = compiler.compile1(ast[i], scope, parent, {nval = _0_}) - utils.map(subexprs, tostring, operands) - end - if (#operands == 1) then - if unary_prefix then - return ("(" .. unary_prefix .. padded_op .. operands[1] .. ")") - else - return operands[1] - end + local operands = {} + local padded_op = (" " .. name .. " ") + for i = 2, len do + local subexprs + local _395_ + if (i < len) then + _395_ = 1 else - return ("(" .. table.concat(operands, padded_op) .. ")") + _395_ = nil end + subexprs = compiler.compile1(ast[i], scope, parent, {nval = _395_}) + utils.map(subexprs, tostring, operands) + end + local _397_ = #operands + if (_397_ == 0) then + local _399_ + do + local _398_ = zero_arity + compiler.assert(_398_, "Expected more than 0 arguments", ast) + _399_ = _398_ + end + return utils.expr(_399_, "literal") + elseif (_397_ == 1) then + if unary_prefix then + return ("(" .. unary_prefix .. padded_op .. operands[1] .. ")") + else + return operands[1] + end + else + local _ = _397_ + return ("(" .. table.concat(operands, padded_op) .. ")") end end local function define_arithmetic_special(name, zero_arity, unary_prefix, lua_name) - local function _0_(...) - return arithmetic_special((lua_name or name), zero_arity, unary_prefix, ...) + local _405_ + do + local _402_ = (lua_name or name) + local _403_ = zero_arity + local _404_ = unary_prefix + local function _406_(...) + return arithmetic_special(_402_, _403_, _404_, 1, ...) + end + _405_ = _406_ end - SPECIALS[name] = _0_ + SPECIALS[name] = _405_ return doc_special(name, {"a", "b", "..."}, "Arithmetic operator; works the same as Lua but accepts more arguments.") end define_arithmetic_special("+", "0") @@ -1577,6 +1446,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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, nil, ast, scope, parent) + end + SPECIALS["and"] = function(ast, scope, parent) + return arithmetic_special("and", "true", nil, nil, ast, scope, parent) + end + doc_special("and", {"a", "b", "..."}, "Boolean operator; works the same as Lua but accepts more arguments.") + doc_special("or", {"a", "b", "..."}, "Boolean operator; works the same as Lua but accepts more arguments.") 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) @@ -1586,14 +1463,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local padded_native_name = (" " .. native_name .. " ") local prefixed_lib_name = ("bit." .. lib_name) for i = 2, len do - local subexprs = nil - local _0_ + local subexprs + local _407_ if (i ~= len) then - _0_ = 1 + _407_ = 1 else - _0_ = nil + _407_ = nil end - subexprs = compiler.compile1(ast[i], scope, parent, {nval = _0_}) + subexprs = compiler.compile1(ast[i], scope, parent, {nval = _407_}) utils.map(subexprs, tostring, operands) end if (#operands == 1) then @@ -1612,10 +1489,18 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end end local function define_bitop_special(name, zero_arity, unary_prefix, native) - local function _0_(...) - return bitop_special(native, name, zero_arity, unary_prefix, ...) + local _417_ + do + local _413_ = native + local _414_ = name + local _415_ = zero_arity + local _416_ = unary_prefix + local function _418_(...) + return bitop_special(_413_, _414_, _415_, _416_, ...) + end + _417_ = _418_ end - SPECIALS[name] = _0_ + SPECIALS[name] = _417_ return nil end define_bitop_special("lshift", nil, "1", "<<") @@ -1628,20 +1513,16 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") - define_arithmetic_special("or", "false") - define_arithmetic_special("and", "true") - 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.") doc_special("..", {"a", "b", "..."}, "String concatenation operator; works the same as Lua but accepts more arguments.") - local function native_comparator(op, _0_0, scope, parent) - local _1_ = _0_0 - local _ = _1_[1] - local lhs_ast = _1_[2] - local rhs_ast = _1_[3] - local _2_ = compiler.compile1(lhs_ast, scope, parent, {nval = 1}) - local lhs = _2_[1] - local _3_ = compiler.compile1(rhs_ast, scope, parent, {nval = 1}) - local rhs = _3_[1] + local function native_comparator(op, _419_, scope, parent) + local _arg_420_ = _419_ + local _ = _arg_420_[1] + local lhs_ast = _arg_420_[2] + local rhs_ast = _arg_420_[3] + local _let_421_ = compiler.compile1(lhs_ast, scope, parent, {nval = 1}) + local lhs = _let_421_[1] + local _let_422_ = compiler.compile1(rhs_ast, scope, parent, {nval = 1}) + local rhs = _let_422_[1] return string.format("(%s %s %s)", tostring(lhs), op, tostring(rhs)) end local function double_eval_protected_comparator(op, chain_op, ast, scope, parent) @@ -1651,7 +1532,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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])) + 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)])) @@ -1694,7 +1575,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") - SPECIALS["~="] = SPECIALS["not="] + do end (SPECIALS)["~="] = SPECIALS["not="] SPECIALS["#"] = SPECIALS.length SPECIALS.quote = function(ast, scope, parent) compiler.assert((#ast == 2), "expected one argument") @@ -1708,63 +1589,65 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 already_warned_3f = {} - local compile_env_warning = table.concat({"WARNING: Attempting to %s %s in compile scope.", "In future versions of Fennel this will not be allowed without the", "--no-compiler-sandbox flag or passing a :compilerEnv globals table", "in the options.\n"}, "\n") - local function compiler_env_warn(_, key) - local v = _G[key] - if (v and io and io.stderr and not already_warned_3f[key]) then - already_warned_3f[key] = true - do end (io.stderr):write(compile_env_warning:format("use global", key)) - end - return v - end + 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(strict_3f) - local _1_ - if strict_3f then - _1_ = nil - else - _1_ = compiler_env_warn - end - return setmetatable({assert = assert, bit = rawget(_G, "bit"), error = error, getmetatable = safe_getmetatable, ipairs = ipairs, math = utils.copy(math), next = next, pairs = pairs, pcall = pcall, print = print, rawequal = rawequal, rawget = rawget, rawlen = rawget(_G, "rawlen"), rawset = rawset, require = safe_require, select = select, setmetatable = setmetatable, string = utils.copy(string), table = utils.copy(table), tonumber = tonumber, tostring = tostring, type = type, xpcall = xpcall}, {__index = _1_}) + local function safe_compiler_env() + return {table = utils.copy(table), math = utils.copy(math), string = utils.copy(string), pairs = pairs, ipairs = ipairs, select = select, tostring = tostring, tonumber = tonumber, bit = rawget(_G, "bit"), pcall = pcall, xpcall = xpcall, next = next, print = print, type = type, assert = assert, error = error, setmetatable = setmetatable, getmetatable = safe_getmetatable, require = safe_require, rawlen = rawget(_G, "rawlen"), rawget = rawget, rawset = rawset, rawequal = rawequal} end - local function make_compiler_env(ast, scope, parent, strict_3f) - local function _1_() + local function combined_mt_pairs(env) + local combined = {} + local _let_425_ = getmetatable(env) + local __index = _let_425_["__index"] + if ("table" == type(__index)) then + for k, v in pairs(__index) do + combined[k] = v + end + end + for k, v in next, env, nil do + combined[k] = v + end + return next, combined, nil + end + local function make_compiler_env(ast, scope, parent, _3fopts) + local provided + do + local _427_ = (_3fopts or utils.root.options) + if ((_G.type(_427_) == "table") and ((_427_)["compiler-env"] == "strict")) then + provided = safe_compiler_env() + elseif ((_G.type(_427_) == "table") and (nil ~= (_427_).compilerEnv)) then + local compilerEnv = (_427_).compilerEnv + provided = compilerEnv + elseif ((_G.type(_427_) == "table") and (nil ~= (_427_)["compiler-env"])) then + local compiler_env = (_427_)["compiler-env"] + provided = compiler_env + else + local _ = _427_ + provided = safe_compiler_env(false) + end + end + local env + local function _429_(base) + return utils.sym(compiler.gensym((compiler.scopes.macro or scope), base)) + end + local function _430_() return compiler.scopes.macro end - local function _2_(symbol) + local function _431_(symbol) compiler.assert(compiler.scopes.macro, "must call from macro", ast) return compiler.scopes.macro.manglings[tostring(symbol)] end - local function _3_(base) - return utils.sym(compiler.gensym((compiler.scopes.macro or scope), base)) - end - local function _4_(form) + local function _432_(form) compiler.assert(compiler.scopes.macro, "must call from macro", ast) return compiler.macroexpand(form, compiler.scopes.macro) end - local _6_ - do - local _5_0 = utils.root.options - if ((type(_5_0) == "table") and (_5_0["compiler-env"] == "strict")) then - _6_ = safe_compiler_env(true) - elseif ((type(_5_0) == "table") and (nil ~= _5_0.compilerEnv)) then - local compilerEnv = _5_0.compilerEnv - _6_ = compilerEnv - elseif ((type(_5_0) == "table") and (nil ~= _5_0["compiler-env"])) then - local compiler_env = _5_0["compiler-env"] - _6_ = compiler_env - else - local _ = _5_0 - _6_ = safe_compiler_env(false) - end - end - return setmetatable({["assert-compile"] = compiler.assert, ["get-scope"] = _1_, ["in-scope?"] = _2_, ["list?"] = utils["list?"], ["multi-sym?"] = utils["multi-sym?"], ["sequence?"] = utils["sequence?"], ["sym?"] = utils["sym?"], ["table?"] = utils["table?"], ["varg?"] = utils["varg?"], _AST = ast, _CHUNK = parent, _IS_COMPILER = true, _SCOPE = scope, _SPECIALS = compiler.scopes.global.specials, _VARARG = utils.varg(), gensym = _3_, list = utils.list, macroexpand = _4_, sequence = utils.sequence, sym = utils.sym, unpack = unpack, view = view}, {__index = _6_}) + env = {_AST = ast, _CHUNK = parent, _IS_COMPILER = true, _SCOPE = scope, _SPECIALS = compiler.scopes.global.specials, _VARARG = utils.varg(), ["macro-loaded"] = macro_loaded, unpack = unpack, ["assert-compile"] = compiler.assert, list = utils.list, ["list?"] = utils["list?"], ["multi-sym?"] = utils["multi-sym?"], sequence = utils.sequence, ["sequence?"] = utils["sequence?"], sym = utils.sym, ["sym?"] = utils["sym?"], ["table?"] = utils["table?"], ["varg?"] = utils["varg?"], view = view, gensym = _429_, ["get-scope"] = _430_, ["in-scope?"] = _431_, macroexpand = _432_} + env._G = env + return setmetatable(env, {__index = provided, __newindex = provided, __pairs = combined_mt_pairs}) end local cfg = string.gmatch(package.config, "([^\n]+)") local dirsep, pathsep, pathmark = (cfg() or "/"), (cfg() or ";"), (cfg() or "?") @@ -1780,39 +1663,45 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 _1_0 = (io.open(filename) or io.open(filename2)) - if (nil ~= _1_0) then - local file = _1_0 + local _433_ = (io.open(filename) or io.open(filename2)) + if (nil ~= _433_) then + local file = _433_ file:close() return filename end end local function find_in_path(start) - local _1_0 = fullpath:match(pattern, start) - if (nil ~= _1_0) then - local path = _1_0 + local _435_ = fullpath:match(pattern, start) + if (nil ~= _435_) then + local path = _435_ return (try_path(path) or find_in_path((start + #path + 1))) end end return find_in_path(1) end local function make_searcher(options) - local function _1_(module_name) + local function _437_(module_name) local opts = utils.copy(utils.root.options) for k, v in pairs((options or {})) do opts[k] = v end opts["module-name"] = module_name - local _2_0 = search_module(module_name) - if (nil ~= _2_0) then - local filename = _2_0 - local function _3_(...) - return utils["fennel-module"].dofile(filename, opts, ...) + local _438_ = search_module(module_name) + if (nil ~= _438_) then + local filename = _438_ + local _441_ + do + local _439_ = filename + local _440_ = opts + local function _442_(...) + return utils["fennel-module"].dofile(_439_, _440_, ...) + end + _441_ = _442_ end - return _3_, filename + return _441_, filename end end - return _1_ + return _437_ end local function macro_globals(env, globals) local allowed = current_global_names(env) @@ -1821,67 +1710,110 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end return allowed end - local function default_macro_searcher(module_name) - local _1_0 = search_module(module_name) - if (nil ~= _1_0) then - local filename = _1_0 - local function _2_(...) - return utils["fennel-module"].dofile(filename, {env = "_COMPILER"}, ...) + local function fennel_macro_searcher(module_name) + local opts + do + local _444_ = utils.copy(utils.root.options) + do end (_444_)["env"] = "_COMPILER" + _444_["allowedGlobals"] = nil + opts = _444_ + end + local _445_ = search_module(module_name, utils["fennel-module"]["macro-path"]) + if (nil ~= _445_) then + local filename = _445_ + local _448_ + do + local _446_ = filename + local _447_ = opts + local function _449_(...) + return utils["fennel-module"].dofile(_446_, _447_, ...) + end + _448_ = _449_ end - return _2_, filename + return _448_, filename end end - local macro_searchers = {default_macro_searcher} + local function lua_macro_searcher(module_name) + local _451_ = search_module(module_name, package.path) + if (nil ~= _451_) then + local filename = _451_ + local code + do + local f = io.open(filename) + local function close_handlers_7_auto(ok_8_auto, ...) + f:close() + if ok_8_auto then + return ... + else + return error(..., 0) + end + end + local function _453_() + return assert(f:read("*a")) + end + code = close_handlers_7_auto(_G.xpcall(_453_, (package.loaded.fennel or debug).traceback)) + end + local chunk = load_code(code, make_compiler_env(), filename) + return chunk, filename + end + end + local macro_searchers = {lua_macro_searcher, fennel_macro_searcher} local function search_macro_module(modname, n) - local _1_0 = macro_searchers[n] - if (nil ~= _1_0) then - local f = _1_0 - local _2_0, _3_0 = f(modname) - if ((nil ~= _2_0) and true) then - local loader = _2_0 - local _3ffilename = _3_0 + local _455_ = macro_searchers[n] + if (nil ~= _455_) then + local f = _455_ + local _456_, _457_ = f(modname) + if ((nil ~= _456_) and true) then + local loader = _456_ + local _3ffilename = _457_ return loader, _3ffilename else - local _ = _2_0 + local _ = _456_ return search_macro_module(modname, (n + 1)) end end end - local macro_loaded = {} local function metadata_only_fennel(modname) if ((modname == "fennel.macros") or (package and package.loaded and ("table" == type(package.loaded[modname])) and (package.loaded[modname].metadata == compiler.metadata))) then return {metadata = compiler.metadata} end end - local function _1_(modname) - local function _2_() + local function _461_(modname) + local function _462_() local loader, filename = search_macro_module(modname, 1) compiler.assert(loader, (modname .. " module not found.")) - macro_loaded[modname] = loader(modname, filename) + do end (macro_loaded)[modname] = loader(modname, filename) return macro_loaded[modname] end - return (macro_loaded[modname] or metadata_only_fennel(modname) or _2_()) + return (macro_loaded[modname] or metadata_only_fennel(modname) or _462_()) end - safe_require = _1_ + safe_require = _461_ 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) - scope.macros[k] = v + do end (scope.macros)[k] = v end return nil end + local function resolve_module_name(_463_, scope, parent, opts) + local _arg_464_ = _463_ + local filename = _arg_464_["filename"] + local second = _arg_464_[2] + local filename0 = (filename or (utils["table?"](second) and second.filename)) + local module_name = utils.root.options["module-name"] + local modexpr = compiler.compile(second, opts) + local modname_chunk = load_code(modexpr) + return modname_chunk(module_name, filename0) + end SPECIALS["require-macros"] = function(ast, scope, parent, real_ast) compiler.assert((#ast == 2), "Expected one module name argument", (real_ast or ast)) - local filename = (ast[2].filename or ast.filename) - local modname_chunk = load_code(compiler.compile(ast[2]), nil, filename) - local modname = modname_chunk(utils.root.options["module-name"], filename) - compiler.assert((type(modname) == "string"), "module name must compile to string", (real_ast or ast)) + local modname = resolve_module_name(ast, scope, parent, {}) + compiler.assert(("string" == type(modname)), "module name must compile to string", (real_ast or ast)) if not macro_loaded[modname] then - local env = make_compiler_env(ast, scope, parent) - local loader, filename0 = search_macro_module(modname, 1) + local loader, filename = search_macro_module(modname, 1) compiler.assert(loader, (modname .. " module not found."), ast) - macro_loaded[modname] = loader(modname, filename0) + do end (macro_loaded)[modname] = loader(modname, filename) end return add_macros(macro_loaded[modname], ast, scope, parent) end @@ -1896,7 +1828,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct table.insert(forms, val) end for i = 1, #forms do - local subopts = nil + local subopts if (i == #forms) then subopts = {tail = true} else @@ -1909,21 +1841,21 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end local function include_path(ast, opts, path, mod, fennel_3f) utils.root.scope.includes[mod] = "fnl/loading" - local src = nil + local src do local f = assert(io.open(path)) - local function close_handlers_0_(ok_0_, ...) + local function close_handlers_7_auto(ok_8_auto, ...) f:close() - if ok_0_ then + if ok_8_auto then return ... else return error(..., 0) end end - local function _2_() + local function _469_() return f:read("*all"):gsub("[\13\n]*$", "") end - src = close_handlers_0_(xpcall(_2_, (package.loaded.fennel or debug).traceback)) + src = close_handlers_7_auto(_G.xpcall(_469_, (package.loaded.fennel or debug).traceback)) end local ret = utils.expr(("require(\"" .. mod .. "\")"), "statement") local target = ("package.preload[%q]"):format(mod) @@ -1951,7 +1883,20 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end SPECIALS.include = function(ast, scope, parent, opts) compiler.assert((#ast == 2), "expected one argument", ast) - local modexpr = compiler.compile1(ast[2], scope, parent, {nval = 1})[1] + local modexpr + do + local _472_, _473_ = pcall(resolve_module_name, ast, scope, parent, opts) + if ((_472_ == true) and (nil ~= _473_)) then + local modname = _473_ + modexpr = utils.expr(string.format("%q", modname), "literal") + elseif (true and (nil ~= _473_)) then + local _ = _472_ + local err = _473_ + modexpr = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1] + else + modexpr = nil + end + end if ((modexpr.type ~= "literal") or ((modexpr[1]):byte() ~= 34)) then if opts.fallback then return opts.fallback(modexpr) @@ -1960,13 +1905,18 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end else local mod = load_code(("return " .. modexpr[1]))() - local function _3_() - local _2_0 = search_module(mod) - if (nil ~= _2_0) then - local fennel_path = _2_0 + local oldmod = utils.root.options["module-name"] + local _ + utils.root.options["module-name"] = mod + _ = nil + local res + local function _477_() + local _476_ = search_module(mod) + if (nil ~= _476_) then + local fennel_path = _476_ return include_path(ast, opts, fennel_path, mod, true) else - local _ = _2_0 + local _0 = _476_ local lua_path = search_module(mod, package.path) if lua_path then return include_path(ast, opts, lua_path, mod, false) @@ -1977,7 +1927,9 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end end end - return (include_circular_fallback(mod, modexpr, opts.fallback, ast) or utils.root.scope.includes[mod] or _3_()) + res = ((utils["member?"](mod, (utils.root.options.skipInclude or {})) and utils.expr("nil --[[SKIPPED INCLUDE]]--", "literal")) or include_circular_fallback(mod, modexpr, opts.fallback, ast) or utils.root.scope.includes[mod] or _477_()) + utils.root.options["module-name"] = oldmod + return res 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.") @@ -1997,11 +1949,11 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local old_first = ast[1] ast[1] = utils.sym("do") local val = eval_compiler_2a(ast, scope, parent) - ast[1] = old_first + 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.") - return {["current-global-names"] = current_global_names, ["load-code"] = load_code, ["macro-loaded"] = macro_loaded, ["macro-searchers"] = macro_searchers, ["make-compiler-env"] = make_compiler_env, ["make-searcher"] = make_searcher, ["search-module"] = search_module, ["wrap-env"] = wrap_env, doc = doc_2a} + 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") @@ -2011,16 +1963,16 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local scopes = {} local function make_scope(parent) local parent0 = (parent or scopes.global) - local _0_ + local _176_ if parent0 then - _0_ = ((parent0.depth or 0) + 1) + _176_ = ((parent0.depth or 0) + 1) else - _0_ = 0 + _176_ = 0 end - return {autogensyms = {}, depth = _0_, hashfn = (parent0 and parent0.hashfn), includes = setmetatable({}, {__index = (parent0 and parent0.includes)}), macros = setmetatable({}, {__index = (parent0 and parent0.macros)}), manglings = setmetatable({}, {__index = (parent0 and parent0.manglings)}), parent = parent0, refedglobals = setmetatable({}, {__index = (parent0 and parent0.refedglobals)}), specials = setmetatable({}, {__index = (parent0 and parent0.specials)}), symmeta = setmetatable({}, {__index = (parent0 and parent0.symmeta)}), unmanglings = setmetatable({}, {__index = (parent0 and parent0.unmanglings)}), vararg = (parent0 and parent0.vararg)} + return {includes = setmetatable({}, {__index = (parent0 and parent0.includes)}), macros = setmetatable({}, {__index = (parent0 and parent0.macros)}), manglings = setmetatable({}, {__index = (parent0 and parent0.manglings)}), refedglobals = setmetatable({}, {__index = (parent0 and parent0.refedglobals)}), specials = setmetatable({}, {__index = (parent0 and parent0.specials)}), symmeta = setmetatable({}, {__index = (parent0 and parent0.symmeta)}), unmanglings = setmetatable({}, {__index = (parent0 and parent0.unmanglings)}), gensyms = setmetatable({}, {__index = (parent0 and parent0.gensyms)}), autogensyms = setmetatable({}, {__index = (parent0 and parent0.autogensyms)}), vararg = (parent0 and parent0.vararg), depth = _176_, hashfn = (parent0 and parent0.hashfn), parent = parent0} end local function assert_msg(ast, msg) - local ast_tbl = nil + local ast_tbl if ("table" == type(ast)) then ast_tbl = ast else @@ -2029,24 +1981,16 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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 target = nil - local function _1_() - if utils["sym?"](ast_tbl[1]) then - return utils.deref(ast_tbl[1]) - else - return (ast_tbl[1] or "()") - end - end - target = tostring(_1_()) - return string.format("Compile error in '%s' %s:%s: %s", target, filename, line, msg) + local target = tostring((utils["sym?"](ast_tbl[1]) or ast_tbl[1] or "()")) + return string.format("%s:%s: Compile error in '%s': %s", filename, line, target, msg) end local function assert_compile(condition, msg, ast) if not condition then - local _0_ = (utils.root.options or {}) - local source = _0_["source"] - local unfriendly = _0_["unfriendly"] + local _let_179_ = (utils.root.options or {}) + local source = _let_179_["source"] + local unfriendly = _let_179_["unfriendly"] utils.root.reset() - if unfriendly then + 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) @@ -2058,44 +2002,44 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct scopes.global.vararg = true scopes.compiler = make_scope(scopes.global) scopes.macro = scopes.global - local serialize_subst = {["\11"] = "\\v", ["\12"] = "\\f", ["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\n"] = "n"} + local serialize_subst = {["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\n"] = "n", ["\11"] = "\\v", ["\12"] = "\\f"} local function serialize_string(str) - local function _0_(_241) + local function _182_(_241) return ("\\" .. _241:byte()) end - return string.gsub(string.gsub(string.format("%q", str), ".", serialize_subst), "[\128-\255]", _0_) + return string.gsub(string.gsub(string.format("%q", str), ".", serialize_subst), "[\128-\255]", _182_) end local function global_mangling(str) if utils["valid-lua-identifier?"](str) then return str else - local function _0_(_241) + local function _183_(_241) return string.format("_%02x", _241:byte()) end - return ("__fnl_global__" .. str:gsub("[^%w]", _0_)) + return ("__fnl_global__" .. str:gsub("[^%w]", _183_)) end end local function global_unmangling(identifier) - local _0_0 = string.match(identifier, "^__fnl_global__(.*)$") - if (nil ~= _0_0) then - local rest = _0_0 - local _1_0 = nil - local function _2_(_241) + local _185_ = string.match(identifier, "^__fnl_global__(.*)$") + if (nil ~= _185_) then + local rest = _185_ + local _186_ + local function _187_(_241) return string.char(tonumber(_241:sub(2), 16)) end - _1_0 = string.gsub(rest, "_[%da-f][%da-f]", _2_) - return _1_0 + _186_ = string.gsub(rest, "_[%da-f][%da-f]", _187_) + return _186_ else - local _ = _0_0 + local _ = _185_ return identifier end end local allowed_globals = nil - local function global_allowed(name) + 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] then + if (scope.unmanglings[mangling] and not scope.gensyms[mangling]) then return unique_mangling(original, (original .. append), scope, (append + 1)) else return mangling @@ -2103,29 +2047,29 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end local function local_mangling(str, scope, ast, temp_manglings) assert_compile(not utils["multi-sym?"](str), ("unexpected multi symbol " .. str), ast) - local raw = nil - if (utils["lua-keywords"][str] or str:match("^%d")) then + local raw + if ((utils["lua-keywords"])[str] or str:match("^%d")) then raw = ("_" .. str) else raw = str end - local mangling = nil - local function _1_(_241) + local mangling + local function _191_(_241) return string.format("_%02x", _241:byte()) end - mangling = string.gsub(string.gsub(raw, "-", "_"), "[^%w_]", _1_) + mangling = string.gsub(string.gsub(raw, "-", "_"), "[^%w_]", _191_) local unique = unique_mangling(mangling, mangling, scope, 0) - scope.unmanglings[unique] = str + do end (scope.unmanglings)[unique] = str do local manglings = (temp_manglings or scope.manglings) - manglings[str] = unique + 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) - scope.manglings[raw] = mangled + do end (scope.manglings)[raw] = mangled end return nil end @@ -2144,46 +2088,46 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end return ret end - local function gensym(scope, base) - local append, mangling = 0, ((base or "") .. "_0_") + local function next_append() + utils.root.scope["gensym-append"] = ((utils.root.scope["gensym-append"] or 0) + 1) + return ("_" .. utils.root.scope["gensym-append"] .. "_") + end + local function gensym(scope, base, _3fsuffix) + local mangling = ((base or "") .. next_append() .. (_3fsuffix or "")) while scope.unmanglings[mangling] do - mangling = ((base or "") .. "_" .. append .. "_") - append = (append + 1) + mangling = ((base or "") .. next_append() .. (_3fsuffix or "")) end scope.unmanglings[mangling] = (base or true) + do end (scope.gensyms)[mangling] = true return mangling end local function autogensym(base, scope) - local _0_0 = utils["multi-sym?"](base) - if (nil ~= _0_0) then - local parts = _0_0 + local _194_ = utils["multi-sym?"](base) + if (nil ~= _194_) then + local parts = _194_ parts[1] = autogensym(parts[1], scope) return table.concat(parts, ((parts["multi-sym-method-call"] and ":") or ".")) else - local _ = _0_0 - local function _1_() - local mangling = gensym(scope, base:sub(1, ( - 2))) - scope.autogensyms[base] = mangling + local _ = _194_ + local function _195_() + local mangling = gensym(scope, base:sub(1, ( - 2)), "auto") + do end (scope.autogensyms)[base] = mangling return mangling end - return (scope.autogensyms[base] or _1_()) + return (scope.autogensyms[base] or _195_()) end end - local already_warned = {} local function check_binding_valid(symbol, scope, ast) - local name = utils.deref(symbol) - if (io and io.stderr and name:find("&") and not already_warned[symbol]) then - already_warned[symbol] = true - do end (io.stderr):write(("-- Warning: & will not be allowed in identifier names in " .. "future versions: " .. (symbol.filename or "unknown") .. ":" .. (symbol.line or "?") .. "\n")) - end + local name = tostring(symbol) + assert_compile(not name:find("&"), "illegal 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, temp_manglings) check_binding_valid(symbol, scope, ast) - local name = utils.deref(symbol) + local name = tostring(symbol) assert_compile(not utils["multi-sym?"](name), ("unexpected multi symbol " .. name), ast) - scope.symmeta[name] = meta + do end (scope.symmeta)[name] = meta return local_mangling(name, scope, ast, temp_manglings) end local function hashfn_arg_name(name, multi_sym_parts, scope) @@ -2209,7 +2153,8 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct if (local_3f and scope.symmeta[parts[1]]) then scope.symmeta[parts[1]]["used"] = true end - assert_compile((not reference_3f or local_3f or global_allowed(parts[1])), ("unknown global in strict mode: " .. tostring(parts[1])), symbol) + assert_compile(not scope.macros[parts[1]], "tried to reference a macro at runtime", symbol) + assert_compile((not reference_3f or local_3f or ("_ENV" == parts[1]) or global_allowed_3f(parts[1])), ("unknown global in strict mode: " .. tostring(parts[1])), symbol) if (allowed_globals and not local_3f) then utils.root.scope.refedglobals[parts[1]] = true end @@ -2225,7 +2170,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local function peephole(chunk) if chunk.leaf then return chunk - elseif ((#chunk >= 3) and (chunk[(#chunk - 2)].leaf == "do") and not chunk[(#chunk - 1)].leaf and (chunk[#chunk].leaf == "end")) then + elseif ((#chunk >= 3) 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 @@ -2243,7 +2188,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local m = getmetatable(ast) return ((m and m.line and m) or (("table" == type(ast)) and ast) or {}) end - local function flatten_chunk_correlated(main_chunk) + 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 @@ -2252,7 +2197,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct for _, subchunk in ipairs(chunk) do if (subchunk.leaf or (#subchunk > 0)) then local source = ast_source(subchunk.ast) - if (file == source.file) then + if (file == source.filename) then last_line0 = math.max(last_line0, (source.line or 0)) end last_line0 = flatten(subchunk, out, last_line0, file) @@ -2262,7 +2207,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct return last_line0 end local out = {} - local last = flatten(main_chunk, out, 1, main_chunk.file) + local last = flatten(main_chunk, out, 1, options.filename) for i = 1, last do if (out[i] == nil) then out[i] = "" @@ -2279,16 +2224,16 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end return code else - local tab0 = nil + local tab0 do - local _0_0 = tab - if (_0_0 == true) then + local _208_ = tab + if (_208_ == true) then tab0 = " " - elseif (_0_0 == false) then + elseif (_208_ == false) then tab0 = "" - elseif (_0_0 == tab) then + elseif (_208_ == tab) then tab0 = tab - elseif (_0_0 == nil) then + elseif (_208_ == nil) then tab0 = "" else tab0 = nil @@ -2319,7 +2264,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local function flatten(chunk, options) local chunk0 = peephole(chunk) if options.correlate then - return flatten_chunk_correlated(chunk0), {} + return flatten_chunk_correlated(chunk0, options), {} else local sm = {} local ret = flatten_chunk(sm, chunk0, options.indent, 0) @@ -2336,17 +2281,17 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function make_metadata() - local function _0_(self, tgt, key) + local function _217_(self, tgt, key) if self[tgt] then return self[tgt][key] end end - local function _1_(self, tgt, key, value) + local function _219_(self, tgt, key, value) self[tgt] = (self[tgt] or {}) - self[tgt][key] = value + do end (self[tgt])[key] = value return tgt end - local function _2_(self, tgt, ...) + local function _220_(self, tgt, ...) local kv_len = select("#", ...) local kvs = {...} if ((kv_len % 2) ~= 0) then @@ -2358,25 +2303,26 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end return tgt end - return setmetatable({}, {__index = {get = _0_, set = _1_, setall = _2_}, __mode = "k"}) + return setmetatable({}, {__index = {get = _217_, set = _219_, setall = _220_}, __mode = "k"}) end local function exprs1(exprs) - return table.concat(utils.map(exprs, 1), ", ") - end - local function disambiguate_parens(code, chunk) - if ((code:byte() == 40) and (1 < #chunk)) then - return ("; " .. code) - else - return code - end + return table.concat(utils.map(exprs, tostring), ", ") end local function keep_side_effects(exprs, chunk, start, ast) - for j = (start or 1), #exprs do + 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 - emit(chunk, disambiguate_parens(tostring(se), chunk), ast) + local code = tostring(se) + local disambiguated + if (code:byte() == 40) then + disambiguated = ("do end " .. code) + else + disambiguated = code + end + emit(chunk, disambiguated, ast) end end return nil @@ -2403,21 +2349,21 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end if opts.target then local result = exprs1(exprs) - local function _2_() + local function _228_() if (result == "") then return "nil" else return result end end - emit(parent, string.format("%s = %s", opts.target, _2_()), ast) + emit(parent, string.format("%s = %s", opts.target, _228_()), ast) end if (opts.tail or opts.target) then return {returned = true} else - local _3_0 = exprs - _3_0["returned"] = true - return _3_0 + local _230_ = exprs + _230_["returned"] = true + return _230_ end end local function find_macro(ast, scope, multi_sym_parts) @@ -2428,7 +2374,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct return t end end - local macro_2a = (utils["sym?"](ast[1]) and scope.macros[utils.deref(ast[1])]) + local macro_2a = (utils["sym?"](ast[1]) and scope.macros[tostring(ast[1])]) if (not macro_2a and multi_sym_parts) then local nested_macro = find_in_table(scope.macros, 1) assert_compile((not scope.macros[multi_sym_parts[1]] or (type(nested_macro) == "function")), "macro not found in imported macro module", ast) @@ -2438,25 +2384,25 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function macroexpand_2a(ast, scope, once) - local _0_0 = nil + local _234_ if utils["list?"](ast) then - _0_0 = find_macro(ast, scope, utils["multi-sym?"](ast[1])) + _234_ = find_macro(ast, scope, utils["multi-sym?"](ast[1])) else - _0_0 = nil + _234_ = nil end - if (_0_0 == false) then + if (_234_ == false) then return ast - elseif (nil ~= _0_0) then - local macro_2a = _0_0 + elseif (nil ~= _234_) then + local macro_2a = _234_ local old_scope = scopes.macro - local _ = nil + local _ scopes.macro = scope _ = nil local ok, transformed = nil, nil - local function _2_() + local function _236_() return macro_2a(unpack(ast, 2)) end - ok, transformed = xpcall(_2_, debug.traceback) + ok, transformed = xpcall(_236_, debug.traceback) scopes.macro = old_scope assert_compile(ok, transformed, ast) if (once or not transformed) then @@ -2465,19 +2411,19 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct return macroexpand_2a(transformed, scope) end else - local _ = _0_0 + local _ = _234_ return ast 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 = nil - if (type(exprs) == "string") then + local exprs0 + if ("table" ~= type(exprs)) then exprs0 = utils.expr(exprs, "expression") else exprs0 = exprs end - local exprs2 = nil + local exprs2 if utils["expr?"](exprs0) then exprs2 = {exprs0} else @@ -2493,17 +2439,17 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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((fcallee.type ~= "literal"), ("cannot call literal value " .. tostring(ast[1])), ast) + local fcallee = (compile1(ast[1], scope, parent, {nval = 1}))[1] + assert_compile((("string" == type(ast[1])) or (fcallee.type ~= "literal")), ("cannot call literal value " .. tostring(ast[1])), ast) for i = 2, len do - local subexprs = nil - local _0_ + local subexprs + local _242_ if (i ~= len) then - _0_ = 1 + _242_ = 1 else - _0_ = nil + _242_ = nil end - subexprs = compile1(ast[i], scope, parent, {nval = _0_}) + subexprs = compile1(ast[i], scope, parent, {nval = _242_}) table.insert(fargs, (subexprs[1] or utils.expr("nil", "literal"))) if (i == len) then for j = 2, #subexprs do @@ -2513,7 +2459,13 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct keep_side_effects(subexprs, parent, 2, ast[i]) end end - local call = string.format("%s(%s)", tostring(fcallee), exprs1(fargs)) + 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) @@ -2521,7 +2473,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local len = #ast local first = ast[1] local multi_sym_parts = utils["multi-sym?"](first) - local special = (utils["sym?"](first) and scope.specials[utils.deref(first)]) + local special = (utils["sym?"](first) and scope.specials[tostring(first)]) assert_compile((len > 0), "expected a function, macro, or special to call", ast) if special then return compile_special(ast, scope, parent, opts, special) @@ -2541,7 +2493,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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 = nil + local e if (ast[1] == "nil") then e = utils.expr("nil", "literal") else @@ -2550,20 +2502,20 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct return handle_compile_opts({e}, parent, opts, ast) end local function serialize_number(n) - local _0_0 = string.gsub(tostring(n), ",", ".") - return _0_0 + local _248_ = string.gsub(tostring(n), ",", ".") + return _248_ end local function compile_scalar(ast, _scope, parent, opts) - local serialize = nil + local serialize do - local _0_0 = type(ast) - if (_0_0 == "nil") then + local _249_ = type(ast) + if (_249_ == "nil") then serialize = tostring - elseif (_0_0 == "boolean") then + elseif (_249_ == "boolean") then serialize = tostring - elseif (_0_0 == "string") then + elseif (_249_ == "string") then serialize = serialize_string - elseif (_0_0 == "number") then + elseif (_249_ == "number") then serialize = serialize_number else serialize = nil @@ -2582,32 +2534,31 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct if ((type(k) == "string") and utils["valid-lua-identifier?"](k)) then return {k, k} else - local _0_ = compile1(k, scope, parent, {nval = 1}) - local compiled = _0_[1] + local _let_251_ = compile1(k, scope, parent, {nval = 1}) + local compiled = _let_251_[1] local kstr = ("[" .. tostring(compiled) .. "]") return {kstr, k} end end end do - local keys = nil + local keys do - local _0_0 = utils.kvmap(ast, write_other_values) - local function _1_(a, b) - return (a[1] < b[1]) + local tbl_13_auto = {} + for k, v in utils.stablepairs(ast) do + tbl_13_auto[(#tbl_13_auto + 1)] = write_other_values(k, v) end - table.sort(_0_0, _1_) - keys = _0_0 + keys = tbl_13_auto end - local function _1_(_2_0) - local _3_ = _2_0 - local k1 = _3_[1] - local k2 = _3_[2] - local _4_ = compile1(ast[k2], scope, parent, {nval = 1}) - local v = _4_[1] + local function _256_(_254_) + local _arg_255_ = _254_ + local k1 = _arg_255_[1] + local k2 = _arg_255_[2] + local _let_257_ = compile1(ast[k2], scope, parent, {nval = 1}) + local v = _let_257_[1] return string.format("%s = %s", k1, tostring(v)) end - utils.map(keys, _1_, buffer) + utils.map(keys, _256_, buffer) end return handle_compile_opts({utils.expr(("{" .. table.concat(buffer, ", ") .. "}"), "expression")}, parent, opts, ast) end @@ -2630,14 +2581,14 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end local function destructure(to, from, ast, scope, parent, opts) local opts0 = (opts or {}) - local _0_ = opts0 - local declaration = _0_["declaration"] - local forceglobal = _0_["forceglobal"] - local forceset = _0_["forceset"] - local isvar = _0_["isvar"] - local symtype = _0_["symtype"] + local _let_259_ = opts0 + local isvar = _let_259_["isvar"] + local declaration = _let_259_["declaration"] + local forceglobal = _let_259_["forceglobal"] + local forceset = _let_259_["forceset"] + local symtype = _let_259_["symtype"] local symtype0 = ("_" .. (symtype or "dst")) - local setter = nil + local setter if declaration then setter = "local %s = %s" else @@ -2652,6 +2603,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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) @@ -2659,8 +2611,8 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end if forceglobal then assert_compile(not scope.symmeta[scope.unmanglings[raw]], ("global " .. raw .. " conflicts with local"), symbol) - scope.manglings[raw] = global_mangling(raw) - scope.unmanglings[global_mangling(raw)] = raw + 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) end @@ -2669,15 +2621,15 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function compile_top_target(lvalues) - local inits = nil - local function _2_(_241) + local inits + local function _265_(_241) if scope.manglings[_241] then return _241 else return "nil" end end - inits = utils.map(lvalues, _2_) + inits = utils.map(lvalues, _265_) local init = table.concat(inits, ", ") local lvalue = table.concat(lvalues, ", ") local plen, plast = #parent, parent[#parent] @@ -2707,24 +2659,24 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct emit(parent, setter:format(lname, exprs1(rightexprs)), left) end if declaration then - scope.symmeta[utils.deref(left)] = {var = isvar} + scope.symmeta[tostring(left)] = {var = isvar} return nil end end local function destructure_table(left, rightexprs, top_3f, destructure1) local s = gensym(scope, symtype0) - local right = nil + local right do - local _2_0 = nil + local _272_ if top_3f then - _2_0 = exprs1(compile1(from, scope, parent)) + _272_ = exprs1(compile1(from, scope, parent)) else - _2_0 = exprs1(rightexprs) + _272_ = exprs1(rightexprs) end - if (_2_0 == "") then + if (_272_ == "") then right = "nil" - elseif (nil ~= _2_0) then - local right0 = _2_0 + elseif (nil ~= _272_) then + local right0 = _272_ right = right0 else right = nil @@ -2733,20 +2685,20 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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?"](v) and (utils.deref(v) == "&")) then + if (utils["sym?"](v) and (tostring(v) == "&")) then local unpack_str = "{(table.unpack or unpack)(%s, %s)}" local formatted = string.format(unpack_str, 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) destructure1(left[(k + 1)], {subexpr}, left) - elseif (utils["sym?"](k) and (utils.deref(k) == "&as")) then + elseif (utils["sym?"](k) and (tostring(k) == "&as")) then destructure_sym(v, {utils.expr(tostring(s))}, left) - elseif (utils["sequence?"](left) and (utils.deref(v) == "&as")) then + 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 = nil + local key if (type(k) == "string") then key = serialize_string(k) else @@ -2767,14 +2719,16 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct else local symname = gensym(scope, symtype0) table.insert(left_names, symname) - tables[i] = {name, utils.expr(symname, "sym")} + do end (tables)[i] = {name, utils.expr(symname, "sym")} end end assert_compile(top_3f, "can't nest multi-value destructuring", left) compile_top_target(left_names) if declaration then for _, sym in ipairs(left) do - scope.symmeta[utils.deref(sym)] = {var = isvar} + if utils["sym?"](sym) then + scope.symmeta[tostring(sym)] = {var = isvar} + end end end for _, pair in utils.stablepairs(tables) do @@ -2790,7 +2744,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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)) + 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} @@ -2813,8 +2767,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local scope = (opts.scope or make_scope(scopes.global)) local vals = {} local chunk = {} - local _0_ = utils.root - _0_["set-reset"](_0_) + 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 = " " @@ -2842,8 +2795,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local old_globals = allowed_globals local chunk = {} local scope = (opts0.scope or make_scope(scopes.global)) - local _0_ = utils.root - _0_["set-reset"](_0_) + 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 = " " @@ -2874,14 +2826,14 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct info.currentline = (remap[info.currentline][2] or -1) end if (info.what == "Lua") then - local function _1_() + local function _289_() if info.name then return ("'" .. info.name .. "'") else return "?" end end - return string.format(" %s:%d: in function %s", info.short_src, info.currentline, _1_()) + return string.format(" %s:%d: in function %s", info.short_src, info.currentline, _289_()) elseif (info.short_src == "(tail call)") then return " (tail call)" else @@ -2890,12 +2842,12 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function traceback(msg, start) - local msg0 = (msg or "") + local msg0 = tostring((msg or "")) if ((msg0:find("^Compile error") or msg0:find("^Parse error")) and not utils["debug-on?"]("trace")) then return msg0 else local lines = {} - if (msg0:find("^Compile error") or msg0:find("^Parse error")) then + if (msg0:find(":%d+: Compile error") or msg0:find(":%d+: Parse error")) then table.insert(lines, msg0) else local newmsg = msg0:gsub("^[^:]*:%d+:%s+", "runtime error: ") @@ -2905,11 +2857,11 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local done_3f, level = false, (start or 2) while not done_3f do do - local _1_0 = debug.getinfo(level, "Sln") - if (_1_0 == nil) then + local _293_ = debug.getinfo(level, "Sln") + if (_293_ == nil) then done_3f = true - elseif (nil ~= _1_0) then - local info = _1_0 + elseif (nil ~= _293_) then + local info = _293_ table.insert(lines, traceback_frame(info)) end end @@ -2919,14 +2871,14 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function entry_transform(fk, fv) - local function _0_(k, v) + local function _296_(k, v) if (type(k) == "number") then return k, fv(v) else return fk(k), fv(v) end end - return _0_ + return _296_ end local function mixed_concat(t, joiner) local seen = {} @@ -2952,30 +2904,30 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct assert_compile(not runtime_3f, "quoted ... may only be used at compile time", form) return "_VARARG" elseif utils["sym?"](form) then - local filename = nil + local filename if form.filename then filename = string.format("%q", form.filename) else filename = "nil" end - local symstr = utils.deref(form) + 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 (utils.deref(form[1]) == "unquote")) then + 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 = nil - local function _0_() + local mapped + local function _301_() return nil end - mapped = utils.kvmap(form, entry_transform(_0_, q)) - local filename = nil + mapped = utils.kvmap(form, entry_transform(_301_, q)) + local filename if form.filename then filename = string.format("%q", form.filename) else @@ -2986,50 +2938,50 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct elseif utils["sequence?"](form) then local mapped = utils.kvmap(form, entry_transform(q, q)) local source = getmetatable(form) - local filename = nil + local filename if source.filename then filename = string.format("%q", source.filename) else filename = "nil" end - local _1_ + local _304_ if source then - _1_ = source.line + _304_ = source.line else - _1_ = "nil" + _304_ = "nil" end - return string.format("setmetatable({%s}, {filename=%s, line=%s, sequence=%s})", mixed_concat(mapped, ", "), filename, _1_, "(getmetatable(sequence()))['sequence']") + return string.format("setmetatable({%s}, {filename=%s, line=%s, sequence=%s})", mixed_concat(mapped, ", "), filename, _304_, "(getmetatable(sequence()))['sequence']") elseif (type(form) == "table") then local mapped = utils.kvmap(form, entry_transform(q, q)) local source = getmetatable(form) - local filename = nil + local filename if source.filename then filename = string.format("%q", source.filename) else filename = "nil" end - local function _1_() + local function _307_() if source then return source.line else return "nil" end end - return string.format("setmetatable({%s}, {filename=%s, line=%s})", mixed_concat(mapped, ", "), filename, _1_()) + return string.format("setmetatable({%s}, {filename=%s, line=%s})", mixed_concat(mapped, ", "), filename, _307_()) elseif (type(form) == "string") then return serialize_string(form) else return tostring(form) end end - return {["apply-manglings"] = apply_manglings, ["compile-stream"] = compile_stream, ["compile-string"] = compile_string, ["declare-local"] = declare_local, ["do-quote"] = do_quote, ["global-mangling"] = global_mangling, ["global-unmangling"] = global_unmangling, ["keep-side-effects"] = keep_side_effects, ["make-scope"] = make_scope, ["require-include"] = require_include, ["symbol-to-expression"] = symbol_to_expression, assert = assert_compile, autogensym = autogensym, compile = compile, compile1 = compile1, destructure = destructure, emit = emit, gensym = gensym, macroexpand = macroexpand_2a, metadata = make_metadata(), scopes = scopes, traceback = traceback} + return {compile = compile, compile1 = compile1, ["compile-stream"] = compile_stream, ["compile-string"] = compile_string, emit = emit, destructure = destructure, ["require-include"] = require_include, autogensym = autogensym, gensym = gensym, ["do-quote"] = do_quote, ["global-mangling"] = global_mangling, ["global-unmangling"] = global_unmangling, ["apply-manglings"] = apply_manglings, macroexpand = macroexpand_2a, ["declare-local"] = declare_local, ["make-scope"] = make_scope, ["keep-side-effects"] = keep_side_effects, ["symbol-to-expression"] = symbol_to_expression, assert = assert_compile, scopes = scopes, traceback = traceback, metadata = make_metadata()} end package.preload["fennel.friend"] = package.preload["fennel.friend"] or function(...) local function ast_source(ast) local m = getmetatable(ast) return ((m and m.line and m) or (("table" == type(ast)) and ast) or {}) end - local suggestions = {["$ and $... in hashfn are mutually exclusive"] = {"modifying the hashfn so it only contains $... or $, $1, $2, $3, etc"}, ["can't start multisym segment with a digit"] = {"removing the digit", "adding a non-digit before the digit"}, ["cannot call literal value"] = {"checking for typos", "checking for a missing function name"}, ["could not compile value of type "] = {"debugging the macro you're calling to return a list or table"}, ["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"}, ["expected a function.* to call"] = {"removing the empty parentheses", "using square brackets if you want an empty table"}, ["expected binding table"] = {"placing a table here in square brackets containing identifiers to bind"}, ["expected body expression"] = {"putting some code in the body of this form after the bindings"}, ["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"}, ["expected even number of name/value bindings"] = {"finding where the identifier or value is missing"}, ["expected even number of values in table literal"] = {"removing a key", "adding a value"}, ["expected local"] = {"looking for a typo", "looking for a local which is used out of its scope"}, ["expected macros to be table"] = {"ensuring your macro definitions return a table"}, ["expected parameters"] = {"adding function parameters as a list of identifiers in brackets"}, ["expected rest argument before last parameter"] = {"moving & to right before the final identifier when destructuring"}, ["expected symbol for function parameter: (.*)"] = {"changing %s to an identifier instead of a literal value"}, ["expected var (.*)"] = {"declaring %s using var instead of let/local", "introducing a new local instead of changing the value of %s"}, ["expected vararg as last parameter"] = {"moving the \"...\" to the end of the parameter list"}, ["expected whitespace before opening delimiter"] = {"adding whitespace"}, ["global (.*) conflicts with local"] = {"renaming local %s"}, ["illegal character: (.)"] = {"deleting or replacing %s", "avoiding reserved characters like \", \\, ', ~, ;, @, `, and comma"}, ["local (.*) was overshadowed by a special form or macro"] = {"renaming local %s"}, ["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"}, ["malformed multisym"] = {"ensuring each period or colon is not followed by another period or colon"}, ["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"}, ["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"}, ["mismatched closing delimiter (.), expected (.)"] = {"replacing %s with %s", "deleting %s", "adding matching opening delimiter earlier"}, ["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"}, ["unable to bind (.*)"] = {"replacing the %s with an identifier"}, ["unexpected closing delimiter (.)"] = {"deleting %s", "adding matching opening delimiter earlier"}, ["unexpected multi symbol (.*)"] = {"removing periods or colons from %s"}, ["unexpected vararg"] = {"putting \"...\" at the end of the fn parameters if the vararg was intended"}, ["unknown global in strict mode: (.*)"] = {"looking to see if there's a typo", "using the _G table instead, eg. _G.%s if you really want a global", "moving this code to somewhere that %s is in scope", "binding %s as a local in the scope of this code"}, ["unused local (.*)"] = {"fixing a typo so %s is used", "renaming the local to _%s"}, ["use of global (.*) is aliased by a local"] = {"renaming local %s", "refer to the global using _G.%s instead of directly"}} + local suggestions = {["unexpected multi symbol (.*)"] = {"removing periods or colons from %s"}, ["use of global (.*) is aliased by a local"] = {"renaming local %s", "refer to the global using _G.%s instead of directly"}, ["local (.*) was overshadowed by a special form or macro"] = {"renaming local %s"}, ["global (.*) conflicts with local"] = {"renaming local %s"}, ["expected var (.*)"] = {"declaring %s using var instead of let/local", "introducing a new local instead of changing the value of %s"}, ["expected macros to be table"] = {"ensuring your macro definitions return a table"}, ["expected each macro to be function"] = {"ensuring that the value for each key in your macros table contains a function", "avoid defining nested macro tables"}, ["macro not found in macro module"] = {"checking the keys of the imported macro module's returned table"}, ["macro tried to bind (.*) without gensym"] = {"changing to %s# when introducing identifiers inside macros"}, ["unknown global in strict mode: (.*)"] = {"looking to see if there's a typo", "using the _G table instead, eg. _G.%s if you really want a global", "moving this code to somewhere that %s is in scope", "binding %s as a local in the scope of this code"}, ["expected a function.* to call"] = {"removing the empty parentheses", "using square brackets if you want an empty table"}, ["cannot call literal value"] = {"checking for typos", "checking for a missing function name"}, ["unexpected vararg"] = {"putting \"...\" at the end of the fn parameters if the vararg was intended"}, ["multisym method calls may only be in call position"] = {"using a period instead of a colon to reference a table's fields", "putting parens around this"}, ["unused local (.*)"] = {"fixing a typo so %s is used", "renaming the local to _%s"}, ["expected parameters"] = {"adding function parameters as a list of identifiers in brackets"}, ["unable to bind (.*)"] = {"replacing the %s with an identifier"}, ["expected rest argument before last parameter"] = {"moving & to right before the final identifier when destructuring"}, ["expected vararg as last parameter"] = {"moving the \"...\" to the end of the parameter list"}, ["expected symbol for function parameter: (.*)"] = {"changing %s to an identifier instead of a literal value"}, ["could not compile value of type "] = {"debugging the macro you're calling to return a list or table"}, ["expected local"] = {"looking for a typo", "looking for a local which is used out of its scope"}, ["expected body expression"] = {"putting some code in the body of this form after the bindings"}, ["expected binding and iterator"] = {"making sure you haven't omitted a local name or iterator"}, ["expected binding sequence"] = {"placing a table here in square brackets containing identifiers to bind"}, ["expected even number of name/value bindings"] = {"finding where the identifier or value is missing"}, ["may only be used at compile time"] = {"moving this to inside a macro if you need to manipulate symbols/lists", "using square brackets instead of parens to construct a table"}, ["unexpected closing delimiter (.)"] = {"deleting %s", "adding matching opening delimiter earlier"}, ["mismatched closing delimiter (.), expected (.)"] = {"replacing %s with %s", "deleting %s", "adding matching opening delimiter earlier"}, ["expected even number of values in table literal"] = {"removing a key", "adding a value"}, ["expected whitespace before opening delimiter"] = {"adding whitespace"}, ["illegal character: (.)"] = {"deleting or replacing %s", "avoiding reserved characters like \", \\, ', ~, ;, @, `, and comma"}, ["could not read number (.*)"] = {"removing the non-digit character", "beginning the identifier with a non-digit if it is not meant to be a number"}, ["can't start multisym segment with a digit"] = {"removing the digit", "adding a non-digit before the digit"}, ["malformed multisym"] = {"ensuring each period or colon is not followed by another period or colon"}, ["method must be last component"] = {"using a period instead of a colon for field access", "removing segments after the colon", "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"}, ["expected even number of pattern/body pairs"] = {"checking that every pattern has a body to go with it", "adding _ before the final body"}, ["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 @@ -3052,7 +3004,7 @@ package.preload["fennel.friend"] = package.preload["fennel.friend"] or function( local function read_line_from_file(filename, line) local bytes = 0 local f = assert(io.open(filename)) - local _ = nil + local _ for _0 = 1, (line - 1) do bytes = (bytes + 1 + #f:read()) end @@ -3066,7 +3018,7 @@ package.preload["fennel.friend"] = package.preload["fennel.friend"] or function( local current_line = (_3fcurrent_line or 1) local bytes = ((_3fbytes or 0) + #this_line + #newline) if (target_line == current_line) then - return this_line, bytes + return this_line, (bytes - #this_line - 1) elseif this_line then return read_line_from_string(matcher, target_line, (current_line + 1), bytes) end @@ -3078,12 +3030,12 @@ package.preload["fennel.friend"] = package.preload["fennel.friend"] or function( return read_line_from_file(filename, line) end end - local function friendly_msg(msg, _0_0, source) - local _1_ = _0_0 - local byteend = _1_["byteend"] - local bytestart = _1_["bytestart"] - local filename = _1_["filename"] - local line = _1_["line"] + local function friendly_msg(msg, _116_, source) + local _arg_117_ = _116_ + local filename = _arg_117_["filename"] + local line = _arg_117_["line"] + local bytestart = _arg_117_["bytestart"] + local byteend = _arg_117_["byteend"] local ok, codeline, bol = pcall(read_line, filename, line, source) local suggestions0 = suggest(msg) local out = {msg, ""} @@ -3106,15 +3058,15 @@ package.preload["fennel.friend"] = package.preload["fennel.friend"] or function( end local function assert_compile(condition, msg, ast, source) if not condition then - local _1_ = ast_source(ast) - local filename = _1_["filename"] - local line = _1_["line"] + local _let_122_ = ast_source(ast) + local filename = _let_122_["filename"] + local line = _let_122_["line"] error(friendly_msg(("Compile error in %s:%s\n %s"):format((filename or "unknown"), (line or "?"), msg), ast_source(ast), source), 0) end return condition end local function parse_error(msg, filename, line, bytestart, source) - return error(friendly_msg(("Parse error in %s:%s\n %s"):format(filename, line, msg), {bytestart = bytestart, filename = filename, line = line}, source), 0) + return error(friendly_msg(("Parse error in %s:%s\n %s"):format(filename, line, msg), {filename = filename, line = line, bytestart = bytestart}, source), 0) end return {["assert-compile"] = assert_compile, ["parse-error"] = parse_error} end @@ -3124,54 +3076,53 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( local unpack = (table.unpack or _G.unpack) local function granulate(getchunk) local c, index, done_3f = "", 1, false - local function _0_(parser_state) + local function _124_(parser_state) if not done_3f then if (index <= #c) then local b = c:byte(index) index = (index + 1) return b else - local _1_0, _2_0, _3_0 = getchunk(parser_state) - local _4_ - do - local char = _1_0 - _4_ = ((nil ~= _1_0) and (char ~= "")) + local _125_ = getchunk(parser_state) + local function _126_() + local char = _125_ + return (char ~= "") end - if _4_ then - local char = _1_0 + if ((nil ~= _125_) and _126_()) then + local char = _125_ c = char index = 2 return c:byte() else - local _ = _1_0 + local _ = _125_ done_3f = true return nil end end end end - local function _1_() + local function _130_() c = "" return nil end - return _0_, _1_ + return _124_, _130_ end local function string_stream(str) local str0 = str:gsub("^#!", ";;") local index = 1 - local function _0_() + local function _131_() local r = str0:byte(index) index = (index + 1) return r end - return _0_ + return _131_ end - local delims = {[123] = 125, [125] = true, [40] = 41, [41] = true, [91] = 93, [93] = true} + local delims = {[40] = 41, [41] = true, [91] = 93, [93] = true, [123] = 125, [125] = true} local function whitespace_3f(b) return ((b == 32) or ((b >= 9) and (b <= 13))) end local function sym_char_3f(b) - local b0 = nil + local b0 if ("number" == type(b)) then b0 = b else @@ -3208,12 +3159,12 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end assert(((nil == filename) or ("string" == type(filename))), "expected filename as second argument to parser") local function parse_error(msg, byteindex_override) - local _0_ = (options or utils.root.options or {}) - local source = _0_["source"] - local unfriendly = _0_["unfriendly"] + local _let_136_ = (options or utils.root.options or {}) + local source = _let_136_["source"] + local unfriendly = _let_136_["unfriendly"] utils.root.reset() - if unfriendly then - return error(string.format("Parse error in %s:%s: %s", (filename or "unknown"), (line or "?"), msg), 0) + if (unfriendly or not friend or not _G.io or not _G.io.read) then + return error(string.format("%s:%s: Parse error: %s", (filename or "unknown"), (line or "?"), msg), 0) else return friend["parse-error"](msg, (filename or "unknown"), (line or "?"), (byteindex_override or byteindex), source) end @@ -3221,38 +3172,38 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( local function parse_stream() local whitespace_since_dispatch, done_3f, retval = true local function dispatch(v) - local _0_0 = stack[#stack] - if (_0_0 == nil) then + local _138_ = stack[#stack] + if (_138_ == nil) then retval, done_3f, whitespace_since_dispatch = v, true, false return nil - elseif ((type(_0_0) == "table") and (nil ~= _0_0.prefix)) then - local prefix = _0_0.prefix - local source = nil + elseif ((_G.type(_138_) == "table") and (nil ~= (_138_).prefix)) then + local prefix = (_138_).prefix + local source do - local _1_0 = table.remove(stack) - _1_0["byteend"] = byteindex - source = _1_0 + local _139_ = table.remove(stack) + do end (_139_)["byteend"] = byteindex + source = _139_ end local list = utils.list(utils.sym(prefix, source), v) for k, v0 in pairs(source) do list[k] = v0 end return dispatch(list) - elseif (nil ~= _0_0) then - local top = _0_0 + elseif (nil ~= _138_) then + local top = _138_ whitespace_since_dispatch = false return table.insert(top, v) end end local function badend() local accum = utils.map(stack, "closer") - local _0_ + local _141_ if (#stack == 1) then - _0_ = "" + _141_ = "" else - _0_ = "s" + _141_ = "s" end - return parse_error(string.format("expected closing delimiter%s %s", _0_, string.char(unpack(accum)))) + return parse_error(string.format("expected closing delimiter%s %s", _141_, string.char(unpack(accum)))) end local function skip_whitespace(b) if (b and whitespace_3f(b)) then @@ -3266,14 +3217,14 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end local function parse_comment(b, contents) if (b and (10 ~= b)) then - local function _1_() - local _0_0 = contents - table.insert(_0_0, string.char(b)) - return _0_0 + local function _145_() + local _144_ = contents + table.insert(_144_, string.char(b)) + return _144_ end - return parse_comment(getb(), _1_()) + return parse_comment(getb(), _145_()) elseif (options and options.comments) then - return dispatch(utils.comment(table.concat(contents), {filename = filename, line = (line - 1)})) + return dispatch(utils.comment(table.concat(contents), {line = (line - 1), filename = filename})) else return b end @@ -3295,12 +3246,12 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( return dispatch(val) end local function add_comment_at(comments, index, node) - local _0_0 = comments[index] - if (nil ~= _0_0) then - local existing = _0_0 + local _148_ = comments[index] + if (nil ~= _148_) then + local existing = _148_ return table.insert(existing, node) else - local _ = _0_0 + local _ = _148_ comments[index] = {node} return nil end @@ -3313,7 +3264,7 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end end local function extract_comments(tbl) - local comments = {keys = {}, last = {}, values = {}} + local comments = {keys = {}, values = {}, last = {}} while utils["comment?"](tbl[#tbl]) do table.insert(comments.last, 1, table.remove(tbl)) end @@ -3373,15 +3324,15 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end local function parse_string_loop(chars, b, state) table.insert(chars, b) - local state0 = nil + local state0 do - local _0_0 = {state, b} - if ((type(_0_0) == "table") and (_0_0[1] == "base") and (_0_0[2] == 92)) then + local _158_ = {state, b} + if ((_G.type(_158_) == "table") and ((_158_)[1] == "base") and ((_158_)[2] == 92)) then state0 = "backslash" - elseif ((type(_0_0) == "table") and (_0_0[1] == "base") and (_0_0[2] == 34)) then + elseif ((_G.type(_158_) == "table") and ((_158_)[1] == "base") and ((_158_)[2] == 34)) then state0 = "done" else - local _ = _0_0 + local _ = _158_ state0 = "base" end end @@ -3392,7 +3343,7 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end end local function escape_char(c) - return ({[10] = "\\n", [11] = "\\v", [12] = "\\f", [13] = "\\r", [7] = "\\a", [8] = "\\b", [9] = "\\t"})[c:byte()] + return ({[7] = "\\a", [8] = "\\b", [9] = "\\t", [10] = "\\n", [11] = "\\v", [12] = "\\f", [13] = "\\r"})[c:byte()] end local function parse_string() table.insert(stack, {closer = 34}) @@ -3403,11 +3354,16 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( table.remove(stack) local raw = string.char(unpack(chars)) local formatted = raw:gsub("[\7-\13]", escape_char) - local load_fn = (rawget(_G, "loadstring") or load)(("return " .. formatted)) - return dispatch(load_fn()) + local _162_ = (rawget(_G, "loadstring") or load)(("return " .. formatted)) + if (nil ~= _162_) then + local load_fn = _162_ + return dispatch(load_fn()) + elseif (_162_ == nil) then + return parse_error(("Invalid string: " .. raw)) + end end local function parse_prefix(b) - table.insert(stack, {bytestart = byteindex, filename = filename, line = line, prefix = prefixes[b]}) + table.insert(stack, {prefix = prefixes[b], filename = filename, line = line, bytestart = byteindex}) local nextb = getb() if (whitespace_3f(nextb) or (true == delims[nextb])) then if (b ~= 35) then @@ -3435,13 +3391,13 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( dispatch((tonumber(number_with_stripped_underscores) or parse_error(("could not read number \"" .. rawstr .. "\"")))) return true else - local _0_0 = tonumber(number_with_stripped_underscores) - if (nil ~= _0_0) then - local x = _0_0 + local _168_ = tonumber(number_with_stripped_underscores) + if (nil ~= _168_) then + local x = _168_ dispatch(x) return true else - local _ = _0_0 + local _ = _168_ return false end end @@ -3453,6 +3409,8 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( return parse_error(("can't start multisym segment with a digit: " .. rawstr), (((byteindex - #rawstr) + rawstr:find("%.[0-9]")) + 1)) elseif (rawstr:match("[%.:][%.:]") and (rawstr ~= "..") and (rawstr ~= "$...")) then return parse_error(("malformed multisym: " .. rawstr), ((byteindex - #rawstr) + 1 + rawstr:find("[%.:][%.:]"))) + elseif ((rawstr ~= ":") and rawstr:match(":$")) then + return parse_error(("malformed multisym: " .. rawstr), ((byteindex - #rawstr) + 1 + rawstr:find(":$"))) elseif rawstr:match(":.+[%.:]") then return parse_error(("method must be last component of multisym: " .. rawstr), ((byteindex - #rawstr) + rawstr:find(":.+[%.:]"))) else @@ -3488,7 +3446,7 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( parse_prefix(b) elseif (sym_char_3f(b) or (b == string.byte("~"))) then parse_sym(b) - else + elseif not utils.hook("illegal-char", b, getb, ungetb, dispatch) then parse_error(("illegal character: " .. string.char(b))) end if not b then @@ -3501,36 +3459,479 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end return parse_loop(skip_whitespace(getb())) end - local function _0_() - stack = {} + local function _175_() + stack, line, byteindex = {}, 1, 0 return nil end - return parse_stream, _0_ + return parse_stream, _175_ end - return {["string-stream"] = string_stream, ["sym-char?"] = sym_char_3f, granulate = granulate, parser = parser} + return {granulate = granulate, parser = parser, ["string-stream"] = string_stream, ["sym-char?"] = sym_char_3f} +end +package.preload["fennel.view"] = package.preload["fennel.view"] or function(...) + local type_order = {number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7} + local function sort_keys(_1_, _3_) + local _arg_2_ = _1_ + local a = _arg_2_[1] + local _arg_4_ = _3_ + local b = _arg_4_[1] + local ta = type(a) + local tb = type(b) + if ((ta == tb) and ((ta == "string") or (ta == "number"))) then + return (a < b) + else + local dta = type_order[ta] + local dtb = type_order[tb] + if (dta and dtb) then + return (dta < dtb) + elseif dta then + return true + elseif dtb then + return false + else + return (ta < tb) + end + end + end + local function max_index_gap(kv) + local gap = 0 + if (#kv > 0) then + local i = 0 + for _, _7_ in ipairs(kv) do + local _each_8_ = _7_ + local k = _each_8_[1] + if ((k - i) > gap) then + gap = (k - i) + end + i = k + end + end + return gap + end + local function fill_gaps(kv) + local missing_indexes = {} + local i = 0 + for _, _11_ in ipairs(kv) do + local _each_12_ = _11_ + local j = _each_12_[1] + i = (i + 1) + while (i < j) do + table.insert(missing_indexes, i) + i = (i + 1) + end + end + for _, k in ipairs(missing_indexes) do + table.insert(kv, k, {k}) + end + return nil + end + local function table_kv_pairs(t, options) + local assoc_3f = false + local kv = {} + local insert = table.insert + for k, v in pairs(t) do + if (type(k) ~= "number") then + assoc_3f = true + end + insert(kv, {k, v}) + end + table.sort(kv, sort_keys) + if not assoc_3f then + local gap = max_index_gap(kv) + if (max_index_gap(kv) > options["max-sparse-gap"]) then + assoc_3f = true + else + fill_gaps(kv) + end + end + if (#kv == 0) then + return kv, "empty" + else + local function _16_() + if assoc_3f then + return "table" + else + return "seq" + end + end + return kv, _16_() + end + end + local function count_table_appearances(t, appearances) + if (type(t) == "table") then + if not appearances[t] then + appearances[t] = 1 + for k, v in pairs(t) do + count_table_appearances(k, appearances) + count_table_appearances(v, appearances) + end + else + appearances[t] = ((appearances[t] or 0) + 1) + end + end + return appearances + end + local function save_table(t, seen) + local seen0 = (seen or {len = 0}) + local id = (seen0.len + 1) + if not (seen0)[t] then + seen0[t] = id + seen0.len = id + end + return seen0 + end + local function detect_cycle(t, seen, _3fk) + if ("table" == type(t)) then + seen[t] = true + local _21_, _22_ = next(t, _3fk) + if ((nil ~= _21_) and (nil ~= _22_)) then + local k = _21_ + local v = _22_ + return (seen[k] or detect_cycle(k, seen) or seen[v] or detect_cycle(v, seen) or detect_cycle(t, seen, k)) + end + end + end + local function visible_cycle_3f(t, options) + return (options["detect-cycles?"] and detect_cycle(t, {}) and save_table(t, options.seen) and (1 < (options.appearances[t] or 0))) + end + local function table_indent(t, indent, id) + local opener_length + if id then + opener_length = (#tostring(id) + 2) + else + opener_length = 1 + end + return (indent + opener_length) + end + local pp = nil + local function concat_table_lines(elements, options, multiline_3f, indent, table_type, prefix) + local indent_str = ("\n" .. string.rep(" ", indent)) + local open + local _26_ + if ("seq" == table_type) then + _26_ = "[" + else + _26_ = "{" + end + open = ((prefix or "") .. _26_) + local close + if ("seq" == table_type) then + close = "]" + else + close = "}" + end + local oneline = (open .. table.concat(elements, " ") .. close) + if (not options["one-line?"] and (multiline_3f or ((indent + #oneline) > options["line-length"]))) then + return (open .. table.concat(elements, indent_str) .. close) + else + return oneline + end + end + local function pp_associative(t, kv, options, indent, key_3f) + local multiline_3f = false + local id = options.seen[t] + if (options.level >= options.depth) then + return "{...}" + elseif (id and options["detect-cycles?"]) then + return ("@" .. id .. "{...}") + else + local visible_cycle_3f0 = visible_cycle_3f(t, options) + local id0 = (visible_cycle_3f0 and options.seen[t]) + local indent0 = table_indent(t, indent, id0) + local slength + local function _31_() + local _30_ = rawget(_G, "utf8") + if _30_ then + return (_30_).len + else + return _30_ + end + end + local function _33_(_241) + return #_241 + end + slength = ((options["utf8?"] and _31_()) or _33_) + local prefix + if visible_cycle_3f0 then + prefix = ("@" .. id0) + else + prefix = "" + end + local items + do + local tbl_13_auto = {} + for _, _35_ in pairs(kv) do + local _each_36_ = _35_ + local k = _each_36_[1] + local v = _each_36_[2] + local _37_ + do + local k0 = pp(k, options, (indent0 + 1), true) + local v0 = pp(v, options, (indent0 + slength(k0) + 1)) + multiline_3f = (multiline_3f or k0:find("\n") or v0:find("\n")) + _37_ = (k0 .. " " .. v0) + end + tbl_13_auto[(#tbl_13_auto + 1)] = _37_ + end + items = tbl_13_auto + end + return concat_table_lines(items, options, multiline_3f, indent0, "table", prefix) + end + end + local function pp_sequence(t, kv, options, indent) + local multiline_3f = false + local id = options.seen[t] + if (options.level >= options.depth) then + return "[...]" + elseif (id and options["detect-cycles?"]) then + return ("@" .. id .. "[...]") + else + local visible_cycle_3f0 = visible_cycle_3f(t, options) + local id0 = (visible_cycle_3f0 and options.seen[t]) + local indent0 = table_indent(t, indent, id0) + local prefix + if visible_cycle_3f0 then + prefix = ("@" .. id0) + else + prefix = "" + end + local items + do + local tbl_13_auto = {} + for _, _40_ in pairs(kv) do + local _each_41_ = _40_ + local _0 = _each_41_[1] + local v = _each_41_[2] + local _42_ + do + local v0 = pp(v, options, indent0) + multiline_3f = (multiline_3f or v0:find("\n")) + _42_ = v0 + end + tbl_13_auto[(#tbl_13_auto + 1)] = _42_ + end + items = tbl_13_auto + end + return concat_table_lines(items, options, multiline_3f, indent0, "seq", prefix) + end + end + local function concat_lines(lines, options, indent, force_multi_line_3f) + if (#lines == 0) then + if options["empty-as-sequence?"] then + return "[]" + else + return "{}" + end + else + local oneline + local _45_ + do + local tbl_13_auto = {} + for _, line in ipairs(lines) do + tbl_13_auto[(#tbl_13_auto + 1)] = line:gsub("^%s+", "") + end + _45_ = tbl_13_auto + end + oneline = table.concat(_45_, " ") + if (not options["one-line?"] and (force_multi_line_3f or oneline:find("\n") or ((indent + #oneline) > options["line-length"]))) then + return table.concat(lines, ("\n" .. string.rep(" ", indent))) + else + return oneline + end + end + end + local function pp_metamethod(t, metamethod, options, indent) + if (options.level >= options.depth) then + if options["empty-as-sequence?"] then + return "[...]" + else + return "{...}" + end + else + local _ + local function _49_(_241) + return visible_cycle_3f(_241, options) + end + options["visible-cycle?"] = _49_ + _ = nil + local lines, force_multi_line_3f = metamethod(t, pp, options, indent) + options["visible-cycle?"] = nil + local _50_ = type(lines) + if (_50_ == "string") then + return lines + elseif (_50_ == "table") then + return concat_lines(lines, options, indent, force_multi_line_3f) + else + local _0 = _50_ + return error("__fennelview metamethod must return a table of lines") + end + end + end + local function pp_table(x, options, indent) + options.level = (options.level + 1) + local x0 + do + local _53_ + if options["metamethod?"] then + local _54_ = x + if _54_ then + local _55_ = getmetatable(_54_) + if _55_ then + _53_ = (_55_).__fennelview + else + _53_ = _55_ + end + else + _53_ = _54_ + end + else + _53_ = nil + end + if (nil ~= _53_) then + local metamethod = _53_ + x0 = pp_metamethod(x, metamethod, options, indent) + else + local _ = _53_ + local _59_, _60_ = table_kv_pairs(x, options) + if (true and (_60_ == "empty")) then + local _0 = _59_ + if options["empty-as-sequence?"] then + x0 = "[]" + else + x0 = "{}" + end + elseif ((nil ~= _59_) and (_60_ == "table")) then + local kv = _59_ + x0 = pp_associative(x, kv, options, indent) + elseif ((nil ~= _59_) and (_60_ == "seq")) then + local kv = _59_ + x0 = pp_sequence(x, kv, options, indent) + else + x0 = nil + end + end + end + options.level = (options.level - 1) + return x0 + end + local function number__3estring(n) + local _64_ = string.gsub(tostring(n), ",", ".") + return _64_ + end + local function colon_string_3f(s) + return s:find("^[-%w?^_!$%&*+./@|<=>]+$") + end + local function pp_string(str, options, indent) + local escs + local _65_ + if (options["escape-newlines?"] and (#str < (options["line-length"] - indent))) then + _65_ = "\\n" + else + _65_ = "\n" + end + local function _67_(_241, _242) + return ("\\%03d"):format(_242:byte()) + end + escs = setmetatable({["\7"] = "\\a", ["\8"] = "\\b", ["\12"] = "\\f", ["\11"] = "\\v", ["\13"] = "\\r", ["\9"] = "\\t", ["\\"] = "\\\\", ["\""] = "\\\"", ["\n"] = _65_}, {__index = _67_}) + return ("\"" .. str:gsub("[%c\\\"]", escs) .. "\"") + end + local function make_options(t, options) + local defaults = {["line-length"] = 80, ["one-line?"] = false, depth = 128, ["detect-cycles?"] = true, ["empty-as-sequence?"] = false, ["metamethod?"] = true, ["prefer-colon?"] = false, ["escape-newlines?"] = false, ["utf8?"] = true, ["max-sparse-gap"] = 10} + local overrides = {level = 0, appearances = count_table_appearances(t, {}), seen = {len = 0}} + for k, v in pairs((options or {})) do + defaults[k] = v + end + for k, v in pairs(overrides) do + defaults[k] = v + end + return defaults + end + local function _68_(x, options, indent, colon_3f) + local indent0 = (indent or 0) + local options0 = (options or make_options(x)) + local x0 + if options0.preprocess then + x0 = options0.preprocess(x, options0) + else + x0 = x + end + local tv = type(x0) + local function _71_() + local _70_ = getmetatable(x0) + if _70_ then + return (_70_).__fennelview + else + return _70_ + end + end + if ((tv == "table") or ((tv == "userdata") and _71_())) then + return pp_table(x0, options0, indent0) + elseif (tv == "number") then + return number__3estring(x0) + else + local function _73_() + if (colon_3f ~= nil) then + return colon_3f + elseif ("function" == type(options0["prefer-colon?"])) then + return options0["prefer-colon?"](x0) + else + return options0["prefer-colon?"] + end + end + if ((tv == "string") and colon_string_3f(x0) and _73_()) then + return (":" .. x0) + elseif (tv == "string") then + return pp_string(x0, options0, indent0) + elseif ((tv == "boolean") or (tv == "nil")) then + return tostring(x0) + else + return ("#<" .. tostring(x0) .. ">") + end + end + end + pp = _68_ + local function view(x, options) + return pp(x, make_options(x, options), 0) + end + return view end package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(...) + local view = require("fennel.view") local function stablepairs(t) local keys = {} + local used_keys = {} local succ = {} - for k in pairs(t) do - table.insert(keys, k) + if (getmetatable(t) and getmetatable(t).keys) then + for _, k in ipairs(getmetatable(t).keys) do + if used_keys[k] then + for i = #keys, 1, -1 do + if (keys[i] == k) then + table.remove(keys, i) + end + end + end + used_keys[k] = true + table.insert(keys, k) + end + else + for k in pairs(t) do + table.insert(keys, k) + end + local function _77_(_241, _242) + return (tostring(_241) < tostring(_242)) + end + table.sort(keys, _77_) end - local function _0_(_241, _242) - return (tostring(_241) < tostring(_242)) - end - table.sort(keys, _0_) for i, k in ipairs(keys) do succ[k] = keys[(i + 1)] end local function stablenext(tbl, idx) - local key = nil + local key if (idx == nil) then key = keys[1] else key = succ[idx] end - local value = nil + local value if (key == nil) then value = nil else @@ -3542,19 +3943,19 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. end local function map(t, f, out) local out0 = (out or {}) - local f0 = nil + local f0 if (type(f) == "function") then f0 = f else - local function _0_(_241) - return _241[f] + local function _81_(_241) + return (_241)[f] end - f0 = _0_ + f0 = _81_ end for _, x in ipairs(t) do - local _1_0 = f0(x) - if (nil ~= _1_0) then - local v = _1_0 + local _83_ = f0(x) + if (nil ~= _83_) then + local v = _83_ table.insert(out0, v) end end @@ -3562,23 +3963,23 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. end local function kvmap(t, f, out) local out0 = (out or {}) - local f0 = nil + local f0 if (type(f) == "function") then f0 = f else - local function _0_(_241) - return _241[f] + local function _85_(_241) + return (_241)[f] end - f0 = _0_ + f0 = _85_ end for k, x in stablepairs(t) do - local _1_0, _2_0 = f0(k, x) - if ((nil ~= _1_0) and (nil ~= _2_0)) then - local key = _1_0 - local value = _2_0 + local _87_, _88_ = f0(k, x) + if ((nil ~= _87_) and (nil ~= _88_)) then + local key = _87_ + local value = _88_ out0[key] = value - elseif (nil ~= _1_0) then - local value = _1_0 + elseif (nil ~= _87_) then + local value = _87_ table.insert(out0, value) end end @@ -3592,13 +3993,13 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. return to0 end local function member_3f(x, tbl, n) - local _0_0 = tbl[(n or 1)] - if (_0_0 == x) then + local _90_ = tbl[(n or 1)] + if (_90_ == x) then return true - elseif (_0_0 == nil) then - return false + elseif (_90_ == nil) then + return nil else - local _ = _0_0 + local _ = _90_ return member_3f(x, tbl, ((n or 1) + 1)) end end @@ -3614,10 +4015,13 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. seen[next_state] = true return next_state, value else - local meta = getmetatable(t) - if (meta and meta.__index) then - t = meta.__index - return allpairs_next(t) + local _92_ = getmetatable(t) + if ((_G.type(_92_) == "table") and true) then + local __index = (_92_).__index + if ("table" == type(__index)) then + t = __index + return allpairs_next(t) + end end end end @@ -3637,7 +4041,7 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. for i = 1, max do safe[i] = (((self[i] == nil) and nil_sym) or self[i]) end - return ("(" .. table.concat(map(safe, (tostring2 or tostring)), " ", 1, max) .. ")") + return ("(" .. table.concat(map(safe, (tostring2 or view)), " ", 1, max) .. ")") end local function comment_view(c) return c, true @@ -3648,17 +4052,21 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. local function sym_3c(a, b) return (a[1] < tostring(b)) end - local symbol_mt = {"SYMBOL", __eq = sym_3d, __fennelview = deref, __lt = sym_3c, __tostring = deref} - local expr_mt = {"EXPR", __tostring = deref} + local symbol_mt = {"SYMBOL", __fennelview = deref, __tostring = deref, __eq = sym_3d, __lt = sym_3c} + local expr_mt + local function _97_(x) + return tostring(deref(x)) + end + expr_mt = {"EXPR", __tostring = _97_} local list_mt = {"LIST", __fennelview = list__3estring, __tostring = list__3estring} - local comment_mt = {"COMMENT", __eq = sym_3d, __fennelview = comment_view, __lt = sym_3c, __tostring = deref} + local comment_mt = {"COMMENT", __fennelview = comment_view, __tostring = deref, __eq = sym_3d, __lt = sym_3c} local sequence_marker = {"SEQUENCE"} local vararg = setmetatable({"..."}, {"VARARG", __fennelview = deref, __tostring = deref}) - local getenv = nil - local function _0_() + local getenv + local function _98_() return nil end - getenv = ((os and os.getenv) or _0_) + getenv = ((os and os.getenv) or _98_) local function debug_on_3f(flag) local level = (getenv("FENNEL_DEBUG") or "") return ((level == "all") or level:find(flag)) @@ -3683,9 +4091,9 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. return setmetatable({strcode, type = etype}, expr_mt) end local function comment_2a(contents, _3fsource) - local _1_ = (_3fsource or {}) - local filename = _1_["filename"] - local line = _1_["line"] + local _let_100_ = (_3fsource or {}) + local filename = _let_100_["filename"] + local line = _let_100_["line"] return setmetatable({contents, filename = filename, line = line}, comment_mt) end local function varg() @@ -3763,16 +4171,16 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. end return subopts end - local root = nil - local function _1_() + local root + local function _105_() end - root = {chunk = nil, options = nil, reset = _1_, scope = nil} - root["set-reset"] = function(_2_0) - local _3_ = _2_0 - local chunk = _3_["chunk"] - local options = _3_["options"] - local reset = _3_["reset"] - local scope = _3_["scope"] + root = {chunk = nil, scope = nil, options = nil, reset = _105_} + root["set-reset"] = function(_106_) + local _arg_107_ = _106_ + local chunk = _arg_107_["chunk"] + local scope = _arg_107_["scope"] + local options = _arg_107_["options"] + local reset = _arg_107_["reset"] root.reset = function() root.chunk, root.scope, root.options, root.reset = chunk, scope, options, reset return nil @@ -3780,18 +4188,24 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. return root.reset end local function hook(event, ...) + local result = nil if (root.options and root.options.plugins) then for _, plugin in ipairs(root.options.plugins) do - local _3_0 = plugin[event] - if (nil ~= _3_0) then - local f = _3_0 - f(...) + do + local _108_ = plugin[event] + if (nil ~= _108_) then + local f = _108_ + result = f(...) + end + end + if (nil ~= result) then + return result end end return nil end end - return {["comment?"] = comment_3f, ["debug-on?"] = debug_on_3f, ["expr?"] = expr_3f, ["list?"] = list_3f, ["lua-keywords"] = lua_keywords, ["member?"] = member_3f, ["multi-sym?"] = multi_sym_3f, ["propagate-options"] = propagate_options, ["quoted?"] = quoted_3f, ["sequence?"] = sequence_3f, ["sym?"] = sym_3f, ["table?"] = table_3f, ["valid-lua-identifier?"] = valid_lua_identifier_3f, ["varg?"] = varg_3f, ["walk-tree"] = walk_tree, allpairs = allpairs, comment = comment_2a, copy = copy, deref = deref, expr = expr, hook = hook, kvmap = kvmap, list = list, map = map, path = table.concat({"./?.fnl", "./?/init.fnl", getenv("FENNEL_PATH")}, ";"), root = root, sequence = sequence, stablepairs = stablepairs, sym = sym, varg = varg} + return {allpairs = allpairs, stablepairs = stablepairs, copy = copy, kvmap = kvmap, map = map, ["walk-tree"] = walk_tree, ["member?"] = member_3f, list = list, sequence = sequence, sym = sym, varg = varg, expr = expr, comment = comment_2a, ["comment?"] = comment_3f, ["expr?"] = expr_3f, ["list?"] = list_3f, ["multi-sym?"] = multi_sym_3f, ["sequence?"] = sequence_3f, ["sym?"] = sym_3f, ["table?"] = table_3f, ["varg?"] = varg_3f, ["quoted?"] = quoted_3f, ["valid-lua-identifier?"] = valid_lua_identifier_3f, ["lua-keywords"] = lua_keywords, hook = hook, ["propagate-options"] = propagate_options, root = root, ["debug-on?"] = debug_on_3f, path = table.concat({"./?.fnl", "./?/init.fnl", getenv("FENNEL_PATH")}, ";"), ["macro-path"] = table.concat({"./?.fnl", "./?/init-macros.fnl", "./?/init.fnl", getenv("FENNEL_MACRO_PATH")}, ";")} end package.preload["fennel"] = package.preload["fennel"] or function(...) local utils = require("fennel.utils") @@ -3800,11 +4214,12 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) local specials = require("fennel.specials") local repl = require("fennel.repl") local view = require("fennel.view") - local function eval_env(env) + local function eval_env(env, opts) if (env == "_COMPILER") then - local env0 = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}) - local mt = getmetatable(env0) - mt.__index = _G + local env0 = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}, opts) + if (opts.allowedGlobals == nil) then + opts.allowedGlobals = specials["current-global-names"](env0) + end return specials["wrap-env"](env0) else return (env and specials["wrap-env"](env)) @@ -3812,7 +4227,7 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) end local function eval_opts(options, str) local opts = utils.copy(options) - if ((opts.allowedGlobals == nil) and not getmetatable(opts.env)) then + if (opts.allowedGlobals == nil) then opts.allowedGlobals = specials["current-global-names"](opts.env) end if (not opts.filename and not opts.source) then @@ -3825,17 +4240,17 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) end local function eval(str, options, ...) local opts = eval_opts(options, str) - local env = eval_env(opts.env) + local env = eval_env(opts.env, opts) local lua_source = compiler["compile-string"](str, opts) - local loader = nil - local function _0_(...) + local loader + local function _563_(...) if opts.filename then return ("@" .. opts.filename) else return str end end - loader = specials["load-code"](lua_source, env, _0_(...)) + loader = specials["load-code"](lua_source, env, _563_(...)) opts.filename = nil return loader(...) end @@ -3847,7 +4262,34 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) opts.filename = filename return eval(source, opts, ...) end - local mod = {["comment?"] = utils["comment?"], ["compile-stream"] = compiler["compile-stream"], ["compile-string"] = compiler["compile-string"], ["list?"] = utils["list?"], ["load-code"] = specials["load-code"], ["macro-loaded"] = specials["macro-loaded"], ["macro-searchers"] = specials["macro-searchers"], ["make-searcher"] = specials["make-searcher"], ["search-module"] = specials["search-module"], ["sequence?"] = utils["sequence?"], ["string-stream"] = parser["string-stream"], ["sym-char?"] = parser["sym-char?"], ["sym?"] = utils["sym?"], comment = utils.comment, compile = compiler.compile, compile1 = compiler.compile1, compileStream = compiler["compile-stream"], compileString = compiler["compile-string"], doc = specials.doc, dofile = dofile_2a, eval = eval, gensym = compiler.gensym, granulate = parser.granulate, list = utils.list, loadCode = specials["load-code"], macroLoaded = specials["macro-loaded"], makeSearcher = specials["make-searcher"], make_searcher = specials["make-searcher"], mangle = compiler["global-mangling"], metadata = compiler.metadata, parser = parser.parser, path = utils.path, repl = repl, scope = compiler["make-scope"], searchModule = specials["search-module"], searcher = specials["make-searcher"](), sequence = utils.sequence, stringStream = parser["string-stream"], sym = utils.sym, traceback = compiler.traceback, unmangle = compiler["global-unmangling"], varg = utils.varg, version = "0.9.1", view = view} + local function syntax() + local body_3f = {"when", "with-open", "collect", "icollect", "lambda", "\206\187", "macro", "match", "accumulate"} + local binding_3f = {"collect", "icollect", "each", "for", "let", "with-open", "accumulate"} + local define_3f = {"fn", "lambda", "\206\187", "var", "local", "macro", "macros", "global"} + local out = {} + for k, v in pairs(compiler.scopes.global.specials) do + local metadata = (compiler.metadata[v] or {}) + do end (out)[k] = {["special?"] = true, ["body-form?"] = metadata["fnl/body-form?"], ["binding-form?"] = utils["member?"](k, binding_3f), ["define?"] = utils["member?"](k, define_3f)} + end + for k, v in pairs(compiler.scopes.global.macros) do + out[k] = {["macro?"] = true, ["body-form?"] = utils["member?"](k, body_3f), ["binding-form?"] = utils["member?"](k, binding_3f), ["define?"] = utils["member?"](k, define_3f)} + end + for k, v in pairs(_G) do + local _564_ = type(v) + if (_564_ == "function") then + out[k] = {["global?"] = true, ["function?"] = true} + elseif (_564_ == "table") then + for k2, v2 in pairs(v) do + if (("function" == type(v2)) and (k ~= "_G")) then + out[(k .. "." .. k2)] = {["function?"] = true, ["global?"] = true} + end + end + out[k] = {["global?"] = true} + end + end + return out + end + local mod = {list = utils.list, ["list?"] = utils["list?"], sym = utils.sym, ["sym?"] = utils["sym?"], sequence = utils.sequence, ["sequence?"] = utils["sequence?"], comment = utils.comment, ["comment?"] = utils["comment?"], varg = utils.varg, path = utils.path, ["macro-path"] = utils["macro-path"], ["sym-char?"] = parser["sym-char?"], parser = parser.parser, granulate = parser.granulate, ["string-stream"] = parser["string-stream"], compile = compiler.compile, ["compile-string"] = compiler["compile-string"], ["compile-stream"] = compiler["compile-stream"], compile1 = compiler.compile1, traceback = compiler.traceback, mangle = compiler["global-mangling"], unmangle = compiler["global-unmangling"], metadata = compiler.metadata, scope = compiler["make-scope"], gensym = compiler.gensym, ["load-code"] = specials["load-code"], ["macro-loaded"] = specials["macro-loaded"], ["macro-searchers"] = specials["macro-searchers"], ["search-module"] = specials["search-module"], ["make-searcher"] = specials["make-searcher"], makeSearcher = specials["make-searcher"], searcher = specials["make-searcher"](), doc = specials.doc, view = view, eval = eval, dofile = dofile_2a, version = "1.0.0-dev", repl = repl, syntax = syntax, loadCode = specials["load-code"], make_searcher = specials["make-searcher"], searchModule = specials["search-module"], macroLoaded = specials["macro-loaded"], compileStream = compiler["compile-stream"], compileString = compiler["compile-string"], stringStream = parser["string-stream"]} utils["fennel-module"] = mod do local builtin_macros = [===[;; This module contains all the built-in Fennel macros. Unlike all the other @@ -3912,12 +4354,18 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (-?>> ,el ,(unpack els)) ,tmp))))) - (fn ?dot [tbl k ...] + (fn ?dot [tbl ...] "Nil-safe table look up. Same as . (dot), except will short-circuit with nil when it encounters a nil value in any of subsequent keys." - (if (= nil k) tbl `(let [res# (. ,tbl ,k)] - (and res# (?. res# ,...))))) + (let [head (gensym :t) + lookups `(do (var ,head ,tbl) ,head)] + (each [_ k (ipairs [...])] + ;; Kinda gnarly to reassign in place like this, but it emits the best lua. + ;; With this impl, it emits a flat, concise, and readable set of if blocks. + (table.insert lookups (# lookups) `(if (not= nil ,head) + (set ,head (. ,head ,k))))) + lookups)) (fn doto* [val ...] "Evaluates val and splices it into the first argument of subsequent forms." @@ -3952,7 +4400,16 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (table.insert closer 4 `(: ,(. closable-bindings i) :close))) `(let ,closable-bindings ,closer - (close-handlers# (xpcall ,bodyfn ,traceback))))) + (close-handlers# (_G.xpcall ,bodyfn ,traceback))))) + + (fn into-val [iter-tbl] + (var into nil) + (for [i (length iter-tbl) 2 -1] + (if (= :into (. iter-tbl i)) + (do (set into (table.remove iter-tbl (+ i 1))) + (table.remove iter-tbl i)))) + (assert (or (not into) (table? into)) "expected table in :into clause") + (or into [])) (fn collect* [iter-tbl key-value-expr ...] "Returns a table made by running an iterator and evaluating an expression @@ -3964,13 +4421,16 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (collect [k v (pairs {:apple \"red\" :orange \"orange\"})] (values v k)) returns - {:red \"apple\" :orange \"orange\"}" + {:red \"apple\" :orange \"orange\"} + + Supports an :into clause after the iterator to put results in an existing table. + Supports early termination with an :until clause." (assert (and (sequence? iter-tbl) (>= (length iter-tbl) 2)) "expected iterator binding table") (assert (not= nil key-value-expr) "expected key-value expression") (assert (= nil ...) "expected exactly one body expression. Wrap multiple expressions with do") - `(let [tbl# {}] + `(let [tbl# ,(into-val iter-tbl)] (each ,iter-tbl (match ,key-value-expr (k# v#) (tset tbl# k# v#))) @@ -3984,24 +4444,68 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) For example, (icollect [_ v (ipairs [1 2 3 4 5])] (when (> v 2) (* v v))) returns - [9 16 25]" + [9 16 25] + + Supports an :into clause after the iterator to put results in an existing table. + Supports early termination with an :until clause." (assert (and (sequence? iter-tbl) (>= (length iter-tbl) 2)) "expected iterator binding table") (assert (not= nil value-expr) "expected table value expression") (assert (= nil ...) "expected exactly one body expression. Wrap multiple expressions with do") - `(let [tbl# []] + `(let [tbl# ,(into-val iter-tbl)] (each ,iter-tbl (tset tbl# (+ (length tbl#) 1) ,value-expr)) tbl#)) + (fn accumulate* [iter-tbl accum-expr ...] + "Accumulation macro. + It takes a binding table and an expression as its arguments. + In the binding table, the first symbol is bound to the second value, being an + initial accumulator variable. The rest are an iterator binding table in the + format `each` takes. + It runs through the iterator in each step of which the given expression is + evaluated, and its returned value updates the accumulator variable. + It eventually returns the final value of the accumulator variable. + + For example, + (accumulate [total 0 + _ n (pairs {:apple 2 :orange 3})] + (+ total n)) + returns + 5" + (assert (and (sequence? iter-tbl) (>= (length iter-tbl) 4)) + "expected initial value and iterator binding table") + (assert (not= nil accum-expr) "expected accumulating expression") + (assert (= nil ...) + "expected exactly one body expression. Wrap multiple expressions with do") + (let [accum-var (table.remove iter-tbl 1) + accum-init (table.remove iter-tbl 1)] + `(do (var ,accum-var ,accum-init) + (each ,iter-tbl + (set ,accum-var ,accum-expr)) + ,accum-var))) + (fn partial* [f ...] "Returns a function with all arguments partially applied to f." (assert f "expected a function to partially apply") - (let [body (list f ...)] - (table.insert body _VARARG) - `(fn [,_VARARG] - ,body))) + (let [bindings [] + args []] + (each [_ arg (ipairs [...])] + (if (or (= :number (type arg)) + (= :string (type arg)) + (= :boolean (type arg)) + (= `nil arg)) + (table.insert args arg) + (let [name (gensym)] + (table.insert bindings name) + (table.insert bindings arg) + (table.insert args name)))) + (let [body (list f (unpack args))] + (table.insert body _VARARG) + `(let ,bindings + (fn [,_VARARG] + ,body))))) (fn pick-args* [n f] "Creates a function of arity n that applies its arguments to f. @@ -4010,6 +4514,9 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (pick-args 2 func) expands to (fn [_0_ _1_] (func _0_ _1_))" + (if (and _G.io _G.io.stderr) + (_G.io.stderr:write + "-- WARNING: pick-args is deprecated and will be removed in the future.\n")) (assert (and (= (type n) :number) (= n (math.floor n)) (>= n 0)) (.. "Expected n to be an integer literal >= 0, got " (tostring n))) (let [bindings []] @@ -4037,9 +4544,9 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (values ,(unpack let-syms)))))) (fn lambda* [...] - "Function literal with arity checking. - Will throw an exception if a declared argument is passed in as nil, unless - that argument name begins with ?." + "Function literal with nil-checked arguments. + Like `fn`, but will throw an exception if a declared argument is passed in as + nil, unless that argument's name begins with a question mark." (let [args [...] has-internal-name? (sym? (. args 1)) arglist (if has-internal-name? (. args 2) (. args 1)) @@ -4055,13 +4562,13 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (check! a)) (let [as (tostring a)] (and (not (as:match "^?")) (not= as "&") (not= as "_") - (not= as "..."))) + (not= as "...") (not= as "&as"))) (table.insert args arity-check-position - `(assert (not= nil ,a) - (string.format "Missing argument %s on %s:%s" - ,(tostring a) - ,(or a.filename :unknown) - ,(or a.line "?")))))) + `(_G.assert (not= nil ,a) + ,(: "Missing argument %s on %s:%s" :format + (tostring a) + (or a.filename :unknown) + (or a.line "?")))))) (assert (= :table (type arglist)) "expected arg list") (each [_ a (ipairs arglist)] @@ -4100,10 +4607,7 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (_SPECIALS.require-macros `(require-macros ,modname) subscope {} ast) (if (sym? binding) ;; bind whole table of macros to table bound to symbol - (do - (tset scope.macros (. binding 1) {}) - (each [k v (pairs subscope.macros)] - (tset (. scope.macros (. binding 1)) k v))) + (tset scope.macros (. binding 1) (. macro-loaded modname)) ;; 1-level table destructuring for importing individual macros (table? binding) (each [macro-name [import-key] (pairs binding)] @@ -4127,7 +4631,7 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (values condition bindings))) (fn match-table [val pattern unifications match-pattern] - (let [condition `(and (= (type ,val) :table)) + (let [condition `(and (= (_G.type ,val) :table)) bindings []] (each [k pat (pairs pattern)] (if (= pat `&) @@ -4184,11 +4688,10 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) (and (list? pattern) (= (. pattern 2) `?)) (let [(pcondition bindings) (match-pattern vals (. pattern 1) unifications) - condition `(and ,pcondition)] - (for [i 3 (length pattern)] ; splice in guard clauses - (table.insert condition (. pattern i))) - (values `(let ,bindings - ,condition) bindings)) + condition `(and ,(unpack pattern 3))] + (values `(and ,pcondition + (let ,bindings + ,condition)) bindings)) ;; multi-valued patterns (represented as lists) (list? pattern) (match-values vals pattern unifications match-pattern) @@ -4216,10 +4719,13 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) "How many multi-valued clauses are there? return a list of that many gensyms." (let [syms (list (gensym))] (for [i 1 (length clauses) 2] - (if (list? (. clauses i)) - (each [valnum (ipairs (. clauses i))] - (if (not (. syms valnum)) - (tset syms valnum (gensym)))))) + (let [clause (if (and (list? (. clauses i)) (= `? (. clauses i 2))) + (. clauses i 1) + (. clauses i))] + (if (list? clause) + (each [valnum (ipairs clause)] + (if (not (. syms valnum)) + (tset syms valnum (gensym))))))) syms)) (fn match* [val ...] @@ -4228,6 +4734,8 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) ;; which simply generates old syntax and feeds it to `match*'. (let [clauses [...] vals (match-val-syms clauses)] + (assert (= 0 (math.fmod (length clauses) 2)) + "expected even number of pattern/body pairs") ;; protect against multiple evaluation of the value, bind against as ;; many values as we ever match against in the clauses. (list `let [vals val] (match-condition vals clauses)))) @@ -4309,6 +4817,7 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) :with-open with-open* :collect collect* :icollect icollect* + :accumulate accumulate* :partial partial* :lambda lambda* :pick-args pick-args* @@ -4319,20 +4828,20 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) :match match-where} ]===] local module_name = "fennel.macros" - local _ = nil - local function _0_() + local _ + local function _567_() return mod end - package.preload[module_name] = _0_ + package.preload[module_name] = _567_ _ = nil - local env = nil + local env do - local _1_0 = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}) - _1_0["utils"] = utils - _1_0["fennel"] = mod - env = _1_0 + local _568_ = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}) + do end (_568_)["utils"] = utils + _568_["fennel"] = mod + env = _568_ end - local built_ins = eval(builtin_macros, {allowedGlobals = false, env = env, filename = "src/fennel/macros.fnl", moduleName = module_name, scope = compiler.scopes.compiler, useMetadata = true}) + local built_ins = eval(builtin_macros, {env = env, scope = compiler.scopes.compiler, allowedGlobals = false, useMetadata = true, filename = "src/fennel/macros.fnl", moduleName = module_name}) for k, v in pairs(built_ins) do compiler.scopes.global.macros[k] = v end @@ -4343,27 +4852,42 @@ package.preload["fennel"] = package.preload["fennel"] or function(...) end fennel = require("fennel") local unpack = (table.unpack or _G.unpack) -local help = "\nUsage: fennel [FLAG] [FILE]\n\nRun fennel, a lisp programming language for the Lua runtime.\n\n --repl : Command to launch an interactive repl session\n --compile FILES : Command to AOT compile files, writing Lua to stdout\n --eval SOURCE (-e) : Command to evaluate source code and print the result\n\n --no-searcher : Skip installing package.searchers entry\n --indent VAL : Indent compiler output with VAL\n --add-package-path PATH : Add PATH to package.path for finding Lua modules\n --add-fennel-path PATH : Add PATH to fennel.path for finding Fennel modules\n --globals G1[,G2...] : Allow these globals in addition to standard ones\n --globals-only G1[,G2] : Same as above, but exclude standard ones\n --require-as-include : Inline required modules in the output\n --use-bit-lib : Use LuaJITs bit library instead of operators\n --metadata : Enable function metadata, even in compiled output\n --no-metadata : Disable function metadata, even in REPL\n --correlate : Make Lua output line numbers match Fennel input\n --load FILE (-l) : Load the specified FILE before executing the command\n --lua LUA_EXE : Run in a child process with LUA_EXE\n --no-fennelrc : Skip loading ~/.fennelrc when launching repl\n --plugin FILE : Activate the compiler plugin in FILE\n --compile-binary FILE\n OUT LUA_LIB LUA_DIR : Compile FILE to standalone binary OUT\n --compile-binary --help : Display further help for compiling binaries\n --no-compiler-sandbox : Do not limit compiler environment to minimal sandbox\n\n --help (-h) : Display this text\n --version (-v) : Show version\n\n Globals are not checked when doing AOT (ahead-of-time) compilation unless\n the --globals-only flag is provided.\n\n Metadata is typically considered a development feature and is not recommended\n for production. It is used for docstrings and enabled by default in the REPL.\n\n When not given a command, runs the file given as the first argument.\n When given neither command nor file, launches a repl.\n\n If ~/.fennelrc exists, loads it before launching a repl." +local help = "\nUsage: fennel [FLAG] [FILE]\n\nRun fennel, a lisp programming language for the Lua runtime.\n\n --repl : Command to launch an interactive repl session\n --compile FILES (-c) : Command to AOT compile files, writing Lua to stdout\n --eval SOURCE (-e) : Command to evaluate source code and print the result\n\n --no-searcher : Skip installing package.searchers entry\n --indent VAL : Indent compiler output with VAL\n --add-package-path PATH : Add PATH to package.path for finding Lua modules\n --add-fennel-path PATH : Add PATH to fennel.path for finding Fennel modules\n --globals G1[,G2...] : Allow these globals in addition to standard ones\n --globals-only G1[,G2] : Same as above, but exclude standard ones\n --require-as-include : Inline required modules in the output\n --skip-include M1[,M2] : Omit certain modules from output when included\n --use-bit-lib : Use LuaJITs bit library instead of operators\n --metadata : Enable function metadata, even in compiled output\n --no-metadata : Disable function metadata, even in REPL\n --correlate : Make Lua output line numbers match Fennel input\n --load FILE (-l) : Load the specified FILE before executing the command\n --lua LUA_EXE : Run in a child process with LUA_EXE\n --no-fennelrc : Skip loading ~/.fennelrc when launching repl\n --raw-errors : Disable friendly compile error reporting\n --plugin FILE : Activate the compiler plugin in FILE\n --compile-binary FILE\n OUT LUA_LIB LUA_DIR : Compile FILE to standalone binary OUT\n --compile-binary --help : Display further help for compiling binaries\n --no-compiler-sandbox : Do not limit compiler environment to minimal sandbox\n\n --help (-h) : Display this text\n --version (-v) : Show version\n\nGlobals are not checked when doing AOT (ahead-of-time) compilation unless\nthe --globals-only or --globals flag is provided. Use --globals \"*\" to disable\nstrict globals checking in other contexts.\n\nMetadata is typically considered a development feature and is not recommended\nfor production. It is used for docstrings and enabled by default in the REPL.\n\nWhen not given a command, runs the file given as the first argument.\nWhen given neither command nor file, launches a repl.\n\nIf ~/.fennelrc exists, it will be loaded before launching a repl." local options = {plugins = {}} local function dosafely(f, ...) local args = {...} - local ok, val = nil, nil - local function _0_() + local _569_, _570_ = nil, nil + local function _571_() return f(unpack(args)) end - ok, val = xpcall(_0_, fennel.traceback) - if not ok then - do end (io.stderr):write((val .. "\n")) - os.exit(1) + _569_, _570_ = xpcall(_571_, fennel.traceback) + if ((_569_ == true) and (nil ~= _570_)) then + local val = _570_ + return val + elseif (true and (nil ~= _570_)) then + local _ = _569_ + local msg = _570_ + do end (io.stderr):write((msg .. "\n")) + return os.exit(1) end - return val end -local function allow_globals(global_names) - options.allowedGlobals = {} - for g in global_names:gmatch("([^,]+),?") do - table.insert(options.allowedGlobals, g) +local function allow_globals(global_names, globals) + if (global_names == "*") then + options.allowedGlobals = false + return nil + else + do + local tbl_13_auto = {} + for g in global_names:gmatch("([^,]+),?") do + tbl_13_auto[(#tbl_13_auto + 1)] = g + end + options.allowedGlobals = tbl_13_auto + end + for global_name in pairs(globals) do + table.insert(options.allowedGlobals, global_name) + end + return nil end - return nil end local function handle_load(i) local file = table.remove(arg, (i + 1)) @@ -4378,78 +4902,91 @@ local function handle_lua(i) table.insert(cmd, string.format("%q", arg[i0])) end local ok = os.execute(table.concat(cmd, " ")) - local _0_ + local _574_ if ok then - _0_ = 0 + _574_ = 0 else - _0_ = 1 + _574_ = 1 end - return os.exit(_0_, true) + return os.exit(_574_, true) end for i = #arg, 1, -1 do - local _0_0 = arg[i] - if (_0_0 == "--lua") then + local _576_ = arg[i] + if (_576_ == "--lua") then handle_lua(i) end end for i = #arg, 1, -1 do - local _0_0 = arg[i] - if (_0_0 == "--no-searcher") then + local _578_ = arg[i] + if (_578_ == "--no-searcher") then options["no-searcher"] = true table.remove(arg, i) - elseif (_0_0 == "--indent") then + elseif (_578_ == "--indent") then options.indent = table.remove(arg, (i + 1)) if (options.indent == "false") then options.indent = false end table.remove(arg, i) - elseif (_0_0 == "--add-package-path") then + elseif (_578_ == "--add-package-path") then local entry = table.remove(arg, (i + 1)) package.path = (entry .. ";" .. package.path) table.remove(arg, i) - elseif (_0_0 == "--add-fennel-path") then + elseif (_578_ == "--add-fennel-path") then local entry = table.remove(arg, (i + 1)) fennel.path = (entry .. ";" .. fennel.path) table.remove(arg, i) - elseif (_0_0 == "--load") then + elseif (_578_ == "--load") then handle_load(i) - elseif (_0_0 == "-l") then + elseif (_578_ == "-l") then handle_load(i) - elseif (_0_0 == "--no-fennelrc") then + elseif (_578_ == "--no-fennelrc") then options.fennelrc = false table.remove(arg, i) - elseif (_0_0 == "--correlate") then + elseif (_578_ == "--correlate") then options.correlate = true table.remove(arg, i) - elseif (_0_0 == "--check-unused-locals") then + elseif (_578_ == "--check-unused-locals") then options.checkUnusedLocals = true table.remove(arg, i) - elseif (_0_0 == "--globals") then - allow_globals(table.remove(arg, (i + 1))) - for global_name in pairs(_G) do - table.insert(options.allowedGlobals, global_name) - end + elseif (_578_ == "--globals") then + allow_globals(table.remove(arg, (i + 1)), _G) table.remove(arg, i) - elseif (_0_0 == "--globals-only") then - allow_globals(table.remove(arg, (i + 1))) + elseif (_578_ == "--globals-only") then + allow_globals(table.remove(arg, (i + 1)), {}) table.remove(arg, i) - elseif (_0_0 == "--require-as-include") then + elseif (_578_ == "--require-as-include") then options.requireAsInclude = true table.remove(arg, i) - elseif (_0_0 == "--use-bit-lib") then + elseif (_578_ == "--skip-include") then + local skip_names = table.remove(arg, (i + 1)) + local skip + do + local tbl_13_auto = {} + for m in skip_names:gmatch("([^,]+)") do + tbl_13_auto[(#tbl_13_auto + 1)] = m + end + skip = tbl_13_auto + end + options.skipInclude = skip + table.remove(arg, i) + elseif (_578_ == "--use-bit-lib") then options.useBitLib = true table.remove(arg, i) - elseif (_0_0 == "--metadata") then + elseif (_578_ == "--metadata") then options.useMetadata = true table.remove(arg, i) - elseif (_0_0 == "--no-metadata") then + elseif (_578_ == "--no-metadata") then options.useMetadata = false table.remove(arg, i) - elseif (_0_0 == "--no-compiler-sandbox") then + elseif (_578_ == "--no-compiler-sandbox") then options["compiler-env"] = _G table.remove(arg, i) - elseif (_0_0 == "--plugin") then - local plugin = fennel.dofile(table.remove(arg, (i + 1)), {env = "_COMPILER", useMetadata = true}) + elseif (_578_ == "--raw-errors") then + options.unfriendly = true + table.remove(arg, i) + elseif (_578_ == "--plugin") then + local opts = {env = "_COMPILER", useMetadata = true, ["compiler-env"] = _G} + local plugin = fennel.dofile(table.remove(arg, (i + 1)), opts) table.insert(options.plugins, 1, plugin) table.remove(arg, i) end @@ -4466,9 +5003,9 @@ local function try_readline(ok, readline) if readline.set_readline_name then readline.set_readline_name("fennel") end - readline.set_options({histfile = "", keeplines = 1000}) + readline.set_options({keeplines = 1000, histfile = ""}) options.readChunk = function(parser_state) - local prompt = nil + local prompt if (0 < parser_state["stack-size"]) then prompt = ".. " else @@ -4502,7 +5039,7 @@ local function load_initfile() local xdg_initfile = (xdg_config_home .. "/fennel/fennelrc") local home_initfile = (home .. "/.fennelrc") local init = io.open(xdg_initfile, "rb") - local init_filename = nil + local init_filename if init then init_filename = xdg_initfile else @@ -4515,7 +5052,7 @@ local function load_initfile() end end local function repl() - local readline = try_readline(pcall(require, "readline")) + local readline = (("dumb" ~= os.getenv("TERM")) and try_readline(pcall(require, "readline"))) searcher_opts.useMetadata = (false ~= options.useMetadata) options.pp = require("fennel.view") if (false ~= options.fennelrc) then @@ -4523,7 +5060,7 @@ local function repl() end print(("Welcome to Fennel " .. fennel.version .. " on " .. _VERSION .. "!")) print("Use ,help to see available commands.") - if not readline then + if (not readline and ("dumb" ~= os.getenv("TERM"))) then print("Try installing readline via luarocks for a better repl experience.") end fennel.repl(options) @@ -4532,79 +5069,96 @@ local function repl() end end local function eval(form) - local _1_ + local _592_ if (form == "-") then - _1_ = (io.stdin):read("*a") + _592_ = (io.stdin):read("*a") else - _1_ = form + _592_ = form end - return print(dosafely(fennel.eval, _1_, options)) + return print(dosafely(fennel.eval, _592_, options)) end -local _1_0, _2_0, _3_0 = arg -local _4_ -do - _4_ = ((type(_1_0) == "table") and (0 == #arg)) -end -if _4_ then - return repl() -elseif ((type(_1_0) == "table") and (_1_0[1] == "--repl")) then - return repl() -elseif ((type(_1_0) == "table") and (_1_0[1] == "--compile")) then - local files = {select(2, (_G.unpack or table.unpack)(_1_0))} +local function compile(files) for _, filename in ipairs(files) do options.filename = filename - local f = nil + local f if (filename == "-") then f = io.stdin else f = assert(io.open(filename, "rb")) end - local ok, val = nil, nil - local function _6_() - return fennel["compile-string"](f:read("*a"), options) - end - ok, val = xpcall(_6_, fennel.traceback) - if ok then - print(val) - else - do end (io.stderr):write((val .. "\n")) - os.exit(1) + do + local _595_, _596_ = nil, nil + local function _597_() + return fennel["compile-string"](f:read("*a"), options) + end + _595_, _596_ = xpcall(_597_, fennel.traceback) + if ((_595_ == true) and (nil ~= _596_)) then + local val = _596_ + print(val) + elseif (true and (nil ~= _596_)) then + local _0 = _595_ + local msg = _596_ + do end (io.stderr):write((msg .. "\n")) + os.exit(1) + end end f:close() end return nil -elseif ((type(_1_0) == "table") and (_1_0[1] == "--compile-binary") and (nil ~= _1_0[2]) and (nil ~= _1_0[3]) and (nil ~= _1_0[4]) and (nil ~= _1_0[5])) then - local filename = _1_0[2] - local out = _1_0[3] - local static_lua = _1_0[4] - local lua_include_dir = _1_0[5] - local args = {select(6, (_G.unpack or table.unpack)(_1_0))} +end +local _599_ = arg +local function _600_(...) + return (0 == #arg) +end +if ((_G.type(_599_) == "table") and _600_(...)) then + return repl() +elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--repl")) then + return repl() +elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--compile")) then + local files = {select(2, (table.unpack or _G.unpack)(_599_))} + return compile(files) +elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "-c")) then + local files = {select(2, (table.unpack or _G.unpack)(_599_))} + return compile(files) +elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--compile-binary") and (nil ~= (_599_)[2]) and (nil ~= (_599_)[3]) and (nil ~= (_599_)[4]) and (nil ~= (_599_)[5])) then + local filename = (_599_)[2] + local out = (_599_)[3] + local static_lua = (_599_)[4] + local lua_include_dir = (_599_)[5] + local args = {select(6, (table.unpack or _G.unpack)(_599_))} local bin = require("fennel.binary") options.filename = filename options.requireAsInclude = true return bin.compile(filename, out, static_lua, lua_include_dir, options, args) -elseif ((type(_1_0) == "table") and (_1_0[1] == "--compile-binary")) then - return print(require("fennel.binary").help) -elseif ((type(_1_0) == "table") and (_1_0[1] == "--eval") and (nil ~= _1_0[2])) then - local form = _1_0[2] +elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--compile-binary")) then + return print((require("fennel.binary")).help) +elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--eval") and (nil ~= (_599_)[2])) then + local form = (_599_)[2] return eval(form) -elseif ((type(_1_0) == "table") and (_1_0[1] == "-e") and (nil ~= _1_0[2])) then - local form = _1_0[2] +elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "-e") and (nil ~= (_599_)[2])) then + local form = (_599_)[2] return eval(form) -elseif ((type(_1_0) == "table") and (_1_0[1] == "--version")) then - return print(("Fennel " .. fennel.version .. " on " .. _VERSION)) -elseif ((type(_1_0) == "table") and (_1_0[1] == "--help")) then - return print(help) -elseif ((type(_1_0) == "table") and (_1_0[1] == "-h")) then - return print(help) -elseif ((type(_1_0) == "table") and (_1_0[1] == "-")) then - local args = {select(2, (_G.unpack or table.unpack)(_1_0))} - return dosafely(fennel.eval, (io.stdin):read("*a")) -elseif ((type(_1_0) == "table") and (nil ~= _1_0[1])) then - local filename = _1_0[1] - local args = {select(2, (_G.unpack or table.unpack)(_1_0))} - arg[-2] = arg[-1] - arg[-1] = arg[0] - arg[0] = table.remove(arg, 1) - return dosafely(fennel.dofile, filename, options, unpack(args)) +else + local function _620_(...) + local a = (_599_)[1] + return ((a == "-v") or (a == "--version")) + end + if (((_G.type(_599_) == "table") and (nil ~= (_599_)[1])) and _620_(...)) then + local a = (_599_)[1] + return print(("Fennel " .. fennel.version .. " on " .. _VERSION)) + elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "--help")) then + return print(help) + elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "-h")) then + return print(help) + elseif ((_G.type(_599_) == "table") and ((_599_)[1] == "-")) then + local args = {select(2, (table.unpack or _G.unpack)(_599_))} + return dosafely(fennel.eval, (io.stdin):read("*a")) + elseif ((_G.type(_599_) == "table") and (nil ~= (_599_)[1])) then + local filename = (_599_)[1] + local args = {select(2, (table.unpack or _G.unpack)(_599_))} + arg[-2] = arg[-1] + arg[-1] = arg[0] + arg[0] = table.remove(arg, 1) + return dosafely(fennel.dofile, filename, options, unpack(args)) + end end diff --git a/lib/fennel.lua b/lib/fennel.lua index c880c8f..2ba28e3 100644 --- a/lib/fennel.lua +++ b/lib/fennel.lua @@ -3,15 +3,16 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) local parser = require("fennel.parser") local compiler = require("fennel.compiler") local specials = require("fennel.specials") + local unpack = (table.unpack or _G.unpack) local function default_read_chunk(parser_state) - local function _0_() + local function _481_() if (0 < parser_state["stack-size"]) then return ".." else return ">> " end end - io.write(_0_()) + io.write(_481_()) io.flush() local input = io.read() return (input and (input .. "\n")) @@ -21,18 +22,18 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) return io.write("\n") end local function default_on_error(errtype, err, lua_source) - local function _1_() - local _0_0 = errtype - if (_0_0 == "Lua Compile") then + local function _483_() + local _482_ = errtype + if (_482_ == "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 (_0_0 == "Runtime") then + elseif (_482_ == "Runtime") then return (compiler.traceback(tostring(err), 4) .. "\n") else - local _ = _0_0 + local _ = _482_ return ("%s error: %s\n"):format(errtype, tostring(err)) end end - return io.write(_1_()) + return io.write(_483_()) 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) @@ -50,34 +51,105 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) end return table.concat(spliced_source, "\n") end + local function completer(env, scope, text) + local matches = {} + local input_fragment = text:gsub(".*[%s)(]+", "") + local stop_looking_3f = false + local function add_partials(input, tbl, prefix, method_3f) + for k in utils.allpairs(tbl) do + local k0 + if ((tbl == env) or (tbl == env.___replLocals___)) then + k0 = scope.unmanglings[k] + else + k0 = k + end + if ((#matches < 2000) and (type(k0) == "string") and (input == k0:sub(0, #input)) and (not method_3f or ("function" == type(tbl[k0])))) then + local function _487_() + if method_3f then + return (prefix .. ":" .. k0) + else + return (prefix .. k0) + end + end + table.insert(matches, _487_()) + end + end + return nil + end + local function descend(input, tbl, prefix, add_matches, method_3f) + local splitter + if method_3f then + splitter = "^([^:]+):(.*)" + else + splitter = "^([^.]+)%.(.*)" + end + local head, tail = input:match(splitter) + local raw_head + if ((tbl == env) or (tbl == env.___replLocals___)) then + raw_head = scope.manglings[head] + else + raw_head = head + end + if (type(tbl[raw_head]) == "table") then + stop_looking_3f = true + if method_3f then + return add_partials(tail, tbl[raw_head], (prefix .. head), true) + else + return add_matches(tail, tbl[raw_head], (prefix .. head)) + end + end + end + local function add_matches(input, tbl, prefix) + local prefix0 + if prefix then + prefix0 = (prefix .. ".") + else + prefix0 = "" + end + if (not input:find("%.") and input:find(":")) then + return descend(input, tbl, prefix0, add_matches, true) + elseif not input:find("%.") then + return add_partials(input, tbl, prefix0) + else + return descend(input, tbl, prefix0, add_matches, false) + end + end + for _, source in ipairs({scope.specials, scope.macros, (env.___replLocals___ or {}), env, env._G}) do + add_matches(input_fragment, source) + if stop_looking_3f then + break + end + end + return matches + end local commands = {} local function command_3f(input) return input:match("^%s*,") end local function command_docs() - local _0_ + local _496_ do - local tbl_0_ = {} + local tbl_13_auto = {} for name, f in pairs(commands) do - tbl_0_[(#tbl_0_ + 1)] = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented")) + tbl_13_auto[(#tbl_13_auto + 1)] = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented")) end - _0_ = tbl_0_ + _496_ = tbl_13_auto end - return table.concat(_0_, "\n") + return table.concat(_496_, "\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 _0_0, _1_0 = pcall(specials["load-code"]("return require(...)", env), module_name) - if ((_0_0 == true) and (nil ~= _1_0)) then - local old = _1_0 - local _ = nil + local _497_, _498_ = pcall(specials["load-code"]("return require(...)", env), module_name) + if ((_497_ == true) and (nil ~= _498_)) then + local old = _498_ + local _ package.loaded[module_name] = nil _ = nil local ok, new = pcall(require, module_name) - local new0 = nil + local new0 if not ok then on_values({new}) new0 = old @@ -89,32 +161,38 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) old[k] = v end for k in pairs(old) do - if (nil == new0[k]) then + if (nil == (new0)[k]) then old[k] = nil end end package.loaded[module_name] = old end return on_values({"ok"}) - elseif ((_0_0 == false) and (nil ~= _1_0)) then - local msg = _1_0 - local function _3_() - local _2_0 = msg:gsub("\n.*", "") - return _2_0 + elseif ((_497_ == false) and (nil ~= _498_)) then + local msg = _498_ + local function _503_() + local _502_ = msg:gsub("\n.*", "") + return _502_ end - return on_error("Runtime", _3_()) + return on_error("Runtime", _503_()) + end + end + local function run_command(read, on_error, f) + local _505_, _506_, _507_ = pcall(read) + if ((_505_ == true) and (_506_ == true) and (nil ~= _507_)) then + local val = _507_ + return f(val) + elseif ((_505_ == false) and true and true) then + local _3fparse_ok = _506_ + local _3ferr = _507_ + return on_error("Parse", "Couldn't parse input.") end end commands.reload = function(env, read, on_values, on_error) - local _0_0, _1_0, _2_0 = pcall(read) - if ((_0_0 == true) and (_1_0 == true) and (nil ~= _2_0)) then - local module_sym = _2_0 - return reload(tostring(module_sym), env, on_values, on_error) - elseif ((_0_0 == false) and true and true) then - local _3fparse_ok = _1_0 - local _3fmsg = _2_0 - return on_error("Parse", (_3fmsg or _3fparse_ok)) + local function _509_(_241) + return reload(tostring(_241), env, on_values, on_error) end + return run_command(read, on_error, _509_) end do end (compiler.metadata):set(commands.reload, "fnl/docstring", "Reload the specified module.") commands.reset = function(env, _, on_values) @@ -122,13 +200,121 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) 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 _510_() + return on_values(completer(env, scope, string.char(unpack(chars)):gsub(",complete +", ""):sub(1, -2))) + end + return run_command(read, on_error, _510_) + end + do end (compiler.metadata):set(commands.complete, "fnl/docstring", "Print all possible completions for a given input symbol.") + local function apropos_2a(pattern, module, prefix, seen, names) + for name, module0 in pairs(module) do + if (("string" == type(name)) and (package ~= module0)) then + local _511_ = type(module0) + if (_511_ == "function") then + if ((prefix .. name)):match(pattern) then + table.insert(names, (prefix .. name)) + end + elseif (_511_ == "table") then + if not seen[module0] then + local _514_ + do + local _513_ = seen + _513_[module0] = true + _514_ = _513_ + end + apropos_2a(pattern, module0, (prefix .. name:gsub("%.", "/") .. "."), _514_, names) + end + end + end + end + return names + end + local function apropos(pattern) + local names = apropos_2a(pattern, package.loaded, "", {}, {}) + local tbl_13_auto = {} + for _, name in ipairs(names) do + tbl_13_auto[(#tbl_13_auto + 1)] = name:gsub("^_G%.", "") + end + return tbl_13_auto + end + commands.apropos = function(env, read, on_values, on_error, scope) + local function _518_(_241) + return on_values(apropos(tostring(_241))) + end + return run_command(read, on_error, _518_) + end + do end (compiler.metadata):set(commands.apropos, "fnl/docstring", "Print all functions matching a pattern in all loaded modules.") + local function apropos_follow_path(path) + local paths + do + local tbl_13_auto = {} + for p in path:gmatch("[^%.]+") do + tbl_13_auto[(#tbl_13_auto + 1)] = p + end + paths = tbl_13_auto + end + local tgt = package.loaded + for _, path0 in ipairs(paths) do + local _520_ + do + local _519_ = path0:gsub("%/", ".") + _520_ = _519_ + end + tgt = tgt[_520_] + if (nil == tgt) then + break + end + end + return tgt + end + local function apropos_doc(pattern) + local names = {} + for _, path in ipairs(apropos(".*")) do + local tgt = apropos_follow_path(path) + if ("function" == type(tgt)) then + local _522_ = (compiler.metadata):get(tgt, "fnl/docstring") + if (nil ~= _522_) then + local docstr = _522_ + if docstr:match(pattern) then + table.insert(names, path) + end + end + end + end + return names + end + commands["apropos-doc"] = function(env, read, on_values, on_error, scope) + local function _526_(_241) + return on_values(apropos_doc(tostring(_241))) + end + return run_command(read, on_error, _526_) + end + do end (compiler.metadata):set(commands["apropos-doc"], "fnl/docstring", "Print all functions that match the pattern in their docs") + local function apropos_show_docs(pattern) + for _, path in ipairs(apropos(pattern)) do + local tgt = apropos_follow_path(path) + if (("function" == type(tgt)) and (compiler.metadata):get(tgt, "fnl/docstring")) then + print(specials.doc(tgt, path)) + print() + end + end + return nil + end + commands["apropos-show-docs"] = function(env, read, _, on_error, scope) + local function _528_(_241) + return apropos_show_docs(tostring(_241)) + end + return run_command(read, on_error, _528_) + end + do end (compiler.metadata):set(commands["apropos-show-docs"], "fnl/docstring", "Print all documentations matching a pattern in function name") local function load_plugin_commands() if (utils.root and utils.root.options and utils.root.options.plugins) then for _, plugin in ipairs(utils.root.options.plugins) do for name, f in pairs(plugin) do - local _0_0 = name:match("^repl%-command%-(.*)") - if (nil ~= _0_0) then - local cmd_name = _0_0 + local _529_ = name:match("^repl%-command%-(.*)") + if (nil ~= _529_) then + local cmd_name = _529_ commands[cmd_name] = (commands[cmd_name] or f) end end @@ -136,16 +322,16 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) return nil end end - local function run_command(input, read, loop, env, on_values, on_error) + local function run_command_loop(input, read, loop, env, on_values, on_error, scope, chars) load_plugin_commands() local command_name = input:match(",([^%s/]+)") do - local _0_0 = commands[command_name] - if (nil ~= _0_0) then - local command = _0_0 - command(env, read, on_values, on_error) + local _532_ = commands[command_name] + if (nil ~= _532_) then + local command = _532_ + command(env, read, on_values, on_error, scope, chars) else - local _ = _0_0 + local _ = _532_ if ("exit" ~= command_name) then on_values({"Unknown command", command_name}) end @@ -155,55 +341,9 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) return loop() end end - local function completer(env, scope, text) - local matches = {} - local input_fragment = text:gsub(".*[%s)(]+", "") - local function add_partials(input, tbl, prefix) - for k in utils.allpairs(tbl) do - local k0 = nil - if ((tbl == env) or (tbl == env.___replLocals___)) then - k0 = scope.unmanglings[k] - else - k0 = k - end - if ((#matches < 2000) and (type(k0) == "string") and (input == k0:sub(0, #input))) then - table.insert(matches, (prefix .. k0)) - end - end - return nil - end - local function add_matches(input, tbl, prefix) - local prefix0 = nil - if prefix then - prefix0 = (prefix .. ".") - else - prefix0 = "" - end - if not input:find("%.") then - return add_partials(input, tbl, prefix0) - else - local head, tail = input:match("^([^.]+)%.(.*)") - local raw_head = nil - if ((tbl == env) or (tbl == env.___replLocals___)) then - raw_head = scope.manglings[head] - else - raw_head = head - end - if (type(tbl[raw_head]) == "table") then - return add_matches(tail, tbl[raw_head], (prefix0 .. head)) - end - end - end - add_matches(input_fragment, (scope.specials or {})) - add_matches(input_fragment, (scope.macros or {})) - add_matches(input_fragment, (env.___replLocals___ or {})) - add_matches(input_fragment, env) - add_matches(input_fragment, (env._ENV or env._G or {})) - return matches - end local function repl(options) local old_root_options = utils.root.options - local env = nil + local env if options.env then env = specials["wrap-env"](options.env) else @@ -211,7 +351,7 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) end local save_locals_3f = ((options.saveLocals ~= false) and env.debug and env.debug.getlocal) local opts = {} - local _ = nil + local _ for k, v in pairs(options) do opts[k] = v end @@ -223,22 +363,27 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) local byte_stream, clear_stream = parser.granulate(read_chunk) local chars = {} local read, reset = nil, nil - local function _1_(parser_state) + local function _537_(parser_state) local c = byte_stream(parser_state) table.insert(chars, c) return c end - read, reset = parser.parser(_1_) + read, reset = parser.parser(_537_) local scope = compiler["make-scope"]() opts.useMetadata = (options.useMetadata ~= false) if (opts.allowedGlobals == nil) then opts.allowedGlobals = specials["current-global-names"](opts.env) end if opts.registerCompleter then - local function _3_(...) - return completer(env, scope, ...) + local function _541_() + local _539_ = env + local _540_ = scope + local function _542_(...) + return completer(_539_, _540_, ...) + end + return _542_ end - opts.registerCompleter(_3_) + opts.registerCompleter(_541_()) end local function print_values(...) local vals = {...} @@ -254,46 +399,57 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) chars[k] = nil end local ok, parse_ok_3f, x = pcall(read) - local src_string = string.char((table.unpack or _G.unpack)(chars)) + local src_string = string.char(unpack(chars)) + reset() utils.root.options = opts if not ok then on_error("Parse", parse_ok_3f) clear_stream() - reset() return loop() elseif command_3f(src_string) then - return run_command(src_string, read, loop, env, on_values, on_error) + return run_command_loop(src_string, read, loop, env, on_values, on_error, scope, chars) else if parse_ok_3f then do - local _4_0, _5_0 = pcall(compiler.compile, x, {["assert-compile"] = opts["assert-compile"], ["parse-error"] = opts["parse-error"], correlate = opts.correlate, moduleName = opts.moduleName, scope = scope, source = src_string, useMetadata = opts.useMetadata}) - if ((_4_0 == false) and (nil ~= _5_0)) then - local msg = _5_0 + local _544_, _545_ = nil, nil + local function _547_() + local _546_ = opts + _546_["env"] = env + _546_["source"] = src_string + _546_["scope"] = scope + return _546_ + end + _544_, _545_ = pcall(compiler.compile, x, _547_()) + if ((_544_ == false) and (nil ~= _545_)) then + local msg = _545_ clear_stream() on_error("Compile", msg) - elseif ((_4_0 == true) and (nil ~= _5_0)) then - local src = _5_0 - local src0 = nil + elseif ((_544_ == true) and (nil ~= _545_)) then + local src = _545_ + local src0 if save_locals_3f then src0 = splice_save_locals(env, src) else src0 = src end - local _7_0, _8_0 = pcall(specials["load-code"], src0, env) - if ((_7_0 == false) and (nil ~= _8_0)) then - local msg = _8_0 + local _549_, _550_ = pcall(specials["load-code"], src0, env) + if ((_549_ == false) and (nil ~= _550_)) then + local msg = _550_ clear_stream() on_error("Lua Compile", msg, src0) - elseif (true and (nil ~= _8_0)) then - local _0 = _7_0 - local chunk = _8_0 - local function _9_() + elseif (true and (nil ~= _550_)) then + local _0 = _549_ + local chunk = _550_ + local function _551_() return print_values(chunk()) end - local function _10_(...) - return on_error("Runtime", ...) + local function _552_() + local function _553_(...) + return on_error("Runtime", ...) + end + return _553_ end - xpcall(_9_, _10_) + xpcall(_551_, _552_()) end end end @@ -306,390 +462,6 @@ package.preload["fennel.repl"] = package.preload["fennel.repl"] or function(...) end return repl end -package.preload["fennel.view"] = package.preload["fennel.view"] or function(...) - local type_order = {["function"] = 5, boolean = 2, number = 1, string = 3, table = 4, thread = 7, userdata = 6} - local function sort_keys(_0_0, _1_0) - local _1_ = _0_0 - local a = _1_[1] - local _2_ = _1_0 - local b = _2_[1] - local ta = type(a) - local tb = type(b) - if ((ta == tb) and ((ta == "string") or (ta == "number"))) then - return (a < b) - else - local dta = type_order[ta] - local dtb = type_order[tb] - if (dta and dtb) then - return (dta < dtb) - elseif dta then - return true - elseif dtb then - return false - else - return (ta < tb) - end - end - end - local function table_kv_pairs(t) - local assoc_3f = false - local i = 1 - local kv = {} - local insert = table.insert - for k, v in pairs(t) do - if ((type(k) ~= "number") or (k ~= i)) then - assoc_3f = true - end - i = (i + 1) - insert(kv, {k, v}) - end - table.sort(kv, sort_keys) - if (#kv == 0) then - return kv, "empty" - else - local function _2_() - if assoc_3f then - return "table" - else - return "seq" - end - end - return kv, _2_() - end - end - local function count_table_appearances(t, appearances) - if (type(t) == "table") then - if not appearances[t] then - appearances[t] = 1 - for k, v in pairs(t) do - count_table_appearances(k, appearances) - count_table_appearances(v, appearances) - end - else - appearances[t] = ((appearances[t] or 0) + 1) - end - end - return appearances - end - local function save_table(t, seen) - local seen0 = (seen or {len = 0}) - local id = (seen0.len + 1) - if not seen0[t] then - seen0[t] = id - seen0.len = id - end - return seen0 - end - local function detect_cycle(t, seen, _3fk) - if ("table" == type(t)) then - seen[t] = true - local _2_0, _3_0 = next(t, _3fk) - if ((nil ~= _2_0) and (nil ~= _3_0)) then - local k = _2_0 - local v = _3_0 - return (seen[k] or detect_cycle(k, seen) or seen[v] or detect_cycle(v, seen) or detect_cycle(t, seen, k)) - end - end - end - local function visible_cycle_3f(t, options) - return (options["detect-cycles?"] and detect_cycle(t, {}) and save_table(t, options.seen) and (1 < (options.appearances[t] or 0))) - end - local function table_indent(t, indent, id) - local opener_length = nil - if id then - opener_length = (#tostring(id) + 2) - else - opener_length = 1 - end - return (indent + opener_length) - end - local pp = nil - local function concat_table_lines(elements, options, multiline_3f, indent, table_type, prefix) - local indent_str = ("\n" .. string.rep(" ", indent)) - local open = nil - local function _2_() - if ("seq" == table_type) then - return "[" - else - return "{" - end - end - open = ((prefix or "") .. _2_()) - local close = nil - if ("seq" == table_type) then - close = "]" - else - close = "}" - end - local oneline = (open .. table.concat(elements, " ") .. close) - if (not options["one-line?"] and (multiline_3f or ((indent + #oneline) > options["line-length"]))) then - return (open .. table.concat(elements, indent_str) .. close) - else - return oneline - end - end - local function pp_associative(t, kv, options, indent, key_3f) - local multiline_3f = false - local id = options.seen[t] - if (options.level >= options.depth) then - return "{...}" - elseif (id and options["detect-cycles?"]) then - return ("@" .. id .. "{...}") - else - local visible_cycle_3f0 = visible_cycle_3f(t, options) - local id0 = (visible_cycle_3f0 and options.seen[t]) - local indent0 = table_indent(t, indent, id0) - local slength = nil - local function _3_() - local _2_0 = rawget(_G, "utf8") - if _2_0 then - return _2_0.len - else - return _2_0 - end - end - local function _4_(_241) - return #_241 - end - slength = ((options["utf8?"] and _3_()) or _4_) - local prefix = nil - if visible_cycle_3f0 then - prefix = ("@" .. id0) - else - prefix = "" - end - local items = nil - do - local tbl_0_ = {} - for _, _6_0 in pairs(kv) do - local _7_ = _6_0 - local k = _7_[1] - local v = _7_[2] - local _8_ - do - local k0 = pp(k, options, (indent0 + 1), true) - local v0 = pp(v, options, (indent0 + slength(k0) + 1)) - multiline_3f = (multiline_3f or k0:find("\n") or v0:find("\n")) - _8_ = (k0 .. " " .. v0) - end - tbl_0_[(#tbl_0_ + 1)] = _8_ - end - items = tbl_0_ - end - return concat_table_lines(items, options, multiline_3f, indent0, "table", prefix) - end - end - local function pp_sequence(t, kv, options, indent) - local multiline_3f = false - local id = options.seen[t] - if (options.level >= options.depth) then - return "[...]" - elseif (id and options["detect-cycles?"]) then - return ("@" .. id .. "[...]") - else - local visible_cycle_3f0 = visible_cycle_3f(t, options) - local id0 = (visible_cycle_3f0 and options.seen[t]) - local indent0 = table_indent(t, indent, id0) - local prefix = nil - if visible_cycle_3f0 then - prefix = ("@" .. id0) - else - prefix = "" - end - local items = nil - do - local tbl_0_ = {} - for _, _3_0 in pairs(kv) do - local _4_ = _3_0 - local _0 = _4_[1] - local v = _4_[2] - local _5_ - do - local v0 = pp(v, options, indent0) - multiline_3f = (multiline_3f or v0:find("\n")) - _5_ = v0 - end - tbl_0_[(#tbl_0_ + 1)] = _5_ - end - items = tbl_0_ - end - return concat_table_lines(items, options, multiline_3f, indent0, "seq", prefix) - end - end - local function concat_lines(lines, options, indent, force_multi_line_3f) - if (#lines == 0) then - if options["empty-as-sequence?"] then - return "[]" - else - return "{}" - end - else - local oneline = nil - local _2_ - do - local tbl_0_ = {} - for _, line in ipairs(lines) do - tbl_0_[(#tbl_0_ + 1)] = line:gsub("^%s+", "") - end - _2_ = tbl_0_ - end - oneline = table.concat(_2_, " ") - if (not options["one-line?"] and (force_multi_line_3f or oneline:find("\n") or ((indent + #oneline) > options["line-length"]))) then - return table.concat(lines, ("\n" .. string.rep(" ", indent))) - else - return oneline - end - end - end - local function pp_metamethod(t, metamethod, options, indent) - if (options.level >= options.depth) then - if options["empty-as-sequence?"] then - return "[...]" - else - return "{...}" - end - else - local _ = nil - local function _2_(_241) - return visible_cycle_3f(_241, options) - end - options["visible-cycle?"] = _2_ - _ = nil - local lines, force_multi_line_3f = metamethod(t, pp, options, indent) - options["visible-cycle?"] = nil - local _3_0 = type(lines) - if (_3_0 == "string") then - return lines - elseif (_3_0 == "table") then - return concat_lines(lines, options, indent, force_multi_line_3f) - else - local _0 = _3_0 - return error("__fennelview metamethod must return a table of lines") - end - end - end - local function pp_table(x, options, indent) - options.level = (options.level + 1) - local x0 = nil - do - local _2_0 = nil - if options["metamethod?"] then - local _3_0 = x - if _3_0 then - local _4_0 = getmetatable(_3_0) - if _4_0 then - _2_0 = _4_0.__fennelview - else - _2_0 = _4_0 - end - else - _2_0 = _3_0 - end - else - _2_0 = nil - end - if (nil ~= _2_0) then - local metamethod = _2_0 - x0 = pp_metamethod(x, metamethod, options, indent) - else - local _ = _2_0 - local _4_0, _5_0 = table_kv_pairs(x) - if (true and (_5_0 == "empty")) then - local _0 = _4_0 - if options["empty-as-sequence?"] then - x0 = "[]" - else - x0 = "{}" - end - elseif ((nil ~= _4_0) and (_5_0 == "table")) then - local kv = _4_0 - x0 = pp_associative(x, kv, options, indent) - elseif ((nil ~= _4_0) and (_5_0 == "seq")) then - local kv = _4_0 - x0 = pp_sequence(x, kv, options, indent) - else - x0 = nil - end - end - end - options.level = (options.level - 1) - return x0 - end - local function number__3estring(n) - local _2_0 = string.gsub(tostring(n), ",", ".") - return _2_0 - end - local function colon_string_3f(s) - return s:find("^[-%w?^_!$%&*+./@|<=>]+$") - end - local function pp_string(str, options, indent) - local escs = nil - local _2_ - if (options["escape-newlines?"] and (#str < (options["line-length"] - indent))) then - _2_ = "\\n" - else - _2_ = "\n" - end - local function _4_(_241, _242) - return ("\\%03d"):format(_242:byte()) - end - escs = setmetatable({["\""] = "\\\"", ["\11"] = "\\v", ["\12"] = "\\f", ["\13"] = "\\r", ["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\\"] = "\\\\", ["\n"] = _2_}, {__index = _4_}) - return ("\"" .. str:gsub("[%c\\\"]", escs) .. "\"") - end - local function make_options(t, options) - local defaults = {["detect-cycles?"] = true, ["empty-as-sequence?"] = false, ["escape-newlines?"] = false, ["line-length"] = 80, ["metamethod?"] = true, ["one-line?"] = false, ["prefer-colon?"] = false, ["utf8?"] = true, depth = 128} - local overrides = {appearances = count_table_appearances(t, {}), level = 0, seen = {len = 0}} - for k, v in pairs((options or {})) do - defaults[k] = v - end - for k, v in pairs(overrides) do - defaults[k] = v - end - return defaults - end - local function _2_(x, options, indent, colon_3f) - local indent0 = (indent or 0) - local options0 = (options or make_options(x)) - local tv = type(x) - local function _4_() - local _3_0 = getmetatable(x) - if _3_0 then - return _3_0.__fennelview - else - return _3_0 - end - end - if ((tv == "table") or ((tv == "userdata") and _4_())) then - return pp_table(x, options0, indent0) - elseif (tv == "number") then - return number__3estring(x) - else - local function _5_() - if (colon_3f ~= nil) then - return colon_3f - elseif ("function" == type(options0["prefer-colon?"])) then - return options0["prefer-colon?"](x) - else - return options0["prefer-colon?"] - end - end - if ((tv == "string") and colon_string_3f(x) and _5_()) then - return (":" .. x) - elseif (tv == "string") then - return pp_string(x, options0, indent0) - elseif ((tv == "boolean") or (tv == "nil")) then - return tostring(x) - else - return ("#<" .. tostring(x) .. ">") - end - end - end - pp = _2_ - local function view(x, options) - return pp(x, make_options(x, options), 0) - end - return view -end package.preload["fennel.specials"] = package.preload["fennel.specials"] or function(...) local utils = require("fennel.utils") local view = require("fennel.view") @@ -698,14 +470,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local unpack = (table.unpack or _G.unpack) local SPECIALS = compiler.scopes.global.specials local function wrap_env(env) - local function _0_(_, key) + local function _309_(_, key) if (type(key) == "string") then return env[compiler["global-unmangling"](key)] else return env[key] end end - local function _1_(_, key, value) + local function _311_(_, key, value) if (type(key) == "string") then env[compiler["global-unmangling"](key)] = value return nil @@ -714,22 +486,47 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return nil end end - local function _2_() + local function _313_() local function putenv(k, v) - local _3_ + local _314_ if (type(k) == "string") then - _3_ = compiler["global-unmangling"](k) + _314_ = compiler["global-unmangling"](k) else - _3_ = k + _314_ = k end - return _3_, v + return _314_, v end return next, utils.kvmap(env, putenv), nil end - return setmetatable({}, {__index = _0_, __newindex = _1_, __pairs = _2_}) + return setmetatable({}, {__index = _309_, __newindex = _311_, __pairs = _313_}) end local function current_global_names(env) - return utils.kvmap((env or _G), compiler["global-unmangling"]) + local mt + do + local _316_ = getmetatable(env) + local function _317_() + local __pairs = (_316_).__pairs + return __pairs + end + if (((_G.type(_316_) == "table") and true) and _317_()) then + local __pairs = (_316_).__pairs + local tbl_10_auto = {} + for k, v in __pairs(env) do + local _318_, _319_ = k, v + if ((nil ~= _318_) and (nil ~= _319_)) then + local k_11_auto = _318_ + local v_12_auto = _319_ + tbl_10_auto[k_11_auto] = v_12_auto + end + end + mt = tbl_10_auto + elseif (_316_ == nil) then + mt = (env or _G) + else + mt = nil + end + end + return (mt and utils.kvmap(mt, compiler["global-unmangling"])) end local function load_code(code, environment, filename) local environment0 = (environment or rawget(_G, "_ENV") or _G) @@ -749,20 +546,20 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 {"#"}), " ") - local _0_ + local _323_ if (#arglist > 0) then - _0_ = " " + _323_ = " " else - _0_ = "" + _323_ = "" end - return string.format("(%s%s%s)\n %s", name, _0_, arglist, docstring) + return string.format("(%s%s%s)\n %s", name, _323_, arglist, docstring) else return string.format("%s\n %s", name, docstring) end end end - local function doc_special(name, arglist, docstring) - compiler.metadata[SPECIALS[name]] = {["fnl/arglist"] = arglist, ["fnl/docstring"] = docstring} + 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, start) @@ -804,7 +601,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local syms = {} for i = 1, opts.nval do local s = ((pre_syms and pre_syms[i]) or compiler.gensym(scope)) - syms[i] = s + do end (syms)[i] = s retexprs[i] = utils.expr(s, "sym") end local outer_target = table.concat(syms, ", ") @@ -813,7 +610,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return compile_body(outer_target, opts.tail) else local fname = compiler.gensym(scope) - local fargs = nil + local fargs if scope.vararg then fargs = "..." else @@ -824,7 +621,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return compile_body(nil, true, utils.expr((fname .. "(" .. fargs .. ")"), "statement")) end end - doc_special("do", {"..."}, "Evaluate multiple forms; return last value.") + doc_special("do", {"..."}, "Evaluate multiple forms; return last value.", true) SPECIALS.values = function(ast, scope, parent) local len = #ast local exprs = {} @@ -843,25 +640,25 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local function deep_tostring(x, key_3f) local elems = {} if utils["sequence?"](x) then - local _0_ + local _332_ do - local tbl_0_ = {} + local tbl_13_auto = {} for _, v in ipairs(x) do - tbl_0_[(#tbl_0_ + 1)] = deep_tostring(v) + tbl_13_auto[(#tbl_13_auto + 1)] = deep_tostring(v) end - _0_ = tbl_0_ + _332_ = tbl_13_auto end - return ("[" .. table.concat(_0_, " ") .. "]") + return ("[" .. table.concat(_332_, " ") .. "]") elseif utils["table?"](x) then - local _0_ + local _333_ do - local tbl_0_ = {} + local tbl_13_auto = {} for k, v in pairs(x) do - tbl_0_[(#tbl_0_ + 1)] = (deep_tostring(k, true) .. " " .. deep_tostring(v)) + tbl_13_auto[(#tbl_13_auto + 1)] = (deep_tostring(k, true) .. " " .. deep_tostring(v)) end - _0_ = tbl_0_ + _333_ = tbl_13_auto end - return ("{" .. table.concat(_0_, " ") .. "}") + return ("{" .. table.concat(_333_, " ") .. "}") elseif (key_3f and (type(x) == "string") and x:find("^[-%w?\\^_!$%&*+./@:|<=>]+$")) then return (":" .. x) elseif (type(x) == "string") then @@ -872,11 +669,11 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end local function set_fn_metadata(arg_list, docstring, parent, fn_name) if utils.root.options.useMetadata then - local args = nil - local function _0_(_241) + local args + local function _335_(_241) return ("\"%s\""):format(deep_tostring(_241)) end - args = utils.map(arg_list, _0_) + args = utils.map(arg_list, _335_) local meta_fields = {"\"fnl/arglist\"", ("{" .. table.concat(args, ", ") .. "}")} if docstring then table.insert(meta_fields, "\"fnl/docstring\"") @@ -888,13 +685,13 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end local function get_fn_name(ast, scope, fn_name, multi) if (fn_name and (fn_name[1] ~= "nil")) then - local _0_ + local _338_ if not multi then - _0_ = compiler["declare-local"](fn_name, {}, scope, ast) + _338_ = compiler["declare-local"](fn_name, {}, scope, ast) else - _0_ = compiler["symbol-to-expression"](fn_name, scope)[1] + _338_ = (compiler["symbol-to-expression"](fn_name, scope))[1] end - return _0_, not multi, 3 + return _338_, not multi, 3 else return nil, true, 2 end @@ -903,13 +700,13 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 _0_ + local _341_ if local_3f then - _0_ = "local function %s(%s)" + _341_ = "local function %s(%s)" else - _0_ = "%s = function(%s)" + _341_ = "%s = function(%s)" end - compiler.emit(parent, string.format(_0_, fn_name, table.concat(arg_name_list, ", ")), ast) + compiler.emit(parent, string.format(_341_, fn_name, table.concat(arg_name_list, ", ")), ast) compiler.emit(parent, f_chunk, ast) compiler.emit(parent, "end", ast) set_fn_metadata(arg_list, docstring, parent, fn_name) @@ -921,11 +718,11 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, true, arg_name_list, arg_list, docstring) end SPECIALS.fn = function(ast, scope, parent) - local f_scope = nil + local f_scope do - local _0_0 = compiler["make-scope"](scope) - _0_0["vararg"] = false - f_scope = _0_0 + local _343_ = compiler["make-scope"](scope) + do end (_343_)["vararg"] = false + f_scope = _343_ end local f_chunk = {} local fn_sym = utils["sym?"](ast[2]) @@ -938,7 +735,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct compiler.assert((arg == arg_list[#arg_list]), "expected vararg as last parameter", ast) f_scope.vararg = true return "..." - elseif (utils["sym?"](arg) and (utils.deref(arg) ~= "nil") and not utils["multi-sym?"](utils.deref(arg))) then + 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)) @@ -962,26 +759,44 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return compile_anonymous_fn(ast, f_scope, f_chunk, parent, index0, arg_name_list, arg_list, docstring, scope) end end - doc_special("fn", {"name?", "args", "docstring?", "..."}, "Function syntax. May optionally include a name and docstring.\nIf a name is provided, the function will be bound in the current scope.\nWhen called with the wrong number of args, excess args will be discarded\nand lacking args will be nil, use lambda for arity-checked functions.") + doc_special("fn", {"name?", "args", "docstring?", "..."}, "Function syntax. May optionally include a name and docstring.\nIf a name is provided, the function will be bound in the current scope.\nWhen called with the wrong number of args, excess args will be discarded\nand lacking args will be nil, use lambda for arity-checked functions.", true) SPECIALS.lua = function(ast, _, parent) compiler.assert(((#ast == 2) or (#ast == 3)), "expected 1 or 2 arguments", ast) - if (ast[2] ~= nil) then + local _348_ + do + local _347_ = utils["sym?"](ast[2]) + if _347_ then + _348_ = tostring(_347_) + else + _348_ = _347_ + end + end + if ("nil" ~= _348_) then table.insert(parent, {ast = ast, leaf = tostring(ast[2])}) end - if (ast[3] ~= nil) then + local _352_ + do + local _351_ = utils["sym?"](ast[3]) + if _351_ then + _352_ = tostring(_351_) + else + _352_ = _351_ + end + end + if ("nil" ~= _352_) then return tostring(ast[3]) end end SPECIALS.doc = function(ast, scope, parent) assert(utils.root.options.useMetadata, "can't look up doc with metadata disabled.") compiler.assert((#ast == 2), "expected one argument", ast) - local target = utils.deref(ast[2]) + local target = tostring(ast[2]) local special_or_macro = (scope.specials[target] or scope.macros[target]) if special_or_macro then return ("print(%q)"):format(doc_2a(special_or_macro, target)) else - local _0_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) - local value = _0_[1] + local _let_355_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) + local value = _let_355_[1] return ("print(require('%s').doc(%s, '%s'))"):format((utils.root.options.moduleName or "fennel"), tostring(value), tostring(ast[2])) end end @@ -989,8 +804,8 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local function dot(ast, scope, parent) compiler.assert((1 < #ast), "expected table argument", ast) local len = #ast - local _0_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) - local lhs = _0_[1] + local _let_357_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) + local lhs = _let_357_[1] if (len == 2) then return tostring(lhs) else @@ -1000,8 +815,8 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct if ((type(index) == "string") and utils["valid-lua-identifier?"](index)) then table.insert(indices, ("." .. index)) else - local _1_ = compiler.compile1(index, scope, parent, {nval = 1}) - local index0 = _1_[1] + local _let_358_ = compiler.compile1(index, scope, parent, {nval = 1}) + local index0 = _let_358_[1] table.insert(indices, ("[" .. tostring(index0) .. "]")) end end @@ -1045,10 +860,27 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return nil end doc_special("var", {"name", "val"}, "Introduce new mutable local.") + local function kv_3f(t) + local _362_ + do + local tbl_13_auto = {} + for k in pairs(t) do + local _363_ + if not ("number" == type(k)) then + _363_ = k + else + _363_ = nil + end + tbl_13_auto[(#tbl_13_auto + 1)] = _363_ + end + _362_ = tbl_13_auto + end + return (_362_)[1] + end SPECIALS.let = function(ast, scope, parent, opts) local bindings = ast[2] local pre_syms = {} - compiler.assert((utils["list?"](bindings) or utils["table?"](bindings)), "expected binding table", ast) + compiler.assert((utils["table?"](bindings) and not kv_3f(bindings)), "expected binding sequence", bindings) compiler.assert(((#bindings % 2) == 0), "expected even number of name/value bindings", ast[2]) compiler.assert((#ast >= 3), "expected body expression", ast[1]) for _ = 1, (opts.nval or 0) do @@ -1061,25 +893,42 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") + 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 _367_() + local _366_ = get_prev_line(parent) + if (nil ~= _366_) then + local prev_line = _366_ + return prev_line:match("%)$") + end + end + return (rootstr:match("^{") or _367_()) + end SPECIALS.tset = function(ast, scope, parent) compiler.assert((#ast > 3), "expected table, key, and value arguments", ast) - local root = compiler.compile1(ast[2], scope, parent, {nval = 1})[1] + local root = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1] local keys = {} for i = 3, (#ast - 1) do - local _0_ = compiler.compile1(ast[i], scope, parent, {nval = 1}) - local key = _0_[1] + local _let_369_ = compiler.compile1(ast[i], scope, parent, {nval = 1}) + local key = _let_369_[1] table.insert(keys, tostring(key)) end - local value = compiler.compile1(ast[#ast], scope, parent, {nval = 1})[1] + local value = (compiler.compile1(ast[#ast], scope, parent, {nval = 1}))[1] local rootstr = tostring(root) - local fmtstr = nil - if rootstr:match("^{") then + 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(tostring(root), table.concat(keys, "]["), tostring(value)), ast) + 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) @@ -1090,7 +939,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local target_exprs = {} for i = 1, opts.nval do local s = compiler.gensym(scope) - accum[i] = s + do end (accum)[i] = s target_exprs[i] = utils.expr(s, "sym") end return "target", opts.tail, table.concat(accum, ", "), target_exprs @@ -1126,14 +975,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local last_buffer = buffer for i = 1, #branches do local branch = branches[i] - local fstr = nil + 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 = nil + local cond_line if ((cond == "true") and branch.nested and (i == #branches) and not has_else_3f) then cond_line = "else" else @@ -1157,7 +1006,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct compiler.emit(last_buffer, ("%s = nil"):format(inner_target), ast) end compiler.emit(last_buffer, "end", ast) - elseif not branches[(i + 1)].nested then + elseif not (branches[(i + 1)]).nested then local next_buffer = {} compiler.emit(last_buffer, "else", ast) compiler.emit(last_buffer, next_buffer, ast) @@ -1194,25 +1043,27 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end local function compile_until(condition, scope, chunk) if condition then - local _0_ = compiler.compile1(condition, scope, chunk, {nval = 1}) - local condition_lua = _0_[1] - return compiler.emit(chunk, ("if %s then break end"):format(tostring(condition_lua)), condition) + local _let_379_ = compiler.compile1(condition, scope, chunk, {nval = 1}) + local condition_lua = _let_379_[1] + return compiler.emit(chunk, ("if %s then break end"):format(tostring(condition_lua)), utils.expr(condition, "expression")) end end SPECIALS.each = function(ast, scope, parent) compiler.assert((#ast >= 3), "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(("string" ~= type(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)) - destructures[raw] = v + do end (destructures)[raw] = v return compiler["declare-local"](raw, {}, sub_scope, ast) end end @@ -1230,16 +1081,16 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") + 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 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]) - parent[i] = nil + 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) @@ -1251,7 +1102,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") + 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]) @@ -1261,8 +1112,9 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local chunk = {} compiler.assert(utils["sym?"](binding_sym), ("unable to bind %s %s"):format(type(binding_sym), tostring(binding_sym)), ast[2]) compiler.assert((#ast >= 3), "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], sub_scope, parent, {nval = 1})[1]) + range_args[i] = tostring((compiler.compile1(ranges[i], sub_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) @@ -1271,14 +1123,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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).") + 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 _0_ = ast - local _ = _0_[1] - local _0 = _0_[2] - local method_string = _0_[3] - local call_string = nil - if ((target.type == "literal") or (target.type == "expression")) then + local _let_383_ = ast + local _ = _let_383_[1] + local _0 = _let_383_[2] + local method_string = _let_383_[3] + local call_string + if ((target.type == "literal") or (target.type == "varg") or (target.type == "expression")) then call_string = "(%s):%s(%s)" else call_string = "%s:%s(%s)" @@ -1286,30 +1138,30 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 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 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 _0_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) - local target = _0_[1] + local _let_385_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) + local target = _let_385_[1] local args = {} for i = 4, #ast do - local subexprs = nil - local _1_ + local subexprs + local _386_ if (i ~= #ast) then - _1_ = 1 + _386_ = 1 else - _1_ = nil + _386_ = nil end - subexprs = compiler.compile1(ast[i], scope, parent, {nval = _1_}) + subexprs = compiler.compile1(ast[i], scope, parent, {nval = _386_}) utils.map(subexprs, tostring, args) end if ((type(ast[3]) == "string") and utils["valid-lua-identifier?"](ast[3])) then @@ -1325,17 +1177,13 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct SPECIALS.comment = function(ast, _, parent) local els = {} for i = 2, #ast do - local function _1_() - local _0_0 = tostring(ast[i]):gsub("\n", " ") - return _0_0 - end - table.insert(els, _1_()) + 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.") + doc_special("comment", {"..."}, "Comment which will be emitted in Lua output.", true) local function hashfn_max_used(f_scope, i, max) - local max0 = nil + local max0 if f_scope.symmeta[("$" .. i)].used then max0 = i else @@ -1349,12 +1197,12 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end SPECIALS.hashfn = function(ast, scope, parent) compiler.assert((#ast == 2), "expected one argument", ast) - local f_scope = nil + local f_scope do - local _0_0 = compiler["make-scope"](scope) - _0_0["vararg"] = false - _0_0["hashfn"] = true - f_scope = _0_0 + local _391_ = compiler["make-scope"](scope) + do end (_391_)["vararg"] = false + _391_["hashfn"] = true + f_scope = _391_ end local f_chunk = {} local name = compiler.gensym(scope) @@ -1365,7 +1213,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct args[i] = compiler["declare-local"](utils.sym(("$" .. i)), {}, f_scope, ast) end local function walker(idx, node, parent_node) - if (utils["sym?"](node) and (utils.deref(node) == "$...")) then + if (utils["sym?"](node) and (tostring(node) == "$...")) then parent_node[idx] = utils.varg() f_scope.vararg = true return nil @@ -1379,9 +1227,9 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct if f_scope.vararg then compiler.assert((max_used == 0), "$ and $... in hashfn are mutually exclusive", ast) end - local arg_str = nil + local arg_str if f_scope.vararg then - arg_str = utils.deref(utils.varg()) + arg_str = tostring(utils.varg()) else arg_str = table.concat(args, ", ", 1, max_used) end @@ -1391,41 +1239,53 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct return utils.expr(name, "sym") end doc_special("hashfn", {"..."}, "Function literal shorthand; args are either $... OR $1, $2, etc.") - local function arithmetic_special(name, zero_arity, unary_prefix, ast, scope, parent) + local function arithmetic_special(name, zero_arity, unary_prefix, nval, ast, scope, parent) local len = #ast - if (len == 1) then - compiler.assert(zero_arity, "Expected more than 0 arguments", ast) - return utils.expr(zero_arity, "literal") - else - local operands = {} - local padded_op = (" " .. name .. " ") - for i = 2, len do - local subexprs = nil - local _0_ - if (i ~= len) then - _0_ = 1 - else - _0_ = nil - end - subexprs = compiler.compile1(ast[i], scope, parent, {nval = _0_}) - utils.map(subexprs, tostring, operands) - end - if (#operands == 1) then - if unary_prefix then - return ("(" .. unary_prefix .. padded_op .. operands[1] .. ")") - else - return operands[1] - end + local operands = {} + local padded_op = (" " .. name .. " ") + for i = 2, len do + local subexprs + local _395_ + if (i < len) then + _395_ = 1 else - return ("(" .. table.concat(operands, padded_op) .. ")") + _395_ = nil end + subexprs = compiler.compile1(ast[i], scope, parent, {nval = _395_}) + utils.map(subexprs, tostring, operands) + end + local _397_ = #operands + if (_397_ == 0) then + local _399_ + do + local _398_ = zero_arity + compiler.assert(_398_, "Expected more than 0 arguments", ast) + _399_ = _398_ + end + return utils.expr(_399_, "literal") + elseif (_397_ == 1) then + if unary_prefix then + return ("(" .. unary_prefix .. padded_op .. operands[1] .. ")") + else + return operands[1] + end + else + local _ = _397_ + return ("(" .. table.concat(operands, padded_op) .. ")") end end local function define_arithmetic_special(name, zero_arity, unary_prefix, lua_name) - local function _0_(...) - return arithmetic_special((lua_name or name), zero_arity, unary_prefix, ...) + local _405_ + do + local _402_ = (lua_name or name) + local _403_ = zero_arity + local _404_ = unary_prefix + local function _406_(...) + return arithmetic_special(_402_, _403_, _404_, 1, ...) + end + _405_ = _406_ end - SPECIALS[name] = _0_ + SPECIALS[name] = _405_ return doc_special(name, {"a", "b", "..."}, "Arithmetic operator; works the same as Lua but accepts more arguments.") end define_arithmetic_special("+", "0") @@ -1436,6 +1296,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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, nil, ast, scope, parent) + end + SPECIALS["and"] = function(ast, scope, parent) + return arithmetic_special("and", "true", nil, nil, ast, scope, parent) + end + doc_special("and", {"a", "b", "..."}, "Boolean operator; works the same as Lua but accepts more arguments.") + doc_special("or", {"a", "b", "..."}, "Boolean operator; works the same as Lua but accepts more arguments.") 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) @@ -1445,14 +1313,14 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local padded_native_name = (" " .. native_name .. " ") local prefixed_lib_name = ("bit." .. lib_name) for i = 2, len do - local subexprs = nil - local _0_ + local subexprs + local _407_ if (i ~= len) then - _0_ = 1 + _407_ = 1 else - _0_ = nil + _407_ = nil end - subexprs = compiler.compile1(ast[i], scope, parent, {nval = _0_}) + subexprs = compiler.compile1(ast[i], scope, parent, {nval = _407_}) utils.map(subexprs, tostring, operands) end if (#operands == 1) then @@ -1471,10 +1339,18 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end end local function define_bitop_special(name, zero_arity, unary_prefix, native) - local function _0_(...) - return bitop_special(native, name, zero_arity, unary_prefix, ...) + local _417_ + do + local _413_ = native + local _414_ = name + local _415_ = zero_arity + local _416_ = unary_prefix + local function _418_(...) + return bitop_special(_413_, _414_, _415_, _416_, ...) + end + _417_ = _418_ end - SPECIALS[name] = _0_ + SPECIALS[name] = _417_ return nil end define_bitop_special("lshift", nil, "1", "<<") @@ -1487,20 +1363,16 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") - define_arithmetic_special("or", "false") - define_arithmetic_special("and", "true") - 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.") doc_special("..", {"a", "b", "..."}, "String concatenation operator; works the same as Lua but accepts more arguments.") - local function native_comparator(op, _0_0, scope, parent) - local _1_ = _0_0 - local _ = _1_[1] - local lhs_ast = _1_[2] - local rhs_ast = _1_[3] - local _2_ = compiler.compile1(lhs_ast, scope, parent, {nval = 1}) - local lhs = _2_[1] - local _3_ = compiler.compile1(rhs_ast, scope, parent, {nval = 1}) - local rhs = _3_[1] + local function native_comparator(op, _419_, scope, parent) + local _arg_420_ = _419_ + local _ = _arg_420_[1] + local lhs_ast = _arg_420_[2] + local rhs_ast = _arg_420_[3] + local _let_421_ = compiler.compile1(lhs_ast, scope, parent, {nval = 1}) + local lhs = _let_421_[1] + local _let_422_ = compiler.compile1(rhs_ast, scope, parent, {nval = 1}) + local rhs = _let_422_[1] return string.format("(%s %s %s)", tostring(lhs), op, tostring(rhs)) end local function double_eval_protected_comparator(op, chain_op, ast, scope, parent) @@ -1510,7 +1382,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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])) + 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)])) @@ -1553,7 +1425,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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.") - SPECIALS["~="] = SPECIALS["not="] + do end (SPECIALS)["~="] = SPECIALS["not="] SPECIALS["#"] = SPECIALS.length SPECIALS.quote = function(ast, scope, parent) compiler.assert((#ast == 2), "expected one argument") @@ -1567,63 +1439,65 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 already_warned_3f = {} - local compile_env_warning = table.concat({"WARNING: Attempting to %s %s in compile scope.", "In future versions of Fennel this will not be allowed without the", "--no-compiler-sandbox flag or passing a :compilerEnv globals table", "in the options.\n"}, "\n") - local function compiler_env_warn(_, key) - local v = _G[key] - if (v and io and io.stderr and not already_warned_3f[key]) then - already_warned_3f[key] = true - do end (io.stderr):write(compile_env_warning:format("use global", key)) - end - return v - end + 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(strict_3f) - local _1_ - if strict_3f then - _1_ = nil - else - _1_ = compiler_env_warn - end - return setmetatable({assert = assert, bit = rawget(_G, "bit"), error = error, getmetatable = safe_getmetatable, ipairs = ipairs, math = utils.copy(math), next = next, pairs = pairs, pcall = pcall, print = print, rawequal = rawequal, rawget = rawget, rawlen = rawget(_G, "rawlen"), rawset = rawset, require = safe_require, select = select, setmetatable = setmetatable, string = utils.copy(string), table = utils.copy(table), tonumber = tonumber, tostring = tostring, type = type, xpcall = xpcall}, {__index = _1_}) + local function safe_compiler_env() + return {table = utils.copy(table), math = utils.copy(math), string = utils.copy(string), pairs = pairs, ipairs = ipairs, select = select, tostring = tostring, tonumber = tonumber, bit = rawget(_G, "bit"), pcall = pcall, xpcall = xpcall, next = next, print = print, type = type, assert = assert, error = error, setmetatable = setmetatable, getmetatable = safe_getmetatable, require = safe_require, rawlen = rawget(_G, "rawlen"), rawget = rawget, rawset = rawset, rawequal = rawequal} end - local function make_compiler_env(ast, scope, parent, strict_3f) - local function _1_() + local function combined_mt_pairs(env) + local combined = {} + local _let_425_ = getmetatable(env) + local __index = _let_425_["__index"] + if ("table" == type(__index)) then + for k, v in pairs(__index) do + combined[k] = v + end + end + for k, v in next, env, nil do + combined[k] = v + end + return next, combined, nil + end + local function make_compiler_env(ast, scope, parent, _3fopts) + local provided + do + local _427_ = (_3fopts or utils.root.options) + if ((_G.type(_427_) == "table") and ((_427_)["compiler-env"] == "strict")) then + provided = safe_compiler_env() + elseif ((_G.type(_427_) == "table") and (nil ~= (_427_).compilerEnv)) then + local compilerEnv = (_427_).compilerEnv + provided = compilerEnv + elseif ((_G.type(_427_) == "table") and (nil ~= (_427_)["compiler-env"])) then + local compiler_env = (_427_)["compiler-env"] + provided = compiler_env + else + local _ = _427_ + provided = safe_compiler_env(false) + end + end + local env + local function _429_(base) + return utils.sym(compiler.gensym((compiler.scopes.macro or scope), base)) + end + local function _430_() return compiler.scopes.macro end - local function _2_(symbol) + local function _431_(symbol) compiler.assert(compiler.scopes.macro, "must call from macro", ast) return compiler.scopes.macro.manglings[tostring(symbol)] end - local function _3_(base) - return utils.sym(compiler.gensym((compiler.scopes.macro or scope), base)) - end - local function _4_(form) + local function _432_(form) compiler.assert(compiler.scopes.macro, "must call from macro", ast) return compiler.macroexpand(form, compiler.scopes.macro) end - local _6_ - do - local _5_0 = utils.root.options - if ((type(_5_0) == "table") and (_5_0["compiler-env"] == "strict")) then - _6_ = safe_compiler_env(true) - elseif ((type(_5_0) == "table") and (nil ~= _5_0.compilerEnv)) then - local compilerEnv = _5_0.compilerEnv - _6_ = compilerEnv - elseif ((type(_5_0) == "table") and (nil ~= _5_0["compiler-env"])) then - local compiler_env = _5_0["compiler-env"] - _6_ = compiler_env - else - local _ = _5_0 - _6_ = safe_compiler_env(false) - end - end - return setmetatable({["assert-compile"] = compiler.assert, ["get-scope"] = _1_, ["in-scope?"] = _2_, ["list?"] = utils["list?"], ["multi-sym?"] = utils["multi-sym?"], ["sequence?"] = utils["sequence?"], ["sym?"] = utils["sym?"], ["table?"] = utils["table?"], ["varg?"] = utils["varg?"], _AST = ast, _CHUNK = parent, _IS_COMPILER = true, _SCOPE = scope, _SPECIALS = compiler.scopes.global.specials, _VARARG = utils.varg(), gensym = _3_, list = utils.list, macroexpand = _4_, sequence = utils.sequence, sym = utils.sym, unpack = unpack, view = view}, {__index = _6_}) + env = {_AST = ast, _CHUNK = parent, _IS_COMPILER = true, _SCOPE = scope, _SPECIALS = compiler.scopes.global.specials, _VARARG = utils.varg(), ["macro-loaded"] = macro_loaded, unpack = unpack, ["assert-compile"] = compiler.assert, list = utils.list, ["list?"] = utils["list?"], ["multi-sym?"] = utils["multi-sym?"], sequence = utils.sequence, ["sequence?"] = utils["sequence?"], sym = utils.sym, ["sym?"] = utils["sym?"], ["table?"] = utils["table?"], ["varg?"] = utils["varg?"], view = view, gensym = _429_, ["get-scope"] = _430_, ["in-scope?"] = _431_, macroexpand = _432_} + env._G = env + return setmetatable(env, {__index = provided, __newindex = provided, __pairs = combined_mt_pairs}) end local cfg = string.gmatch(package.config, "([^\n]+)") local dirsep, pathsep, pathmark = (cfg() or "/"), (cfg() or ";"), (cfg() or "?") @@ -1639,39 +1513,45 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct 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 _1_0 = (io.open(filename) or io.open(filename2)) - if (nil ~= _1_0) then - local file = _1_0 + local _433_ = (io.open(filename) or io.open(filename2)) + if (nil ~= _433_) then + local file = _433_ file:close() return filename end end local function find_in_path(start) - local _1_0 = fullpath:match(pattern, start) - if (nil ~= _1_0) then - local path = _1_0 + local _435_ = fullpath:match(pattern, start) + if (nil ~= _435_) then + local path = _435_ return (try_path(path) or find_in_path((start + #path + 1))) end end return find_in_path(1) end local function make_searcher(options) - local function _1_(module_name) + local function _437_(module_name) local opts = utils.copy(utils.root.options) for k, v in pairs((options or {})) do opts[k] = v end opts["module-name"] = module_name - local _2_0 = search_module(module_name) - if (nil ~= _2_0) then - local filename = _2_0 - local function _3_(...) - return utils["fennel-module"].dofile(filename, opts, ...) + local _438_ = search_module(module_name) + if (nil ~= _438_) then + local filename = _438_ + local _441_ + do + local _439_ = filename + local _440_ = opts + local function _442_(...) + return utils["fennel-module"].dofile(_439_, _440_, ...) + end + _441_ = _442_ end - return _3_, filename + return _441_, filename end end - return _1_ + return _437_ end local function macro_globals(env, globals) local allowed = current_global_names(env) @@ -1680,67 +1560,110 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end return allowed end - local function default_macro_searcher(module_name) - local _1_0 = search_module(module_name) - if (nil ~= _1_0) then - local filename = _1_0 - local function _2_(...) - return utils["fennel-module"].dofile(filename, {env = "_COMPILER"}, ...) + local function fennel_macro_searcher(module_name) + local opts + do + local _444_ = utils.copy(utils.root.options) + do end (_444_)["env"] = "_COMPILER" + _444_["allowedGlobals"] = nil + opts = _444_ + end + local _445_ = search_module(module_name, utils["fennel-module"]["macro-path"]) + if (nil ~= _445_) then + local filename = _445_ + local _448_ + do + local _446_ = filename + local _447_ = opts + local function _449_(...) + return utils["fennel-module"].dofile(_446_, _447_, ...) + end + _448_ = _449_ end - return _2_, filename + return _448_, filename end end - local macro_searchers = {default_macro_searcher} + local function lua_macro_searcher(module_name) + local _451_ = search_module(module_name, package.path) + if (nil ~= _451_) then + local filename = _451_ + local code + do + local f = io.open(filename) + local function close_handlers_7_auto(ok_8_auto, ...) + f:close() + if ok_8_auto then + return ... + else + return error(..., 0) + end + end + local function _453_() + return assert(f:read("*a")) + end + code = close_handlers_7_auto(_G.xpcall(_453_, (package.loaded.fennel or debug).traceback)) + end + local chunk = load_code(code, make_compiler_env(), filename) + return chunk, filename + end + end + local macro_searchers = {lua_macro_searcher, fennel_macro_searcher} local function search_macro_module(modname, n) - local _1_0 = macro_searchers[n] - if (nil ~= _1_0) then - local f = _1_0 - local _2_0, _3_0 = f(modname) - if ((nil ~= _2_0) and true) then - local loader = _2_0 - local _3ffilename = _3_0 + local _455_ = macro_searchers[n] + if (nil ~= _455_) then + local f = _455_ + local _456_, _457_ = f(modname) + if ((nil ~= _456_) and true) then + local loader = _456_ + local _3ffilename = _457_ return loader, _3ffilename else - local _ = _2_0 + local _ = _456_ return search_macro_module(modname, (n + 1)) end end end - local macro_loaded = {} local function metadata_only_fennel(modname) if ((modname == "fennel.macros") or (package and package.loaded and ("table" == type(package.loaded[modname])) and (package.loaded[modname].metadata == compiler.metadata))) then return {metadata = compiler.metadata} end end - local function _1_(modname) - local function _2_() + local function _461_(modname) + local function _462_() local loader, filename = search_macro_module(modname, 1) compiler.assert(loader, (modname .. " module not found.")) - macro_loaded[modname] = loader(modname, filename) + do end (macro_loaded)[modname] = loader(modname, filename) return macro_loaded[modname] end - return (macro_loaded[modname] or metadata_only_fennel(modname) or _2_()) + return (macro_loaded[modname] or metadata_only_fennel(modname) or _462_()) end - safe_require = _1_ + safe_require = _461_ 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) - scope.macros[k] = v + do end (scope.macros)[k] = v end return nil end + local function resolve_module_name(_463_, scope, parent, opts) + local _arg_464_ = _463_ + local filename = _arg_464_["filename"] + local second = _arg_464_[2] + local filename0 = (filename or (utils["table?"](second) and second.filename)) + local module_name = utils.root.options["module-name"] + local modexpr = compiler.compile(second, opts) + local modname_chunk = load_code(modexpr) + return modname_chunk(module_name, filename0) + end SPECIALS["require-macros"] = function(ast, scope, parent, real_ast) compiler.assert((#ast == 2), "Expected one module name argument", (real_ast or ast)) - local filename = (ast[2].filename or ast.filename) - local modname_chunk = load_code(compiler.compile(ast[2]), nil, filename) - local modname = modname_chunk(utils.root.options["module-name"], filename) - compiler.assert((type(modname) == "string"), "module name must compile to string", (real_ast or ast)) + local modname = resolve_module_name(ast, scope, parent, {}) + compiler.assert(("string" == type(modname)), "module name must compile to string", (real_ast or ast)) if not macro_loaded[modname] then - local env = make_compiler_env(ast, scope, parent) - local loader, filename0 = search_macro_module(modname, 1) + local loader, filename = search_macro_module(modname, 1) compiler.assert(loader, (modname .. " module not found."), ast) - macro_loaded[modname] = loader(modname, filename0) + do end (macro_loaded)[modname] = loader(modname, filename) end return add_macros(macro_loaded[modname], ast, scope, parent) end @@ -1755,7 +1678,7 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct table.insert(forms, val) end for i = 1, #forms do - local subopts = nil + local subopts if (i == #forms) then subopts = {tail = true} else @@ -1768,21 +1691,21 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end local function include_path(ast, opts, path, mod, fennel_3f) utils.root.scope.includes[mod] = "fnl/loading" - local src = nil + local src do local f = assert(io.open(path)) - local function close_handlers_0_(ok_0_, ...) + local function close_handlers_7_auto(ok_8_auto, ...) f:close() - if ok_0_ then + if ok_8_auto then return ... else return error(..., 0) end end - local function _2_() + local function _469_() return f:read("*all"):gsub("[\13\n]*$", "") end - src = close_handlers_0_(xpcall(_2_, (package.loaded.fennel or debug).traceback)) + src = close_handlers_7_auto(_G.xpcall(_469_, (package.loaded.fennel or debug).traceback)) end local ret = utils.expr(("require(\"" .. mod .. "\")"), "statement") local target = ("package.preload[%q]"):format(mod) @@ -1810,7 +1733,20 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end SPECIALS.include = function(ast, scope, parent, opts) compiler.assert((#ast == 2), "expected one argument", ast) - local modexpr = compiler.compile1(ast[2], scope, parent, {nval = 1})[1] + local modexpr + do + local _472_, _473_ = pcall(resolve_module_name, ast, scope, parent, opts) + if ((_472_ == true) and (nil ~= _473_)) then + local modname = _473_ + modexpr = utils.expr(string.format("%q", modname), "literal") + elseif (true and (nil ~= _473_)) then + local _ = _472_ + local err = _473_ + modexpr = (compiler.compile1(ast[2], scope, parent, {nval = 1}))[1] + else + modexpr = nil + end + end if ((modexpr.type ~= "literal") or ((modexpr[1]):byte() ~= 34)) then if opts.fallback then return opts.fallback(modexpr) @@ -1819,13 +1755,18 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end else local mod = load_code(("return " .. modexpr[1]))() - local function _3_() - local _2_0 = search_module(mod) - if (nil ~= _2_0) then - local fennel_path = _2_0 + local oldmod = utils.root.options["module-name"] + local _ + utils.root.options["module-name"] = mod + _ = nil + local res + local function _477_() + local _476_ = search_module(mod) + if (nil ~= _476_) then + local fennel_path = _476_ return include_path(ast, opts, fennel_path, mod, true) else - local _ = _2_0 + local _0 = _476_ local lua_path = search_module(mod, package.path) if lua_path then return include_path(ast, opts, lua_path, mod, false) @@ -1836,7 +1777,9 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct end end end - return (include_circular_fallback(mod, modexpr, opts.fallback, ast) or utils.root.scope.includes[mod] or _3_()) + res = ((utils["member?"](mod, (utils.root.options.skipInclude or {})) and utils.expr("nil --[[SKIPPED INCLUDE]]--", "literal")) or include_circular_fallback(mod, modexpr, opts.fallback, ast) or utils.root.scope.includes[mod] or _477_()) + utils.root.options["module-name"] = oldmod + return res 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.") @@ -1856,11 +1799,11 @@ package.preload["fennel.specials"] = package.preload["fennel.specials"] or funct local old_first = ast[1] ast[1] = utils.sym("do") local val = eval_compiler_2a(ast, scope, parent) - ast[1] = old_first + 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.") - return {["current-global-names"] = current_global_names, ["load-code"] = load_code, ["macro-loaded"] = macro_loaded, ["macro-searchers"] = macro_searchers, ["make-compiler-env"] = make_compiler_env, ["make-searcher"] = make_searcher, ["search-module"] = search_module, ["wrap-env"] = wrap_env, doc = doc_2a} + 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") @@ -1870,16 +1813,16 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local scopes = {} local function make_scope(parent) local parent0 = (parent or scopes.global) - local _0_ + local _176_ if parent0 then - _0_ = ((parent0.depth or 0) + 1) + _176_ = ((parent0.depth or 0) + 1) else - _0_ = 0 + _176_ = 0 end - return {autogensyms = {}, depth = _0_, hashfn = (parent0 and parent0.hashfn), includes = setmetatable({}, {__index = (parent0 and parent0.includes)}), macros = setmetatable({}, {__index = (parent0 and parent0.macros)}), manglings = setmetatable({}, {__index = (parent0 and parent0.manglings)}), parent = parent0, refedglobals = setmetatable({}, {__index = (parent0 and parent0.refedglobals)}), specials = setmetatable({}, {__index = (parent0 and parent0.specials)}), symmeta = setmetatable({}, {__index = (parent0 and parent0.symmeta)}), unmanglings = setmetatable({}, {__index = (parent0 and parent0.unmanglings)}), vararg = (parent0 and parent0.vararg)} + return {includes = setmetatable({}, {__index = (parent0 and parent0.includes)}), macros = setmetatable({}, {__index = (parent0 and parent0.macros)}), manglings = setmetatable({}, {__index = (parent0 and parent0.manglings)}), refedglobals = setmetatable({}, {__index = (parent0 and parent0.refedglobals)}), specials = setmetatable({}, {__index = (parent0 and parent0.specials)}), symmeta = setmetatable({}, {__index = (parent0 and parent0.symmeta)}), unmanglings = setmetatable({}, {__index = (parent0 and parent0.unmanglings)}), gensyms = setmetatable({}, {__index = (parent0 and parent0.gensyms)}), autogensyms = setmetatable({}, {__index = (parent0 and parent0.autogensyms)}), vararg = (parent0 and parent0.vararg), depth = _176_, hashfn = (parent0 and parent0.hashfn), parent = parent0} end local function assert_msg(ast, msg) - local ast_tbl = nil + local ast_tbl if ("table" == type(ast)) then ast_tbl = ast else @@ -1888,24 +1831,16 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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 target = nil - local function _1_() - if utils["sym?"](ast_tbl[1]) then - return utils.deref(ast_tbl[1]) - else - return (ast_tbl[1] or "()") - end - end - target = tostring(_1_()) - return string.format("Compile error in '%s' %s:%s: %s", target, filename, line, msg) + local target = tostring((utils["sym?"](ast_tbl[1]) or ast_tbl[1] or "()")) + return string.format("%s:%s: Compile error in '%s': %s", filename, line, target, msg) end local function assert_compile(condition, msg, ast) if not condition then - local _0_ = (utils.root.options or {}) - local source = _0_["source"] - local unfriendly = _0_["unfriendly"] + local _let_179_ = (utils.root.options or {}) + local source = _let_179_["source"] + local unfriendly = _let_179_["unfriendly"] utils.root.reset() - if unfriendly then + 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) @@ -1917,44 +1852,44 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct scopes.global.vararg = true scopes.compiler = make_scope(scopes.global) scopes.macro = scopes.global - local serialize_subst = {["\11"] = "\\v", ["\12"] = "\\f", ["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\n"] = "n"} + local serialize_subst = {["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\n"] = "n", ["\11"] = "\\v", ["\12"] = "\\f"} local function serialize_string(str) - local function _0_(_241) + local function _182_(_241) return ("\\" .. _241:byte()) end - return string.gsub(string.gsub(string.format("%q", str), ".", serialize_subst), "[\128-\255]", _0_) + return string.gsub(string.gsub(string.format("%q", str), ".", serialize_subst), "[\128-\255]", _182_) end local function global_mangling(str) if utils["valid-lua-identifier?"](str) then return str else - local function _0_(_241) + local function _183_(_241) return string.format("_%02x", _241:byte()) end - return ("__fnl_global__" .. str:gsub("[^%w]", _0_)) + return ("__fnl_global__" .. str:gsub("[^%w]", _183_)) end end local function global_unmangling(identifier) - local _0_0 = string.match(identifier, "^__fnl_global__(.*)$") - if (nil ~= _0_0) then - local rest = _0_0 - local _1_0 = nil - local function _2_(_241) + local _185_ = string.match(identifier, "^__fnl_global__(.*)$") + if (nil ~= _185_) then + local rest = _185_ + local _186_ + local function _187_(_241) return string.char(tonumber(_241:sub(2), 16)) end - _1_0 = string.gsub(rest, "_[%da-f][%da-f]", _2_) - return _1_0 + _186_ = string.gsub(rest, "_[%da-f][%da-f]", _187_) + return _186_ else - local _ = _0_0 + local _ = _185_ return identifier end end local allowed_globals = nil - local function global_allowed(name) + 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] then + if (scope.unmanglings[mangling] and not scope.gensyms[mangling]) then return unique_mangling(original, (original .. append), scope, (append + 1)) else return mangling @@ -1962,29 +1897,29 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end local function local_mangling(str, scope, ast, temp_manglings) assert_compile(not utils["multi-sym?"](str), ("unexpected multi symbol " .. str), ast) - local raw = nil - if (utils["lua-keywords"][str] or str:match("^%d")) then + local raw + if ((utils["lua-keywords"])[str] or str:match("^%d")) then raw = ("_" .. str) else raw = str end - local mangling = nil - local function _1_(_241) + local mangling + local function _191_(_241) return string.format("_%02x", _241:byte()) end - mangling = string.gsub(string.gsub(raw, "-", "_"), "[^%w_]", _1_) + mangling = string.gsub(string.gsub(raw, "-", "_"), "[^%w_]", _191_) local unique = unique_mangling(mangling, mangling, scope, 0) - scope.unmanglings[unique] = str + do end (scope.unmanglings)[unique] = str do local manglings = (temp_manglings or scope.manglings) - manglings[str] = unique + 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) - scope.manglings[raw] = mangled + do end (scope.manglings)[raw] = mangled end return nil end @@ -2003,46 +1938,46 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end return ret end - local function gensym(scope, base) - local append, mangling = 0, ((base or "") .. "_0_") + local function next_append() + utils.root.scope["gensym-append"] = ((utils.root.scope["gensym-append"] or 0) + 1) + return ("_" .. utils.root.scope["gensym-append"] .. "_") + end + local function gensym(scope, base, _3fsuffix) + local mangling = ((base or "") .. next_append() .. (_3fsuffix or "")) while scope.unmanglings[mangling] do - mangling = ((base or "") .. "_" .. append .. "_") - append = (append + 1) + mangling = ((base or "") .. next_append() .. (_3fsuffix or "")) end scope.unmanglings[mangling] = (base or true) + do end (scope.gensyms)[mangling] = true return mangling end local function autogensym(base, scope) - local _0_0 = utils["multi-sym?"](base) - if (nil ~= _0_0) then - local parts = _0_0 + local _194_ = utils["multi-sym?"](base) + if (nil ~= _194_) then + local parts = _194_ parts[1] = autogensym(parts[1], scope) return table.concat(parts, ((parts["multi-sym-method-call"] and ":") or ".")) else - local _ = _0_0 - local function _1_() - local mangling = gensym(scope, base:sub(1, ( - 2))) - scope.autogensyms[base] = mangling + local _ = _194_ + local function _195_() + local mangling = gensym(scope, base:sub(1, ( - 2)), "auto") + do end (scope.autogensyms)[base] = mangling return mangling end - return (scope.autogensyms[base] or _1_()) + return (scope.autogensyms[base] or _195_()) end end - local already_warned = {} local function check_binding_valid(symbol, scope, ast) - local name = utils.deref(symbol) - if (io and io.stderr and name:find("&") and not already_warned[symbol]) then - already_warned[symbol] = true - do end (io.stderr):write(("-- Warning: & will not be allowed in identifier names in " .. "future versions: " .. (symbol.filename or "unknown") .. ":" .. (symbol.line or "?") .. "\n")) - end + local name = tostring(symbol) + assert_compile(not name:find("&"), "illegal 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, temp_manglings) check_binding_valid(symbol, scope, ast) - local name = utils.deref(symbol) + local name = tostring(symbol) assert_compile(not utils["multi-sym?"](name), ("unexpected multi symbol " .. name), ast) - scope.symmeta[name] = meta + do end (scope.symmeta)[name] = meta return local_mangling(name, scope, ast, temp_manglings) end local function hashfn_arg_name(name, multi_sym_parts, scope) @@ -2068,7 +2003,8 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct if (local_3f and scope.symmeta[parts[1]]) then scope.symmeta[parts[1]]["used"] = true end - assert_compile((not reference_3f or local_3f or global_allowed(parts[1])), ("unknown global in strict mode: " .. tostring(parts[1])), symbol) + assert_compile(not scope.macros[parts[1]], "tried to reference a macro at runtime", symbol) + assert_compile((not reference_3f or local_3f or ("_ENV" == parts[1]) or global_allowed_3f(parts[1])), ("unknown global in strict mode: " .. tostring(parts[1])), symbol) if (allowed_globals and not local_3f) then utils.root.scope.refedglobals[parts[1]] = true end @@ -2084,7 +2020,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local function peephole(chunk) if chunk.leaf then return chunk - elseif ((#chunk >= 3) and (chunk[(#chunk - 2)].leaf == "do") and not chunk[(#chunk - 1)].leaf and (chunk[#chunk].leaf == "end")) then + elseif ((#chunk >= 3) 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 @@ -2102,7 +2038,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local m = getmetatable(ast) return ((m and m.line and m) or (("table" == type(ast)) and ast) or {}) end - local function flatten_chunk_correlated(main_chunk) + 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 @@ -2111,7 +2047,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct for _, subchunk in ipairs(chunk) do if (subchunk.leaf or (#subchunk > 0)) then local source = ast_source(subchunk.ast) - if (file == source.file) then + if (file == source.filename) then last_line0 = math.max(last_line0, (source.line or 0)) end last_line0 = flatten(subchunk, out, last_line0, file) @@ -2121,7 +2057,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct return last_line0 end local out = {} - local last = flatten(main_chunk, out, 1, main_chunk.file) + local last = flatten(main_chunk, out, 1, options.filename) for i = 1, last do if (out[i] == nil) then out[i] = "" @@ -2138,16 +2074,16 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end return code else - local tab0 = nil + local tab0 do - local _0_0 = tab - if (_0_0 == true) then + local _208_ = tab + if (_208_ == true) then tab0 = " " - elseif (_0_0 == false) then + elseif (_208_ == false) then tab0 = "" - elseif (_0_0 == tab) then + elseif (_208_ == tab) then tab0 = tab - elseif (_0_0 == nil) then + elseif (_208_ == nil) then tab0 = "" else tab0 = nil @@ -2178,7 +2114,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local function flatten(chunk, options) local chunk0 = peephole(chunk) if options.correlate then - return flatten_chunk_correlated(chunk0), {} + return flatten_chunk_correlated(chunk0, options), {} else local sm = {} local ret = flatten_chunk(sm, chunk0, options.indent, 0) @@ -2195,17 +2131,17 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function make_metadata() - local function _0_(self, tgt, key) + local function _217_(self, tgt, key) if self[tgt] then return self[tgt][key] end end - local function _1_(self, tgt, key, value) + local function _219_(self, tgt, key, value) self[tgt] = (self[tgt] or {}) - self[tgt][key] = value + do end (self[tgt])[key] = value return tgt end - local function _2_(self, tgt, ...) + local function _220_(self, tgt, ...) local kv_len = select("#", ...) local kvs = {...} if ((kv_len % 2) ~= 0) then @@ -2217,25 +2153,26 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end return tgt end - return setmetatable({}, {__index = {get = _0_, set = _1_, setall = _2_}, __mode = "k"}) + return setmetatable({}, {__index = {get = _217_, set = _219_, setall = _220_}, __mode = "k"}) end local function exprs1(exprs) - return table.concat(utils.map(exprs, 1), ", ") - end - local function disambiguate_parens(code, chunk) - if ((code:byte() == 40) and (1 < #chunk)) then - return ("; " .. code) - else - return code - end + return table.concat(utils.map(exprs, tostring), ", ") end local function keep_side_effects(exprs, chunk, start, ast) - for j = (start or 1), #exprs do + 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 - emit(chunk, disambiguate_parens(tostring(se), chunk), ast) + local code = tostring(se) + local disambiguated + if (code:byte() == 40) then + disambiguated = ("do end " .. code) + else + disambiguated = code + end + emit(chunk, disambiguated, ast) end end return nil @@ -2262,21 +2199,21 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end if opts.target then local result = exprs1(exprs) - local function _2_() + local function _228_() if (result == "") then return "nil" else return result end end - emit(parent, string.format("%s = %s", opts.target, _2_()), ast) + emit(parent, string.format("%s = %s", opts.target, _228_()), ast) end if (opts.tail or opts.target) then return {returned = true} else - local _3_0 = exprs - _3_0["returned"] = true - return _3_0 + local _230_ = exprs + _230_["returned"] = true + return _230_ end end local function find_macro(ast, scope, multi_sym_parts) @@ -2287,7 +2224,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct return t end end - local macro_2a = (utils["sym?"](ast[1]) and scope.macros[utils.deref(ast[1])]) + local macro_2a = (utils["sym?"](ast[1]) and scope.macros[tostring(ast[1])]) if (not macro_2a and multi_sym_parts) then local nested_macro = find_in_table(scope.macros, 1) assert_compile((not scope.macros[multi_sym_parts[1]] or (type(nested_macro) == "function")), "macro not found in imported macro module", ast) @@ -2297,25 +2234,25 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function macroexpand_2a(ast, scope, once) - local _0_0 = nil + local _234_ if utils["list?"](ast) then - _0_0 = find_macro(ast, scope, utils["multi-sym?"](ast[1])) + _234_ = find_macro(ast, scope, utils["multi-sym?"](ast[1])) else - _0_0 = nil + _234_ = nil end - if (_0_0 == false) then + if (_234_ == false) then return ast - elseif (nil ~= _0_0) then - local macro_2a = _0_0 + elseif (nil ~= _234_) then + local macro_2a = _234_ local old_scope = scopes.macro - local _ = nil + local _ scopes.macro = scope _ = nil local ok, transformed = nil, nil - local function _2_() + local function _236_() return macro_2a(unpack(ast, 2)) end - ok, transformed = xpcall(_2_, debug.traceback) + ok, transformed = xpcall(_236_, debug.traceback) scopes.macro = old_scope assert_compile(ok, transformed, ast) if (once or not transformed) then @@ -2324,19 +2261,19 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct return macroexpand_2a(transformed, scope) end else - local _ = _0_0 + local _ = _234_ return ast 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 = nil - if (type(exprs) == "string") then + local exprs0 + if ("table" ~= type(exprs)) then exprs0 = utils.expr(exprs, "expression") else exprs0 = exprs end - local exprs2 = nil + local exprs2 if utils["expr?"](exprs0) then exprs2 = {exprs0} else @@ -2352,17 +2289,17 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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((fcallee.type ~= "literal"), ("cannot call literal value " .. tostring(ast[1])), ast) + local fcallee = (compile1(ast[1], scope, parent, {nval = 1}))[1] + assert_compile((("string" == type(ast[1])) or (fcallee.type ~= "literal")), ("cannot call literal value " .. tostring(ast[1])), ast) for i = 2, len do - local subexprs = nil - local _0_ + local subexprs + local _242_ if (i ~= len) then - _0_ = 1 + _242_ = 1 else - _0_ = nil + _242_ = nil end - subexprs = compile1(ast[i], scope, parent, {nval = _0_}) + subexprs = compile1(ast[i], scope, parent, {nval = _242_}) table.insert(fargs, (subexprs[1] or utils.expr("nil", "literal"))) if (i == len) then for j = 2, #subexprs do @@ -2372,7 +2309,13 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct keep_side_effects(subexprs, parent, 2, ast[i]) end end - local call = string.format("%s(%s)", tostring(fcallee), exprs1(fargs)) + 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) @@ -2380,7 +2323,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local len = #ast local first = ast[1] local multi_sym_parts = utils["multi-sym?"](first) - local special = (utils["sym?"](first) and scope.specials[utils.deref(first)]) + local special = (utils["sym?"](first) and scope.specials[tostring(first)]) assert_compile((len > 0), "expected a function, macro, or special to call", ast) if special then return compile_special(ast, scope, parent, opts, special) @@ -2400,7 +2343,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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 = nil + local e if (ast[1] == "nil") then e = utils.expr("nil", "literal") else @@ -2409,20 +2352,20 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct return handle_compile_opts({e}, parent, opts, ast) end local function serialize_number(n) - local _0_0 = string.gsub(tostring(n), ",", ".") - return _0_0 + local _248_ = string.gsub(tostring(n), ",", ".") + return _248_ end local function compile_scalar(ast, _scope, parent, opts) - local serialize = nil + local serialize do - local _0_0 = type(ast) - if (_0_0 == "nil") then + local _249_ = type(ast) + if (_249_ == "nil") then serialize = tostring - elseif (_0_0 == "boolean") then + elseif (_249_ == "boolean") then serialize = tostring - elseif (_0_0 == "string") then + elseif (_249_ == "string") then serialize = serialize_string - elseif (_0_0 == "number") then + elseif (_249_ == "number") then serialize = serialize_number else serialize = nil @@ -2441,32 +2384,31 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct if ((type(k) == "string") and utils["valid-lua-identifier?"](k)) then return {k, k} else - local _0_ = compile1(k, scope, parent, {nval = 1}) - local compiled = _0_[1] + local _let_251_ = compile1(k, scope, parent, {nval = 1}) + local compiled = _let_251_[1] local kstr = ("[" .. tostring(compiled) .. "]") return {kstr, k} end end end do - local keys = nil + local keys do - local _0_0 = utils.kvmap(ast, write_other_values) - local function _1_(a, b) - return (a[1] < b[1]) + local tbl_13_auto = {} + for k, v in utils.stablepairs(ast) do + tbl_13_auto[(#tbl_13_auto + 1)] = write_other_values(k, v) end - table.sort(_0_0, _1_) - keys = _0_0 + keys = tbl_13_auto end - local function _1_(_2_0) - local _3_ = _2_0 - local k1 = _3_[1] - local k2 = _3_[2] - local _4_ = compile1(ast[k2], scope, parent, {nval = 1}) - local v = _4_[1] + local function _256_(_254_) + local _arg_255_ = _254_ + local k1 = _arg_255_[1] + local k2 = _arg_255_[2] + local _let_257_ = compile1(ast[k2], scope, parent, {nval = 1}) + local v = _let_257_[1] return string.format("%s = %s", k1, tostring(v)) end - utils.map(keys, _1_, buffer) + utils.map(keys, _256_, buffer) end return handle_compile_opts({utils.expr(("{" .. table.concat(buffer, ", ") .. "}"), "expression")}, parent, opts, ast) end @@ -2489,14 +2431,14 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end local function destructure(to, from, ast, scope, parent, opts) local opts0 = (opts or {}) - local _0_ = opts0 - local declaration = _0_["declaration"] - local forceglobal = _0_["forceglobal"] - local forceset = _0_["forceset"] - local isvar = _0_["isvar"] - local symtype = _0_["symtype"] + local _let_259_ = opts0 + local isvar = _let_259_["isvar"] + local declaration = _let_259_["declaration"] + local forceglobal = _let_259_["forceglobal"] + local forceset = _let_259_["forceset"] + local symtype = _let_259_["symtype"] local symtype0 = ("_" .. (symtype or "dst")) - local setter = nil + local setter if declaration then setter = "local %s = %s" else @@ -2511,6 +2453,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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) @@ -2518,8 +2461,8 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end if forceglobal then assert_compile(not scope.symmeta[scope.unmanglings[raw]], ("global " .. raw .. " conflicts with local"), symbol) - scope.manglings[raw] = global_mangling(raw) - scope.unmanglings[global_mangling(raw)] = raw + 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) end @@ -2528,15 +2471,15 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function compile_top_target(lvalues) - local inits = nil - local function _2_(_241) + local inits + local function _265_(_241) if scope.manglings[_241] then return _241 else return "nil" end end - inits = utils.map(lvalues, _2_) + inits = utils.map(lvalues, _265_) local init = table.concat(inits, ", ") local lvalue = table.concat(lvalues, ", ") local plen, plast = #parent, parent[#parent] @@ -2566,24 +2509,24 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct emit(parent, setter:format(lname, exprs1(rightexprs)), left) end if declaration then - scope.symmeta[utils.deref(left)] = {var = isvar} + scope.symmeta[tostring(left)] = {var = isvar} return nil end end local function destructure_table(left, rightexprs, top_3f, destructure1) local s = gensym(scope, symtype0) - local right = nil + local right do - local _2_0 = nil + local _272_ if top_3f then - _2_0 = exprs1(compile1(from, scope, parent)) + _272_ = exprs1(compile1(from, scope, parent)) else - _2_0 = exprs1(rightexprs) + _272_ = exprs1(rightexprs) end - if (_2_0 == "") then + if (_272_ == "") then right = "nil" - elseif (nil ~= _2_0) then - local right0 = _2_0 + elseif (nil ~= _272_) then + local right0 = _272_ right = right0 else right = nil @@ -2592,20 +2535,20 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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?"](v) and (utils.deref(v) == "&")) then + if (utils["sym?"](v) and (tostring(v) == "&")) then local unpack_str = "{(table.unpack or unpack)(%s, %s)}" local formatted = string.format(unpack_str, 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) destructure1(left[(k + 1)], {subexpr}, left) - elseif (utils["sym?"](k) and (utils.deref(k) == "&as")) then + elseif (utils["sym?"](k) and (tostring(k) == "&as")) then destructure_sym(v, {utils.expr(tostring(s))}, left) - elseif (utils["sequence?"](left) and (utils.deref(v) == "&as")) then + 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 = nil + local key if (type(k) == "string") then key = serialize_string(k) else @@ -2626,14 +2569,16 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct else local symname = gensym(scope, symtype0) table.insert(left_names, symname) - tables[i] = {name, utils.expr(symname, "sym")} + do end (tables)[i] = {name, utils.expr(symname, "sym")} end end assert_compile(top_3f, "can't nest multi-value destructuring", left) compile_top_target(left_names) if declaration then for _, sym in ipairs(left) do - scope.symmeta[utils.deref(sym)] = {var = isvar} + if utils["sym?"](sym) then + scope.symmeta[tostring(sym)] = {var = isvar} + end end end for _, pair in utils.stablepairs(tables) do @@ -2649,7 +2594,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct 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)) + 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} @@ -2672,8 +2617,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local scope = (opts.scope or make_scope(scopes.global)) local vals = {} local chunk = {} - local _0_ = utils.root - _0_["set-reset"](_0_) + 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 = " " @@ -2701,8 +2645,7 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local old_globals = allowed_globals local chunk = {} local scope = (opts0.scope or make_scope(scopes.global)) - local _0_ = utils.root - _0_["set-reset"](_0_) + 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 = " " @@ -2733,14 +2676,14 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct info.currentline = (remap[info.currentline][2] or -1) end if (info.what == "Lua") then - local function _1_() + local function _289_() if info.name then return ("'" .. info.name .. "'") else return "?" end end - return string.format(" %s:%d: in function %s", info.short_src, info.currentline, _1_()) + return string.format(" %s:%d: in function %s", info.short_src, info.currentline, _289_()) elseif (info.short_src == "(tail call)") then return " (tail call)" else @@ -2749,12 +2692,12 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function traceback(msg, start) - local msg0 = (msg or "") + local msg0 = tostring((msg or "")) if ((msg0:find("^Compile error") or msg0:find("^Parse error")) and not utils["debug-on?"]("trace")) then return msg0 else local lines = {} - if (msg0:find("^Compile error") or msg0:find("^Parse error")) then + if (msg0:find(":%d+: Compile error") or msg0:find(":%d+: Parse error")) then table.insert(lines, msg0) else local newmsg = msg0:gsub("^[^:]*:%d+:%s+", "runtime error: ") @@ -2764,11 +2707,11 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct local done_3f, level = false, (start or 2) while not done_3f do do - local _1_0 = debug.getinfo(level, "Sln") - if (_1_0 == nil) then + local _293_ = debug.getinfo(level, "Sln") + if (_293_ == nil) then done_3f = true - elseif (nil ~= _1_0) then - local info = _1_0 + elseif (nil ~= _293_) then + local info = _293_ table.insert(lines, traceback_frame(info)) end end @@ -2778,14 +2721,14 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct end end local function entry_transform(fk, fv) - local function _0_(k, v) + local function _296_(k, v) if (type(k) == "number") then return k, fv(v) else return fk(k), fv(v) end end - return _0_ + return _296_ end local function mixed_concat(t, joiner) local seen = {} @@ -2811,30 +2754,30 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct assert_compile(not runtime_3f, "quoted ... may only be used at compile time", form) return "_VARARG" elseif utils["sym?"](form) then - local filename = nil + local filename if form.filename then filename = string.format("%q", form.filename) else filename = "nil" end - local symstr = utils.deref(form) + 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 (utils.deref(form[1]) == "unquote")) then + 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 = nil - local function _0_() + local mapped + local function _301_() return nil end - mapped = utils.kvmap(form, entry_transform(_0_, q)) - local filename = nil + mapped = utils.kvmap(form, entry_transform(_301_, q)) + local filename if form.filename then filename = string.format("%q", form.filename) else @@ -2845,50 +2788,50 @@ package.preload["fennel.compiler"] = package.preload["fennel.compiler"] or funct elseif utils["sequence?"](form) then local mapped = utils.kvmap(form, entry_transform(q, q)) local source = getmetatable(form) - local filename = nil + local filename if source.filename then filename = string.format("%q", source.filename) else filename = "nil" end - local _1_ + local _304_ if source then - _1_ = source.line + _304_ = source.line else - _1_ = "nil" + _304_ = "nil" end - return string.format("setmetatable({%s}, {filename=%s, line=%s, sequence=%s})", mixed_concat(mapped, ", "), filename, _1_, "(getmetatable(sequence()))['sequence']") + return string.format("setmetatable({%s}, {filename=%s, line=%s, sequence=%s})", mixed_concat(mapped, ", "), filename, _304_, "(getmetatable(sequence()))['sequence']") elseif (type(form) == "table") then local mapped = utils.kvmap(form, entry_transform(q, q)) local source = getmetatable(form) - local filename = nil + local filename if source.filename then filename = string.format("%q", source.filename) else filename = "nil" end - local function _1_() + local function _307_() if source then return source.line else return "nil" end end - return string.format("setmetatable({%s}, {filename=%s, line=%s})", mixed_concat(mapped, ", "), filename, _1_()) + return string.format("setmetatable({%s}, {filename=%s, line=%s})", mixed_concat(mapped, ", "), filename, _307_()) elseif (type(form) == "string") then return serialize_string(form) else return tostring(form) end end - return {["apply-manglings"] = apply_manglings, ["compile-stream"] = compile_stream, ["compile-string"] = compile_string, ["declare-local"] = declare_local, ["do-quote"] = do_quote, ["global-mangling"] = global_mangling, ["global-unmangling"] = global_unmangling, ["keep-side-effects"] = keep_side_effects, ["make-scope"] = make_scope, ["require-include"] = require_include, ["symbol-to-expression"] = symbol_to_expression, assert = assert_compile, autogensym = autogensym, compile = compile, compile1 = compile1, destructure = destructure, emit = emit, gensym = gensym, macroexpand = macroexpand_2a, metadata = make_metadata(), scopes = scopes, traceback = traceback} + return {compile = compile, compile1 = compile1, ["compile-stream"] = compile_stream, ["compile-string"] = compile_string, emit = emit, destructure = destructure, ["require-include"] = require_include, autogensym = autogensym, gensym = gensym, ["do-quote"] = do_quote, ["global-mangling"] = global_mangling, ["global-unmangling"] = global_unmangling, ["apply-manglings"] = apply_manglings, macroexpand = macroexpand_2a, ["declare-local"] = declare_local, ["make-scope"] = make_scope, ["keep-side-effects"] = keep_side_effects, ["symbol-to-expression"] = symbol_to_expression, assert = assert_compile, scopes = scopes, traceback = traceback, metadata = make_metadata()} end package.preload["fennel.friend"] = package.preload["fennel.friend"] or function(...) local function ast_source(ast) local m = getmetatable(ast) return ((m and m.line and m) or (("table" == type(ast)) and ast) or {}) end - local suggestions = {["$ and $... in hashfn are mutually exclusive"] = {"modifying the hashfn so it only contains $... or $, $1, $2, $3, etc"}, ["can't start multisym segment with a digit"] = {"removing the digit", "adding a non-digit before the digit"}, ["cannot call literal value"] = {"checking for typos", "checking for a missing function name"}, ["could not compile value of type "] = {"debugging the macro you're calling to return a list or table"}, ["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"}, ["expected a function.* to call"] = {"removing the empty parentheses", "using square brackets if you want an empty table"}, ["expected binding table"] = {"placing a table here in square brackets containing identifiers to bind"}, ["expected body expression"] = {"putting some code in the body of this form after the bindings"}, ["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"}, ["expected even number of name/value bindings"] = {"finding where the identifier or value is missing"}, ["expected even number of values in table literal"] = {"removing a key", "adding a value"}, ["expected local"] = {"looking for a typo", "looking for a local which is used out of its scope"}, ["expected macros to be table"] = {"ensuring your macro definitions return a table"}, ["expected parameters"] = {"adding function parameters as a list of identifiers in brackets"}, ["expected rest argument before last parameter"] = {"moving & to right before the final identifier when destructuring"}, ["expected symbol for function parameter: (.*)"] = {"changing %s to an identifier instead of a literal value"}, ["expected var (.*)"] = {"declaring %s using var instead of let/local", "introducing a new local instead of changing the value of %s"}, ["expected vararg as last parameter"] = {"moving the \"...\" to the end of the parameter list"}, ["expected whitespace before opening delimiter"] = {"adding whitespace"}, ["global (.*) conflicts with local"] = {"renaming local %s"}, ["illegal character: (.)"] = {"deleting or replacing %s", "avoiding reserved characters like \", \\, ', ~, ;, @, `, and comma"}, ["local (.*) was overshadowed by a special form or macro"] = {"renaming local %s"}, ["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"}, ["malformed multisym"] = {"ensuring each period or colon is not followed by another period or colon"}, ["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"}, ["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"}, ["mismatched closing delimiter (.), expected (.)"] = {"replacing %s with %s", "deleting %s", "adding matching opening delimiter earlier"}, ["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"}, ["unable to bind (.*)"] = {"replacing the %s with an identifier"}, ["unexpected closing delimiter (.)"] = {"deleting %s", "adding matching opening delimiter earlier"}, ["unexpected multi symbol (.*)"] = {"removing periods or colons from %s"}, ["unexpected vararg"] = {"putting \"...\" at the end of the fn parameters if the vararg was intended"}, ["unknown global in strict mode: (.*)"] = {"looking to see if there's a typo", "using the _G table instead, eg. _G.%s if you really want a global", "moving this code to somewhere that %s is in scope", "binding %s as a local in the scope of this code"}, ["unused local (.*)"] = {"fixing a typo so %s is used", "renaming the local to _%s"}, ["use of global (.*) is aliased by a local"] = {"renaming local %s", "refer to the global using _G.%s instead of directly"}} + local suggestions = {["unexpected multi symbol (.*)"] = {"removing periods or colons from %s"}, ["use of global (.*) is aliased by a local"] = {"renaming local %s", "refer to the global using _G.%s instead of directly"}, ["local (.*) was overshadowed by a special form or macro"] = {"renaming local %s"}, ["global (.*) conflicts with local"] = {"renaming local %s"}, ["expected var (.*)"] = {"declaring %s using var instead of let/local", "introducing a new local instead of changing the value of %s"}, ["expected macros to be table"] = {"ensuring your macro definitions return a table"}, ["expected each macro to be function"] = {"ensuring that the value for each key in your macros table contains a function", "avoid defining nested macro tables"}, ["macro not found in macro module"] = {"checking the keys of the imported macro module's returned table"}, ["macro tried to bind (.*) without gensym"] = {"changing to %s# when introducing identifiers inside macros"}, ["unknown global in strict mode: (.*)"] = {"looking to see if there's a typo", "using the _G table instead, eg. _G.%s if you really want a global", "moving this code to somewhere that %s is in scope", "binding %s as a local in the scope of this code"}, ["expected a function.* to call"] = {"removing the empty parentheses", "using square brackets if you want an empty table"}, ["cannot call literal value"] = {"checking for typos", "checking for a missing function name"}, ["unexpected vararg"] = {"putting \"...\" at the end of the fn parameters if the vararg was intended"}, ["multisym method calls may only be in call position"] = {"using a period instead of a colon to reference a table's fields", "putting parens around this"}, ["unused local (.*)"] = {"fixing a typo so %s is used", "renaming the local to _%s"}, ["expected parameters"] = {"adding function parameters as a list of identifiers in brackets"}, ["unable to bind (.*)"] = {"replacing the %s with an identifier"}, ["expected rest argument before last parameter"] = {"moving & to right before the final identifier when destructuring"}, ["expected vararg as last parameter"] = {"moving the \"...\" to the end of the parameter list"}, ["expected symbol for function parameter: (.*)"] = {"changing %s to an identifier instead of a literal value"}, ["could not compile value of type "] = {"debugging the macro you're calling to return a list or table"}, ["expected local"] = {"looking for a typo", "looking for a local which is used out of its scope"}, ["expected body expression"] = {"putting some code in the body of this form after the bindings"}, ["expected binding and iterator"] = {"making sure you haven't omitted a local name or iterator"}, ["expected binding sequence"] = {"placing a table here in square brackets containing identifiers to bind"}, ["expected even number of name/value bindings"] = {"finding where the identifier or value is missing"}, ["may only be used at compile time"] = {"moving this to inside a macro if you need to manipulate symbols/lists", "using square brackets instead of parens to construct a table"}, ["unexpected closing delimiter (.)"] = {"deleting %s", "adding matching opening delimiter earlier"}, ["mismatched closing delimiter (.), expected (.)"] = {"replacing %s with %s", "deleting %s", "adding matching opening delimiter earlier"}, ["expected even number of values in table literal"] = {"removing a key", "adding a value"}, ["expected whitespace before opening delimiter"] = {"adding whitespace"}, ["illegal character: (.)"] = {"deleting or replacing %s", "avoiding reserved characters like \", \\, ', ~, ;, @, `, and comma"}, ["could not read number (.*)"] = {"removing the non-digit character", "beginning the identifier with a non-digit if it is not meant to be a number"}, ["can't start multisym segment with a digit"] = {"removing the digit", "adding a non-digit before the digit"}, ["malformed multisym"] = {"ensuring each period or colon is not followed by another period or colon"}, ["method must be last component"] = {"using a period instead of a colon for field access", "removing segments after the colon", "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"}, ["expected even number of pattern/body pairs"] = {"checking that every pattern has a body to go with it", "adding _ before the final body"}, ["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 @@ -2911,7 +2854,7 @@ package.preload["fennel.friend"] = package.preload["fennel.friend"] or function( local function read_line_from_file(filename, line) local bytes = 0 local f = assert(io.open(filename)) - local _ = nil + local _ for _0 = 1, (line - 1) do bytes = (bytes + 1 + #f:read()) end @@ -2925,7 +2868,7 @@ package.preload["fennel.friend"] = package.preload["fennel.friend"] or function( local current_line = (_3fcurrent_line or 1) local bytes = ((_3fbytes or 0) + #this_line + #newline) if (target_line == current_line) then - return this_line, bytes + return this_line, (bytes - #this_line - 1) elseif this_line then return read_line_from_string(matcher, target_line, (current_line + 1), bytes) end @@ -2937,12 +2880,12 @@ package.preload["fennel.friend"] = package.preload["fennel.friend"] or function( return read_line_from_file(filename, line) end end - local function friendly_msg(msg, _0_0, source) - local _1_ = _0_0 - local byteend = _1_["byteend"] - local bytestart = _1_["bytestart"] - local filename = _1_["filename"] - local line = _1_["line"] + local function friendly_msg(msg, _116_, source) + local _arg_117_ = _116_ + local filename = _arg_117_["filename"] + local line = _arg_117_["line"] + local bytestart = _arg_117_["bytestart"] + local byteend = _arg_117_["byteend"] local ok, codeline, bol = pcall(read_line, filename, line, source) local suggestions0 = suggest(msg) local out = {msg, ""} @@ -2965,15 +2908,15 @@ package.preload["fennel.friend"] = package.preload["fennel.friend"] or function( end local function assert_compile(condition, msg, ast, source) if not condition then - local _1_ = ast_source(ast) - local filename = _1_["filename"] - local line = _1_["line"] + local _let_122_ = ast_source(ast) + local filename = _let_122_["filename"] + local line = _let_122_["line"] error(friendly_msg(("Compile error in %s:%s\n %s"):format((filename or "unknown"), (line or "?"), msg), ast_source(ast), source), 0) end return condition end local function parse_error(msg, filename, line, bytestart, source) - return error(friendly_msg(("Parse error in %s:%s\n %s"):format(filename, line, msg), {bytestart = bytestart, filename = filename, line = line}, source), 0) + return error(friendly_msg(("Parse error in %s:%s\n %s"):format(filename, line, msg), {filename = filename, line = line, bytestart = bytestart}, source), 0) end return {["assert-compile"] = assert_compile, ["parse-error"] = parse_error} end @@ -2983,54 +2926,53 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( local unpack = (table.unpack or _G.unpack) local function granulate(getchunk) local c, index, done_3f = "", 1, false - local function _0_(parser_state) + local function _124_(parser_state) if not done_3f then if (index <= #c) then local b = c:byte(index) index = (index + 1) return b else - local _1_0, _2_0, _3_0 = getchunk(parser_state) - local _4_ - do - local char = _1_0 - _4_ = ((nil ~= _1_0) and (char ~= "")) + local _125_ = getchunk(parser_state) + local function _126_() + local char = _125_ + return (char ~= "") end - if _4_ then - local char = _1_0 + if ((nil ~= _125_) and _126_()) then + local char = _125_ c = char index = 2 return c:byte() else - local _ = _1_0 + local _ = _125_ done_3f = true return nil end end end end - local function _1_() + local function _130_() c = "" return nil end - return _0_, _1_ + return _124_, _130_ end local function string_stream(str) local str0 = str:gsub("^#!", ";;") local index = 1 - local function _0_() + local function _131_() local r = str0:byte(index) index = (index + 1) return r end - return _0_ + return _131_ end - local delims = {[123] = 125, [125] = true, [40] = 41, [41] = true, [91] = 93, [93] = true} + local delims = {[40] = 41, [41] = true, [91] = 93, [93] = true, [123] = 125, [125] = true} local function whitespace_3f(b) return ((b == 32) or ((b >= 9) and (b <= 13))) end local function sym_char_3f(b) - local b0 = nil + local b0 if ("number" == type(b)) then b0 = b else @@ -3067,12 +3009,12 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end assert(((nil == filename) or ("string" == type(filename))), "expected filename as second argument to parser") local function parse_error(msg, byteindex_override) - local _0_ = (options or utils.root.options or {}) - local source = _0_["source"] - local unfriendly = _0_["unfriendly"] + local _let_136_ = (options or utils.root.options or {}) + local source = _let_136_["source"] + local unfriendly = _let_136_["unfriendly"] utils.root.reset() - if unfriendly then - return error(string.format("Parse error in %s:%s: %s", (filename or "unknown"), (line or "?"), msg), 0) + if (unfriendly or not friend or not _G.io or not _G.io.read) then + return error(string.format("%s:%s: Parse error: %s", (filename or "unknown"), (line or "?"), msg), 0) else return friend["parse-error"](msg, (filename or "unknown"), (line or "?"), (byteindex_override or byteindex), source) end @@ -3080,38 +3022,38 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( local function parse_stream() local whitespace_since_dispatch, done_3f, retval = true local function dispatch(v) - local _0_0 = stack[#stack] - if (_0_0 == nil) then + local _138_ = stack[#stack] + if (_138_ == nil) then retval, done_3f, whitespace_since_dispatch = v, true, false return nil - elseif ((type(_0_0) == "table") and (nil ~= _0_0.prefix)) then - local prefix = _0_0.prefix - local source = nil + elseif ((_G.type(_138_) == "table") and (nil ~= (_138_).prefix)) then + local prefix = (_138_).prefix + local source do - local _1_0 = table.remove(stack) - _1_0["byteend"] = byteindex - source = _1_0 + local _139_ = table.remove(stack) + do end (_139_)["byteend"] = byteindex + source = _139_ end local list = utils.list(utils.sym(prefix, source), v) for k, v0 in pairs(source) do list[k] = v0 end return dispatch(list) - elseif (nil ~= _0_0) then - local top = _0_0 + elseif (nil ~= _138_) then + local top = _138_ whitespace_since_dispatch = false return table.insert(top, v) end end local function badend() local accum = utils.map(stack, "closer") - local _0_ + local _141_ if (#stack == 1) then - _0_ = "" + _141_ = "" else - _0_ = "s" + _141_ = "s" end - return parse_error(string.format("expected closing delimiter%s %s", _0_, string.char(unpack(accum)))) + return parse_error(string.format("expected closing delimiter%s %s", _141_, string.char(unpack(accum)))) end local function skip_whitespace(b) if (b and whitespace_3f(b)) then @@ -3125,14 +3067,14 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end local function parse_comment(b, contents) if (b and (10 ~= b)) then - local function _1_() - local _0_0 = contents - table.insert(_0_0, string.char(b)) - return _0_0 + local function _145_() + local _144_ = contents + table.insert(_144_, string.char(b)) + return _144_ end - return parse_comment(getb(), _1_()) + return parse_comment(getb(), _145_()) elseif (options and options.comments) then - return dispatch(utils.comment(table.concat(contents), {filename = filename, line = (line - 1)})) + return dispatch(utils.comment(table.concat(contents), {line = (line - 1), filename = filename})) else return b end @@ -3154,12 +3096,12 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( return dispatch(val) end local function add_comment_at(comments, index, node) - local _0_0 = comments[index] - if (nil ~= _0_0) then - local existing = _0_0 + local _148_ = comments[index] + if (nil ~= _148_) then + local existing = _148_ return table.insert(existing, node) else - local _ = _0_0 + local _ = _148_ comments[index] = {node} return nil end @@ -3172,7 +3114,7 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end end local function extract_comments(tbl) - local comments = {keys = {}, last = {}, values = {}} + local comments = {keys = {}, values = {}, last = {}} while utils["comment?"](tbl[#tbl]) do table.insert(comments.last, 1, table.remove(tbl)) end @@ -3232,15 +3174,15 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end local function parse_string_loop(chars, b, state) table.insert(chars, b) - local state0 = nil + local state0 do - local _0_0 = {state, b} - if ((type(_0_0) == "table") and (_0_0[1] == "base") and (_0_0[2] == 92)) then + local _158_ = {state, b} + if ((_G.type(_158_) == "table") and ((_158_)[1] == "base") and ((_158_)[2] == 92)) then state0 = "backslash" - elseif ((type(_0_0) == "table") and (_0_0[1] == "base") and (_0_0[2] == 34)) then + elseif ((_G.type(_158_) == "table") and ((_158_)[1] == "base") and ((_158_)[2] == 34)) then state0 = "done" else - local _ = _0_0 + local _ = _158_ state0 = "base" end end @@ -3251,7 +3193,7 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end end local function escape_char(c) - return ({[10] = "\\n", [11] = "\\v", [12] = "\\f", [13] = "\\r", [7] = "\\a", [8] = "\\b", [9] = "\\t"})[c:byte()] + return ({[7] = "\\a", [8] = "\\b", [9] = "\\t", [10] = "\\n", [11] = "\\v", [12] = "\\f", [13] = "\\r"})[c:byte()] end local function parse_string() table.insert(stack, {closer = 34}) @@ -3262,11 +3204,16 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( table.remove(stack) local raw = string.char(unpack(chars)) local formatted = raw:gsub("[\7-\13]", escape_char) - local load_fn = (rawget(_G, "loadstring") or load)(("return " .. formatted)) - return dispatch(load_fn()) + local _162_ = (rawget(_G, "loadstring") or load)(("return " .. formatted)) + if (nil ~= _162_) then + local load_fn = _162_ + return dispatch(load_fn()) + elseif (_162_ == nil) then + return parse_error(("Invalid string: " .. raw)) + end end local function parse_prefix(b) - table.insert(stack, {bytestart = byteindex, filename = filename, line = line, prefix = prefixes[b]}) + table.insert(stack, {prefix = prefixes[b], filename = filename, line = line, bytestart = byteindex}) local nextb = getb() if (whitespace_3f(nextb) or (true == delims[nextb])) then if (b ~= 35) then @@ -3294,13 +3241,13 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( dispatch((tonumber(number_with_stripped_underscores) or parse_error(("could not read number \"" .. rawstr .. "\"")))) return true else - local _0_0 = tonumber(number_with_stripped_underscores) - if (nil ~= _0_0) then - local x = _0_0 + local _168_ = tonumber(number_with_stripped_underscores) + if (nil ~= _168_) then + local x = _168_ dispatch(x) return true else - local _ = _0_0 + local _ = _168_ return false end end @@ -3312,6 +3259,8 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( return parse_error(("can't start multisym segment with a digit: " .. rawstr), (((byteindex - #rawstr) + rawstr:find("%.[0-9]")) + 1)) elseif (rawstr:match("[%.:][%.:]") and (rawstr ~= "..") and (rawstr ~= "$...")) then return parse_error(("malformed multisym: " .. rawstr), ((byteindex - #rawstr) + 1 + rawstr:find("[%.:][%.:]"))) + elseif ((rawstr ~= ":") and rawstr:match(":$")) then + return parse_error(("malformed multisym: " .. rawstr), ((byteindex - #rawstr) + 1 + rawstr:find(":$"))) elseif rawstr:match(":.+[%.:]") then return parse_error(("method must be last component of multisym: " .. rawstr), ((byteindex - #rawstr) + rawstr:find(":.+[%.:]"))) else @@ -3347,7 +3296,7 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( parse_prefix(b) elseif (sym_char_3f(b) or (b == string.byte("~"))) then parse_sym(b) - else + elseif not utils.hook("illegal-char", b, getb, ungetb, dispatch) then parse_error(("illegal character: " .. string.char(b))) end if not b then @@ -3360,37 +3309,480 @@ package.preload["fennel.parser"] = package.preload["fennel.parser"] or function( end return parse_loop(skip_whitespace(getb())) end - local function _0_() - stack = {} + local function _175_() + stack, line, byteindex = {}, 1, 0 return nil end - return parse_stream, _0_ + return parse_stream, _175_ end - return {["string-stream"] = string_stream, ["sym-char?"] = sym_char_3f, granulate = granulate, parser = parser} + return {granulate = granulate, parser = parser, ["string-stream"] = string_stream, ["sym-char?"] = sym_char_3f} +end +local utils +package.preload["fennel.view"] = package.preload["fennel.view"] or function(...) + local type_order = {number = 1, boolean = 2, string = 3, table = 4, ["function"] = 5, userdata = 6, thread = 7} + local function sort_keys(_1_, _3_) + local _arg_2_ = _1_ + local a = _arg_2_[1] + local _arg_4_ = _3_ + local b = _arg_4_[1] + local ta = type(a) + local tb = type(b) + if ((ta == tb) and ((ta == "string") or (ta == "number"))) then + return (a < b) + else + local dta = type_order[ta] + local dtb = type_order[tb] + if (dta and dtb) then + return (dta < dtb) + elseif dta then + return true + elseif dtb then + return false + else + return (ta < tb) + end + end + end + local function max_index_gap(kv) + local gap = 0 + if (#kv > 0) then + local i = 0 + for _, _7_ in ipairs(kv) do + local _each_8_ = _7_ + local k = _each_8_[1] + if ((k - i) > gap) then + gap = (k - i) + end + i = k + end + end + return gap + end + local function fill_gaps(kv) + local missing_indexes = {} + local i = 0 + for _, _11_ in ipairs(kv) do + local _each_12_ = _11_ + local j = _each_12_[1] + i = (i + 1) + while (i < j) do + table.insert(missing_indexes, i) + i = (i + 1) + end + end + for _, k in ipairs(missing_indexes) do + table.insert(kv, k, {k}) + end + return nil + end + local function table_kv_pairs(t, options) + local assoc_3f = false + local kv = {} + local insert = table.insert + for k, v in pairs(t) do + if (type(k) ~= "number") then + assoc_3f = true + end + insert(kv, {k, v}) + end + table.sort(kv, sort_keys) + if not assoc_3f then + local gap = max_index_gap(kv) + if (max_index_gap(kv) > options["max-sparse-gap"]) then + assoc_3f = true + else + fill_gaps(kv) + end + end + if (#kv == 0) then + return kv, "empty" + else + local function _16_() + if assoc_3f then + return "table" + else + return "seq" + end + end + return kv, _16_() + end + end + local function count_table_appearances(t, appearances) + if (type(t) == "table") then + if not appearances[t] then + appearances[t] = 1 + for k, v in pairs(t) do + count_table_appearances(k, appearances) + count_table_appearances(v, appearances) + end + else + appearances[t] = ((appearances[t] or 0) + 1) + end + end + return appearances + end + local function save_table(t, seen) + local seen0 = (seen or {len = 0}) + local id = (seen0.len + 1) + if not (seen0)[t] then + seen0[t] = id + seen0.len = id + end + return seen0 + end + local function detect_cycle(t, seen, _3fk) + if ("table" == type(t)) then + seen[t] = true + local _21_, _22_ = next(t, _3fk) + if ((nil ~= _21_) and (nil ~= _22_)) then + local k = _21_ + local v = _22_ + return (seen[k] or detect_cycle(k, seen) or seen[v] or detect_cycle(v, seen) or detect_cycle(t, seen, k)) + end + end + end + local function visible_cycle_3f(t, options) + return (options["detect-cycles?"] and detect_cycle(t, {}) and save_table(t, options.seen) and (1 < (options.appearances[t] or 0))) + end + local function table_indent(t, indent, id) + local opener_length + if id then + opener_length = (#tostring(id) + 2) + else + opener_length = 1 + end + return (indent + opener_length) + end + local pp = nil + local function concat_table_lines(elements, options, multiline_3f, indent, table_type, prefix) + local indent_str = ("\n" .. string.rep(" ", indent)) + local open + local _26_ + if ("seq" == table_type) then + _26_ = "[" + else + _26_ = "{" + end + open = ((prefix or "") .. _26_) + local close + if ("seq" == table_type) then + close = "]" + else + close = "}" + end + local oneline = (open .. table.concat(elements, " ") .. close) + if (not options["one-line?"] and (multiline_3f or ((indent + #oneline) > options["line-length"]))) then + return (open .. table.concat(elements, indent_str) .. close) + else + return oneline + end + end + local function pp_associative(t, kv, options, indent, key_3f) + local multiline_3f = false + local id = options.seen[t] + if (options.level >= options.depth) then + return "{...}" + elseif (id and options["detect-cycles?"]) then + return ("@" .. id .. "{...}") + else + local visible_cycle_3f0 = visible_cycle_3f(t, options) + local id0 = (visible_cycle_3f0 and options.seen[t]) + local indent0 = table_indent(t, indent, id0) + local slength + local function _31_() + local _30_ = rawget(_G, "utf8") + if _30_ then + return (_30_).len + else + return _30_ + end + end + local function _33_(_241) + return #_241 + end + slength = ((options["utf8?"] and _31_()) or _33_) + local prefix + if visible_cycle_3f0 then + prefix = ("@" .. id0) + else + prefix = "" + end + local items + do + local tbl_13_auto = {} + for _, _35_ in pairs(kv) do + local _each_36_ = _35_ + local k = _each_36_[1] + local v = _each_36_[2] + local _37_ + do + local k0 = pp(k, options, (indent0 + 1), true) + local v0 = pp(v, options, (indent0 + slength(k0) + 1)) + multiline_3f = (multiline_3f or k0:find("\n") or v0:find("\n")) + _37_ = (k0 .. " " .. v0) + end + tbl_13_auto[(#tbl_13_auto + 1)] = _37_ + end + items = tbl_13_auto + end + return concat_table_lines(items, options, multiline_3f, indent0, "table", prefix) + end + end + local function pp_sequence(t, kv, options, indent) + local multiline_3f = false + local id = options.seen[t] + if (options.level >= options.depth) then + return "[...]" + elseif (id and options["detect-cycles?"]) then + return ("@" .. id .. "[...]") + else + local visible_cycle_3f0 = visible_cycle_3f(t, options) + local id0 = (visible_cycle_3f0 and options.seen[t]) + local indent0 = table_indent(t, indent, id0) + local prefix + if visible_cycle_3f0 then + prefix = ("@" .. id0) + else + prefix = "" + end + local items + do + local tbl_13_auto = {} + for _, _40_ in pairs(kv) do + local _each_41_ = _40_ + local _0 = _each_41_[1] + local v = _each_41_[2] + local _42_ + do + local v0 = pp(v, options, indent0) + multiline_3f = (multiline_3f or v0:find("\n")) + _42_ = v0 + end + tbl_13_auto[(#tbl_13_auto + 1)] = _42_ + end + items = tbl_13_auto + end + return concat_table_lines(items, options, multiline_3f, indent0, "seq", prefix) + end + end + local function concat_lines(lines, options, indent, force_multi_line_3f) + if (#lines == 0) then + if options["empty-as-sequence?"] then + return "[]" + else + return "{}" + end + else + local oneline + local _45_ + do + local tbl_13_auto = {} + for _, line in ipairs(lines) do + tbl_13_auto[(#tbl_13_auto + 1)] = line:gsub("^%s+", "") + end + _45_ = tbl_13_auto + end + oneline = table.concat(_45_, " ") + if (not options["one-line?"] and (force_multi_line_3f or oneline:find("\n") or ((indent + #oneline) > options["line-length"]))) then + return table.concat(lines, ("\n" .. string.rep(" ", indent))) + else + return oneline + end + end + end + local function pp_metamethod(t, metamethod, options, indent) + if (options.level >= options.depth) then + if options["empty-as-sequence?"] then + return "[...]" + else + return "{...}" + end + else + local _ + local function _49_(_241) + return visible_cycle_3f(_241, options) + end + options["visible-cycle?"] = _49_ + _ = nil + local lines, force_multi_line_3f = metamethod(t, pp, options, indent) + options["visible-cycle?"] = nil + local _50_ = type(lines) + if (_50_ == "string") then + return lines + elseif (_50_ == "table") then + return concat_lines(lines, options, indent, force_multi_line_3f) + else + local _0 = _50_ + return error("__fennelview metamethod must return a table of lines") + end + end + end + local function pp_table(x, options, indent) + options.level = (options.level + 1) + local x0 + do + local _53_ + if options["metamethod?"] then + local _54_ = x + if _54_ then + local _55_ = getmetatable(_54_) + if _55_ then + _53_ = (_55_).__fennelview + else + _53_ = _55_ + end + else + _53_ = _54_ + end + else + _53_ = nil + end + if (nil ~= _53_) then + local metamethod = _53_ + x0 = pp_metamethod(x, metamethod, options, indent) + else + local _ = _53_ + local _59_, _60_ = table_kv_pairs(x, options) + if (true and (_60_ == "empty")) then + local _0 = _59_ + if options["empty-as-sequence?"] then + x0 = "[]" + else + x0 = "{}" + end + elseif ((nil ~= _59_) and (_60_ == "table")) then + local kv = _59_ + x0 = pp_associative(x, kv, options, indent) + elseif ((nil ~= _59_) and (_60_ == "seq")) then + local kv = _59_ + x0 = pp_sequence(x, kv, options, indent) + else + x0 = nil + end + end + end + options.level = (options.level - 1) + return x0 + end + local function number__3estring(n) + local _64_ = string.gsub(tostring(n), ",", ".") + return _64_ + end + local function colon_string_3f(s) + return s:find("^[-%w?^_!$%&*+./@|<=>]+$") + end + local function pp_string(str, options, indent) + local escs + local _65_ + if (options["escape-newlines?"] and (#str < (options["line-length"] - indent))) then + _65_ = "\\n" + else + _65_ = "\n" + end + local function _67_(_241, _242) + return ("\\%03d"):format(_242:byte()) + end + escs = setmetatable({["\7"] = "\\a", ["\8"] = "\\b", ["\12"] = "\\f", ["\11"] = "\\v", ["\13"] = "\\r", ["\9"] = "\\t", ["\\"] = "\\\\", ["\""] = "\\\"", ["\n"] = _65_}, {__index = _67_}) + return ("\"" .. str:gsub("[%c\\\"]", escs) .. "\"") + end + local function make_options(t, options) + local defaults = {["line-length"] = 80, ["one-line?"] = false, depth = 128, ["detect-cycles?"] = true, ["empty-as-sequence?"] = false, ["metamethod?"] = true, ["prefer-colon?"] = false, ["escape-newlines?"] = false, ["utf8?"] = true, ["max-sparse-gap"] = 10} + local overrides = {level = 0, appearances = count_table_appearances(t, {}), seen = {len = 0}} + for k, v in pairs((options or {})) do + defaults[k] = v + end + for k, v in pairs(overrides) do + defaults[k] = v + end + return defaults + end + local function _68_(x, options, indent, colon_3f) + local indent0 = (indent or 0) + local options0 = (options or make_options(x)) + local x0 + if options0.preprocess then + x0 = options0.preprocess(x, options0) + else + x0 = x + end + local tv = type(x0) + local function _71_() + local _70_ = getmetatable(x0) + if _70_ then + return (_70_).__fennelview + else + return _70_ + end + end + if ((tv == "table") or ((tv == "userdata") and _71_())) then + return pp_table(x0, options0, indent0) + elseif (tv == "number") then + return number__3estring(x0) + else + local function _73_() + if (colon_3f ~= nil) then + return colon_3f + elseif ("function" == type(options0["prefer-colon?"])) then + return options0["prefer-colon?"](x0) + else + return options0["prefer-colon?"] + end + end + if ((tv == "string") and colon_string_3f(x0) and _73_()) then + return (":" .. x0) + elseif (tv == "string") then + return pp_string(x0, options0, indent0) + elseif ((tv == "boolean") or (tv == "nil")) then + return tostring(x0) + else + return ("#<" .. tostring(x0) .. ">") + end + end + end + pp = _68_ + local function view(x, options) + return pp(x, make_options(x, options), 0) + end + return view end -local utils = nil package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(...) + local view = require("fennel.view") local function stablepairs(t) local keys = {} + local used_keys = {} local succ = {} - for k in pairs(t) do - table.insert(keys, k) + if (getmetatable(t) and getmetatable(t).keys) then + for _, k in ipairs(getmetatable(t).keys) do + if used_keys[k] then + for i = #keys, 1, -1 do + if (keys[i] == k) then + table.remove(keys, i) + end + end + end + used_keys[k] = true + table.insert(keys, k) + end + else + for k in pairs(t) do + table.insert(keys, k) + end + local function _77_(_241, _242) + return (tostring(_241) < tostring(_242)) + end + table.sort(keys, _77_) end - local function _0_(_241, _242) - return (tostring(_241) < tostring(_242)) - end - table.sort(keys, _0_) for i, k in ipairs(keys) do succ[k] = keys[(i + 1)] end local function stablenext(tbl, idx) - local key = nil + local key if (idx == nil) then key = keys[1] else key = succ[idx] end - local value = nil + local value if (key == nil) then value = nil else @@ -3402,19 +3794,19 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. end local function map(t, f, out) local out0 = (out or {}) - local f0 = nil + local f0 if (type(f) == "function") then f0 = f else - local function _0_(_241) - return _241[f] + local function _81_(_241) + return (_241)[f] end - f0 = _0_ + f0 = _81_ end for _, x in ipairs(t) do - local _1_0 = f0(x) - if (nil ~= _1_0) then - local v = _1_0 + local _83_ = f0(x) + if (nil ~= _83_) then + local v = _83_ table.insert(out0, v) end end @@ -3422,23 +3814,23 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. end local function kvmap(t, f, out) local out0 = (out or {}) - local f0 = nil + local f0 if (type(f) == "function") then f0 = f else - local function _0_(_241) - return _241[f] + local function _85_(_241) + return (_241)[f] end - f0 = _0_ + f0 = _85_ end for k, x in stablepairs(t) do - local _1_0, _2_0 = f0(k, x) - if ((nil ~= _1_0) and (nil ~= _2_0)) then - local key = _1_0 - local value = _2_0 + local _87_, _88_ = f0(k, x) + if ((nil ~= _87_) and (nil ~= _88_)) then + local key = _87_ + local value = _88_ out0[key] = value - elseif (nil ~= _1_0) then - local value = _1_0 + elseif (nil ~= _87_) then + local value = _87_ table.insert(out0, value) end end @@ -3452,13 +3844,13 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. return to0 end local function member_3f(x, tbl, n) - local _0_0 = tbl[(n or 1)] - if (_0_0 == x) then + local _90_ = tbl[(n or 1)] + if (_90_ == x) then return true - elseif (_0_0 == nil) then - return false + elseif (_90_ == nil) then + return nil else - local _ = _0_0 + local _ = _90_ return member_3f(x, tbl, ((n or 1) + 1)) end end @@ -3474,10 +3866,13 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. seen[next_state] = true return next_state, value else - local meta = getmetatable(t) - if (meta and meta.__index) then - t = meta.__index - return allpairs_next(t) + local _92_ = getmetatable(t) + if ((_G.type(_92_) == "table") and true) then + local __index = (_92_).__index + if ("table" == type(__index)) then + t = __index + return allpairs_next(t) + end end end end @@ -3497,7 +3892,7 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. for i = 1, max do safe[i] = (((self[i] == nil) and nil_sym) or self[i]) end - return ("(" .. table.concat(map(safe, (tostring2 or tostring)), " ", 1, max) .. ")") + return ("(" .. table.concat(map(safe, (tostring2 or view)), " ", 1, max) .. ")") end local function comment_view(c) return c, true @@ -3508,17 +3903,21 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. local function sym_3c(a, b) return (a[1] < tostring(b)) end - local symbol_mt = {"SYMBOL", __eq = sym_3d, __fennelview = deref, __lt = sym_3c, __tostring = deref} - local expr_mt = {"EXPR", __tostring = deref} + local symbol_mt = {"SYMBOL", __fennelview = deref, __tostring = deref, __eq = sym_3d, __lt = sym_3c} + local expr_mt + local function _97_(x) + return tostring(deref(x)) + end + expr_mt = {"EXPR", __tostring = _97_} local list_mt = {"LIST", __fennelview = list__3estring, __tostring = list__3estring} - local comment_mt = {"COMMENT", __eq = sym_3d, __fennelview = comment_view, __lt = sym_3c, __tostring = deref} + local comment_mt = {"COMMENT", __fennelview = comment_view, __tostring = deref, __eq = sym_3d, __lt = sym_3c} local sequence_marker = {"SEQUENCE"} local vararg = setmetatable({"..."}, {"VARARG", __fennelview = deref, __tostring = deref}) - local getenv = nil - local function _0_() + local getenv + local function _98_() return nil end - getenv = ((os and os.getenv) or _0_) + getenv = ((os and os.getenv) or _98_) local function debug_on_3f(flag) local level = (getenv("FENNEL_DEBUG") or "") return ((level == "all") or level:find(flag)) @@ -3543,9 +3942,9 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. return setmetatable({strcode, type = etype}, expr_mt) end local function comment_2a(contents, _3fsource) - local _1_ = (_3fsource or {}) - local filename = _1_["filename"] - local line = _1_["line"] + local _let_100_ = (_3fsource or {}) + local filename = _let_100_["filename"] + local line = _let_100_["line"] return setmetatable({contents, filename = filename, line = line}, comment_mt) end local function varg() @@ -3623,16 +4022,16 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. end return subopts end - local root = nil - local function _1_() + local root + local function _105_() end - root = {chunk = nil, options = nil, reset = _1_, scope = nil} - root["set-reset"] = function(_2_0) - local _3_ = _2_0 - local chunk = _3_["chunk"] - local options = _3_["options"] - local reset = _3_["reset"] - local scope = _3_["scope"] + root = {chunk = nil, scope = nil, options = nil, reset = _105_} + root["set-reset"] = function(_106_) + local _arg_107_ = _106_ + local chunk = _arg_107_["chunk"] + local scope = _arg_107_["scope"] + local options = _arg_107_["options"] + local reset = _arg_107_["reset"] root.reset = function() root.chunk, root.scope, root.options, root.reset = chunk, scope, options, reset return nil @@ -3640,18 +4039,24 @@ package.preload["fennel.utils"] = package.preload["fennel.utils"] or function(.. return root.reset end local function hook(event, ...) + local result = nil if (root.options and root.options.plugins) then for _, plugin in ipairs(root.options.plugins) do - local _3_0 = plugin[event] - if (nil ~= _3_0) then - local f = _3_0 - f(...) + do + local _108_ = plugin[event] + if (nil ~= _108_) then + local f = _108_ + result = f(...) + end + end + if (nil ~= result) then + return result end end return nil end end - return {["comment?"] = comment_3f, ["debug-on?"] = debug_on_3f, ["expr?"] = expr_3f, ["list?"] = list_3f, ["lua-keywords"] = lua_keywords, ["member?"] = member_3f, ["multi-sym?"] = multi_sym_3f, ["propagate-options"] = propagate_options, ["quoted?"] = quoted_3f, ["sequence?"] = sequence_3f, ["sym?"] = sym_3f, ["table?"] = table_3f, ["valid-lua-identifier?"] = valid_lua_identifier_3f, ["varg?"] = varg_3f, ["walk-tree"] = walk_tree, allpairs = allpairs, comment = comment_2a, copy = copy, deref = deref, expr = expr, hook = hook, kvmap = kvmap, list = list, map = map, path = table.concat({"./?.fnl", "./?/init.fnl", getenv("FENNEL_PATH")}, ";"), root = root, sequence = sequence, stablepairs = stablepairs, sym = sym, varg = varg} + return {allpairs = allpairs, stablepairs = stablepairs, copy = copy, kvmap = kvmap, map = map, ["walk-tree"] = walk_tree, ["member?"] = member_3f, list = list, sequence = sequence, sym = sym, varg = varg, expr = expr, comment = comment_2a, ["comment?"] = comment_3f, ["expr?"] = expr_3f, ["list?"] = list_3f, ["multi-sym?"] = multi_sym_3f, ["sequence?"] = sequence_3f, ["sym?"] = sym_3f, ["table?"] = table_3f, ["varg?"] = varg_3f, ["quoted?"] = quoted_3f, ["valid-lua-identifier?"] = valid_lua_identifier_3f, ["lua-keywords"] = lua_keywords, hook = hook, ["propagate-options"] = propagate_options, root = root, ["debug-on?"] = debug_on_3f, path = table.concat({"./?.fnl", "./?/init.fnl", getenv("FENNEL_PATH")}, ";"), ["macro-path"] = table.concat({"./?.fnl", "./?/init-macros.fnl", "./?/init.fnl", getenv("FENNEL_MACRO_PATH")}, ";")} end utils = require("fennel.utils") local parser = require("fennel.parser") @@ -3659,11 +4064,12 @@ local compiler = require("fennel.compiler") local specials = require("fennel.specials") local repl = require("fennel.repl") local view = require("fennel.view") -local function eval_env(env) +local function eval_env(env, opts) if (env == "_COMPILER") then - local env0 = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}) - local mt = getmetatable(env0) - mt.__index = _G + local env0 = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}, opts) + if (opts.allowedGlobals == nil) then + opts.allowedGlobals = specials["current-global-names"](env0) + end return specials["wrap-env"](env0) else return (env and specials["wrap-env"](env)) @@ -3671,7 +4077,7 @@ local function eval_env(env) end local function eval_opts(options, str) local opts = utils.copy(options) - if ((opts.allowedGlobals == nil) and not getmetatable(opts.env)) then + if (opts.allowedGlobals == nil) then opts.allowedGlobals = specials["current-global-names"](opts.env) end if (not opts.filename and not opts.source) then @@ -3684,17 +4090,17 @@ local function eval_opts(options, str) end local function eval(str, options, ...) local opts = eval_opts(options, str) - local env = eval_env(opts.env) + local env = eval_env(opts.env, opts) local lua_source = compiler["compile-string"](str, opts) - local loader = nil - local function _0_(...) + local loader + local function _563_(...) if opts.filename then return ("@" .. opts.filename) else return str end end - loader = specials["load-code"](lua_source, env, _0_(...)) + loader = specials["load-code"](lua_source, env, _563_(...)) opts.filename = nil return loader(...) end @@ -3706,7 +4112,34 @@ local function dofile_2a(filename, options, ...) opts.filename = filename return eval(source, opts, ...) end -local mod = {["comment?"] = utils["comment?"], ["compile-stream"] = compiler["compile-stream"], ["compile-string"] = compiler["compile-string"], ["list?"] = utils["list?"], ["load-code"] = specials["load-code"], ["macro-loaded"] = specials["macro-loaded"], ["macro-searchers"] = specials["macro-searchers"], ["make-searcher"] = specials["make-searcher"], ["search-module"] = specials["search-module"], ["sequence?"] = utils["sequence?"], ["string-stream"] = parser["string-stream"], ["sym-char?"] = parser["sym-char?"], ["sym?"] = utils["sym?"], comment = utils.comment, compile = compiler.compile, compile1 = compiler.compile1, compileStream = compiler["compile-stream"], compileString = compiler["compile-string"], doc = specials.doc, dofile = dofile_2a, eval = eval, gensym = compiler.gensym, granulate = parser.granulate, list = utils.list, loadCode = specials["load-code"], macroLoaded = specials["macro-loaded"], makeSearcher = specials["make-searcher"], make_searcher = specials["make-searcher"], mangle = compiler["global-mangling"], metadata = compiler.metadata, parser = parser.parser, path = utils.path, repl = repl, scope = compiler["make-scope"], searchModule = specials["search-module"], searcher = specials["make-searcher"](), sequence = utils.sequence, stringStream = parser["string-stream"], sym = utils.sym, traceback = compiler.traceback, unmangle = compiler["global-unmangling"], varg = utils.varg, version = "0.9.1", view = view} +local function syntax() + local body_3f = {"when", "with-open", "collect", "icollect", "lambda", "\206\187", "macro", "match", "accumulate"} + local binding_3f = {"collect", "icollect", "each", "for", "let", "with-open", "accumulate"} + local define_3f = {"fn", "lambda", "\206\187", "var", "local", "macro", "macros", "global"} + local out = {} + for k, v in pairs(compiler.scopes.global.specials) do + local metadata = (compiler.metadata[v] or {}) + do end (out)[k] = {["special?"] = true, ["body-form?"] = metadata["fnl/body-form?"], ["binding-form?"] = utils["member?"](k, binding_3f), ["define?"] = utils["member?"](k, define_3f)} + end + for k, v in pairs(compiler.scopes.global.macros) do + out[k] = {["macro?"] = true, ["body-form?"] = utils["member?"](k, body_3f), ["binding-form?"] = utils["member?"](k, binding_3f), ["define?"] = utils["member?"](k, define_3f)} + end + for k, v in pairs(_G) do + local _564_ = type(v) + if (_564_ == "function") then + out[k] = {["global?"] = true, ["function?"] = true} + elseif (_564_ == "table") then + for k2, v2 in pairs(v) do + if (("function" == type(v2)) and (k ~= "_G")) then + out[(k .. "." .. k2)] = {["function?"] = true, ["global?"] = true} + end + end + out[k] = {["global?"] = true} + end + end + return out +end +local mod = {list = utils.list, ["list?"] = utils["list?"], sym = utils.sym, ["sym?"] = utils["sym?"], sequence = utils.sequence, ["sequence?"] = utils["sequence?"], comment = utils.comment, ["comment?"] = utils["comment?"], varg = utils.varg, path = utils.path, ["macro-path"] = utils["macro-path"], ["sym-char?"] = parser["sym-char?"], parser = parser.parser, granulate = parser.granulate, ["string-stream"] = parser["string-stream"], compile = compiler.compile, ["compile-string"] = compiler["compile-string"], ["compile-stream"] = compiler["compile-stream"], compile1 = compiler.compile1, traceback = compiler.traceback, mangle = compiler["global-mangling"], unmangle = compiler["global-unmangling"], metadata = compiler.metadata, scope = compiler["make-scope"], gensym = compiler.gensym, ["load-code"] = specials["load-code"], ["macro-loaded"] = specials["macro-loaded"], ["macro-searchers"] = specials["macro-searchers"], ["search-module"] = specials["search-module"], ["make-searcher"] = specials["make-searcher"], makeSearcher = specials["make-searcher"], searcher = specials["make-searcher"](), doc = specials.doc, view = view, eval = eval, dofile = dofile_2a, version = "1.0.0-dev", repl = repl, syntax = syntax, loadCode = specials["load-code"], make_searcher = specials["make-searcher"], searchModule = specials["search-module"], macroLoaded = specials["macro-loaded"], compileStream = compiler["compile-stream"], compileString = compiler["compile-string"], stringStream = parser["string-stream"]} utils["fennel-module"] = mod do local builtin_macros = [===[;; This module contains all the built-in Fennel macros. Unlike all the other @@ -3771,12 +4204,18 @@ do (-?>> ,el ,(unpack els)) ,tmp))))) - (fn ?dot [tbl k ...] + (fn ?dot [tbl ...] "Nil-safe table look up. Same as . (dot), except will short-circuit with nil when it encounters a nil value in any of subsequent keys." - (if (= nil k) tbl `(let [res# (. ,tbl ,k)] - (and res# (?. res# ,...))))) + (let [head (gensym :t) + lookups `(do (var ,head ,tbl) ,head)] + (each [_ k (ipairs [...])] + ;; Kinda gnarly to reassign in place like this, but it emits the best lua. + ;; With this impl, it emits a flat, concise, and readable set of if blocks. + (table.insert lookups (# lookups) `(if (not= nil ,head) + (set ,head (. ,head ,k))))) + lookups)) (fn doto* [val ...] "Evaluates val and splices it into the first argument of subsequent forms." @@ -3811,7 +4250,16 @@ do (table.insert closer 4 `(: ,(. closable-bindings i) :close))) `(let ,closable-bindings ,closer - (close-handlers# (xpcall ,bodyfn ,traceback))))) + (close-handlers# (_G.xpcall ,bodyfn ,traceback))))) + + (fn into-val [iter-tbl] + (var into nil) + (for [i (length iter-tbl) 2 -1] + (if (= :into (. iter-tbl i)) + (do (set into (table.remove iter-tbl (+ i 1))) + (table.remove iter-tbl i)))) + (assert (or (not into) (table? into)) "expected table in :into clause") + (or into [])) (fn collect* [iter-tbl key-value-expr ...] "Returns a table made by running an iterator and evaluating an expression @@ -3823,13 +4271,16 @@ do (collect [k v (pairs {:apple \"red\" :orange \"orange\"})] (values v k)) returns - {:red \"apple\" :orange \"orange\"}" + {:red \"apple\" :orange \"orange\"} + + Supports an :into clause after the iterator to put results in an existing table. + Supports early termination with an :until clause." (assert (and (sequence? iter-tbl) (>= (length iter-tbl) 2)) "expected iterator binding table") (assert (not= nil key-value-expr) "expected key-value expression") (assert (= nil ...) "expected exactly one body expression. Wrap multiple expressions with do") - `(let [tbl# {}] + `(let [tbl# ,(into-val iter-tbl)] (each ,iter-tbl (match ,key-value-expr (k# v#) (tset tbl# k# v#))) @@ -3843,24 +4294,68 @@ do For example, (icollect [_ v (ipairs [1 2 3 4 5])] (when (> v 2) (* v v))) returns - [9 16 25]" + [9 16 25] + + Supports an :into clause after the iterator to put results in an existing table. + Supports early termination with an :until clause." (assert (and (sequence? iter-tbl) (>= (length iter-tbl) 2)) "expected iterator binding table") (assert (not= nil value-expr) "expected table value expression") (assert (= nil ...) "expected exactly one body expression. Wrap multiple expressions with do") - `(let [tbl# []] + `(let [tbl# ,(into-val iter-tbl)] (each ,iter-tbl (tset tbl# (+ (length tbl#) 1) ,value-expr)) tbl#)) + (fn accumulate* [iter-tbl accum-expr ...] + "Accumulation macro. + It takes a binding table and an expression as its arguments. + In the binding table, the first symbol is bound to the second value, being an + initial accumulator variable. The rest are an iterator binding table in the + format `each` takes. + It runs through the iterator in each step of which the given expression is + evaluated, and its returned value updates the accumulator variable. + It eventually returns the final value of the accumulator variable. + + For example, + (accumulate [total 0 + _ n (pairs {:apple 2 :orange 3})] + (+ total n)) + returns + 5" + (assert (and (sequence? iter-tbl) (>= (length iter-tbl) 4)) + "expected initial value and iterator binding table") + (assert (not= nil accum-expr) "expected accumulating expression") + (assert (= nil ...) + "expected exactly one body expression. Wrap multiple expressions with do") + (let [accum-var (table.remove iter-tbl 1) + accum-init (table.remove iter-tbl 1)] + `(do (var ,accum-var ,accum-init) + (each ,iter-tbl + (set ,accum-var ,accum-expr)) + ,accum-var))) + (fn partial* [f ...] "Returns a function with all arguments partially applied to f." (assert f "expected a function to partially apply") - (let [body (list f ...)] - (table.insert body _VARARG) - `(fn [,_VARARG] - ,body))) + (let [bindings [] + args []] + (each [_ arg (ipairs [...])] + (if (or (= :number (type arg)) + (= :string (type arg)) + (= :boolean (type arg)) + (= `nil arg)) + (table.insert args arg) + (let [name (gensym)] + (table.insert bindings name) + (table.insert bindings arg) + (table.insert args name)))) + (let [body (list f (unpack args))] + (table.insert body _VARARG) + `(let ,bindings + (fn [,_VARARG] + ,body))))) (fn pick-args* [n f] "Creates a function of arity n that applies its arguments to f. @@ -3869,6 +4364,9 @@ do (pick-args 2 func) expands to (fn [_0_ _1_] (func _0_ _1_))" + (if (and _G.io _G.io.stderr) + (_G.io.stderr:write + "-- WARNING: pick-args is deprecated and will be removed in the future.\n")) (assert (and (= (type n) :number) (= n (math.floor n)) (>= n 0)) (.. "Expected n to be an integer literal >= 0, got " (tostring n))) (let [bindings []] @@ -3896,9 +4394,9 @@ do (values ,(unpack let-syms)))))) (fn lambda* [...] - "Function literal with arity checking. - Will throw an exception if a declared argument is passed in as nil, unless - that argument name begins with ?." + "Function literal with nil-checked arguments. + Like `fn`, but will throw an exception if a declared argument is passed in as + nil, unless that argument's name begins with a question mark." (let [args [...] has-internal-name? (sym? (. args 1)) arglist (if has-internal-name? (. args 2) (. args 1)) @@ -3914,13 +4412,13 @@ do (check! a)) (let [as (tostring a)] (and (not (as:match "^?")) (not= as "&") (not= as "_") - (not= as "..."))) + (not= as "...") (not= as "&as"))) (table.insert args arity-check-position - `(assert (not= nil ,a) - (string.format "Missing argument %s on %s:%s" - ,(tostring a) - ,(or a.filename :unknown) - ,(or a.line "?")))))) + `(_G.assert (not= nil ,a) + ,(: "Missing argument %s on %s:%s" :format + (tostring a) + (or a.filename :unknown) + (or a.line "?")))))) (assert (= :table (type arglist)) "expected arg list") (each [_ a (ipairs arglist)] @@ -3959,10 +4457,7 @@ do (_SPECIALS.require-macros `(require-macros ,modname) subscope {} ast) (if (sym? binding) ;; bind whole table of macros to table bound to symbol - (do - (tset scope.macros (. binding 1) {}) - (each [k v (pairs subscope.macros)] - (tset (. scope.macros (. binding 1)) k v))) + (tset scope.macros (. binding 1) (. macro-loaded modname)) ;; 1-level table destructuring for importing individual macros (table? binding) (each [macro-name [import-key] (pairs binding)] @@ -3986,7 +4481,7 @@ do (values condition bindings))) (fn match-table [val pattern unifications match-pattern] - (let [condition `(and (= (type ,val) :table)) + (let [condition `(and (= (_G.type ,val) :table)) bindings []] (each [k pat (pairs pattern)] (if (= pat `&) @@ -4043,11 +4538,10 @@ do (and (list? pattern) (= (. pattern 2) `?)) (let [(pcondition bindings) (match-pattern vals (. pattern 1) unifications) - condition `(and ,pcondition)] - (for [i 3 (length pattern)] ; splice in guard clauses - (table.insert condition (. pattern i))) - (values `(let ,bindings - ,condition) bindings)) + condition `(and ,(unpack pattern 3))] + (values `(and ,pcondition + (let ,bindings + ,condition)) bindings)) ;; multi-valued patterns (represented as lists) (list? pattern) (match-values vals pattern unifications match-pattern) @@ -4075,10 +4569,13 @@ do "How many multi-valued clauses are there? return a list of that many gensyms." (let [syms (list (gensym))] (for [i 1 (length clauses) 2] - (if (list? (. clauses i)) - (each [valnum (ipairs (. clauses i))] - (if (not (. syms valnum)) - (tset syms valnum (gensym)))))) + (let [clause (if (and (list? (. clauses i)) (= `? (. clauses i 2))) + (. clauses i 1) + (. clauses i))] + (if (list? clause) + (each [valnum (ipairs clause)] + (if (not (. syms valnum)) + (tset syms valnum (gensym))))))) syms)) (fn match* [val ...] @@ -4087,6 +4584,8 @@ do ;; which simply generates old syntax and feeds it to `match*'. (let [clauses [...] vals (match-val-syms clauses)] + (assert (= 0 (math.fmod (length clauses) 2)) + "expected even number of pattern/body pairs") ;; protect against multiple evaluation of the value, bind against as ;; many values as we ever match against in the clauses. (list `let [vals val] (match-condition vals clauses)))) @@ -4168,6 +4667,7 @@ do :with-open with-open* :collect collect* :icollect icollect* + :accumulate accumulate* :partial partial* :lambda lambda* :pick-args pick-args* @@ -4178,20 +4678,20 @@ do :match match-where} ]===] local module_name = "fennel.macros" - local _ = nil - local function _0_() + local _ + local function _567_() return mod end - package.preload[module_name] = _0_ + package.preload[module_name] = _567_ _ = nil - local env = nil + local env do - local _1_0 = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}) - _1_0["utils"] = utils - _1_0["fennel"] = mod - env = _1_0 + local _568_ = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}) + do end (_568_)["utils"] = utils + _568_["fennel"] = mod + env = _568_ end - local built_ins = eval(builtin_macros, {allowedGlobals = false, env = env, filename = "src/fennel/macros.fnl", moduleName = module_name, scope = compiler.scopes.compiler, useMetadata = true}) + local built_ins = eval(builtin_macros, {env = env, scope = compiler.scopes.compiler, allowedGlobals = false, useMetadata = true, filename = "src/fennel/macros.fnl", moduleName = module_name}) for k, v in pairs(built_ins) do compiler.scopes.global.macros[k] = v end