|
| 1 | +local isJit = (tostring(assert):match('builtin') ~= nil) |
| 2 | + |
| 3 | +if not isJit then |
| 4 | + return function() end |
| 5 | +end |
| 6 | + |
| 7 | +-- pre-load the ffi module, such that it becomes part of the environment |
| 8 | +-- and Busted will not try to GC and reload it. The ffi is not suited |
| 9 | +-- for that and will occasionally segfault if done so. |
| 10 | +local ffi = require "ffi" |
| 11 | + |
| 12 | + |
| 13 | +-- patching assumes; |
| 14 | +-- * first parameter to be a unique key to identify repeated calls |
| 15 | +-- * only a single return value |
| 16 | + |
| 17 | +local function patch_with_return_value(func_name) |
| 18 | + local original = ffi[func_name] |
| 19 | + local original_store = {} |
| 20 | + |
| 21 | + ffi[func_name] = function (primary, ...) |
| 22 | + if original_store[primary] then |
| 23 | + return original_store[primary] |
| 24 | + end |
| 25 | + local success, result, err = pcall(original, primary, ...) |
| 26 | + if not success then |
| 27 | + -- hard error was thrown |
| 28 | + error(result, 2) |
| 29 | + end |
| 30 | + if not result then |
| 31 | + -- soft error was returned |
| 32 | + return result, err |
| 33 | + end |
| 34 | + -- it worked, store and return |
| 35 | + original_store[primary] = result |
| 36 | + return result |
| 37 | + end |
| 38 | +end |
| 39 | + |
| 40 | +local function patch_without_return_value(func_name) |
| 41 | + local original = ffi[func_name] |
| 42 | + local original_store = {} |
| 43 | + |
| 44 | + ffi[func_name] = function (primary, ...) |
| 45 | + if original_store[primary] then |
| 46 | + return |
| 47 | + end |
| 48 | + local success, result = pcall(original, primary, ...) |
| 49 | + if not success then |
| 50 | + -- hard error was thrown |
| 51 | + error(result, 2) |
| 52 | + end |
| 53 | + -- store and return |
| 54 | + original_store[primary] = true |
| 55 | + return result |
| 56 | + end |
| 57 | +end |
| 58 | + |
| 59 | +return function() |
| 60 | + patch_without_return_value("cdef") |
| 61 | + patch_with_return_value("typeof") |
| 62 | + patch_with_return_value("metatype") |
| 63 | + end |
0 commit comments