Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions compiler/rustc_lint/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2322,19 +2322,21 @@ pub(crate) enum InvalidNanComparisons {
#[derive(Subdiagnostic)]
pub(crate) enum InvalidNanComparisonsSuggestion {
#[multipart_suggestion(
"use `f32::is_nan()` or `f64::is_nan()` instead",
"use the `is_nan` method instead",
style = "verbose",
applicability = "machine-applicable"
)]
Spanful {
#[suggestion_part(code = "!")]
neg: Option<Span>,
#[suggestion_part(code = ".is_nan()")]
float: Span,
Ufcs {
prefix: String,
#[suggestion_part(code = "{prefix}")]
prefix_span: Span,
suffix: &'static str,
#[suggestion_part(code = "{suffix}")]
close_span: Span,
#[suggestion_part(code = "")]
nan_plus_binop: Span,
remove_nan: Span,
},
#[help("use `f32::is_nan()` or `f64::is_nan()` instead")]
#[help("use the `is_nan` method instead")]
Spanless,
}

Expand Down
158 changes: 112 additions & 46 deletions compiler/rustc_lint/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::iter;

use rustc_abi::{BackendRepr, TagEncoding, Variants, WrappingRange};
use rustc_ast as ast;
use rustc_ast::util::parser::ExprPrecedence;
use rustc_attr_ir::find_attr;
use rustc_attr_ir::lang_items::LangItem;
use rustc_hir as hir;
Expand Down Expand Up @@ -113,8 +114,8 @@ declare_lint! {
}

