Skip to content

identity_conversion false positive (macro + ?) #4098

Closed
@realcr

Description

@realcr

Hi, I think I'm having a false positive with the identity_conversion lint. Minimal example:

pub trait SafeSignedArithmetic: Copy {
    type Unsigned;

    fn checked_add_unsigned(self, u: Self::Unsigned) -> Option<Self>;
}

macro_rules! impl_safe_signed_arithmetic {
    ( $i:ty, $u:ty ) => {
        impl SafeSignedArithmetic for $i {
            type Unsigned = $u;

            fn checked_add_unsigned(self, u: $u) -> Option<$i> {
                let u_half = (u / 2) as $i;
                let u_rem = (u % 2) as $i;

                self.checked_add(u_half)?
                    .checked_add(u_half)?
                    .checked_add(u_rem)
            }
        }
    };
}

impl_safe_signed_arithmetic!(i8, u8);

fn main() {
    println!("Hello, world!");
}

Versions:

$ cargo clippy -V
clippy 0.0.212 (3710ec5 2019-05-11)

$ rustc --version
rustc 1.36.0-nightly (af98304b9 2019-05-11)

Clippy's output:

$ cargo clippy
    Checking check_identical_conversion v0.1.0 (/home/real/temp/check_identical_conversion)
warning: identical conversion
  --> src/main.rs:17:41
   |
17 |                 self.checked_add(u_half)?
   |                                         ^
...
25 | impl_safe_signed_arithmetic!(i8, u8);
   | ------------------------------------- in this macro invocation
   |
   = note: #[warn(clippy::identity_conversion)] on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_conversion

warning: identical conversion
  --> src/main.rs:18:41
   |
18 |                     .checked_add(u_half)?
   |                                         ^
...
25 | impl_safe_signed_arithmetic!(i8, u8);
   | ------------------------------------- in this macro invocation
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_conversion

    Finished dev [unoptimized + debuginfo] target(s) in 0.20s

Interestingly enough, if I try to implement this code without the macro, the clippy warnings disappear.

Thank you for developing clippy!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions