Skip to content

Commit e3f7b40

Browse files
authored
Merge pull request #3203 from yaahallo/master
Lint for chaining flatten after map
2 parents 1be78b9 + 14feb36 commit e3f7b40

File tree

6 files changed

+80
-14
lines changed

6 files changed

+80
-14
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,7 @@ All notable changes to this project will be documented in this file.
736736
[`many_single_char_names`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#many_single_char_names
737737
[`map_clone`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#map_clone
738738
[`map_entry`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#map_entry
739+
[`map_flatten`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#map_flatten
739740
[`match_as_ref`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#match_as_ref
740741
[`match_bool`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#match_bool
741742
[`match_overlapping_arm`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#match_overlapping_arm

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ We are currently in the process of discussing Clippy 1.0 via the RFC process in
99

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

12-
[There are 277 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
12+
[There are 278 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
1313

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

clippy_lints/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
473473
loops::EXPLICIT_ITER_LOOP,
474474
matches::SINGLE_MATCH_ELSE,
475475
methods::FILTER_MAP,
476+
methods::MAP_FLATTEN,
476477
methods::OPTION_MAP_UNWRAP_OR,
477478
methods::OPTION_MAP_UNWRAP_OR_ELSE,
478479
methods::RESULT_MAP_UNWRAP_OR_ELSE,

clippy_lints/src/methods.rs

Lines changed: 60 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
1-
use matches::matches;
21
use crate::rustc::hir;
3-
use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, Lint, LintContext};
2+
use crate::rustc::hir::def::Def;
3+
use crate::rustc::lint::{in_external_macro, LateContext, LateLintPass, Lint, LintArray, LintContext, LintPass};
4+
use crate::rustc::ty::{self, Ty};
45
use crate::rustc::{declare_tool_lint, lint_array};
6+
use crate::rustc_errors::Applicability;
7+
use crate::syntax::ast;
8+
use crate::syntax::source_map::{BytePos, Span};
9+
use crate::utils::paths;
10+
use crate::utils::sugg;
11+
use crate::utils::{
12+
get_arg_name, get_trait_def_id, implements_trait, in_macro, is_copy, is_expn_of, is_self, is_self_ty,
13+
iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method, match_type,
14+
match_var, method_chain_args, remove_blocks, return_ty, same_tys, single_segment_path, snippet, span_lint,
15+
span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
16+
};
517
use if_chain::if_chain;
6-
use crate::rustc::ty::{self, Ty};
7-
use crate::rustc::hir::def::Def;
18+
use matches::matches;
819
use std::borrow::Cow;
920
use std::fmt;
1021
use std::iter;
11-
use crate::syntax::ast;
12-
use crate::syntax::source_map::{Span, BytePos};
13-
use crate::utils::{get_arg_name, get_trait_def_id, implements_trait, in_macro, is_copy, is_expn_of, is_self,
14-
is_self_ty, iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
15-
match_type, method_chain_args, match_var, return_ty, remove_blocks, same_tys, single_segment_path, snippet,
16-
span_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq};
17-
use crate::utils::paths;
18-
use crate::utils::sugg;
19-
use crate::rustc_errors::Applicability;
2022

2123
#[derive(Clone)]
2224
pub struct Pass;
@@ -247,6 +249,24 @@ declare_clippy_lint! {
247249
"using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
248250
}
249251

252+
/// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
253+
///
254+
/// **Why is this bad?** Readability, this can be written more concisely as a
255+
/// single method call.
256+
///
257+
/// **Known problems:**
258+
///
259+
/// **Example:**
260+
/// ```rust
261+
/// iter.map(|x| x.iter()).flatten()
262+
/// ```
263+
declare_clippy_lint! {
264+
pub MAP_FLATTEN,
265+
pedantic,
266+
"using combinations of `flatten` and `map` which can usually be written as a \
267+
single method call"
268+
}
269+
250270
/// **What it does:** Checks for usage of `_.filter(_).map(_)`,
251271
/// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
252272
///
@@ -698,6 +718,7 @@ impl LintPass for Pass {
698718
TEMPORARY_CSTRING_AS_PTR,
699719
FILTER_NEXT,
700720
FILTER_MAP,
721+
MAP_FLATTEN,
701722
ITER_NTH,
702723
ITER_SKIP_NEXT,
703724
GET_UNWRAP,
@@ -744,6 +765,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
744765
lint_filter_flat_map(cx, expr, arglists[0], arglists[1]);
745766
} else if let Some(arglists) = method_chain_args(expr, &["filter_map", "flat_map"]) {
746767
lint_filter_map_flat_map(cx, expr, arglists[0], arglists[1]);
768+
} else if let Some(arglists) = method_chain_args(expr, &["map", "flatten"]) {
769+
lint_map_flatten(cx, expr, arglists[0]);
747770
} else if let Some(arglists) = method_chain_args(expr, &["find", "is_some"]) {
748771
lint_search_is_some(cx, expr, "find", arglists[0], arglists[1]);
749772
} else if let Some(arglists) = method_chain_args(expr, &["position", "is_some"]) {
@@ -1577,6 +1600,30 @@ fn lint_map_unwrap_or(cx: &LateContext<'_, '_>, expr: &hir::Expr, map_args: &[hi
15771600
}
15781601
}
15791602

1603+
/// lint use of `map().flatten()` for `Iterators`
1604+
fn lint_map_flatten<'a, 'tcx>(
1605+
cx: &LateContext<'a, 'tcx>,
1606+
expr: &'tcx hir::Expr,
1607+
map_args: &'tcx [hir::Expr],
1608+
) {
1609+
// lint if caller of `.map().flatten()` is an Iterator
1610+
if match_trait_method(cx, expr, &paths::ITERATOR) {
1611+
let msg = "called `map(..).flatten()` on an `Iterator`. \
1612+
This is more succinctly expressed by calling `.flat_map(..)`";
1613+
let self_snippet = snippet(cx, map_args[0].span, "..");
1614+
let func_snippet = snippet(cx, map_args[1].span, "..");
1615+
let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
1616+
span_lint_and_then(cx, MAP_FLATTEN, expr.span, msg, |db| {
1617+
db.span_suggestion_with_applicability(
1618+
expr.span,
1619+
"try using flat_map instead",
1620+
hint,
1621+
Applicability::MachineApplicable,
1622+
);
1623+
});
1624+
}
1625+
}
1626+
15801627
/// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
15811628
fn lint_map_unwrap_or_else<'a, 'tcx>(
15821629
cx: &LateContext<'a, 'tcx>,

tests/ui/map_flatten.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#![feature(tool_lints)]
2+
#![warn(clippy::all, clippy::pedantic)]
3+
#![allow(clippy::missing_docs_in_private_items)]
4+
5+
fn main() {
6+
let _: Vec<_> = vec![5_i8; 6].into_iter().map(|x| 0..x).flatten().collect();
7+
}

tests/ui/map_flatten.stderr

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: called `map(..).flatten()` on an `Iterator`. This is more succinctly expressed by calling `.flat_map(..)`
2+
--> $DIR/map_flatten.rs:6:21
3+
|
4+
6 | let _: Vec<_> = vec![5_i8; 6].into_iter().map(|x| 0..x).flatten().collect();
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try using flat_map instead: `vec![5_i8; 6].into_iter().flat_map(|x| 0..x)`
6+
|
7+
= note: `-D clippy::map-flatten` implied by `-D warnings`
8+
9+
error: aborting due to previous error
10+

0 commit comments

Comments
 (0)