Skip to content

[SR-5964] dividedReportingOverflow may fail to compile for calculations that overflow #48523

@martinr448

Description

@martinr448
Previous ID SR-5964
Radar None
Original Reporter @martinr448
Type Bug

Attachment: Download

Environment

macOS 10.12.6

Xcode 9.0 (9A235)

Apple Swift version 4.0 (swiftlang-900.0.65 clang-900.0.37)
Target: x86_64-apple-macosx10.9

Additional Detail from JIRA
Votes 1
Component/s Compiler, Standard Library
Labels Bug
Assignee @moiseev
Priority Medium

md5: 3e39aeb0aec9075d1c78c3f6037e42b8

relates to:

  • SR-3535 divideWithOverflow gives Overflow error with edge case

Issue Description:

The documentation of

public func dividedReportingOverflow(by rhs: Self) -> (partialValue: Self, overflow: Bool)

from the FixedWidthInteger protocol states that overflows are indicated by a flag in the return value, and that dividing by zero is not an error.

However, it may fail to even compile in cases where the compiler already detects an overflow or division by zero:

// main1.swift
do {
    let minusOne = -1
    let r1 = Int.min.dividedReportingOverflow(by: minusOne)
    print(r1)
    
    let zero = 0
    let r2 = Int.min.dividedReportingOverflow(by: zero)
    print(r2)
}
$ swiftc main1.swift 
main1.swift:7:19: error: division by zero
        let r2 = Int.min.dividedReportingOverflow(by: zero)
                         ^
main1.swift:3:19: error: division '-9223372036854775808 / -1' results in an overflow
        let r1 = Int.min.dividedReportingOverflow(by: minusOne)

If the same code is on top-level then it compiles and runs as expected:

// main2.swift
let minusOne = -1
let r1 = Int.min.dividedReportingOverflow(by: minusOne)
print(r1)

let zero = 0
let r2 = Int.min.dividedReportingOverflow(by: zero)
print(r2)
$ swiftc main2.swift && ./main2 
(partialValue: -9223372036854775808, overflow: true)
(partialValue: -9223372036854775808, overflow: true)

Metadata

Metadata

Assignees

Labels

bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfstandard libraryArea: Standard library umbrella

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions