Skip to content

Commit

Permalink
fix deepcopy for non-trivial circular references (#56990)
Browse files Browse the repository at this point in the history
Resolves #56775 . Credit for this fix rests entirely with bbrehm .

---------

Co-authored-by: Lilith Orion Hafner <[email protected]>
Co-authored-by: Neven Sajko <[email protected]>
  • Loading branch information
3 people authored Jan 9, 2025
1 parent 4250be8 commit 1ebacac
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
7 changes: 5 additions & 2 deletions base/deepcopy.jl
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,14 @@ function _deepcopy_memory_t(@nospecialize(x::Memory), T, stackdict::IdDict)
end
return dest
end
@eval function deepcopy_internal(x::Array{T, N}, stackdict::IdDict) where {T, N}
function deepcopy_internal(x::Array{T, N}, stackdict::IdDict) where {T, N}
if haskey(stackdict, x)
return stackdict[x]::typeof(x)
end
stackdict[x] = $(Expr(:new, :(Array{T, N}), :(deepcopy_internal(x.ref, stackdict)), :(x.size)))
y = stackdict[x] = Array{T, N}(undef, ntuple(Returns(0), Val{N}()))
setfield!(y, :ref, deepcopy_internal(x.ref, stackdict))
setfield!(y, :size, x.size)
y
end
function deepcopy_internal(x::GenericMemoryRef, stackdict::IdDict)
if haskey(stackdict, x)
Expand Down
9 changes: 9 additions & 0 deletions test/copy.jl
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,15 @@ end
@test copyto!(s, String[]) == [1, 2] # No error
end

@testset "circular reference arrays" begin
# issue 56775
p = Any[nothing]
p[1] = p
p2 = deepcopy(p)
@test p2 === p2[1]
@test p2 !== p
end

@testset "deepcopy_internal arrays" begin
@test (@inferred Base.deepcopy_internal(zeros(), IdDict())) == zeros()
end
Expand Down

0 comments on commit 1ebacac

Please sign in to comment.