Correctly suggest std or core path depending if this is a no_std crate

This commit is contained in:
Guillaume Gomez 2024-01-14 14:13:04 +01:00
parent 37947ffc40
commit 1bcaf29e0b
7 changed files with 44 additions and 28 deletions

View File

@ -1,6 +1,6 @@
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::last_path_segment;
use clippy_utils::source::snippet_with_context; use clippy_utils::source::snippet_with_context;
use clippy_utils::{is_no_std_crate, last_path_segment};
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::{def, Expr, ExprKind, GenericArg, QPath, TyKind}; use rustc_hir::{def, Expr, ExprKind, GenericArg, QPath, TyKind};
use rustc_lint::{LateContext, LateLintPass}; use rustc_lint::{LateContext, LateLintPass};
@ -42,12 +42,17 @@ impl<'tcx> LateLintPass<'tcx> for DefaultIterEmpty {
&& ty.span.ctxt() == ctxt && ty.span.ctxt() == ctxt
{ {
let mut applicability = Applicability::MachineApplicable; let mut applicability = Applicability::MachineApplicable;
let sugg = make_sugg(cx, ty_path, ctxt, &mut applicability); let path = if is_no_std_crate(cx) {
"core::iter::empty"
} else {
"std::iter::empty"
};
let sugg = make_sugg(cx, ty_path, ctxt, &mut applicability, path);
span_lint_and_sugg( span_lint_and_sugg(
cx, cx,
DEFAULT_INSTEAD_OF_ITER_EMPTY, DEFAULT_INSTEAD_OF_ITER_EMPTY,
expr.span, expr.span,
"`std::iter::empty()` is the more idiomatic way", &format!("`{path}()` is the more idiomatic way"),
"try", "try",
sugg, sugg,
applicability, applicability,
@ -61,6 +66,7 @@ fn make_sugg(
ty_path: &rustc_hir::QPath<'_>, ty_path: &rustc_hir::QPath<'_>,
ctxt: SyntaxContext, ctxt: SyntaxContext,
applicability: &mut Applicability, applicability: &mut Applicability,
path: &str,
) -> String { ) -> String {
if let Some(last) = last_path_segment(ty_path).args if let Some(last) = last_path_segment(ty_path).args
&& let Some(iter_ty) = last.args.iter().find_map(|arg| match arg { && let Some(iter_ty) = last.args.iter().find_map(|arg| match arg {
@ -69,10 +75,10 @@ fn make_sugg(
}) })
{ {
format!( format!(
"std::iter::empty::<{}>()", "{path}::<{}>()",
snippet_with_context(cx, iter_ty.span, ctxt, "..", applicability).0 snippet_with_context(cx, iter_ty.span, ctxt, "..", applicability).0
) )
} else { } else {
"std::iter::empty()".to_owned() format!("{path}()")
} }
} }

View File

@ -3,7 +3,7 @@ use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg, span_lin
use clippy_utils::source::{snippet, snippet_with_applicability}; use clippy_utils::source::{snippet, snippet_with_applicability};
use clippy_utils::sugg::Sugg; use clippy_utils::sugg::Sugg;
use clippy_utils::ty::is_non_aggregate_primitive_type; use clippy_utils::ty::is_non_aggregate_primitive_type;
use clippy_utils::{is_default_equivalent, is_res_lang_ctor, path_res, peel_ref_operators}; use clippy_utils::{is_default_equivalent, is_no_std_crate, is_res_lang_ctor, path_res, peel_ref_operators};
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::LangItem::OptionNone; use rustc_hir::LangItem::OptionNone;
use rustc_hir::{Expr, ExprKind}; use rustc_hir::{Expr, ExprKind};
@ -123,6 +123,10 @@ fn check_replace_option_with_none(cx: &LateContext<'_>, dest: &Expr<'_>, expr_sp
); );
} }
fn get_top_crate(cx: &LateContext<'_>) -> &'static str {
if is_no_std_crate(cx) { "core" } else { "std" }
}
fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) { fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(src.hir_id) if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(src.hir_id)
// check if replacement is mem::MaybeUninit::uninit().assume_init() // check if replacement is mem::MaybeUninit::uninit().assume_init()
@ -136,7 +140,8 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
"replacing with `mem::MaybeUninit::uninit().assume_init()`", "replacing with `mem::MaybeUninit::uninit().assume_init()`",
"consider using", "consider using",
format!( format!(
"std::ptr::read({})", "{}::ptr::read({})",
get_top_crate(cx),
snippet_with_applicability(cx, dest.span, "", &mut applicability) snippet_with_applicability(cx, dest.span, "", &mut applicability)
), ),
applicability, applicability,
@ -157,7 +162,8 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
"replacing with `mem::uninitialized()`", "replacing with `mem::uninitialized()`",
"consider using", "consider using",
format!( format!(
"std::ptr::read({})", "{}::ptr::read({})",
get_top_crate(cx),
snippet_with_applicability(cx, dest.span, "", &mut applicability) snippet_with_applicability(cx, dest.span, "", &mut applicability)
), ),
applicability, applicability,
@ -184,14 +190,17 @@ fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<
return; return;
} }
if is_default_equivalent(cx, src) && !in_external_macro(cx.tcx.sess, expr_span) { if is_default_equivalent(cx, src) && !in_external_macro(cx.tcx.sess, expr_span) {
let top_crate = get_top_crate(cx);
span_lint_and_then( span_lint_and_then(
cx, cx,
MEM_REPLACE_WITH_DEFAULT, MEM_REPLACE_WITH_DEFAULT,
expr_span, expr_span,
"replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`", &format!(
"replacing a value of type `T` with `T::default()` is better expressed using `{top_crate}::mem::take`"
),
|diag| { |diag| {
if !expr_span.from_expansion() { if !expr_span.from_expansion() {
let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, "")); let suggestion = format!("{top_crate}::mem::take({})", snippet(cx, dest.span, ""));
diag.span_suggestion( diag.span_suggestion(
expr_span, expr_span,

View File

@ -58,10 +58,10 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: &str, re
return; return;
} }
let top_crate = if is_no_std_crate(cx) { "core" } else { "std" };
if let Some(i) = item { if let Some(i) = item {
let sugg = format!( let sugg = format!(
"{}::iter::once({}{})", "{top_crate}::iter::once({}{})",
if is_no_std_crate(cx) { "core" } else { "std" },
iter_type.ref_prefix(), iter_type.ref_prefix(),
snippet(cx, i.span, "...") snippet(cx, i.span, "...")
); );
@ -81,11 +81,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: &str, re
expr.span, expr.span,
&format!("`{method_name}` call on an empty collection"), &format!("`{method_name}` call on an empty collection"),
"try", "try",
if is_no_std_crate(cx) { format!("{top_crate}::iter::empty()"),
"core::iter::empty()".to_string()
} else {
"std::iter::empty()".to_string()
},
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }

View File

@ -204,7 +204,7 @@ pub(super) fn check<'tcx>(
cx, cx,
UNNECESSARY_SORT_BY, UNNECESSARY_SORT_BY,
expr.span, expr.span,
"use Vec::sort_by_key here instead", "consider using `sort_by_key`",
"try", "try",
format!( format!(
"{}.sort{}_by_key(|{}| {})", "{}.sort{}_by_key(|{}| {})",
@ -227,7 +227,7 @@ pub(super) fn check<'tcx>(
cx, cx,
UNNECESSARY_SORT_BY, UNNECESSARY_SORT_BY,
expr.span, expr.span,
"use Vec::sort here instead", "consider using `sort`",
"try", "try",
format!( format!(
"{}.sort{}()", "{}.sort{}()",

View File

@ -1,4 +1,5 @@
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_no_std_crate;
use clippy_utils::source::snippet_opt; use clippy_utils::source::snippet_opt;
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_hir::{BinOpKind, Expr, ExprKind};
@ -6,8 +7,6 @@ use rustc_lint::LateContext;
use super::PTR_EQ; use super::PTR_EQ;
static LINT_MSG: &str = "use `std::ptr::eq` when comparing raw pointers";
pub(super) fn check<'tcx>( pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>, cx: &LateContext<'tcx>,
expr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>,
@ -26,13 +25,14 @@ pub(super) fn check<'tcx>(
&& let Some(left_snip) = snippet_opt(cx, left_var.span) && let Some(left_snip) = snippet_opt(cx, left_var.span)
&& let Some(right_snip) = snippet_opt(cx, right_var.span) && let Some(right_snip) = snippet_opt(cx, right_var.span)
{ {
let top_crate = if is_no_std_crate(cx) { "core" } else { "std" };
span_lint_and_sugg( span_lint_and_sugg(
cx, cx,
PTR_EQ, PTR_EQ,
expr.span, expr.span,
LINT_MSG, &format!("use `{top_crate}::ptr::eq` when comparing raw pointers"),
"try", "try",
format!("std::ptr::eq({left_snip}, {right_snip})"), format!("{top_crate}::ptr::eq({left_snip}, {right_snip})"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }

View File

@ -1,6 +1,6 @@
use super::TRANSMUTE_INT_TO_CHAR; use super::TRANSMUTE_INT_TO_CHAR;
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::sugg; use clippy_utils::{is_no_std_crate, sugg};
use rustc_ast as ast; use rustc_ast as ast;
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::Expr; use rustc_hir::Expr;
@ -34,7 +34,10 @@ pub(super) fn check<'tcx>(
diag.span_suggestion( diag.span_suggestion(
e.span, e.span,
"consider using", "consider using",
format!("std::char::from_u32({arg}).unwrap()"), format!(
"{}::char::from_u32({arg}).unwrap()",
if is_no_std_crate(cx) { "core" } else { "std" }
),
Applicability::Unspecified, Applicability::Unspecified,
); );
}, },

View File

@ -1,7 +1,7 @@
use super::{TRANSMUTE_BYTES_TO_STR, TRANSMUTE_PTR_TO_PTR}; use super::{TRANSMUTE_BYTES_TO_STR, TRANSMUTE_PTR_TO_PTR};
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::snippet; use clippy_utils::source::snippet;
use clippy_utils::sugg; use clippy_utils::{is_no_std_crate, sugg};
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::{Expr, Mutability}; use rustc_hir::{Expr, Mutability};
use rustc_lint::LateContext; use rustc_lint::LateContext;
@ -29,6 +29,8 @@ pub(super) fn check<'tcx>(
let snippet = snippet(cx, arg.span, ".."); let snippet = snippet(cx, arg.span, "..");
let top_crate = if is_no_std_crate(cx) { "core" } else { "std" };
span_lint_and_sugg( span_lint_and_sugg(
cx, cx,
TRANSMUTE_BYTES_TO_STR, TRANSMUTE_BYTES_TO_STR,
@ -36,9 +38,9 @@ pub(super) fn check<'tcx>(
&format!("transmute from a `{from_ty}` to a `{to_ty}`"), &format!("transmute from a `{from_ty}` to a `{to_ty}`"),
"consider using", "consider using",
if const_context { if const_context {
format!("std::str::from_utf8_unchecked{postfix}({snippet})") format!("{top_crate}::str::from_utf8_unchecked{postfix}({snippet})")
} else { } else {
format!("std::str::from_utf8{postfix}({snippet}).unwrap()") format!("{top_crate}::str::from_utf8{postfix}({snippet}).unwrap()")
}, },
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );