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

Fix unnecessary_filter_map false positive #7175

Merged
merged 1 commit into from
May 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 22 additions & 18 deletions clippy_lints/src/methods/unnecessary_filter_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc_hir::LangItem::{OptionNone, OptionSome};
use rustc_lint::LateContext;
use rustc_middle::hir::map::Map;
use rustc_middle::ty::{self, TyS};
use rustc_span::sym;

use super::UNNECESSARY_FILTER_MAP;
Expand All @@ -28,25 +29,28 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<
found_mapping |= return_visitor.found_mapping;
found_filtering |= return_visitor.found_filtering;

if !found_filtering {
span_lint(
cx,
UNNECESSARY_FILTER_MAP,
expr.span,
"this `.filter_map` can be written more simply using `.map`",
);
return;
}

if !found_mapping && !mutates_arg {
span_lint(
cx,
UNNECESSARY_FILTER_MAP,
expr.span,
"this `.filter_map` can be written more simply using `.filter`",
);
let sugg = if !found_filtering {
"map"
} else if !found_mapping && !mutates_arg {
let in_ty = cx.typeck_results().node_type(body.params[0].hir_id);
match cx.typeck_results().expr_ty(&body.value).kind() {
ty::Adt(adt, subst)
if cx.tcx.is_diagnostic_item(sym::option_type, adt.did)
&& TyS::same_type(in_ty, subst.type_at(0)) =>
{
"filter"
},
_ => return,
}
} else {
return;
}
};
span_lint(
cx,
UNNECESSARY_FILTER_MAP,
expr.span,
&format!("this `.filter_map` can be written more simply using `.{}`", sugg),
);
}
}

Expand Down
4 changes: 4 additions & 0 deletions tests/ui/unnecessary_filter_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ fn main() {

let _ = (0..4).filter_map(i32::checked_abs);
}

fn filter_map_none_changes_item_type() -> impl Iterator<Item = bool> {
"".chars().filter_map(|_| None)
}