Auto merge of #12149 - GuillaumeGomez:core-std-suggestions, r=llogiq

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

A few lints emit suggestions using `std` paths whether or not this is a `no_std` crate, which is an issue when running `rustfix` afterwards. So in case this is an item that is defined in both `std` and `core`, we need to check if the crate is `no_std` to emit the right path.

r? `@llogiq`

changelog: Correctly suggest std or core path depending if this is a `no_std` crate
This commit is contained in:
bors 2024-01-16 06:26:29 +00:00
commit ecb0311fcc
29 changed files with 650 additions and 95 deletions

View file

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

View file

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