Skip to content

Commit

Permalink
Fix up the scoping for the @mock macro.
Browse files Browse the repository at this point in the history
Previously, the macro required `Mocking` to be visible in the caller's context:
It was invoking `Mocking.activated()`, for exmaple.  Now it invokes
`$activated()`, which makes sure that the code uses the right version of
`activated`.  Similarly for `get_alternate` and `Patch`.

Also, the macro was doing some unceessary `gensym` calls, which macro hygene can
take care of automatically.
  • Loading branch information
kuszmaul committed Apr 26, 2024
1 parent 98de500 commit cf9ca82
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 11 deletions.
17 changes: 7 additions & 10 deletions src/mock.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,21 @@ macro mock(expr)
expr.head == :call || error("expression is not a function call")

target = expr.args[1]
args = filter(!Mocking.iskwarg, expr.args[2:end])
args = filter(!iskwarg, expr.args[2:end])
kwargs = extract_kwargs(expr)

args_var = gensym("args")
alternate_var = gensym("alt")

# Due to how world-age works (see Julia issue #265 and PR #17057) when
# `Mocking.activated` is overwritten then all dependent functions will be recompiled.
# When `Mocking.activated() == false` then Julia will optimize the
# code below to have zero-overhead by only executing the original expression.
result = quote
if Mocking.activated()
local $args_var = tuple($(args...))
local $alternate_var = Mocking.get_alternate($target, $args_var...)
if $alternate_var !== nothing
Base.invokelatest($alternate_var, $args_var...; $(kwargs...))
if $activated()
args_var = tuple($(args...))
alternate_var = $get_alternate($target, args_var...)
if alternate_var !== nothing
Base.invokelatest(alternate_var, args_var...; $(kwargs...))
else
$target($args_var...; $(kwargs...))
$target(args_var...; $(kwargs...))
end
else
$target($(args...); $(kwargs...))
Expand Down
2 changes: 1 addition & 1 deletion src/patch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ macro patch(expr::Expr)

# We need to evaluate the alternate function in the context of the `@patch` macro in
# order to support closures.
return esc(:(Mocking.Patch($target, $alternate)))
return esc(:($Patch($target, $alternate)))
end

struct PatchEnv
Expand Down

0 comments on commit cf9ca82

Please sign in to comment.