Skip to content

Commit

Permalink
Integer /: restrict fallback to same-type case (fix #19714)
Browse files Browse the repository at this point in the history
The principle here is that if there's an implementation of a promoted
operator for some type and promotions for that type, unless other
methods are defined, the operation should always be "funnelled"
through the core operator definition for that type. The method for
`/(::Integer, ::Integer)` violated that principle since it would take
precedence in mixed-integer-type division cases even in the presence
of a same-type method definition for a custom integer type and the
appropriate promotion rules.
  • Loading branch information
StefanKarpinski committed Dec 31, 2016
1 parent 9ce0aca commit 2166ec6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
3 changes: 2 additions & 1 deletion base/int.jl
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ typealias BitUnsigned64T Union{Type{UInt8},Type{UInt16},Type{UInt32},Type{UInt64
+{T<:BitInteger}(x::T, y::T) = box(T, add_int(unbox(T,x),unbox(T,y)))
*{T<:BitInteger}(x::T, y::T) = box(T, mul_int(unbox(T,x),unbox(T,y)))

/(x::Integer, y::Integer) = float(x)/float(y)
inv(x::Integer) = float(one(x))/float(x)
/{T<:Integer}(x::T, y::T) = float(x)/float(y)
/(x::BitInteger, y::BitInteger) = float(x)/float(y)

"""
isodd(x::Integer) -> Bool
Expand Down
8 changes: 8 additions & 0 deletions test/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,11 @@ let xs = [[i:i+4;] for i in 1:10]
@test max.(xs[1:n]...) == [n:n+4;]
end
end

# issue #19714
immutable T19714 <: Integer end
Base.float(::T19714) = 19714.0
Base.:/(::T19714, ::T19714) = T19714()
Base.convert(::Type{T19714}, ::Int) = T19714()
Base.promote_rule(::Type{T19714}, ::Type{Int}) = T19714
@test T19714()/1 === 1/T19714() === T19714()

2 comments on commit 2166ec6

@sairus7
Copy link
Contributor

@sairus7 sairus7 commented on 2166ec6 Dec 1, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

E.g., in DSP module, fixed-point arithmetics doesn't work:

using Base.DSP

x = collect(1:100)
b = [3, 5, 3]
a = [2 ,-2]
filt(b, a, v)
  > InexactError()

fx = collect(Float64, 1:100)
fb = Float64[3, 5, 3]
fa = Float64[2 ,-2]
filt(fb, fa, fx)
  > Float64[100]

This operation also will not work in every parametric function run with integers, where T<:Real

@StefanKarpinski
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sairus7, I can't tell if your comment is relevant or not or if it's even intended for this commit.

Please sign in to comment.