Skip to content

Commit

Permalink
prevent canonicalization and hence destruction of terms with metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
shashi committed Aug 31, 2023
1 parent 8f9f5f1 commit bca76e3
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,9 @@ function hasmetadata(s::Symbolic, ctx)
metadata(s) isa AbstractDict && haskey(metadata(s), ctx)
end

nometa(s) = isnothing(metadata(s))
nometa(ss...) = all(nometa, ss)

function getmetadata(s::Symbolic, ctx)
md = metadata(s)
if md isa AbstractDict
Expand Down Expand Up @@ -1058,6 +1061,7 @@ sub_t(a) = promote_symtype(-, symtype(a))

import Base: (+), (-), (*), (//), (/), (\), (^)
function +(a::SN, b::SN)
!nometa(a,b) && term(+, a, b) # Don't flatten if args have metadata
if isadd(a) && isadd(b)
return Add(add_t(a,b),
a.coeff + b.coeff,
Expand All @@ -1073,6 +1077,7 @@ function +(a::SN, b::SN)
end

function +(a::Number, b::SN)
!nometa(b) && return term(+, a, b) # Don't flatten if args have metadata
iszero(a) && return b
if isadd(b)
Add(add_t(a,b), a + b.coeff, b.dict)
Expand All @@ -1086,11 +1091,13 @@ end
+(a::SN) = a

function -(a::SN)
!nometa(b) && return term(-, a)
isadd(a) ? Add(sub_t(a), -a.coeff, mapvalues((_,v) -> -v, a.dict)) :
Add(sub_t(a), makeadd(-1, 0, a)...)
end

function -(a::SN, b::SN)
!nometa(a, b) && return term(-, a, b)
isadd(a) && isadd(b) ? Add(sub_t(a,b),
a.coeff - b.coeff,
_merge(-, a.dict,
Expand All @@ -1109,6 +1116,7 @@ mul_t(a) = promote_symtype(*, symtype(a))

function *(a::SN, b::SN)
# Always make sure Div wraps Mul
!nometa(a, b) && return term(*, a, b)
if isdiv(a) && isdiv(b)
Div(a.num * b.num, a.den * b.den)
elseif isdiv(a)
Expand All @@ -1135,6 +1143,7 @@ function *(a::SN, b::SN)
end

function *(a::Number, b::SN)
!nometa(b) && return term(*, a, b)
if iszero(a)
a
elseif isone(a)
Expand Down Expand Up @@ -1174,6 +1183,7 @@ end
###

function ^(a::SN, b)
!nometa(a,b) && return Pow(a, b)
if b isa Number && iszero(b)
# fast path
1
Expand Down

0 comments on commit bca76e3

Please sign in to comment.