mediawiki-extensions-Scribunto/engines/LuaCommon/lualib/package.lua

162 lines
4.4 KiB
Lua
Raw Normal View History

Added more Lua environment features Package library: * Added a simulation of the Lua 5.1 package library. * Removed mw.import(), replaced it with a package loader. Packages can be retrieved from the wiki, using require('Module:Foo'), or from files distributed with Scribunto, using require('foo'). The "Module:" prefix allows for source compatibility with existing Lua code. * Added a couple of libraries from LuaForge: luabit and stringtools. * Made fetchModuleFromParser() return null on error instead of throwing an exception, to more easily support the desired behaviour of the package loader, which needs to return null on error. * Renamed mw.setupEnvironment() to mw.setup() since it is setting up things other than the environment now. * In MWServer:handleRegisterLibrary(), remove the feature which interprets dots in library names, since LuaSandbox doesn't support this. Improved module isolation and related refactoring: * Expose restricted versions of getfenv() and setfenv() to user Lua code. Requires luasandbox r114952. * Don't cache the export list returned by module execution for later function calls. This breaks isolation of #invoke calls, since the local variables are persistent. * Removed ScribuntoFunctionBase and its children, since it doesn't really have a purpose if it can't cache anything. Instead, invoke functions using a module method called invoke(). * Removed Module::initialize(), replaced it with a validate() function. This is a more elegant interface and works better with the new module caching scheme. * Use a Status object for the return value of Engine::validate() instead of an array. Use the formatting facilities of the Status class. Other: * Removed "too many returns" error, doesn't fit in with Lua conventions. * Use the standalone engine by default, so that the extension will work without configuration for more people. * Added an accessor for $engine->interpreter * Fix mw.clone() to correctly clone metatables * If the standalone interpreter exits due to an error, there are some contexts where the initial error will be caught and ignored, and the user will see the error from checkValid() instead. In this case, rethrow the original error for a more informative message. * Load mw.lua into the initial standalone environment, to reduce code duplication between mw.lua and MWServer.lua. * Fixed a bug in Scribunto_LuaStandaloneInterpreter::handleCall() for functions that return no results. * Fixed a bug in encodeLuaVar() for strings with "\r". Added test case. * In MWServer.lua, don't call error() for internal errors, instead just print the error and exit. This avoids a protocol violation when an error is encountered from within handleCall(). * Added lots of documentation. Lua doc comments are in LuaDoc format. Change-Id: Ie2fd572c362bedf02f45d3fa5352a5280e034740
2012-04-18 03:46:18 +00:00
--[[
-- A package library similar to the one that comes with Lua 5.1, but without
-- the local filesystem access. Based on Compat-5.1 which comes with the
-- following license notice:
--
-- Copyright © 2004-2006 The Kepler Project.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-- the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--]]
local assert, error, getfenv, ipairs, pairs, setfenv, setmetatable, type = assert, error, getfenv, ipairs, pairs, setfenv, setmetatable, type
local find, format, gfind, gsub, sub = string.find, string.format, string.gfind, string.gsub, string.sub
--
-- avoid overwriting the package table if it's already there
--
package = package or {}
local _PACKAGE = package
package.loaded = package.loaded or {}
local _LOADED = package.loaded
--
-- avoid overwriting the package.preload table if it's already there
--
package.preload = package.preload or {}
local _PRELOAD = package.preload
--
-- check whether library is already loaded
--
local function loader_preload (name)
assert (type(name) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
assert (type(_PRELOAD) == "table", "`package.preload' must be a table")
return _PRELOAD[name]
end
-- create `loaders' table
package.loaders = package.loaders or { loader_preload }
local _LOADERS = package.loaders
--
-- iterate over available loaders
--
local function load (name, loaders)
-- iterate over available loaders
assert (type (loaders) == "table", "`package.loaders' must be a table")
for i, loader in ipairs (loaders) do
local f = loader (name)
if f then
return f
end
end
error (format ("module `%s' not found", name))
end
-- sentinel
local sentinel = function () end
--
-- require
--
function _G.require (modname)
assert (type(modname) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
local p = _LOADED[modname]
if p then -- is it there?
if p == sentinel then
error (format ("loop or previous error loading module '%s'", modname))
end
return p -- package is already loaded
end
local init = load (modname, _LOADERS)
_LOADED[modname] = sentinel
local actual_arg = _G.arg
_G.arg = { modname }
local res = init (modname)
if res then
_LOADED[modname] = res
end
_G.arg = actual_arg
if _LOADED[modname] == sentinel then
_LOADED[modname] = true
end
return _LOADED[modname]
end
-- findtable
local function findtable (t, f)
assert (type(f)=="string", "not a valid field name ("..tostring(f)..")")
local ff = f.."."
local ok, e, w = find (ff, '(.-)%.', 1)
while ok do
local nt = rawget (t, w)
if not nt then
nt = {}
t[w] = nt
elseif type(t) ~= "table" then
return sub (f, e+1)
end
t = nt
ok, e, w = find (ff, '(.-)%.', e+1)
end
return t
end
--
-- package.seeall function
--
function _PACKAGE.seeall (module)
local t = type(module)
assert (t == "table", "bad argument #1 to package.seeall (table expected, got "..t..")")
local meta = getmetatable (module)
if not meta then
meta = {}
setmetatable (module, meta)
end
meta.__index = _G
end
--
-- module function
--
function _G.module (modname, ...)
local ns = _LOADED[modname]
if type(ns) ~= "table" then
ns = findtable (_G, modname)
if not ns then
error (string.format ("name conflict for module '%s'", modname))
end
_LOADED[modname] = ns
end
if not ns._NAME then
ns._NAME = modname
ns._M = ns
ns._PACKAGE = gsub (modname, "[^.]*$", "")
end
setfenv (2, ns)
for i, f in ipairs (...) do
f (ns)
end
end