Skip to content

Commit

Permalink
Add isequal2 function for checking metadata comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
bowenszhu committed Nov 5, 2024
1 parent c2d85c3 commit 28e27ff
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
20 changes: 20 additions & 0 deletions src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,26 @@ function _isequal(a, b, E)
end
end

"""
$(TYPEDSIGNATURES)
Checks for equality between two `BasicSymbolic` objects, considering both their
values and metadata.
The default `Base.isequal` function for `BasicSymbolic` only compares their expressions
and ignores metadata. This can lead to hash collisions when metadata is relevant
for distinguishing expressions, particularly in hashing contexts. This function
provides a stricter equality check that includes metadata comparison, preventing
such collisions.
Modifying `Base.isequal` directly breaks numerous tests in `SymbolicUtils.jl` and
downstream packages like `ModelingToolkit.jl`, hence the need for this separate
function.
"""
function isequal2(a::BasicSymbolic, b::BasicSymbolic)::Bool
isequal(a, b) && isequal(metadata(a), metadata(b))
end

Base.one( s::Symbolic) = one( symtype(s))
Base.zero(s::Symbolic) = zero(symtype(s))

Expand Down
9 changes: 8 additions & 1 deletion test/basics.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using SymbolicUtils: Symbolic, Sym, FnType, Term, Add, Mul, Pow, symtype, operation, arguments, issym, isterm, BasicSymbolic, term
using SymbolicUtils: Symbolic, Sym, FnType, Term, Add, Mul, Pow, symtype, operation, arguments, issym, isterm, BasicSymbolic, term, isequal2
using SymbolicUtils
using IfElse: ifelse
using Setfield
Expand Down Expand Up @@ -336,6 +336,13 @@ end

@test !isequal(a, missing)
@test !isequal(missing, b)

a1 = setmetadata(a, Ctx1, "meta_1")
a2 = setmetadata(a, Ctx1, "meta_1")
a3 = setmetadata(a, Ctx2, "meta_2")
@test !isequal2(a, a1)
@test isequal2(a1, a2)
@test !isequal2(a1, a3)
end

@testset "subtyping" begin
Expand Down

0 comments on commit 28e27ff

Please sign in to comment.