Hello,
I’m announcing AutoForward.jl MethodForwarding.jl(still in the registering 3-day waiting period), which should make composing objects much more hasslefree. It’s a bit what I’ve always wanted @forward
from Lazy.jl to be.
The package exports a single @forward
macro. The behaviour is probably best explained with an example (for details check the README in the repo):
struct A
x::Int
end
value(a::A) = a.x
doubleA(a::A) = 2 * value(a)
@forward A struct NamedA
a::A
name::String
end
name(na::NamedA) = na.name
a = A(10)
named_A = NamedA(a, "name")
@assert value(named_A) == 10
@assert doubleA(named_A) == 20
We can also make a wrapper type splat into function arguments:
function1(a::Int, b::Int) = a + b
function2(a::Int, b::Int, c::Int) = a + b + c
@forward {Int, Int},
struct Point2
x::Int
y::Int
end
p = Point2(1,1)
@assert function1(p) == 2
@assert function2(p, 1) == function2(1, p) == 3
By default only the functions defined in the current module are forwarded, but it is possible to specify a list of modules and/or functions for which to forward their methods:
module MainModule
module InnerModule
export innerfunc
innerfunc(a::Int, b::Int) = a + b + 100
anotherfunc(a::Int, b::Int) = a + b + 200
end
using .InnerModule
function1(a::Int, b::Int) = a + b
function2(a::Int, b::Int, c::Int) = a + b + c
@forward {Int, Int},
struct Point2
x::Int
y::Int
end function1
# Generates:
# function1(p)
@forward {Int, Int},
struct Point2
x::Int
y::Int
end InnerModule # forwards only the public/exported methods of InnerModule
# Generates:
# innerfunc(p)
@forward {Int, Int},
struct Point2
x::Int
y::Int
end InnerModule.anotherfunc # forwards a specific method of a specific module
# Generates:
# anotherfunc(p)
@forward {Int, Int},
struct Point2
x::Int
y::Int
end (InnerModule, function2) # exports all public functions of InnerModule, and function2
# Generates:
# function2(a, p)
# function2(p, c)
# innerfunc(p)
end # module
This package has not been used in the wild very much and it’s still highly experimental, so don’t expect flawless outputs.
I am also not married to the name, if the name @forward
or AutoForward
MethodForwarding
rubs you the wrong way i’m open to suggestions (while still in the package registry waiting period if possible)!