1
Fork 0

correct suggestion for drain_collect in a no_std environment

This commit is contained in:
lapla-cogito 2025-01-14 20:37:35 +09:00
parent cb0a479d1f
commit d99eae4325
No known key found for this signature in database
GPG key ID: B39C71D9F127FF9F
4 changed files with 31 additions and 3 deletions

View file

@ -1,8 +1,8 @@
use crate::methods::DRAIN_COLLECT;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_range_full;
use clippy_utils::source::snippet;
use clippy_utils::ty::is_type_lang_item;
use clippy_utils::{is_range_full, std_or_core};
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind, LangItem, Path, QPath};
use rustc_lint::LateContext;
@ -58,12 +58,13 @@ pub(super) fn check(cx: &LateContext<'_>, args: &[Expr<'_>], expr: &Expr<'_>, re
.then_some("Vec")
.or_else(|| check_string(cx, args, expr_ty, recv_ty_no_refs, recv_path).then_some("String"))
.or_else(|| check_collections(cx, expr_ty, recv_ty_no_refs))
&& let Some(exec_context) = std_or_core(cx)
{
let recv = snippet(cx, recv.span, "<expr>");
let sugg = if let ty::Ref(..) = recv_ty.kind() {
format!("std::mem::take({recv})")
format!("{exec_context}::mem::take({recv})")
} else {
format!("std::mem::take(&mut {recv})")
format!("{exec_context}::mem::take(&mut {recv})")
};
span_lint_and_sugg(

View file

@ -0,0 +1,8 @@
#![warn(clippy::drain_collect)]
#![no_std]
extern crate alloc;
use alloc::vec::Vec;
fn remove_all(v: &mut Vec<i32>) -> Vec<i32> {
core::mem::take(v)
}

View file

@ -0,0 +1,8 @@
#![warn(clippy::drain_collect)]
#![no_std]
extern crate alloc;
use alloc::vec::Vec;
fn remove_all(v: &mut Vec<i32>) -> Vec<i32> {
v.drain(..).collect()
}

View file

@ -0,0 +1,11 @@
error: you seem to be trying to move all elements into a new `Vec`
--> tests/ui/drain_collect_nostd.rs:7:5
|
LL | v.drain(..).collect()
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using `mem::take`: `core::mem::take(v)`
|
= note: `-D clippy::drain-collect` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::drain_collect)]`
error: aborting due to 1 previous error