feat(new lint): new lint use_retain

This commit is contained in:
kyoto7250 2022-06-07 12:11:33 +09:00
parent 9b150625a9
commit 5f2b8e67b3
10 changed files with 722 additions and 0 deletions

View file

@ -3840,6 +3840,7 @@ Released 2018-09-13
[`unwrap_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used
[`upper_case_acronyms`]: https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms
[`use_debug`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_debug
[`use_retain`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_retain
[`use_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_self
[`used_underscore_binding`]: https://rust-lang.github.io/rust-clippy/master/index.html#used_underscore_binding
[`useless_asref`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_asref

View file

@ -336,6 +336,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
LintId::of(unwrap::PANICKING_UNWRAP),
LintId::of(unwrap::UNNECESSARY_UNWRAP),
LintId::of(upper_case_acronyms::UPPER_CASE_ACRONYMS),
LintId::of(use_retain::USE_RETAIN),
LintId::of(useless_conversion::USELESS_CONVERSION),
LintId::of(vec::USELESS_VEC),
LintId::of(vec_init_then_push::VEC_INIT_THEN_PUSH),

View file

@ -563,6 +563,7 @@ store.register_lints(&[
unwrap::UNNECESSARY_UNWRAP,
unwrap_in_result::UNWRAP_IN_RESULT,
upper_case_acronyms::UPPER_CASE_ACRONYMS,
use_retain::USE_RETAIN,
use_self::USE_SELF,
useless_conversion::USELESS_CONVERSION,
vec::USELESS_VEC,

View file

@ -117,6 +117,7 @@ store.register_group(true, "clippy::style", Some("clippy_style"), vec![
LintId::of(unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
LintId::of(unused_unit::UNUSED_UNIT),
LintId::of(upper_case_acronyms::UPPER_CASE_ACRONYMS),
LintId::of(use_retain::USE_RETAIN),
LintId::of(write::PRINTLN_EMPTY_STRING),
LintId::of(write::PRINT_LITERAL),
LintId::of(write::PRINT_WITH_NEWLINE),

View file

@ -410,6 +410,7 @@ mod unused_unit;
mod unwrap;
mod unwrap_in_result;
mod upper_case_acronyms;
mod use_retain;
mod use_self;
mod useless_conversion;
mod vec;
@ -914,6 +915,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
store.register_late_pass(|| Box::new(read_zero_byte_vec::ReadZeroByteVec));
store.register_late_pass(|| Box::new(default_instead_of_iter_empty::DefaultIterEmpty));
store.register_late_pass(move || Box::new(manual_rem_euclid::ManualRemEuclid::new(msrv)));
store.register_late_pass(|| Box::new(use_retain::UseRetain));
// add lints here, do not remove this comment, it's used in `new_lint`
}

View file

@ -0,0 +1,233 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{get_parent_expr, match_def_path, paths, SpanlessEq};
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::ExprKind::Assign;
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::symbol::sym;
const ACCEPTABLE_METHODS: [&[&str]; 4] = [
&paths::HASHSET_ITER,
&paths::BTREESET_ITER,
&paths::SLICE_INTO,
&paths::VEC_DEQUE_ITER,
];
const ACCEPTABLE_TYPES: [rustc_span::Symbol; 6] = [
sym::BTreeSet,
sym::BTreeMap,
sym::HashSet,
sym::HashMap,
sym::Vec,
sym::VecDeque,
];
declare_clippy_lint! {
/// ### What it does
/// Checks for code to be replaced by `.retain()`.
/// ### Why is this bad?
/// `.retain()` is simpler.
/// ### Example
/// ```rust
/// let mut vec = vec![0, 1, 2];
/// vec = vec.iter().filter(|&x| x % 2 == 0).copied().collect();
/// vec = vec.into_iter().filter(|x| x % 2 == 0).collect();
/// ```
/// Use instead:
/// ```rust
/// let mut vec = vec![0, 1, 2];
/// vec.retain(|x| x % 2 == 0);
/// ```
#[clippy::version = "1.63.0"]
pub USE_RETAIN,
style,
"`retain()` is simpler and the same functionalitys"
}
declare_lint_pass!(UseRetain => [USE_RETAIN]);
impl<'tcx> LateLintPass<'tcx> for UseRetain {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
if_chain! {
if let Some(parent_expr) = get_parent_expr(cx, expr);
if let Assign(left_expr, collect_expr, _) = &parent_expr.kind;
if let hir::ExprKind::MethodCall(seg, _, _) = &collect_expr.kind;
if seg.args.is_none();
if let hir::ExprKind::MethodCall(_, [target_expr], _) = &collect_expr.kind;
if let Some(collect_def_id) = cx.typeck_results().type_dependent_def_id(collect_expr.hir_id);
if match_def_path(cx, collect_def_id, &paths::CORE_ITER_COLLECT);
then {
check_into_iter(cx, parent_expr, left_expr, target_expr);
check_iter(cx, parent_expr, left_expr, target_expr);
check_to_owned(cx, parent_expr, left_expr, target_expr);
}
}
}
}
fn check_into_iter(
cx: &LateContext<'_>,
parent_expr: &hir::Expr<'_>,
left_expr: &hir::Expr<'_>,
target_expr: &hir::Expr<'_>,
) {
if_chain! {
if let hir::ExprKind::MethodCall(_, [into_iter_expr, _], _) = &target_expr.kind;
if let Some(filter_def_id) = cx.typeck_results().type_dependent_def_id(target_expr.hir_id);
if match_def_path(cx, filter_def_id, &paths::CORE_ITER_FILTER);
if let hir::ExprKind::MethodCall(_, [struct_expr], _) = &into_iter_expr.kind;
if let Some(into_iter_def_id) = cx.typeck_results().type_dependent_def_id(into_iter_expr.hir_id);
if match_def_path(cx, into_iter_def_id, &paths::CORE_ITER_INTO_ITER);
if match_acceptable_type(cx, left_expr);
if SpanlessEq::new(cx).eq_expr(left_expr, struct_expr);
then {
suggest(cx, parent_expr, left_expr, target_expr);
}
}
}
fn check_iter(
cx: &LateContext<'_>,
parent_expr: &hir::Expr<'_>,
left_expr: &hir::Expr<'_>,
target_expr: &hir::Expr<'_>,
) {
if_chain! {
if let hir::ExprKind::MethodCall(_, [filter_expr], _) = &target_expr.kind;
if let Some(copied_def_id) = cx.typeck_results().type_dependent_def_id(target_expr.hir_id);
if match_def_path(cx, copied_def_id, &paths::CORE_ITER_COPIED);
if let hir::ExprKind::MethodCall(_, [iter_expr, _], _) = &filter_expr.kind;
if let Some(filter_def_id) = cx.typeck_results().type_dependent_def_id(filter_expr.hir_id);
if match_def_path(cx, filter_def_id, &paths::CORE_ITER_FILTER);
if let hir::ExprKind::MethodCall(_, [struct_expr], _) = &iter_expr.kind;
if let Some(iter_expr_def_id) = cx.typeck_results().type_dependent_def_id(iter_expr.hir_id);
if match_acceptable_def_path(cx, iter_expr_def_id);
if match_acceptable_type(cx, left_expr);
if SpanlessEq::new(cx).eq_expr(left_expr, struct_expr);
then {
suggest(cx, parent_expr, left_expr, filter_expr);
}
}
}
fn check_to_owned(
cx: &LateContext<'_>,
parent_expr: &hir::Expr<'_>,
left_expr: &hir::Expr<'_>,
target_expr: &hir::Expr<'_>,
) {
if_chain! {
if let hir::ExprKind::MethodCall(_, [filter_expr], _) = &target_expr.kind;
if let Some(to_owned_def_id) = cx.typeck_results().type_dependent_def_id(target_expr.hir_id);
if match_def_path(cx, to_owned_def_id, &paths::TO_OWNED_METHOD);
if let hir::ExprKind::MethodCall(_, [chars_expr, _], _) = &filter_expr.kind;
if let Some(filter_def_id) = cx.typeck_results().type_dependent_def_id(filter_expr.hir_id);
if match_def_path(cx, filter_def_id, &paths::CORE_ITER_FILTER);
if let hir::ExprKind::MethodCall(_, [str_expr], _) = &chars_expr.kind;
if let Some(chars_expr_def_id) = cx.typeck_results().type_dependent_def_id(chars_expr.hir_id);
if match_def_path(cx, chars_expr_def_id, &paths::STR_CHARS);
let ty = cx.typeck_results().expr_ty(str_expr).peel_refs();
if is_type_diagnostic_item(cx, ty, sym::String);
if SpanlessEq::new(cx).eq_expr(left_expr, str_expr);
then {
suggest(cx, parent_expr, left_expr, filter_expr);
}
}
}
fn suggest(cx: &LateContext<'_>, parent_expr: &hir::Expr<'_>, left_expr: &hir::Expr<'_>, filter_expr: &hir::Expr<'_>) {
if_chain! {
if let hir::ExprKind::MethodCall(_, [_, closure], _) = filter_expr.kind;
if let hir::ExprKind::Closure(_, _, filter_body_id, ..) = closure.kind;
let filter_body = cx.tcx.hir().body(filter_body_id);
if let [filter_params] = filter_body.params;
if let Some(sugg) = match filter_params.pat.kind {
hir::PatKind::Binding(_, _, filter_param_ident, None) => {
Some(format!("{}.retain(|{}| {})", snippet(cx, left_expr.span, ".."), filter_param_ident, snippet(cx, filter_body.value.span, "..")))
},
hir::PatKind::Tuple([key_pat, value_pat], _) => {
make_sugg(cx, key_pat, value_pat, left_expr, filter_body)
},
hir::PatKind::Ref(pat, _) => {
match pat.kind {
hir::PatKind::Binding(_, _, filter_param_ident, None) => {
Some(format!("{}.retain(|{}| {})", snippet(cx, left_expr.span, ".."), filter_param_ident, snippet(cx, filter_body.value.span, "..")))
},
_ => None
}
},
_ => None
};
then {
span_lint_and_sugg(
cx,
USE_RETAIN,
parent_expr.span,
"this expression can be written more simply using `.retain()`",
"consider calling `.retain()` instead",
sugg,
Applicability::MachineApplicable
);
}
}
}
fn make_sugg(
cx: &LateContext<'_>,
key_pat: &rustc_hir::Pat<'_>,
value_pat: &rustc_hir::Pat<'_>,
left_expr: &hir::Expr<'_>,
filter_body: &hir::Body<'_>,
) -> Option<String> {
match (&key_pat.kind, &value_pat.kind) {
(hir::PatKind::Binding(_, _, key_param_ident, None), hir::PatKind::Binding(_, _, value_param_ident, None)) => {
Some(format!(
"{}.retain(|{}, &mut {}| {})",
snippet(cx, left_expr.span, ".."),
key_param_ident,
value_param_ident,
snippet(cx, filter_body.value.span, "..")
))
},
(hir::PatKind::Binding(_, _, key_param_ident, None), hir::PatKind::Wild) => Some(format!(
"{}.retain(|{}, _| {})",
snippet(cx, left_expr.span, ".."),
key_param_ident,
snippet(cx, filter_body.value.span, "..")
)),
(hir::PatKind::Wild, hir::PatKind::Binding(_, _, value_param_ident, None)) => Some(format!(
"{}.retain(|_, &mut {}| {})",
snippet(cx, left_expr.span, ".."),
value_param_ident,
snippet(cx, filter_body.value.span, "..")
)),
_ => None,
}
}
fn match_acceptable_def_path(cx: &LateContext<'_>, collect_def_id: DefId) -> bool {
return ACCEPTABLE_METHODS
.iter()
.any(|&method| match_def_path(cx, collect_def_id, method));
}
fn match_acceptable_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
let expr_ty = cx.typeck_results().expr_ty(expr).peel_refs();
return ACCEPTABLE_TYPES
.iter()
.any(|&ty| is_type_diagnostic_item(cx, expr_ty, ty));
}

View file

@ -21,8 +21,13 @@ pub const ASREF_TRAIT: [&str; 3] = ["core", "convert", "AsRef"];
pub const BTREEMAP_CONTAINS_KEY: [&str; 6] = ["alloc", "collections", "btree", "map", "BTreeMap", "contains_key"];
pub const BTREEMAP_ENTRY: [&str; 6] = ["alloc", "collections", "btree", "map", "entry", "Entry"];
pub const BTREEMAP_INSERT: [&str; 6] = ["alloc", "collections", "btree", "map", "BTreeMap", "insert"];
pub const BTREESET_ITER: [&str; 6] = ["alloc", "collections", "btree", "set", "BTreeSet", "iter"];
pub const CLONE_TRAIT_METHOD: [&str; 4] = ["core", "clone", "Clone", "clone"];
pub const COW: [&str; 3] = ["alloc", "borrow", "Cow"];
pub const CORE_ITER_COLLECT: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "collect"];
pub const CORE_ITER_COPIED: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "copied"];
pub const CORE_ITER_FILTER: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "filter"];
pub const CORE_ITER_INTO_ITER: [&str; 6] = ["core", "iter", "traits", "collect", "IntoIterator", "into_iter"];
pub const CSTRING_AS_C_STR: [&str; 5] = ["alloc", "ffi", "c_str", "CString", "as_c_str"];
pub const DEFAULT_TRAIT_METHOD: [&str; 4] = ["core", "default", "Default", "default"];
pub const DEREF_MUT_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "DerefMut", "deref_mut"];
@ -50,6 +55,7 @@ pub const FUTURES_IO_ASYNCWRITEEXT: [&str; 3] = ["futures_util", "io", "AsyncWri
pub const HASHMAP_CONTAINS_KEY: [&str; 6] = ["std", "collections", "hash", "map", "HashMap", "contains_key"];
pub const HASHMAP_ENTRY: [&str; 5] = ["std", "collections", "hash", "map", "Entry"];
pub const HASHMAP_INSERT: [&str; 6] = ["std", "collections", "hash", "map", "HashMap", "insert"];
pub const HASHSET_ITER: [&str; 6] = ["std", "collections", "hash", "set", "HashSet", "iter"];
#[cfg(feature = "internal")]
pub const IDENT: [&str; 3] = ["rustc_span", "symbol", "Ident"];
#[cfg(feature = "internal")]
@ -145,6 +151,7 @@ pub const SLICE_FROM_RAW_PARTS: [&str; 4] = ["core", "slice", "raw", "from_raw_p
pub const SLICE_FROM_RAW_PARTS_MUT: [&str; 4] = ["core", "slice", "raw", "from_raw_parts_mut"];
pub const SLICE_GET: [&str; 4] = ["core", "slice", "<impl [T]>", "get"];
pub const SLICE_INTO_VEC: [&str; 4] = ["alloc", "slice", "<impl [T]>", "into_vec"];
pub const SLICE_INTO: [&str; 4] = ["core", "slice", "<impl [T]>", "iter"];
pub const SLICE_ITER: [&str; 4] = ["core", "slice", "iter", "Iter"];
pub const STDERR: [&str; 4] = ["std", "io", "stdio", "stderr"];
pub const STDOUT: [&str; 4] = ["std", "io", "stdio", "stdout"];
@ -154,6 +161,7 @@ pub const STRING_AS_MUT_STR: [&str; 4] = ["alloc", "string", "String", "as_mut_s
pub const STRING_AS_STR: [&str; 4] = ["alloc", "string", "String", "as_str"];
pub const STRING_NEW: [&str; 4] = ["alloc", "string", "String", "new"];
pub const STR_BYTES: [&str; 4] = ["core", "str", "<impl str>", "bytes"];
pub const STR_CHARS: [&str; 4] = ["core", "str", "<impl str>", "chars"];
pub const STR_ENDS_WITH: [&str; 4] = ["core", "str", "<impl str>", "ends_with"];
pub const STR_FROM_UTF8: [&str; 4] = ["core", "str", "converts", "from_utf8"];
pub const STR_LEN: [&str; 4] = ["core", "str", "<impl str>", "len"];
@ -179,6 +187,7 @@ pub const TOKIO_IO_ASYNCWRITEEXT: [&str; 5] = ["tokio", "io", "util", "async_wri
pub const TRY_FROM: [&str; 4] = ["core", "convert", "TryFrom", "try_from"];
pub const VEC_AS_MUT_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_mut_slice"];
pub const VEC_AS_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_slice"];
pub const VEC_DEQUE_ITER: [&str; 5] = ["alloc", "collections", "vec_deque", "VecDeque", "iter"];
pub const VEC_FROM_ELEM: [&str; 3] = ["alloc", "vec", "from_elem"];
pub const VEC_NEW: [&str; 4] = ["alloc", "vec", "Vec", "new"];
pub const VEC_RESIZE: [&str; 4] = ["alloc", "vec", "Vec", "resize"];

184
tests/ui/use_retain.fixed Normal file
View file

@ -0,0 +1,184 @@
// run-rustfix
#![warn(clippy::use_retain)]
#![allow(unused)]
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
fn main() {
binary_heap_retain();
btree_set_retain();
btree_map_retain();
hash_set_retain();
hash_map_retain();
string_retain();
vec_queue_retain();
vec_retain();
}
fn binary_heap_retain() {
// NOTE: Do not lint now, because binary_heap_retain is nighyly API.
// https://github.com/rust-lang/rust/issues/71503
let mut heap = BinaryHeap::from([1, 2, 3]);
heap = heap.into_iter().filter(|x| x % 2 == 0).collect();
heap = heap.iter().filter(|&x| x % 2 == 0).copied().collect();
// Do not lint, because type conversion is performed
heap = heap.into_iter().filter(|x| x % 2 == 0).collect::<BinaryHeap<i8>>();
heap = heap.iter().filter(|&x| x % 2 == 0).copied().collect::<BinaryHeap<i8>>();
// Do not lint, because this expression is not assign.
let mut bar: BinaryHeap<i8> = heap.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut foobar: BinaryHeap<i8> = heap.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|x| x % 2 == 0).collect();
}
fn btree_map_retain() {
let mut btree_map: BTreeMap<i8, i8> = (0..8).map(|x| (x, x * 10)).collect();
// Do lint.
btree_map.retain(|k, _| k % 2 == 0);
btree_map.retain(|_, &mut v| v % 2 == 0);
btree_map.retain(|k, &mut v| (k % 2 == 0) && (v % 2 == 0));
// Do not lint.
btree_map = btree_map
.into_iter()
.filter(|(x, _)| x % 2 == 0)
.collect::<BTreeMap<i8, i8>>();
// Do not lint, because this expression is not assign.
let mut foobar: BTreeMap<i8, i8> = btree_map.into_iter().filter(|(k, _)| k % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
btree_map = foobar.into_iter().filter(|(k, _)| k % 2 == 0).collect();
}
fn btree_set_retain() {
let mut btree_set = BTreeSet::from([1, 2, 3, 4, 5, 6]);
// Do lint.
btree_set.retain(|x| x % 2 == 0);
btree_set.retain(|x| x % 2 == 0);
// Do not lint, because type conversion is performed
btree_set = btree_set
.iter()
.filter(|&x| x % 2 == 0)
.copied()
.collect::<BTreeSet<i8>>();
btree_set = btree_set.into_iter().filter(|x| x % 2 == 0).collect::<BTreeSet<i8>>();
// Do not lint, because this expression is not assign.
let mut foobar: BTreeSet<i8> = btree_set.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut bar: BTreeSet<i8> = btree_set.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|x| x % 2 == 0).collect();
}
fn hash_map_retain() {
let mut hash_map: HashMap<i8, i8> = (0..8).map(|x| (x, x * 10)).collect();
// Do lint.
hash_map.retain(|k, _| k % 2 == 0);
hash_map.retain(|_, &mut v| v % 2 == 0);
hash_map.retain(|k, &mut v| (k % 2 == 0) && (v % 2 == 0));
// Do not lint.
hash_map = hash_map
.into_iter()
.filter(|(x, _)| x % 2 == 0)
.collect::<HashMap<i8, i8>>();
// Do not lint, because this expression is not assign.
let mut foobar: HashMap<i8, i8> = hash_map.into_iter().filter(|(k, _)| k % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
hash_map = foobar.into_iter().filter(|(k, _)| k % 2 == 0).collect();
}
fn hash_set_retain() {
let mut hash_set = HashSet::from([1, 2, 3, 4, 5, 6]);
// Do lint.
hash_set.retain(|x| x % 2 == 0);
hash_set.retain(|x| x % 2 == 0);
// Do not lint, because type conversion is performed
hash_set = hash_set.into_iter().filter(|x| x % 2 == 0).collect::<HashSet<i8>>();
hash_set = hash_set
.iter()
.filter(|&x| x % 2 == 0)
.copied()
.collect::<HashSet<i8>>();
// Do not lint, because this expression is not assign.
let mut bar: HashSet<i8> = hash_set.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut foobar: HashSet<i8> = hash_set.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|&x| x % 2 == 0).collect();
}
fn string_retain() {
let mut s = String::from("foobar");
// Do lint.
s.retain(|c| c != 'o');
// Do not lint, because this expression is not assign.
let mut bar: String = s.chars().filter(|&c| c != 'o').to_owned().collect();
// Do not lint, because it is an assignment to a different variable.
s = bar.chars().filter(|&c| c != 'o').to_owned().collect();
}
fn vec_retain() {
let mut vec = vec![0, 1, 2];
// Do lint.
vec.retain(|x| x % 2 == 0);
vec.retain(|x| x % 2 == 0);
// Do not lint, because type conversion is performed
vec = vec.into_iter().filter(|x| x % 2 == 0).collect::<Vec<i8>>();
vec = vec.iter().filter(|&x| x % 2 == 0).copied().collect::<Vec<i8>>();
// Do not lint, because this expression is not assign.
let mut bar: Vec<i8> = vec.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut foobar: Vec<i8> = vec.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|x| x % 2 == 0).collect();
}
fn vec_queue_retain() {
let mut vec_deque = VecDeque::new();
vec_deque.extend(1..5);
// Do lint.
vec_deque.retain(|x| x % 2 == 0);
vec_deque.retain(|x| x % 2 == 0);
// Do not lint, because type conversion is performed
vec_deque = vec_deque
.iter()
.filter(|&x| x % 2 == 0)
.copied()
.collect::<VecDeque<i8>>();
vec_deque = vec_deque.into_iter().filter(|x| x % 2 == 0).collect::<VecDeque<i8>>();
// Do not lint, because this expression is not assign.
let mut bar: VecDeque<i8> = vec_deque.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut foobar: VecDeque<i8> = vec_deque.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|x| x % 2 == 0).collect();
}

190
tests/ui/use_retain.rs Normal file
View file

@ -0,0 +1,190 @@
// run-rustfix
#![warn(clippy::use_retain)]
#![allow(unused)]
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
fn main() {
binary_heap_retain();
btree_set_retain();
btree_map_retain();
hash_set_retain();
hash_map_retain();
string_retain();
vec_queue_retain();
vec_retain();
}
fn binary_heap_retain() {
// NOTE: Do not lint now, because binary_heap_retain is nighyly API.
// https://github.com/rust-lang/rust/issues/71503
let mut heap = BinaryHeap::from([1, 2, 3]);
heap = heap.into_iter().filter(|x| x % 2 == 0).collect();
heap = heap.iter().filter(|&x| x % 2 == 0).copied().collect();
// Do not lint, because type conversion is performed
heap = heap.into_iter().filter(|x| x % 2 == 0).collect::<BinaryHeap<i8>>();
heap = heap.iter().filter(|&x| x % 2 == 0).copied().collect::<BinaryHeap<i8>>();
// Do not lint, because this expression is not assign.
let mut bar: BinaryHeap<i8> = heap.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut foobar: BinaryHeap<i8> = heap.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|x| x % 2 == 0).collect();
}
fn btree_map_retain() {
let mut btree_map: BTreeMap<i8, i8> = (0..8).map(|x| (x, x * 10)).collect();
// Do lint.
btree_map = btree_map.into_iter().filter(|(k, _)| k % 2 == 0).collect();
btree_map = btree_map.into_iter().filter(|(_, v)| v % 2 == 0).collect();
btree_map = btree_map
.into_iter()
.filter(|(k, v)| (k % 2 == 0) && (v % 2 == 0))
.collect();
// Do not lint.
btree_map = btree_map
.into_iter()
.filter(|(x, _)| x % 2 == 0)
.collect::<BTreeMap<i8, i8>>();
// Do not lint, because this expression is not assign.
let mut foobar: BTreeMap<i8, i8> = btree_map.into_iter().filter(|(k, _)| k % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
btree_map = foobar.into_iter().filter(|(k, _)| k % 2 == 0).collect();
}
fn btree_set_retain() {
let mut btree_set = BTreeSet::from([1, 2, 3, 4, 5, 6]);
// Do lint.
btree_set = btree_set.iter().filter(|&x| x % 2 == 0).copied().collect();
btree_set = btree_set.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because type conversion is performed
btree_set = btree_set
.iter()
.filter(|&x| x % 2 == 0)
.copied()
.collect::<BTreeSet<i8>>();
btree_set = btree_set.into_iter().filter(|x| x % 2 == 0).collect::<BTreeSet<i8>>();
// Do not lint, because this expression is not assign.
let mut foobar: BTreeSet<i8> = btree_set.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut bar: BTreeSet<i8> = btree_set.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|x| x % 2 == 0).collect();
}
fn hash_map_retain() {
let mut hash_map: HashMap<i8, i8> = (0..8).map(|x| (x, x * 10)).collect();
// Do lint.
hash_map = hash_map.into_iter().filter(|(k, _)| k % 2 == 0).collect();
hash_map = hash_map.into_iter().filter(|(_, v)| v % 2 == 0).collect();
hash_map = hash_map
.into_iter()
.filter(|(k, v)| (k % 2 == 0) && (v % 2 == 0))
.collect();
// Do not lint.
hash_map = hash_map
.into_iter()
.filter(|(x, _)| x % 2 == 0)
.collect::<HashMap<i8, i8>>();
// Do not lint, because this expression is not assign.
let mut foobar: HashMap<i8, i8> = hash_map.into_iter().filter(|(k, _)| k % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
hash_map = foobar.into_iter().filter(|(k, _)| k % 2 == 0).collect();
}
fn hash_set_retain() {
let mut hash_set = HashSet::from([1, 2, 3, 4, 5, 6]);
// Do lint.
hash_set = hash_set.into_iter().filter(|x| x % 2 == 0).collect();
hash_set = hash_set.iter().filter(|&x| x % 2 == 0).copied().collect();
// Do not lint, because type conversion is performed
hash_set = hash_set.into_iter().filter(|x| x % 2 == 0).collect::<HashSet<i8>>();
hash_set = hash_set
.iter()
.filter(|&x| x % 2 == 0)
.copied()
.collect::<HashSet<i8>>();
// Do not lint, because this expression is not assign.
let mut bar: HashSet<i8> = hash_set.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut foobar: HashSet<i8> = hash_set.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|&x| x % 2 == 0).collect();
}
fn string_retain() {
let mut s = String::from("foobar");
// Do lint.
s = s.chars().filter(|&c| c != 'o').to_owned().collect();
// Do not lint, because this expression is not assign.
let mut bar: String = s.chars().filter(|&c| c != 'o').to_owned().collect();
// Do not lint, because it is an assignment to a different variable.
s = bar.chars().filter(|&c| c != 'o').to_owned().collect();
}
fn vec_retain() {
let mut vec = vec![0, 1, 2];
// Do lint.
vec = vec.iter().filter(|&x| x % 2 == 0).copied().collect();
vec = vec.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because type conversion is performed
vec = vec.into_iter().filter(|x| x % 2 == 0).collect::<Vec<i8>>();
vec = vec.iter().filter(|&x| x % 2 == 0).copied().collect::<Vec<i8>>();
// Do not lint, because this expression is not assign.
let mut bar: Vec<i8> = vec.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut foobar: Vec<i8> = vec.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|x| x % 2 == 0).collect();
}
fn vec_queue_retain() {
let mut vec_deque = VecDeque::new();
vec_deque.extend(1..5);
// Do lint.
vec_deque = vec_deque.iter().filter(|&x| x % 2 == 0).copied().collect();
vec_deque = vec_deque.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because type conversion is performed
vec_deque = vec_deque
.iter()
.filter(|&x| x % 2 == 0)
.copied()
.collect::<VecDeque<i8>>();
vec_deque = vec_deque.into_iter().filter(|x| x % 2 == 0).collect::<VecDeque<i8>>();
// Do not lint, because this expression is not assign.
let mut bar: VecDeque<i8> = vec_deque.iter().filter(|&x| x % 2 == 0).copied().collect();
let mut foobar: VecDeque<i8> = vec_deque.into_iter().filter(|x| x % 2 == 0).collect();
// Do not lint, because it is an assignment to a different variable.
bar = foobar.iter().filter(|&x| x % 2 == 0).copied().collect();
bar = foobar.into_iter().filter(|x| x % 2 == 0).collect();
}

