Skip to content

Commit ecb0311

Browse files
committed
Auto merge of rust-lang#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
2 parents 771a2a9 + 874f851 commit ecb0311

29 files changed

+650
-95
lines changed

clippy_lints/src/default_instead_of_iter_empty.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
2-
use clippy_utils::last_path_segment;
32
use clippy_utils::source::snippet_with_context;
3+
use clippy_utils::{last_path_segment, std_or_core};
44
use rustc_errors::Applicability;
55
use rustc_hir::{def, Expr, ExprKind, GenericArg, QPath, TyKind};
66
use rustc_lint::{LateContext, LateLintPass};
@@ -42,12 +42,14 @@ impl<'tcx> LateLintPass<'tcx> for DefaultIterEmpty {
4242
&& ty.span.ctxt() == ctxt
4343
{
4444
let mut applicability = Applicability::MachineApplicable;
45-
let sugg = make_sugg(cx, ty_path, ctxt, &mut applicability);
45+
let Some(path) = std_or_core(cx) else { return };
46+
let path = format!("{path}::iter::empty");
47+
let sugg = make_sugg(cx, ty_path, ctxt, &mut applicability, &path);
4648
span_lint_and_sugg(
4749
cx,
4850
DEFAULT_INSTEAD_OF_ITER_EMPTY,
4951
expr.span,
50-
"`std::iter::empty()` is the more idiomatic way",
52+
&format!("`{path}()` is the more idiomatic way"),
5153
"try",
5254
sugg,
5355
applicability,
@@ -61,6 +63,7 @@ fn make_sugg(
6163
ty_path: &rustc_hir::QPath<'_>,
6264
ctxt: SyntaxContext,
6365
applicability: &mut Applicability,
66+
path: &str,
6467
) -> String {
6568
if let Some(last) = last_path_segment(ty_path).args
6669
&& let Some(iter_ty) = last.args.iter().find_map(|arg| match arg {
@@ -69,10 +72,10 @@ fn make_sugg(
6972
})
7073
{
7174
format!(
72-
"std::iter::empty::<{}>()",
75+
"{path}::<{}>()",
7376
snippet_with_context(cx, iter_ty.span, ctxt, "..", applicability).0
7477
)
7578
} else {
76-
"std::iter::empty()".to_owned()
79+
format!("{path}()")
7780
}
7881
}

clippy_lints/src/mem_replace.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg, span_lin
33
use clippy_utils::source::{snippet, snippet_with_applicability};
44
use clippy_utils::sugg::Sugg;
55
use clippy_utils::ty::is_non_aggregate_primitive_type;
6-
use clippy_utils::{is_default_equivalent, is_res_lang_ctor, path_res, peel_ref_operators};
6+
use clippy_utils::{is_default_equivalent, is_res_lang_ctor, path_res, peel_ref_operators, std_or_core};
77
use rustc_errors::Applicability;
88
use rustc_hir::LangItem::OptionNone;
99
use rustc_hir::{Expr, ExprKind};
@@ -128,6 +128,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
128128
// check if replacement is mem::MaybeUninit::uninit().assume_init()
129129
&& cx.tcx.is_diagnostic_item(sym::assume_init, method_def_id)
130130
{
131+
let Some(top_crate) = std_or_core(cx) else { return };
131132
let mut applicability = Applicability::MachineApplicable;
132133
span_lint_and_sugg(
133134
cx,
@@ -136,7 +137,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
136137
"replacing with `mem::MaybeUninit::uninit().assume_init()`",
137138
"consider using",
138139
format!(
139-
"std::ptr::read({})",
140+
"{top_crate}::ptr::read({})",
140141
snippet_with_applicability(cx, dest.span, "", &mut applicability)
141142
),
142143
applicability,
@@ -149,6 +150,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
149150
&& let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id()
150151
{
151152
if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, repl_def_id) {
153+
let Some(top_crate) = std_or_core(cx) else { return };
152154
let mut applicability = Applicability::MachineApplicable;
153155
span_lint_and_sugg(
154156
cx,
@@ -157,7 +159,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
157159
"replacing with `mem::uninitialized()`",
158160
"consider using",
159161
format!(
160-
"std::ptr::read({})",
162+
"{top_crate}::ptr::read({})",
161163
snippet_with_applicability(cx, dest.span, "", &mut applicability)
162164
),
163165
applicability,
@@ -184,14 +186,17 @@ fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<
184186
return;
185187
}
186188
if is_default_equivalent(cx, src) && !in_external_macro(cx.tcx.sess, expr_span) {
189+
let Some(top_crate) = std_or_core(cx) else { return };
187190
span_lint_and_then(
188191
cx,
189192
MEM_REPLACE_WITH_DEFAULT,
190193
expr_span,
191-
"replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
194+
&format!(
195+
"replacing a value of type `T` with `T::default()` is better expressed using `{top_crate}::mem::take`"
196+
),
192197
|diag| {
193198
if !expr_span.from_expansion() {
194-
let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, ""));
199+
let suggestion = format!("{top_crate}::mem::take({})", snippet(cx, dest.span, ""));
195200

196201
diag.span_suggestion(
197202
expr_span,

clippy_lints/src/methods/iter_on_single_or_empty_collections.rs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
22
use clippy_utils::source::snippet;
3-
use clippy_utils::{get_expr_use_or_unification_node, is_no_std_crate, is_res_lang_ctor, path_res};
3+
use clippy_utils::{get_expr_use_or_unification_node, is_res_lang_ctor, path_res, std_or_core};
44

55
use rustc_errors::Applicability;
66
use rustc_hir::LangItem::{OptionNone, OptionSome};
@@ -58,10 +58,10 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: &str, re
5858
return;
5959
}
6060

61+
let Some(top_crate) = std_or_core(cx) else { return };
6162
if let Some(i) = item {
6263
let sugg = format!(
63-
"{}::iter::once({}{})",
64-
if is_no_std_crate(cx) { "core" } else { "std" },
64+
"{top_crate}::iter::once({}{})",
6565
iter_type.ref_prefix(),
6666
snippet(cx, i.span, "...")
6767
);
@@ -81,11 +81,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: &str, re
8181
expr.span,
8282
&format!("`{method_name}` call on an empty collection"),
8383
"try",
84-
if is_no_std_crate(cx) {
85-
"core::iter::empty()".to_string()
86-
} else {
87-
"std::iter::empty()".to_string()
88-
},
84+
format!("{top_crate}::iter::empty()"),
8985
Applicability::MaybeIncorrect,
9086
);
9187
}

clippy_lints/src/methods/unnecessary_sort_by.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ pub(super) fn check<'tcx>(
204204
cx,
205205
UNNECESSARY_SORT_BY,
206206
expr.span,
207-
"use Vec::sort_by_key here instead",
207+
"consider using `sort_by_key`",
208208
"try",
209209
format!(
210210
"{}.sort{}_by_key(|{}| {})",
@@ -227,7 +227,7 @@ pub(super) fn check<'tcx>(
227227
cx,
228228
UNNECESSARY_SORT_BY,
229229
expr.span,
230-
"use Vec::sort here instead",
230+
"consider using `sort`",
231231
"try",
232232
format!(
233233
"{}.sort{}()",

clippy_lints/src/operators/ptr_eq.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
22
use clippy_utils::source::snippet_opt;
3+
use clippy_utils::std_or_core;
34
use rustc_errors::Applicability;
45
use rustc_hir::{BinOpKind, Expr, ExprKind};
56
use rustc_lint::LateContext;
67

78
use super::PTR_EQ;
89

9-
static LINT_MSG: &str = "use `std::ptr::eq` when comparing raw pointers";
10-
1110
pub(super) fn check<'tcx>(
1211
cx: &LateContext<'tcx>,
1312
expr: &'tcx Expr<'_>,
@@ -26,13 +25,14 @@ pub(super) fn check<'tcx>(
2625
&& let Some(left_snip) = snippet_opt(cx, left_var.span)
2726
&& let Some(right_snip) = snippet_opt(cx, right_var.span)
2827
{
28+
let Some(top_crate) = std_or_core(cx) else { return };
2929
span_lint_and_sugg(
3030
cx,
3131
PTR_EQ,
3232
expr.span,
33-
LINT_MSG,
33+
&format!("use `{top_crate}::ptr::eq` when comparing raw pointers"),
3434
"try",
35-
format!("std::ptr::eq({left_snip}, {right_snip})"),
35+
format!("{top_crate}::ptr::eq({left_snip}, {right_snip})"),
3636
Applicability::MachineApplicable,
3737
);
3838
}

clippy_lints/src/transmute/transmute_int_to_char.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use super::TRANSMUTE_INT_TO_CHAR;
22
use clippy_utils::diagnostics::span_lint_and_then;
3-
use clippy_utils::sugg;
3+
use clippy_utils::{std_or_core, sugg};
44
use rustc_ast as ast;
55
use rustc_errors::Applicability;
66
use rustc_hir::Expr;
@@ -25,6 +25,7 @@ pub(super) fn check<'tcx>(
2525
e.span,
2626
&format!("transmute from a `{from_ty}` to a `char`"),
2727
|diag| {
28+
let Some(top_crate) = std_or_core(cx) else { return };
2829
let arg = sugg::Sugg::hir(cx, arg, "..");
2930
let arg = if let ty::Int(_) = from_ty.kind() {
3031
arg.as_ty(ast::UintTy::U32.name_str())
@@ -34,7 +35,7 @@ pub(super) fn check<'tcx>(
3435
diag.span_suggestion(
3536
e.span,
3637
"consider using",
37-
format!("std::char::from_u32({arg}).unwrap()"),
38+
format!("{top_crate}::char::from_u32({arg}).unwrap()"),
3839
Applicability::Unspecified,
3940
);
4041
},

clippy_lints/src/transmute/transmute_ref_to_ref.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use super::{TRANSMUTE_BYTES_TO_STR, TRANSMUTE_PTR_TO_PTR};
22
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
33
use clippy_utils::source::snippet;
4-
use clippy_utils::sugg;
4+
use clippy_utils::{std_or_core, sugg};
55
use rustc_errors::Applicability;
66
use rustc_hir::{Expr, Mutability};
77
use rustc_lint::LateContext;
@@ -25,6 +25,8 @@ pub(super) fn check<'tcx>(
2525
&& let ty::Uint(ty::UintTy::U8) = slice_ty.kind()
2626
&& from_mutbl == to_mutbl
2727
{
28+
let Some(top_crate) = std_or_core(cx) else { return true };
29+
2830
let postfix = if *from_mutbl == Mutability::Mut { "_mut" } else { "" };
2931

3032
let snippet = snippet(cx, arg.span, "..");
@@ -36,9 +38,9 @@ pub(super) fn check<'tcx>(
3638
&format!("transmute from a `{from_ty}` to a `{to_ty}`"),
3739
"consider using",
3840
if const_context {
39-
format!("std::str::from_utf8_unchecked{postfix}({snippet})")
41+
format!("{top_crate}::str::from_utf8_unchecked{postfix}({snippet})")
4042
} else {
41-
format!("std::str::from_utf8{postfix}({snippet}).unwrap()")
43+
format!("{top_crate}::str::from_utf8{postfix}({snippet}).unwrap()")
4244
},
4345
Applicability::MaybeIncorrect,
4446
);
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#![warn(clippy::default_instead_of_iter_empty)]
2+
#![allow(dead_code)]
3+
#![feature(lang_items)]
4+
#![no_std]
5+
6+
use core::panic::PanicInfo;
7+
8+
#[lang = "eh_personality"]
9+
extern "C" fn eh_personality() {}
10+
11+
#[panic_handler]
12+
fn panic(info: &PanicInfo) -> ! {
13+
loop {}
14+
}
15+
16+
#[derive(Default)]
17+
struct Iter {
18+
iter: core::iter::Empty<usize>,
19+
}
20+
21+
fn main() {
22+
// Do lint.
23+
let _ = core::iter::empty::<usize>();
24+
let _foo: core::iter::Empty<usize> = core::iter::empty();
25+
26+
// Do not lint.
27+
let _ = Iter::default();
28+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#![warn(clippy::default_instead_of_iter_empty)]
2+
#![allow(dead_code)]
3+
#![feature(lang_items)]
4+
#![no_std]
5+
6+
use core::panic::PanicInfo;
7+
8+
#[lang = "eh_personality"]
9+
extern "C" fn eh_personality() {}
10+
11+
#[panic_handler]
12+
fn panic(info: &PanicInfo) -> ! {
13+
loop {}
14+
}
15+
16+
#[derive(Default)]
17+
struct Iter {
18+
iter: core::iter::Empty<usize>,
19+
}
20+
21+
fn main() {
22+
// Do lint.
23+
let _ = core::iter::Empty::<usize>::default();
24+
let _foo: core::iter::Empty<usize> = core::iter::Empty::default();
25+
26+
// Do not lint.
27+
let _ = Iter::default();
28+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error: `core::iter::empty()` is the more idiomatic way
2+
--> $DIR/default_instead_of_iter_empty_no_std.rs:23:13
3+
|
4+
LL | let _ = core::iter::Empty::<usize>::default();
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `core::iter::empty::<usize>()`
6+
|
7+
= note: `-D clippy::default-instead-of-iter-empty` implied by `-D warnings`
8+
= help: to override `-D warnings` add `#[allow(clippy::default_instead_of_iter_empty)]`
9+
10+
error: `core::iter::empty()` is the more idiomatic way
11+
--> $DIR/default_instead_of_iter_empty_no_std.rs:24:42
12+
|
13+
LL | let _foo: core::iter::Empty<usize> = core::iter::Empty::default();
14+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `core::iter::empty()`
15+
16+
error: aborting due to 2 previous errors
17+

0 commit comments

Comments
 (0)