Skip to content

Commit ee0dcb7

Browse files
Add setfield frule
formatting Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 32bf53d commit ee0dcb7

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ SuiteSparse = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"
2020

2121
[compat]
2222
Adapt = "3.4.0, 4"
23-
ChainRulesCore = "1.15.3"
23+
ChainRulesCore = "1.20"
2424
ChainRulesTestUtils = "1.5"
2525
Compat = "3.46, 4.2"
2626
Distributed = "1"

src/rulesets/Base/base.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ function rrule(::typeof(one), x)
2626
return (one(x), one_pullback)
2727
end
2828

29+
30+
function ChainRulesCore.frule((_, ȯbj, _, ẋ), ::typeof(setfield!), obj, field, x)
31+
ȯbj::MutableTangent
32+
y = setfield!(obj, field, x)
33+
= setproperty!(ȯbj, field, ẋ)
34+
return y, ẏ
35+
end
36+
2937
# `adjoint`
3038

3139
frule((_, Δz), ::typeof(adjoint), z::Number) = (z', Δz')

test/rulesets/Base/base.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,15 @@
1818
end
1919
end
2020
end
21+
22+
@testset "setfield!" begin
23+
mutable struct MDemo
24+
x::Float64
25+
end
26+
27+
test_frule(setfield!, MDemo(3.5) MutableTangent{MDemo}(; x=2.0), :x, 5.0)
28+
test_frule(setfield!, MDemo(3.5) MutableTangent{MDemo}(; x=2.0), 1, 5.0)
29+
end
2130

2231
@testset "Trig" begin
2332
@testset "Basics" for x = (Float64(π)-0.01, Complex(π, π/2))

0 commit comments

Comments
 (0)