rust-lang / rust-lang/rust-clippy
unchecked_duration_subtraction fix doesn't account for order of operations
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
The fix for unchecked_duration_subtraction doesn't correctly account for order of operations in expressions it fixes resulting in regressions in the code.
Reproducer
Given this program
use std::time::{Duration, Instant};
fn main() {
let x = Duration::from_millis(10);
let y = Duration::from_millis(50);
let start = Instant::now();
let i = 50;
let result = start + i * x - y;
let relative = result - start;
assert_eq!(relative.as_millis(), 450);
}
Running cargo clippy --fix results in:
use std::time::{Duration, Instant};
fn main() {
let x = Duration::from_millis(10);
let y = Duration::from_millis(50);
let start = Instant::now();
let i = 50;
let result = start + i * x.checked_sub(y).unwrap();
let relative = result - start;
assert_eq!(relative.as_millis(), 450);
}
Here the order of operations have changed from (i * x) - y to i * (x - y).
See full run here:

Version
rustc 1.67.0 (fc594f156 2023-01-24)
binary: rustc
commit-hash: fc594f15669680fa70d255faec3ca3fb507c3405
commit-date: 2023-01-24
host: aarch64-apple-darwin
release: 1.67.0
LLVM version: 15.0.6
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the unchecked_duration_subtraction lint and reproduce the issue with the supplied Rust program and cargo clippy --fix. Verify that the fix preserves the original order of operations, keeping (i * x) - y distinct from i * (x - y), and confirm the corrected output no longer changes the program's result.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100