Skip to content

Commit d0d5b8a

Browse files
authored
Don't emit machine applicable map_flatten lint if there are code comments (#13940)
Fixes rust-lang/rust-clippy#8528. Similar to #13911, if there are code comments, we don't want to remove them automatically. changelog: Don't emit machine applicable `map_flatten` lint if there are code comments r? @xFrednet
2 parents 98b9a26 + 78225cc commit d0d5b8a

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

clippy_lints/src/methods/map_flatten.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
2-
use clippy_utils::is_trait_method;
32
use clippy_utils::source::snippet_with_applicability;
43
use clippy_utils::ty::is_type_diagnostic_item;
4+
use clippy_utils::{is_trait_method, span_contains_comment};
55
use rustc_errors::Applicability;
66
use rustc_hir::Expr;
77
use rustc_lint::LateContext;
@@ -17,10 +17,15 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, map_
1717
let mut applicability = Applicability::MachineApplicable;
1818

1919
let closure_snippet = snippet_with_applicability(cx, map_arg.span, "..", &mut applicability);
20+
let span = expr.span.with_lo(map_span.lo());
21+
// If the methods are separated with comments, we don't apply suggestion automatically.
22+
if span_contains_comment(cx.tcx.sess.source_map(), span) {
23+
applicability = Applicability::Unspecified;
24+
}
2025
span_lint_and_sugg(
2126
cx,
2227
MAP_FLATTEN,
23-
expr.span.with_lo(map_span.lo()),
28+
span,
2429
format!("called `map(..).flatten()` on `{caller_ty_name}`"),
2530
format!("try replacing `map` with `{method_to_use}` and remove the `.flatten()`"),
2631
format!("{method_to_use}({closure_snippet})"),

tests/ui/map_flatten.rs

+12
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,18 @@ fn long_span() {
5555
.collect();
5656
}
5757

58+
#[allow(clippy::useless_vec)]
59+
fn no_suggestion_if_comments_present() {
60+
let vec = vec![vec![1, 2, 3]];
61+
let _ = vec
62+
.iter()
63+
// a lovely comment explaining the code in very detail
64+
.map(|x| x.iter())
65+
//~^ ERROR: called `map(..).flatten()` on `Iterator`
66+
// the answer to life, the universe and everything could be here
67+
.flatten();
68+
}
69+
5870
fn main() {
5971
long_span();
6072
}

tests/ui/map_flatten.stderr

+10-1
Original file line numberDiff line numberDiff line change
@@ -102,5 +102,14 @@ LL + }
102102
LL + })
103103
|
104104

105-
error: aborting due to 4 previous errors
105+
error: called `map(..).flatten()` on `Iterator`
106+
--> tests/ui/map_flatten.rs:64:10
107+
|
108+
LL | .map(|x| x.iter())
109+
| __________^
110+
... |
111+
LL | | .flatten();
112+
| |__________________^ help: try replacing `map` with `flat_map` and remove the `.flatten()`: `flat_map(|x| x.iter())`
113+
114+
error: aborting due to 5 previous errors
106115

0 commit comments

Comments
 (0)