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

WIP: Filter map lint #4521

Closed
wants to merge 3 commits into from
Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,7 @@ Released 2018-09-13
[`map_clone`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_clone
[`map_entry`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_entry
[`map_flatten`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_flatten
[`map_flatten_filtermap`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_flatten_filtermap
[`match_as_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_as_ref
[`match_bool`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_bool
[`match_overlapping_arm`]: https://rust-lang.github.io/rust-clippy/master/index.html#match_overlapping_arm
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.

[There are 313 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
[There are 314 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)

We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:

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 @@ -794,6 +794,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
methods::ITER_NTH,
methods::ITER_SKIP_NEXT,
methods::MANUAL_SATURATING_ARITHMETIC,
methods::MAP_FLATTEN_FILTERMAP,
methods::NEW_RET_NO_SELF,
methods::OK_EXPECT,
methods::OPTION_AND_THEN_SOME,
Expand Down Expand Up @@ -960,6 +961,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
methods::ITER_CLONED_COLLECT,
methods::ITER_SKIP_NEXT,
methods::MANUAL_SATURATING_ARITHMETIC,
methods::MAP_FLATTEN_FILTERMAP,
methods::NEW_RET_NO_SELF,
methods::OK_EXPECT,
methods::OPTION_MAP_OR_NONE,
Expand Down
19 changes: 19 additions & 0 deletions clippy_lints/src/methods/map_flatten_filtermap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use rustc::lint::{LateContext, LateLintPass, LintPass};
use rustc::{declare_lint_pass, declare_tool_lint};
use rustc::hir;
use crate::utils::{span_lint};
use syntax::ast::*;
use syntax_pos::Span;
use syntax::visit::FnKind;

use super::MAP_FLATTEN_FILTERMAP;

pub(super) fn lint(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
eprintln!("LINT has been called");
span_lint(
cx,
MAP_FLATTEN_FILTERMAP,
expr.span,
"this `.map().flatten()` can be written more simply using `.filter_map()`",
);
}
38 changes: 37 additions & 1 deletion clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod manual_saturating_arithmetic;
mod option_map_unwrap_or;
mod unnecessary_filter_map;
mod map_flatten_filtermap;

use std::borrow::Cow;
use std::fmt;
Expand Down Expand Up @@ -1011,6 +1012,35 @@ declare_clippy_lint! {
"`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
}

declare_clippy_lint! {
/// **What it does:** Checks for `.map().flatten()`.
///
/// **Why is this bad?** These functions can be replaced with `filter_map()`.
///
/// *+Example:**
///
/// ```rust
/// let v = [10, 20, 30];
///
/// let filtered1 = v
/// .iter()
/// .map(|x| if *x > 10 { Some(x) } else { None })
/// .flatten()
/// .collect::<Vec<_>>();
/// ```
///
/// can be written using `filter_map()` instead:
///
/// ```rust
/// let filtered2 = v
/// .iter()
/// .filter_map(|x| if *x > 10 { Some(x) } else { None })
/// .collect::<Vec<_>>();
pub MAP_FLATTEN_FILTERMAP,
style,
"`.map().flatten() can be replaced with `.filter_map()`"
}

declare_lint_pass!(Methods => [
OPTION_UNWRAP_USED,
RESULT_UNWRAP_USED,
Expand Down Expand Up @@ -1053,6 +1083,7 @@ declare_lint_pass!(Methods => [
SUSPICIOUS_MAP,
UNINIT_ASSUMED_INIT,
MANUAL_SATURATING_ARITHMETIC,
MAP_FLATTEN_FILTERMAP,
]);

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
Expand Down Expand Up @@ -1102,14 +1133,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
// Temporarily commented out to test the map_flatten_filtermap alone
//["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
["count", "map"] => lint_suspicious_map(cx, expr),
["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
["unwrap_or", arith @ "checked_add"]
| ["unwrap_or", arith @ "checked_sub"]
| ["unwrap_or", arith @ "checked_mul"] => {
manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
},
["map", "flatten"] => {
println!("LINT CALLED");
map_flatten_filtermap::lint(cx, expr, arg_lists[0])
}
_ => {},
}

Expand Down
9 changes: 8 additions & 1 deletion src/lintlist/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub use lint::Lint;
pub use lint::LINT_LEVELS;

// begin lint list, do not remove this comment, it’s used in `update_lints`
pub const ALL_LINTS: [Lint; 313] = [
pub const ALL_LINTS: [Lint; 314] = [
Lint {
name: "absurd_extreme_comparisons",
group: "correctness",
Expand Down Expand Up @@ -973,6 +973,13 @@ pub const ALL_LINTS: [Lint; 313] = [
deprecation: None,
module: "methods",
},
Lint {
name: "map_flatten_filtermap",
group: "style",
desc: "`.map().flatten() can be replaced with `.filter_map()`",
deprecation: None,
module: "methods",
},
Lint {
name: "match_as_ref",
group: "complexity",
Expand Down
18 changes: 18 additions & 0 deletions tests/ui/map_flatten_filtermap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#![warn(clippy::map_flatten_filtermap)]

fn main() {
let v = [10, 20, 30];

let filtered1 = v
.iter()
.map(|x| if *x > 10 { Some(x) } else { None })
.flatten()
.collect::<Vec<_>>();

let filtered2 = v
.iter()
.filter_map(|x| if *x > 10 { Some(x) } else { None })
.collect::<Vec<_>>();

assert_eq!(filtered1, filtered2);
}