Skip to content

Commit 8957290

Browse files
committed
Add isequal2 function for checking metadata comparison
1 parent c2d85c3 commit 8957290

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/types.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,26 @@ function _isequal(a, b, E)
267267
end
268268
end
269269

270+
"""
271+
$(TYPEDSIGNATURES)
272+
273+
Checks for equality between two `BasicSymbolic` objects, considering both their
274+
values and metadata.
275+
276+
The default `Base.isequal` function for `BasicSymbolic` only compares their expressions
277+
and ignores metadata. This does not help deal with hash collisions when metadata is
278+
relevant for distinguishing expressions, particularly in hashing contexts. This function
279+
provides a stricter equality check that includes metadata comparison, preventing
280+
such collisions.
281+
282+
Modifying `Base.isequal` directly breaks numerous tests in `SymbolicUtils.jl` and
283+
downstream packages like `ModelingToolkit.jl`, hence the need for this separate
284+
function.
285+
"""
286+
function isequal2(a::BasicSymbolic, b::BasicSymbolic)::Bool
287+
isequal(a, b) && isequal(metadata(a), metadata(b))
288+
end
289+
270290
Base.one( s::Symbolic) = one( symtype(s))
271291
Base.zero(s::Symbolic) = zero(symtype(s))
272292

test/basics.jl

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using SymbolicUtils: Symbolic, Sym, FnType, Term, Add, Mul, Pow, symtype, operation, arguments, issym, isterm, BasicSymbolic, term
1+
using SymbolicUtils: Symbolic, Sym, FnType, Term, Add, Mul, Pow, symtype, operation, arguments, issym, isterm, BasicSymbolic, term, isequal2
22
using SymbolicUtils
33
using IfElse: ifelse
44
using Setfield
@@ -336,6 +336,13 @@ end
336336

337337
@test !isequal(a, missing)
338338
@test !isequal(missing, b)
339+
340+
a1 = setmetadata(a, Ctx1, "meta_1")
341+
a2 = setmetadata(a, Ctx1, "meta_1")
342+
a3 = setmetadata(a, Ctx2, "meta_2")
343+
@test !isequal2(a, a1)
344+
@test isequal2(a1, a2)
345+
@test !isequal2(a1, a3)
339346
end
340347

341348
@testset "subtyping" begin

0 commit comments

Comments
 (0)