rust-lang / rust-lang/rust-clippy

unchecked_duration_subtraction fix doesn't account for order of operations

Open
#10,239 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug
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:

image

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.