Also suggest .copied() when .clone() is called on a Copy type

This commit is contained in:
Manish Goregaokar 2019-04-15 14:39:41 -07:00
parent d2f7ae70ae
commit ad2c65bd1b
4 changed files with 14 additions and 5 deletions

View file

@ -1,6 +1,6 @@
use crate::utils::paths;
use crate::utils::{
in_macro, match_trait_method, match_type, remove_blocks, snippet_with_applicability, span_lint_and_sugg,
in_macro, match_trait_method, match_type, remove_blocks, snippet_with_applicability, span_lint_and_sugg, is_copy
};
use if_chain::if_chain;
use rustc::hir;
@ -88,8 +88,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
&& match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
let obj_ty = cx.tables.expr_ty(&obj[0]);
if let ty::Ref(..) = obj_ty.sty {
lint(cx, e.span, args[0].span, false);
if let ty::Ref(_, ty, _) = obj_ty.sty {
let copy = is_copy(cx, ty);
lint(cx, e.span, args[0].span, copy);
} else {
lint_needless_cloning(cx, e.span, args[0].span);
}

View file

@ -11,6 +11,7 @@ fn main() {
let _: Vec<String> = vec![String::new()].iter().cloned().collect();
let _: Vec<u32> = vec![42, 43].iter().copied().collect();
let _: Option<u64> = Some(Box::new(16)).map(|b| *b);
let _: Vec<u8> = vec![1; 6].iter().copied().collect();
// Don't lint these
let v = vec![5_i8; 6];

View file

@ -11,6 +11,7 @@ fn main() {
let _: Vec<String> = vec![String::new()].iter().map(|x| x.clone()).collect();
let _: Vec<u32> = vec![42, 43].iter().map(|&x| x).collect();
let _: Option<u64> = Some(Box::new(16)).map(|b| *b);
let _: Vec<u8> = vec![1; 6].iter().map(|x| x.clone()).collect();
// Don't lint these
let v = vec![5_i8; 6];

View file

@ -18,11 +18,17 @@ error: You are using an explicit closure for copying elements
LL | let _: Vec<u32> = vec![42, 43].iter().map(|&x| x).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Consider calling the dedicated `copied` method: `vec![42, 43].iter().copied()`
error: You are using an explicit closure for copying elements
--> $DIR/map_clone.rs:14:22
|
LL | let _: Vec<u8> = vec![1; 6].iter().map(|x| x.clone()).collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Consider calling the dedicated `copied` method: `vec![1; 6].iter().copied()`
error: You are needlessly cloning iterator elements
--> $DIR/map_clone.rs:24:29
--> $DIR/map_clone.rs:25:29
|
LL | let _ = std::env::args().map(|v| v.clone());
| ^^^^^^^^^^^^^^^^^^^ help: Remove the map call
error: aborting due to 4 previous errors
error: aborting due to 5 previous errors