Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 3 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 11 additions & 5 deletions clippy_lints/src/default_instead_of_iter_empty.rs
@@ -1,6 +1,6 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::last_path_segment;
use clippy_utils::source::snippet_with_context;
use clippy_utils::{is_no_std_crate, last_path_segment};
use rustc_errors::Applicability;
use rustc_hir::{def, Expr, ExprKind, GenericArg, QPath, TyKind};
use rustc_lint::{LateContext, LateLintPass};
Expand Down Expand Up @@ -42,12 +42,17 @@ impl<'tcx> LateLintPass<'tcx> for DefaultIterEmpty {
&& ty.span.ctxt() == ctxt
{
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(
cx,
DEFAULT_INSTEAD_OF_ITER_EMPTY,
expr.span,
"`std::iter::empty()` is the more idiomatic way",
&format!("`{path}()` is the more idiomatic way"),
"try",
sugg,
applicability,
Expand All @@ -61,6 +66,7 @@ fn make_sugg(
ty_path: &rustc_hir::QPath<'_>,
ctxt: SyntaxContext,
applicability: &mut Applicability,
path: &str,
) -> String {
if let Some(last) = last_path_segment(ty_path).args
&& let Some(iter_ty) = last.args.iter().find_map(|arg| match arg {
Expand All @@ -69,10 +75,10 @@ fn make_sugg(
})
{
format!(
"std::iter::empty::<{}>()",
"{path}::<{}>()",
snippet_with_context(cx, iter_ty.span, ctxt, "..", applicability).0
)
} else {
"std::iter::empty()".to_owned()
format!("{path}()")
}
}
19 changes: 14 additions & 5 deletions clippy_lints/src/mem_replace.rs
Expand Up @@ -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::sugg::Sugg;
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_hir::LangItem::OptionNone;
use rustc_hir::{Expr, ExprKind};
Expand Down Expand Up @@ -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) {
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()
Expand All @@ -136,7 +140,8 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
"replacing with `mem::MaybeUninit::uninit().assume_init()`",
"consider using",
format!(
"std::ptr::read({})",
"{}::ptr::read({})",
get_top_crate(cx),
snippet_with_applicability(cx, dest.span, "", &mut applicability)
),
applicability,
Expand All @@ -157,7 +162,8 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
"replacing with `mem::uninitialized()`",
"consider using",
format!(
"std::ptr::read({})",
"{}::ptr::read({})",
get_top_crate(cx),
snippet_with_applicability(cx, dest.span, "", &mut applicability)
),
applicability,
Expand All @@ -184,14 +190,17 @@ fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<
return;
}
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(
cx,
MEM_REPLACE_WITH_DEFAULT,
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| {
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(
expr_span,
Expand Down
10 changes: 3 additions & 7 deletions clippy_lints/src/methods/iter_on_single_or_empty_collections.rs
Expand Up @@ -58,10 +58,10 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: &str, re
return;
}

let top_crate = if is_no_std_crate(cx) { "core" } else { "std" };
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, "...")
);
Expand All @@ -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,
);
}
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/methods/unnecessary_sort_by.rs
Expand Up @@ -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`",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method comes from slices so doesn't make much sense to only write Vec::.

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here.

"try",
format!(
"{}.sort{}()",
Expand Down
8 changes: 4 additions & 4 deletions clippy_lints/src/operators/ptr_eq.rs
@@ -1,13 +1,12 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_no_std_crate;
use clippy_utils::source::snippet_opt;
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::LateContext;

use super::PTR_EQ;

static LINT_MSG: &str = "use `std::ptr::eq` when comparing raw pointers";

pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
expr: &'tcx Expr<'_>,
Expand All @@ -26,13 +25,14 @@ pub(super) fn check<'tcx>(
&& let Some(left_snip) = snippet_opt(cx, left_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(
cx,
PTR_EQ,
expr.span,
LINT_MSG,
&format!("use `{top_crate}::ptr::eq` when comparing raw pointers"),
"try",
format!("std::ptr::eq({left_snip}, {right_snip})"),
format!("{top_crate}::ptr::eq({left_snip}, {right_snip})"),
Applicability::MachineApplicable,
);
}
Expand Down
7 changes: 5 additions & 2 deletions clippy_lints/src/transmute/transmute_int_to_char.rs
@@ -1,6 +1,6 @@
use super::TRANSMUTE_INT_TO_CHAR;
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_errors::Applicability;
use rustc_hir::Expr;
Expand Down Expand Up @@ -34,7 +34,10 @@ pub(super) fn check<'tcx>(
diag.span_suggestion(
e.span,
"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,
);
},
Expand Down
8 changes: 5 additions & 3 deletions clippy_lints/src/transmute/transmute_ref_to_ref.rs
@@ -1,7 +1,7 @@
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::source::snippet;
use clippy_utils::sugg;
use clippy_utils::{is_no_std_crate, sugg};
use rustc_errors::Applicability;
use rustc_hir::{Expr, Mutability};
use rustc_lint::LateContext;
Expand Down Expand Up @@ -29,16 +29,18 @@ pub(super) fn check<'tcx>(

let snippet = snippet(cx, arg.span, "..");

let top_crate = if is_no_std_crate(cx) { "core" } else { "std" };

span_lint_and_sugg(
cx,
TRANSMUTE_BYTES_TO_STR,
e.span,
&format!("transmute from a `{from_ty}` to a `{to_ty}`"),
"consider using",
if const_context {
format!("std::str::from_utf8_unchecked{postfix}({snippet})")
format!("{top_crate}::str::from_utf8_unchecked{postfix}({snippet})")
} else {
format!("std::str::from_utf8{postfix}({snippet}).unwrap()")
format!("{top_crate}::str::from_utf8{postfix}({snippet}).unwrap()")
},
Applicability::MaybeIncorrect,
);
Expand Down
28 changes: 28 additions & 0 deletions tests/ui/default_instead_of_iter_empty_no_std.fixed
@@ -0,0 +1,28 @@
#![warn(clippy::default_instead_of_iter_empty)]
#![allow(dead_code)]
#![feature(lang_items)]
#![no_std]

use core::panic::PanicInfo;

#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
loop {}
}

#[derive(Default)]
struct Iter {
iter: core::iter::Empty<usize>,
}

fn main() {
// Do lint.
let _ = core::iter::empty::<usize>();
let _foo: core::iter::Empty<usize> = core::iter::empty();

// Do not lint.
let _ = Iter::default();
}
28 changes: 28 additions & 0 deletions tests/ui/default_instead_of_iter_empty_no_std.rs
@@ -0,0 +1,28 @@
#![warn(clippy::default_instead_of_iter_empty)]
#![allow(dead_code)]
#![feature(lang_items)]
#![no_std]

use core::panic::PanicInfo;

#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
loop {}
}

#[derive(Default)]
struct Iter {
iter: core::iter::Empty<usize>,
}

fn main() {
// Do lint.
let _ = core::iter::Empty::<usize>::default();
let _foo: core::iter::Empty<usize> = core::iter::Empty::default();

// Do not lint.
let _ = Iter::default();
}
17 changes: 17 additions & 0 deletions tests/ui/default_instead_of_iter_empty_no_std.stderr
@@ -0,0 +1,17 @@
error: `core::iter::empty()` is the more idiomatic way
--> $DIR/default_instead_of_iter_empty_no_std.rs:23:13
|
LL | let _ = core::iter::Empty::<usize>::default();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `core::iter::empty::<usize>()`
|
= note: `-D clippy::default-instead-of-iter-empty` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::default_instead_of_iter_empty)]`

error: `core::iter::empty()` is the more idiomatic way
--> $DIR/default_instead_of_iter_empty_no_std.rs:24:42
|
LL | let _foo: core::iter::Empty<usize> = core::iter::Empty::default();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `core::iter::empty()`

error: aborting due to 2 previous errors

82 changes: 82 additions & 0 deletions tests/ui/mem_replace_no_std.fixed
@@ -0,0 +1,82 @@
#![allow(unused)]
#![warn(
clippy::all,
clippy::style,
clippy::mem_replace_option_with_none,
clippy::mem_replace_with_default
)]
#![feature(lang_items)]
#![no_std]

