Debian Codegraph @

test/lua/compat_env.lua

raw
1 --[[
2
3 compat_env v$(_VERSION) - Lua 5.1/5.2 environment compatibility functions
4
5 SYNOPSIS
6
7 -- Get load/loadfile compatibility functions only if using 5.1.
8 local CL = pcall(load, '') and _G or require 'compat_env'
9 local load = CL.load
10 local loadfile = CL.loadfile
11
12 -- The following now works in both Lua 5.1 and 5.2:
13 assert(load('return 2*pi', nil, 't', {pi=math.pi}))()
14 assert(loadfile('ex.lua', 't', {print=print}))()
15
16 -- Get getfenv/setfenv compatibility functions only if using 5.2.
17 local getfenv = _G.getfenv or require 'compat_env'.getfenv
18 local setfenv = _G.setfenv or require 'compat_env'.setfenv
19 local function f() return x end
20 setfenv(f, {x=2})
21 print(x, getfenv(f).x) --> 2, 2
22
23 DESCRIPTION
24
25 This module provides Lua 5.1/5.2 environment related compatibility functions.
26 This includes implementations of Lua 5.2 style `load` and `loadfile`
27 for use in Lua 5.1. It also includes Lua 5.1 style `getfenv` and `setfenv`
28 for use in Lua 5.2.
29
30 API
31
32 local CL = require 'compat_env'
33
34 CL.load (ld [, source [, mode [, env] ] ]) --> f [, err]
35
36 This behaves the same as the Lua 5.2 `load` in both
37 Lua 5.1 and 5.2.
38 http://www.lua.org/manual/5.2/manual.html#pdf-load
39
40 CL.loadfile ([filename [, mode [, env] ] ]) --> f [, err]
41
42 This behaves the same as the Lua 5.2 `loadfile` in both
43 Lua 5.1 and 5.2.
44 http://www.lua.org/manual/5.2/manual.html#pdf-loadfile
45
46 CL.getfenv ([f]) --> t
47
48 This is identical to the Lua 5.1 `getfenv` in Lua 5.1.
49 This behaves similar to the Lua 5.1 `getfenv` in Lua 5.2.
50 When a global environment is to be returned, or when `f` is a
51 C function, this returns `_G` since Lua 5.2 doesn't have
52 (thread) global and C function environments. This will also
53 return `_G` if the Lua function `f` lacks an `_ENV`
54 upvalue, but it will raise an error if uncertain due to lack of
55 debug info. It is not normally considered good design to use
56 this function; when possible, use `load` or `loadfile` instead.
57 http://www.lua.org/manual/5.1/manual.html#pdf-getfenv
58
59 CL.setfenv (f, t)
60
61 This is identical to the Lua 5.1 `setfenv` in Lua 5.1.
62 This behaves similar to the Lua 5.1 `setfenv` in Lua 5.2.
63 This will do nothing if `f` is a Lua function that
64 lacks an `_ENV` upvalue, but it will raise an error if uncertain
65 due to lack of debug info. See also Design Notes below.
66 It is not normally considered good design to use
67 this function; when possible, use `load` or `loadfile` instead.
68 http://www.lua.org/manual/5.1/manual.html#pdf-setfenv
69
70 DESIGN NOTES
71
72 This module intends to provide robust and fairly complete reimplementations
73 of the environment related Lua 5.1 and Lua 5.2 functions.
74 No effort is made, however, to simulate rare or difficult to simulate features,
75 such as thread environments, although this is liable to change in the future.
76 Such 5.1 capabilities are discouraged and ideally
77 removed from 5.1 code, thereby allowing your code to work in both 5.1 and 5.2.
78
79 In Lua 5.2, a `setfenv(f, {})`, where `f` lacks any upvalues, will be silently
80 ignored since there is no `_ENV` in this function to write to, and the
81 environment will have no effect inside the function anyway. However,
82 this does mean that `getfenv(setfenv(f, t))` does not necessarily equal `t`,
83 which is incompatible with 5.1 code (a possible workaround would be [1]).
84 If `setfenv(f, {})` has an upvalue but no debug info, then this will raise
85 an error to prevent inadvertently executing potentially untrusted code in the
86 global environment.
87
88 It is not normally considered good design to use `setfenv` and `getfenv`
89 (one reason they were removed in 5.2). When possible, consider replacing
90 these with `load` or `loadfile`, which are more restrictive and have native
91 implementations in 5.2.
92
93 This module might be merged into a more general Lua 5.1/5.2 compatibility
94 library (e.g. a full reimplementation of Lua 5.2 `_G`). However,
95 `load/loadfile/getfenv/setfenv` perhaps are among the more cumbersome
96 functions not to have.
97
98 INSTALLATION
99
100 Download compat_env.lua:
101
102 wget https://raw.github.com/gist/1654007/compat_env.lua
103
104 Copy compat_env.lua into your LUA_PATH.
105
106 Alternately, unpack, test, and install into LuaRocks:
107
108 wget https://raw.github.com/gist/1422205/sourceunpack.lua
109 lua sourceunpack.lua compat_env.lua
110 (cd out && luarocks make)
111
112 Related work
113
114 http://lua-users.org/wiki/LuaVersionCompatibility
115 https://github.com/stevedonovan/Penlight/blob/master/lua/pl/utils.lua
116 - penlight implementations of getfenv/setfenv
117 http://lua-users.org/lists/lua-l/2010-06/msg00313.html
118 - initial getfenv/setfenv implementation
119
120 References
121
122 [1] http://lua-users.org/lists/lua-l/2010-06/msg00315.html
123
124 Copyright
125
126 (c) 2012 David Manura. Licensed under the same terms as Lua 5.1/5.2 (MIT license).
127
128 Permission is hereby granted, free of charge, to any person obtaining a copy
129 of this software and associated documentation files (the "Software"), to deal
130 in the Software without restriction, including without limitation the rights
131 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
132 copies of the Software, and to permit persons to whom the Software is
133 furnished to do so, subject to the following conditions:
134
135 The above copyright notice and this permission notice shall be included in
136 all copies or substantial portions of the Software.
137
138 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
139 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
140 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
141 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
142 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
143 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
144 THE SOFTWARE.
145
146 --]]---------------------------------------------------------------------
147
148 local M = {_TYPE='module', _NAME='compat_env', _VERSION='0.2.20120124'}
149
150 local function check_chunk_type(s, mode)
151 local nmode = mode or 'bt'
152 local is_binary = s and #s > 0 and s:byte(1) == 27
153 if is_binary and not nmode:match'b' then
154 return nil, ("attempt to load a binary chunk (mode is '%s')"):format(mode)
155 elseif not is_binary and not nmode:match't' then
156 return nil, ("attempt to load a text chunk (mode is '%s')"):format(mode)
157 end
158 return true
159 end
160
161 local IS_52_LOAD = pcall(load, '')
162 if IS_52_LOAD then
163 M.load = _G.load
164 M.loadfile = _G.loadfile
165 else
166 -- 5.2 style `load` implemented in 5.1
167 function M.load(ld, source, mode, env)
168 local f
169 if type(ld) == 'string' then
170 local s = ld
171 local ok, err = check_chunk_type(s, mode); if not ok then return ok, err end
172 local err; f, err = loadstring(s, source); if not f then return f, err end
173 elseif type(ld) == 'function' then
174 local ld2 = ld
175 if (mode or 'bt') ~= 'bt' then
176 local first = ld()
177 local ok, err = check_chunk_type(first, mode); if not ok then return ok, err end
178 ld2 = function()
179 if first then
180 local chunk=first; first=nil; return chunk
181 else return ld() end
182 end
183 end
184 local err; f, err = load(ld2, source); if not f then return f, err end
185 else
186 error(("bad argument #1 to 'load' (function expected, got %s)"):format(type(ld)), 2)
187 end
188 if env then setfenv(f, env) end
189 return f
190 end
191
192 -- 5.2 style `loadfile` implemented in 5.1
193 function M.loadfile(filename, mode, env)
194 if (mode or 'bt') ~= 'bt' then
195 local ioerr
196 local fh, err = io.open(filename, 'rb'); if not fh then return fh, err end
197 local function ld() local chunk; chunk,ioerr = fh:read(4096); return chunk end
198 local f, err = M.load(ld, filename and '@'..filename, mode, env)
199 fh:close()
200 if not f then return f, err end
201 if ioerr then return nil, ioerr end
202 return f
203 else
204 local f, err = loadfile(filename); if not f then return f, err end
205 if env then setfenv(f, env) end
206 return f
207 end
208 end
209 end
210
211 if _G.setfenv then -- Lua 5.1
212 M.setfenv = _G.setfenv
213 M.getfenv = _G.getfenv
214 else -- >= Lua 5.2
215 -- helper function for `getfenv`/`setfenv`
216 local function envlookup(f)
217 local name, val
218 local up = 0
219 local unknown
220 repeat
221 up=up+1; name, val = debug.getupvalue(f, up)
222 if name == '' then unknown = true end
223 until name == '_ENV' or name == nil
224 if name ~= '_ENV' then
225 up = nil
226 if unknown then error("upvalues not readable in Lua 5.2 when debug info missing", 3) end
227 end
228 return (name == '_ENV') and up, val, unknown
229 end
230
231 -- helper function for `getfenv`/`setfenv`
232 local function envhelper(f, name)
233 if type(f) == 'number' then
234 if f < 0 then
235 error(("bad argument #1 to '%s' (level must be non-negative)"):format(name), 3)
236 elseif f < 1 then
237 error("thread environments unsupported in Lua 5.2", 3) --[*]
238 end
239 f = debug.getinfo(f+2, 'f').func
240 elseif type(f) ~= 'function' then
241 error(("bad argument #1 to '%s' (number expected, got %s)"):format(type(name, f)), 2)
242 end
243 return f
244 end
245 -- [*] might simulate with table keyed by coroutine.running()
246
247 -- 5.1 style `setfenv` implemented in 5.2
248 function M.setfenv(f, t)
249 local f = envhelper(f, 'setfenv')
250 local up, val, unknown = envlookup(f)
251 if up then
252 debug.upvaluejoin(f, up, function() return up end, 1) -- unique upvalue [*]
253 debug.setupvalue(f, up, t)
254 else
255 local what = debug.getinfo(f, 'S').what
256 if what ~= 'Lua' and what ~= 'main' then -- not Lua func
257 error("'setfenv' cannot change environment of given object", 2)
258 end -- else ignore no _ENV upvalue (warning: incompatible with 5.1)
259 end
260 -- added in https://gist.github.com/2255007
261 return f
262 end
263 -- [*] http://lua-users.org/lists/lua-l/2010-06/msg00313.html
264
265 -- 5.1 style `getfenv` implemented in 5.2
266 function M.getfenv(f)
267 if f == 0 or f == nil then return _G end -- simulated behavior
268 local f = envhelper(f, 'setfenv')
269 local up, val = envlookup(f)
270 if not up then return _G end -- simulated behavior [**]
271 return val
272 end
273 -- [**] possible reasons: no _ENV upvalue, C function
274 end
275
276
277 return M
278
279 --[[ FILE rockspec.in
280
281 package = 'compat_env'
282 version = '$(_VERSION)-1'
283 source = {
284 url = 'https://raw.github.com/gist/1654007/$(GITID)/compat_env.lua',
285 --url = 'https://raw.github.com/gist/1654007/compat_env.lua', -- latest raw
286 --url = 'https://gist.github.com/gists/1654007/download',
287 md5 = '$(MD5)'
288 }
289 description = {
290 summary = 'Lua 5.1/5.2 environment compatibility functions',
291 detailed = [=[
292 Provides Lua 5.1/5.2 environment related compatibility functions.
293 This includes implementations of Lua 5.2 style `load` and `loadfile`
294 for use in Lua 5.1. It also includes Lua 5.1 style `getfenv` and `setfenv`
295 for use in Lua 5.2.
296 ]=],
297 license = 'MIT/X11',
298 homepage = 'https://gist.github.com/1654007',
299 maintainer = 'David Manura'
300 }
301 dependencies = {} -- Lua 5.1 or 5.2
302 build = {
303 type = 'builtin',
304 modules = {
305 ['compat_env'] = 'compat_env.lua'
306 }
307 }
308
309 --]]---------------------------------------------------------------------
310
311 --[[ FILE test.lua
312
313 -- test.lua - test suite for compat_env module.
314
315 local CL = require 'compat_env'
316 local load = CL.load
317 local loadfile = CL.loadfile
318 local setfenv = CL.setfenv
319 local getfenv = CL.getfenv
320
321 local function checkeq(a, b, e)
322 if a ~= b then error(
323 'not equal ['..tostring(a)..'] ['..tostring(b)..'] ['..tostring(e)..']')
324 end
325 end
326 local function checkerr(pat, ok, err)
327 assert(not ok, 'checkerr')
328 assert(type(err) == 'string' and err:match(pat), err)
329 end
330
331 -- test `load`
332 checkeq(load('return 2')(), 2)
333 checkerr('expected near', load'return 2 2')
334 checkerr('text chunk', load('return 2', nil, 'b'))
335 checkerr('text chunk', load('', nil, 'b'))
336 checkerr('binary chunk', load('\027', nil, 't'))
337 checkeq(load('return 2*x',nil,'bt',{x=5})(), 10)
338 checkeq(debug.getinfo(load('')).source, '')
339 checkeq(debug.getinfo(load('', 'foo')).source, 'foo')
340
341 -- test `loadfile`
342 local fh = assert(io.open('tmp.lua', 'wb'))
343 fh:write('return (...) or x')
344 fh:close()
345 checkeq(loadfile('tmp.lua')(2), 2)
346 checkeq(loadfile('tmp.lua', 't')(2), 2)
347 checkerr('text chunk', loadfile('tmp.lua', 'b'))
348 checkeq(loadfile('tmp.lua', nil, {x=3})(), 3)
349 checkeq(debug.getinfo(loadfile('tmp.lua')).source, '@tmp.lua')
350 checkeq(debug.getinfo(loadfile('tmp.lua', 't', {})).source, '@tmp.lua')
351 os.remove'tmp.lua'
352
353 -- test `setfenv`/`getfenv`
354 x = 5
355 local a,b=true; local function f(c) if a then return x,b,c end end
356 setfenv(f, {x=3})
357 checkeq(f(), 3)
358 checkeq(getfenv(f).x, 3)
359 checkerr('cannot change', pcall(setfenv, string.len, {})) -- C function
360 checkeq(getfenv(string.len), _G) -- C function
361 local function g()
362 setfenv(1, {x=4})
363 checkeq(getfenv(1).x, 4)
364 return x
365 end
366 checkeq(g(), 4) -- numeric level
367 if _G._VERSION ~= 'Lua 5.1' then
368 checkerr('unsupported', pcall(setfenv, 0, {}))
369 end
370 checkeq(getfenv(0), _G)
371 checkeq(getfenv(), _G) -- no arg
372 checkeq(x, 5) -- main unaltered
373 setfenv(function()end, {}) -- no upvalues, ignore
374 checkeq(getfenv(function()end), _G) -- no upvaluse
375 if _G._VERSION ~= 'Lua 5.1' then
376 checkeq(getfenv(setfenv(function()end, {})), _G) -- warning: incompatible with 5.1
377 end
378 x = nil
379
380 print 'OK'
381
382 --]]---------------------------------------------------------------------
383
384 --[[ FILE CHANGES.txt
385 0.2.20120124
386 Renamed module to compat_env (from compat_load)
387 Add getfenv/setfenv functions
388
389 0.1.20120121
390 Initial public release
391 --]]