Skip to content

Commit

Permalink
feat(new lint): new lint use_retain
Browse files Browse the repository at this point in the history
  • Loading branch information
kyoto7250 committed Jun 8, 2022
1 parent 542d474 commit 1f94ae4
Show file tree
Hide file tree
Showing 10 changed files with 723 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3836,6 +3836,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
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,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),
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,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,
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/lib.register_style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,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),
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,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;
Expand Down Expand Up @@ -907,6 +908,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
store.register_late_pass(|| Box::new(swap_ptr_to_ref::SwapPtrToRef));
store.register_late_pass(|| Box::new(mismatching_type_param_order::TypeParamMismatch));
store.register_late_pass(|| Box::new(as_underscore::AsUnderscore));
store.register_late_pass(|| Box::new(use_retain::UseRetain));
// add lints here, do not remove this comment, it's used in `new_lint`
}

Expand Down
234 changes: 234 additions & 0 deletions clippy_lints/src/use_retain.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
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;
then {
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
} {
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));
}
9 changes: 9 additions & 0 deletions clippy_utils/src/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down Expand Up @@ -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")]
Expand Down Expand Up @@ -144,6 +150,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"];
Expand All @@ -153,6 +160,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"];
Expand All @@ -178,6 +186,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"];
Expand Down
Loading

0 comments on commit 1f94ae4

Please sign in to comment.