Skip to content

integer_arithmetic and arithmetic_side_effects trigger on user-defined types #11220

Open
@tarcieri

Description

@tarcieri

Summary

As of Rust 1.71, integer_arithmetic started warning for arithmetic operations on user-defined types. On Rust 1.70 and earlier it did not. As far as I can tell, on earlier versions of Rust the lint was restricted to arithmetic operations on core integer types.

This same problem applies to arithemtic_side_effects which is intended to replace integer_arithmetic.

User-defined types may implement core::ops traits in ways that always use checked and panic-free arithmetic internally. The checked crate is an example. Such an approach makes it possible to use traditional arithmetic operators (which are easier to read) while still performing checked arithmetic, and perhaps more importantly deliberately don't implement unchecked arithmetic, and thus prevent you from doing the wrong thing (much in the same way this lint is intended to do).

Warning for arithmetic operations on such types prevents them being from used as a strategy for mitigating this class of operations in a way that satisfies the lint.

Lint Name

integer_arithmetic

Reproducer

I tried this code:

#![warn(clippy::integer_arithmetic)]

use core::ops::Add;

pub struct MyNewtype(pub u64);

pub struct Error;

impl Add for MyNewtype {
    type Output = Result<Self, Error>;

    fn add(self, other: Self) -> Result<Self, Error> {
        self.0
            .checked_add(other.0)
            .map(Self)
            .ok_or(Error)
    }
}

pub fn example(a: MyNewtype, b: MyNewtype) -> Result<MyNewtype, Error> {
    a + b
}

I saw this happen:

warning: arithmetic operation that can potentially result in unexpected side-effects
  --> src/lib.rs:21:5
   |
21 |     a + b
   |     ^^^^^

I expected to see this happen:

Success

Version

rustc 1.71.0 (8ede3aae2 2023-07-12)
binary: rustc
commit-hash: 8ede3aae28fe6e4d52b38157d7bfe0d3bceef225
commit-date: 2023-07-12
host: aarch64-apple-darwin
release: 1.71.0
LLVM version: 16.0.5

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions