Skip to content

Commit

Permalink
support functors in @Accessor
Browse files Browse the repository at this point in the history
  • Loading branch information
aplavin committed Feb 17, 2023
1 parent 5f3b8e5 commit 45edc3d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/sugar.jl
Original file line number Diff line number Diff line change
Expand Up @@ -417,19 +417,23 @@ macro accessor(ex)
arg = only(def[:args])
argname = splitarg(arg)[1]
body_optic = MacroTools.replace(def[:body], argname, :_)
ftype = :(
if $fname isa Function
typeof($fname)
elseif $fname isa Type
Type{$fname}
else
# is it possible at all?
error("Unsupported accessor $(fname)::$(typeof($fname))")
end
)
farg = if @capture fname name_::T__
fname
else
ftype = :(
::if $fname isa Function
typeof($fname)
elseif $fname isa Type
Type{$fname}
else
# is it possible at all?
error("Unsupported accessor $(fname)::$(typeof($fname))")
end
)
end
quote
Base.@__doc__ $ex
$Accessors.set($arg, ::$ftype, v) = $set($argname, $Accessors.@optic($body_optic), v)
$Accessors.set($arg, $farg, v) = $set($argname, $Accessors.@optic($body_optic), v)
end |> esc
end

Expand Down
3 changes: 3 additions & 0 deletions test/test_core.jl
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,7 @@ end
@accessor Base.:(+)(s::MyStruct) = 5 - s.x.a
@accessor Base.Int(s::MyStruct) = s.x[1]
@accessor Base.Float64(s::MyStruct) = s.x[2]
@accessor (t::MyStruct)(s::MyStruct) = s.x + t.x

@testset "@accessor" begin
s = MyStruct((a=123,))
Expand All @@ -586,6 +587,8 @@ end
s = MyStruct((1, 2.0))
Accessors.test_getset_laws(Int, s, 1, 2)
Accessors.test_getset_laws(Float64, s, 1., 2.)

Accessors.test_getset_laws(MyStruct(2), MyStruct(1), 1, 2)
end

end

2 comments on commit 45edc3d

@aplavin
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registration pull request created: JuliaRegistries/General/77876

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if the Julia TagBot GitHub Action is installed, or can be done manually through the github interface, or via:

git tag -a v0.1.27 -m "<description of version>" 45edc3d16ac42bbe9eec1c6cd7114242ac32c41c
git push origin v0.1.27

Please sign in to comment.