Skip to content

Commit 67a9f20

Browse files
author
Michael Wright
committed
Fix map_clone bad suggestion
`cloned` requires that the elements of the iterator must be references. This change determines if that is the case by examining the type of the closure argument and suggesting `.cloned` only if it is a reference. When the closure argument is not a reference, it suggests removing the `map` call instead. A minor problem with this change is that the new check sometimes overlaps with the `clone_on_copy` lint. Fixes #498
1 parent 19553ae commit 67a9f20

File tree

4 files changed

+80
-25
lines changed

4 files changed

+80
-25
lines changed

clippy_lints/src/map_clone.rs

Lines changed: 46 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::utils::{
55
use if_chain::if_chain;
66
use rustc::hir;
77
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8+
use rustc::ty;
89
use rustc::{declare_tool_lint, lint_array};
910
use rustc_errors::Applicability;
1011
use syntax::ast::Ident;
@@ -69,19 +70,27 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
6970
hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(
7071
hir::BindingAnnotation::Unannotated, _, name, None
7172
) = inner.node {
72-
lint(cx, e.span, args[0].span, name, closure_expr);
73+
if ident_eq(name, closure_expr) {
74+
lint(cx, e.span, args[0].span);
75+
}
7376
},
7477
hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => {
7578
match closure_expr.node {
7679
hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => {
77-
if !cx.tables.expr_ty(inner).is_box() {
78-
lint(cx, e.span, args[0].span, name, inner);
80+
if ident_eq(name, inner) && !cx.tables.expr_ty(inner).is_box() {
81+
lint(cx, e.span, args[0].span);
7982
}
8083
},
8184
hir::ExprKind::MethodCall(ref method, _, ref obj) => {
82-
if method.ident.as_str() == "clone"
85+
if ident_eq(name, &obj[0]) && method.ident.as_str() == "clone"
8386
&& match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
84-
lint(cx, e.span, args[0].span, name, &obj[0]);
87+
88+
let obj_ty = cx.tables.expr_ty(&obj[0]);
89+
if let ty::Ref(..) = obj_ty.sty {
90+
lint(cx, e.span, args[0].span);
91+
} else {
92+
lint_needless_cloning(cx, e.span, args[0].span);
93+
}
8594
}
8695
},
8796
_ => {},
@@ -94,22 +103,38 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
94103
}
95104
}
96105

97-
fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, name: Ident, path: &hir::Expr) {
106+
fn ident_eq(name: Ident, path: &hir::Expr) -> bool {
98107
if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.node {
99-
if path.segments.len() == 1 && path.segments[0].ident == name {
100-
let mut applicability = Applicability::MachineApplicable;
101-
span_lint_and_sugg(
102-
cx,
103-
MAP_CLONE,
104-
replace,
105-
"You are using an explicit closure for cloning elements",
106-
"Consider calling the dedicated `cloned` method",
107-
format!(
108-
"{}.cloned()",
109-
snippet_with_applicability(cx, root, "..", &mut applicability)
110-
),
111-
applicability,
112-
)
113-
}
108+
path.segments.len() == 1 && path.segments[0].ident == name
109+
} else {
110+
false
114111
}
115112
}
113+
114+
fn lint_needless_cloning(cx: &LateContext<'_, '_>, root: Span, receiver: Span) {
115+
span_lint_and_sugg(
116+
cx,
117+
MAP_CLONE,
118+
root.trim_start(receiver).unwrap(),
119+
"You are needlessly cloning iterator elements",
120+
"Remove the map call",
121+
String::new(),
122+
Applicability::MachineApplicable,
123+
)
124+
}
125+
126+
fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span) {
127+
let mut applicability = Applicability::MachineApplicable;
128+
span_lint_and_sugg(
129+
cx,
130+
MAP_CLONE,
131+
replace,
132+
"You are using an explicit closure for cloning elements",
133+
"Consider calling the dedicated `cloned` method",
134+
format!(
135+
"{}.cloned()",
136+
snippet_with_applicability(cx, root, "..", &mut applicability)
137+
),
138+
applicability,
139+
)
140+
}

