-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Open
Labels
C-bugCategory: Clippy is not doing the correct thingCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveIssue: The lint was triggered on code it shouldn't have
Description
Summary
When having a SAFETY
comment on top of a statement that has an unsafe
block, the statement is needed for the block, but is also linted for the (safe) statement.
I'm not entirely sure the best way to fix it easily, but I think a bigger refactor around these lints are needed, where:
- first
SAFETY
comments are gathered, - then each unsafe block is linked to a given SAFETY comment,
- and finally lints are emitted accordingly
Reproducer
I tried this code:
#![warn(clippy::undocumented_unsafe_blocks, clippy::unnecessary_safety_comment)]
#![no_main]
use std::num::NonZeroI32;
struct Date {
value: NonZeroI32,
}
impl Date {
const unsafe fn __from_ordinal_date_unchecked(year: i32, ordinal: u16) -> Self {
Self {
// Safety: The caller must guarantee that `ordinal` is not zero.
value: unsafe { NonZeroI32::new_unchecked((year << 9) | ordinal as i32) },
}
}
const fn into_julian_day_just_make_this_line_longer(self) -> i32 {
42
}
}
unsafe fn foo() {
/// The Julian day of the Unix epoch.
// SAFETY: fail ONLY if `accept-comment-above-attribute = false`
const UNIX_EPOCH_JULIAN_DAY: i32 = unsafe { Date::__from_ordinal_date_unchecked(1970, 1) }
.into_julian_day_just_make_this_line_longer();
/// The Julian day of the Unix epoch.
const UNIX_EPOCH_JULIAN_DAY_2: i32 = unsafe { Date::__from_ordinal_date_unchecked(1970, 1) }
.into_julian_day_just_make_this_line_longer();
}
I expected to see this happen:
No lints around UNIX_EPOCH_JULIAN_DAY
Instead, this happened:
warning: constant has unnecessary safety comment
--> src/lib.rs:26:5
|
26 | const UNIX_EPOCH_JULIAN_DAY: i32 = unsafe { Date::__from_ordinal_date_unchecked(1970, 1) }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
help: consider removing the safety comment
Version
rustc 1.92.0-nightly (4645a7988 2025-09-17)
binary: rustc
commit-hash: 4645a7988177c286f61609cc667ecae4c571a2e8
commit-date: 2025-09-17
host: aarch64-apple-darwin
release: 1.92.0-nightly
LLVM version: 21.1.1
Additional Labels
@rustbot label +I-false-positive
Metadata
Metadata
Assignees
Labels
C-bugCategory: Clippy is not doing the correct thingCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveIssue: The lint was triggered on code it shouldn't have