use core::mem;
use core::panic::PanicInfo;

#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
loop {}
}

fn replace_option_with_none() {
let mut an_option = Some(1);
let _ = an_option.take();
let an_option = &mut Some(1);
let _ = an_option.take();
}

fn replace_with_default() {
let mut refstr = "hello";
let _ = core::mem::take(&mut refstr);

let mut slice: &[i32] = &[1, 2, 3];
let _ = core::mem::take(&mut slice);
}

// lint is disabled for primitives because in this case `take`
// has no clear benefit over `replace` and sometimes is harder to read
fn dont_lint_primitive() {
let mut pbool = true;
let _ = mem::replace(&mut pbool, false);

let mut pint = 5;
let _ = mem::replace(&mut pint, 0);
}

fn main() {
replace_option_with_none();
replace_with_default();
dont_lint_primitive();
}

fn issue9824() {
struct Foo<'a>(Option<&'a str>);
impl<'a> core::ops::Deref for Foo<'a> {
type Target = Option<&'a str>;

fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> core::ops::DerefMut for Foo<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

struct Bar {
opt: Option<u8>,
val: u8,
}

let mut f = Foo(Some("foo"));
let mut b = Bar { opt: Some(1), val: 12 };

// replace option with none
let _ = f.0.take();
let _ = (*f).take();
let _ = b.opt.take();
// replace with default
let _ = mem::replace(&mut b.val, u8::default());
}