tests/ui/map_clone.fixed

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,23 @@
11
// run-rustfix
22
#![warn(clippy::all, clippy::pedantic)]
33
#![allow(clippy::iter_cloned_collect)]
4+
#![allow(clippy::clone_on_copy)]
45
#![allow(clippy::missing_docs_in_private_items)]
56

67
fn main() {
78
let _: Vec<i8> = vec![5_i8; 6].iter().cloned().collect();
89
let _: Vec<String> = vec![String::new()].iter().cloned().collect();
910
let _: Vec<u32> = vec![42, 43].iter().cloned().collect();
1011
let _: Option<u64> = Some(Box::new(16)).map(|b| *b);
12+
13+
// Don't lint these
14+
let v = vec![5_i8; 6];
15+
let a = 0;
16+
let b = &a;
17+
let _ = v.iter().map(|_x| *b);
18+
let _ = v.iter().map(|_x| a.clone());
19+
let _ = v.iter().map(|&_x| a);
20+
21+
// Issue #496
22+
let _ = std::env::args();
1123
}

tests/ui/map_clone.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,23 @@
11
// run-rustfix
22
#![warn(clippy::all, clippy::pedantic)]
33
#![allow(clippy::iter_cloned_collect)]
4+
#![allow(clippy::clone_on_copy)]
45
#![allow(clippy::missing_docs_in_private_items)]
56

67
fn main() {
78
let _: Vec<i8> = vec![5_i8; 6].iter().map(|x| *x).collect();
89
let _: Vec<String> = vec![String::new()].iter().map(|x| x.clone()).collect();
910
let _: Vec<u32> = vec![42, 43].iter().map(|&x| x).collect();
1011
let _: Option<u64> = Some(Box::new(16)).map(|b| *b);
12+
13+
// Don't lint these
14+
let v = vec![5_i8; 6];
15+
let a = 0;
16+
let b = &a;
17+
let _ = v.iter().map(|_x| *b);
18+
let _ = v.iter().map(|_x| a.clone());
19+
let _ = v.iter().map(|&_x| a);
20+
21+
// Issue #496
22+
let _ = std::env::args().map(|v| v.clone());
1123
}

tests/ui/map_clone.stderr

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,28 @@
11
error: You are using an explicit closure for cloning elements
2-
--> $DIR/map_clone.rs:7:22
2+
--> $DIR/map_clone.rs:8:22
33
|
44
LL | let _: Vec<i8> = vec![5_i8; 6].iter().map(|x| *x).collect();
55
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Consider calling the dedicated `cloned` method: `vec![5_i8; 6].iter().cloned()`
66
|
77
= note: `-D clippy::map-clone` implied by `-D warnings`
88

99
error: You are using an explicit closure for cloning elements
10-
--> $DIR/map_clone.rs:8:26
10+
--> $DIR/map_clone.rs:9:26
1111
|
1212
LL | let _: Vec<String> = vec![String::new()].iter().map(|x| x.clone()).collect();
1313
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Consider calling the dedicated `cloned` method: `vec![String::new()].iter().cloned()`
1414

1515
error: You are using an explicit closure for cloning elements
16-
--> $DIR/map_clone.rs:9:23
16+
--> $DIR/map_clone.rs:10:23
1717
|
1818
LL | let _: Vec<u32> = vec![42, 43].iter().map(|&x| x).collect();
1919
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Consider calling the dedicated `cloned` method: `vec![42, 43].iter().cloned()`
2020

21-
error: aborting due to 3 previous errors
21+
error: You are needlessly cloning iterator elements
22+
--> $DIR/map_clone.rs:22:29
23+
|
24+
LL | let _ = std::env::args().map(|v| v.clone());
25+
| ^^^^^^^^^^^^^^^^^^^ help: Remove the map call
26+
27+
error: aborting due to 4 previous errors
2228

0 commit comments

Comments
 (0)