rust-lang / rust-lang/rust-clippy

`non_zero_suggestions` is triggered when converting from a nonzero value to a larger unsigned value

Open
#13,757 7 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

T::from is getting confused with G::from when T is an unsigned integer (e.g., u64) and G is the nonzero version (e.g., NonZeroU64). For example converting a NonZeroU32 into a u64 triggers the lint incorrectly.

Lint Name

non_zero_suggestions

Reproducer

I tried this code:

#![deny(clippy::non_zero_suggestions)]
use core::num::NonZeroU32;
fn main() {
    _ = u64::from(NonZeroU32::new(10).unwrap().get());
}

I saw this happen:

error: consider using `NonZeroU64::from()` for more efficient and type-safe conversion
 --> src/main.rs:4:9
  |
4 |     _ = u64::from(NonZeroU32::new(10).unwrap().get());
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `NonZeroU64::from(NonZeroU32::new(10).unwrap())`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_zero_suggestions
note: the lint level is defined here
 --> src/main.rs:1:9
  |
1 | #![deny(clippy::non_zero_suggestions)]
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: could not compile `bug` (bin "bug") due to 1 previous error

I expected to see this happen: Compilation to succeed since u64::from is not the same as NonZeroU64::from.

Version
rustc 1.83.0 (90b35a623 2024-11-26)
binary: rustc
commit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf
commit-date: 2024-11-26
host: x86_64-unknown-linux-gnu
release: 1.83.0
LLVM version: 19.1.1
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 at the non_zero_suggestions lint implementation and reproduce the reported u64::from(NonZeroU32::new(10).unwrap().get()) case. Trace how the target and source types are identified, then add a regression test showing this conversion is not flagged while the intended suggestion still works.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
56/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.