Skip to content
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
9 changes: 7 additions & 2 deletions clippy_lints/src/methods/map_flatten.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{is_trait_method, span_contains_comment};
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
Expand All @@ -17,10 +17,15 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, map_
let mut applicability = Applicability::MachineApplicable;

let closure_snippet = snippet_with_applicability(cx, map_arg.span, "..", &mut applicability);
let span = expr.span.with_lo(map_span.lo());
// If the methods are separated with comments, we don't apply suggestion automatically.
if span_contains_comment(cx.tcx.sess.source_map(), span) {
applicability = Applicability::Unspecified;
}
span_lint_and_sugg(
cx,
MAP_FLATTEN,
expr.span.with_lo(map_span.lo()),
span,
format!("called `map(..).flatten()` on `{caller_ty_name}`"),
format!("try replacing `map` with `{method_to_use}` and remove the `.flatten()`"),
format!("{method_to_use}({closure_snippet})"),
Expand Down
12 changes: 12 additions & 0 deletions tests/ui/map_flatten.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ fn long_span() {
.collect();
}

#[allow(clippy::useless_vec)]
fn no_suggestion_if_comments_present() {
let vec = vec![vec![1, 2, 3]];
let _ = vec
.iter()
// a lovely comment explaining the code in very detail
.map(|x| x.iter())
//~^ ERROR: called `map(..).flatten()` on `Iterator`
// the answer to life, the universe and everything could be here
.flatten();
}

fn main() {
long_span();
}
11 changes: 10 additions & 1 deletion tests/ui/map_flatten.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,14 @@ LL + }
LL + })
|

error: aborting due to 4 previous errors
error: called `map(..).flatten()` on `Iterator`
--> tests/ui/map_flatten.rs:64:10
|
LL | .map(|x| x.iter())
| __________^
... |
LL | | .flatten();
| |__________________^ help: try replacing `map` with `flat_map` and remove the `.flatten()`: `flat_map(|x| x.iter())`

error: aborting due to 5 previous errors

Loading