declare_lint! {
/// The `invalid_nan_comparisons` lint checks comparison with `f32::NAN` or `f64::NAN`
/// as one of the operand.
/// The `invalid_nan_comparisons` lint checks comparisons with the `NAN` constants
/// of `f16`, `f32`, `f64`, and `f128`.
///
/// ### Example
///
Expand All @@ -127,8 +128,8 @@ declare_lint! {
///
/// ### Explanation
///
/// NaN does not compare meaningfully to anything – not
/// even itself – so those comparisons are always false.
/// NaN compares unequal to every floating-point value, including itself.
/// Use the `is_nan` method to check whether a value is NaN.
INVALID_NAN_COMPARISONS,
Warn,
"detects invalid floating point NaN comparisons"
Expand Down Expand Up @@ -229,59 +230,124 @@ fn lint_nan<'tcx>(
l: &'tcx hir::Expr<'tcx>,
r: &'tcx hir::Expr<'tcx>,
) {
fn is_nan(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
let expr = expr.peel_blocks().peel_borrows();
match expr.kind {
ExprKind::Path(qpath) => {
let Some(def_id) = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id()
else {
return false;
};
fn nan_ty(cx: &LateContext<'_>, mut expr: &hir::Expr<'_>) -> Option<ty::FloatTy> {
loop {
expr = expr.peel_blocks();
match expr.kind {
ExprKind::AddrOf(.., inner) => expr = inner,
_ => break,
}
}
let ExprKind::Path(qpath) = expr.kind else { return None };
let def_id = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id()?;
Some(match cx.tcx.get_diagnostic_name(def_id)? {
sym::f16_nan => ty::FloatTy::F16,
sym::f32_nan => ty::FloatTy::F32,
sym::f64_nan => ty::FloatTy::F64,
sym::f128_nan => ty::FloatTy::F128,
_ => return None,
})
}

matches!(
cx.tcx.get_diagnostic_name(def_id),
Some(sym::f16_nan | sym::f32_nan | sym::f64_nan | sym::f128_nan)
)
fn nan_method_path(
cx: &LateContext<'_>,
mut nan: &hir::Expr<'_>,
float_ty: ty::FloatTy,
cmp_span: Span,
) -> Option<String> {
loop {
match nan.kind {
ExprKind::AddrOf(.., inner) => nan = inner,
ExprKind::Block(block, _) if block.stmts.is_empty() => nan = block.expr?,
_ => break,
}
_ => false,
}
let ExprKind::Path(hir::QPath::TypeRelative(ty, _)) = nan.kind else {
return None;
};
if !ty.span.from_expansion() && cmp_span.contains(ty.span) {
let ty = cx.sess().source_map().span_to_snippet(ty.span).ok()?;
Some(format!("<{ty}>::is_nan"))
} else if matches!(float_ty, ty::FloatTy::F32 | ty::FloatTy::F64) {
let krate = std_or_core(cx)?;
Some(format!("::{krate}::primitive::{}::is_nan", float_ty.name_str()))
} else {
None
}
}

fn eq_ne(
e: &hir::Expr<'_>,
l: &hir::Expr<'_>,
r: &hir::Expr<'_>,
f: impl FnOnce(Span, Span) -> InvalidNanComparisonsSuggestion,
) -> InvalidNanComparisons {
let suggestion = if let Some(l_span) = l.span.find_ancestor_inside(e.span)
&& let Some(r_span) = r.span.find_ancestor_inside(e.span)
{
f(l_span, r_span)
fn eq_ne_suggestion<'a>(
cx: &LateContext<'a>,
cmp: &'a hir::Expr<'a>,
value: &'a hir::Expr<'a>,
nan: &'a hir::Expr<'a>,
float_ty: ty::FloatTy,
is_ne: bool,
) -> InvalidNanComparisonsSuggestion {
if cmp.span.from_expansion() {
return InvalidNanComparisonsSuggestion::Spanless;
}
let (Some(value_span), Some(nan_span)) = (
value.span.find_ancestor_inside_same_ctxt(cmp.span),
nan.span.find_ancestor_inside_same_ctxt(cmp.span),
) else {
return InvalidNanComparisonsSuggestion::Spanless;
};
if value_span.overlaps(nan_span) {
return InvalidNanComparisonsSuggestion::Spanless;
}
let remove_nan = if nan_span.lo() < value_span.lo() {
nan_span.until(value_span)
} else {
InvalidNanComparisonsSuggestion::Spanless
value_span.shrink_to_hi().to(nan_span)
};

InvalidNanComparisons::EqNe { suggestion }
let Some(mut ty) = cx.typeck_results().expr_ty_opt(value) else {
return InvalidNanComparisonsSuggestion::Spanless;
};
let mut deref_count = 0;
while let ty::Ref(_, inner, _) = *ty.kind() {
deref_count += 1;
ty = inner;
}
let neg = if is_ne { "!" } else { "" };
let Some(method_path) = nan_method_path(cx, nan, float_ty, cmp.span) else {
return InvalidNanComparisonsSuggestion::Spanless;
};
let (open, suffix) = if deref_count != 0 && cx.precedence(value) < ExprPrecedence::Prefix {
("(", "))")
} else {
("", ")")
};
InvalidNanComparisonsSuggestion::Ufcs {
prefix: format!("{neg}{method_path}({}{open}", "*".repeat(deref_count)),
prefix_span: value_span.shrink_to_lo(),
suffix,
close_span: value_span.shrink_to_hi(),
remove_nan,
}
}

let Some((value, nan, float_ty)) = nan_ty(cx, l)
.map(|float_ty| (r, l, float_ty))
.or_else(|| nan_ty(cx, r).map(|float_ty| (l, r, float_ty)))
else {
return;
};
let typeck_results = cx.typeck_results();
// Custom comparison implementations need not follow primitive float NaN semantics.
if ![l, r].into_iter().all(|operand| {
typeck_results
.expr_ty_opt(operand)
.is_some_and(|ty| matches!(*ty.peel_refs().kind(), ty::Float(fty) if fty == float_ty))
}) {
return;
}
let lint = match binop {
hir::BinOpKind::Eq | hir::BinOpKind::Ne if is_nan(cx, l) => {
eq_ne(e, l, r, |l_span, r_span| InvalidNanComparisonsSuggestion::Spanful {
nan_plus_binop: l_span.until(r_span),
float: r_span.shrink_to_hi(),
neg: (binop == hir::BinOpKind::Ne).then(|| r_span.shrink_to_lo()),
})
}
hir::BinOpKind::Eq | hir::BinOpKind::Ne if is_nan(cx, r) => {
eq_ne(e, l, r, |l_span, r_span| InvalidNanComparisonsSuggestion::Spanful {
nan_plus_binop: l_span.shrink_to_hi().to(r_span),
float: l_span.shrink_to_hi(),
neg: (binop == hir::BinOpKind::Ne).then(|| l_span.shrink_to_lo()),
})
}
hir::BinOpKind::Lt | hir::BinOpKind::Le | hir::BinOpKind::Gt | hir::BinOpKind::Ge
if is_nan(cx, l) || is_nan(cx, r) =>
{
hir::BinOpKind::Eq | hir::BinOpKind::Ne => InvalidNanComparisons::EqNe {
suggestion: eq_ne_suggestion(cx, e, value, nan, float_ty, binop == hir::BinOpKind::Ne),
},
hir::BinOpKind::Lt | hir::BinOpKind::Le | hir::BinOpKind::Gt | hir::BinOpKind::Ge => {
InvalidNanComparisons::LtLeGtGe
}
_ => return,
Expand Down
50 changes: 0 additions & 50 deletions tests/ui/lint/invalid-nan-comparison-suggestion.fixed

This file was deleted.

53 changes: 0 additions & 53 deletions tests/ui/lint/invalid-nan-comparison-suggestion.rs

This file was deleted.

Loading
Loading