100
tests/ui/use_retain.stderr Normal file
View file

@ -0,0 +1,100 @@
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:45:5
|
LL | btree_map = btree_map.into_iter().filter(|(k, _)| k % 2 == 0).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `btree_map.retain(|k, _| k % 2 == 0)`
|
= note: `-D clippy::use-retain` implied by `-D warnings`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:46:5
|
LL | btree_map = btree_map.into_iter().filter(|(_, v)| v % 2 == 0).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `btree_map.retain(|_, &mut v| v % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:47:5
|
LL | / btree_map = btree_map
LL | | .into_iter()
LL | | .filter(|(k, v)| (k % 2 == 0) && (v % 2 == 0))
LL | | .collect();
| |__________________^ help: consider calling `.retain()` instead: `btree_map.retain(|k, &mut v| (k % 2 == 0) && (v % 2 == 0))`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:69:5
|
LL | btree_set = btree_set.iter().filter(|&x| x % 2 == 0).copied().collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `btree_set.retain(|x| x % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:70:5
|
LL | btree_set = btree_set.into_iter().filter(|x| x % 2 == 0).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `btree_set.retain(|x| x % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:93:5
|
LL | hash_map = hash_map.into_iter().filter(|(k, _)| k % 2 == 0).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `hash_map.retain(|k, _| k % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:94:5
|
LL | hash_map = hash_map.into_iter().filter(|(_, v)| v % 2 == 0).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `hash_map.retain(|_, &mut v| v % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:95:5
|
LL | / hash_map = hash_map
LL | | .into_iter()
LL | | .filter(|(k, v)| (k % 2 == 0) && (v % 2 == 0))
LL | | .collect();
| |__________________^ help: consider calling `.retain()` instead: `hash_map.retain(|k, &mut v| (k % 2 == 0) && (v % 2 == 0))`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:116:5
|
LL | hash_set = hash_set.into_iter().filter(|x| x % 2 == 0).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `hash_set.retain(|x| x % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:117:5
|
LL | hash_set = hash_set.iter().filter(|&x| x % 2 == 0).copied().collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `hash_set.retain(|x| x % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:139:5
|
LL | s = s.chars().filter(|&c| c != 'o').to_owned().collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `s.retain(|c| c != 'o')`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:151:5
|
LL | vec = vec.iter().filter(|&x| x % 2 == 0).copied().collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `vec.retain(|x| x % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:152:5
|
LL | vec = vec.into_iter().filter(|x| x % 2 == 0).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `vec.retain(|x| x % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:172:5
|
LL | vec_deque = vec_deque.iter().filter(|&x| x % 2 == 0).copied().collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `vec_deque.retain(|x| x % 2 == 0)`
error: this expression can be written more simply using `.retain()`
--> $DIR/use_retain.rs:173:5
|
LL | vec_deque = vec_deque.into_iter().filter(|x| x % 2 == 0).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.retain()` instead: `vec_deque.retain(|x| x % 2 == 0)`
error: aborting due to 15 previous errors