swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.58k stars 10.36k forks source link

[SR-1105] Range indices crash when self is greater than end #43718

Open swift-ci opened 8 years ago

swift-ci commented 8 years ago
Previous ID SR-1105
Radar None
Original Reporter melhuang (JIRA User)
Type Bug
Environment Swift Snapshot 2016-01-25
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 0 | |Component/s | Standard Library | |Labels | Bug | |Assignee | None | |Priority | Medium | md5: c9702ec110d36c0987fa2a8ead9b98f4

cloned from:

Issue Description:

This should either be caught at compile time or return a negative value. Run-time crashes are pretty inconvenient.

Alternatively, since distance is an absolute value function, can we add support to make make that supported?

let string = "Hello, playground"
let substring = "play"
if let rangeOfSubstring = string.rangeOfString(substring) {
    let distance = rangeOfSubstring.startIndex.distanceTo(string.startIndex)
}

ERROR: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

belkadan commented 8 years ago

Forming a backwards range is considered a programmer error, just like indexing outside the bounds of the array. (In debug mode you should see an error message before the abort.)

It would definitely be nice if the compiler caught some specific cases, but I'm not sure it'd really be possible to describe the rule that would catch this one.