Skip to content

Commit b36bb0a

Browse files
committed
Reimplement the map_clone lint from scratch
1 parent 057243f commit b36bb0a

File tree

6 files changed

+136
-3
lines changed

6 files changed

+136
-3
lines changed

CHANGELOG.md

-2
Original file line numberDiff line numberDiff line change
@@ -688,8 +688,6 @@ All notable changes to this project will be documented in this file.
688688
[`float_arithmetic`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#float_arithmetic
689689
[`float_cmp`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#float_cmp
690690
[`float_cmp_const`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#float_cmp_const
691-
[`fn_to_numeric_cast`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#fn_to_numeric_cast
692-
[`fn_to_numeric_cast_with_truncation`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#fn_to_numeric_cast_with_truncation
693691
[`for_kv_map`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#for_kv_map
694692
[`for_loop_over_option`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#for_loop_over_option
695693
[`for_loop_over_result`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#for_loop_over_result

README.md

+1-1
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 279 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
12+
[There are 277 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

+4
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ pub mod let_if_seq;
129129
pub mod lifetimes;
130130
pub mod literal_representation;
131131
pub mod loops;
132+
pub mod map_clone;
132133
pub mod map_unit_fn;
133134
pub mod matches;
134135
pub mod mem_forget;
@@ -327,6 +328,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
327328
reg.register_late_lint_pass(box strings::StringAdd);
328329
reg.register_early_lint_pass(box returns::ReturnPass);
329330
reg.register_late_lint_pass(box methods::Pass);
331+
reg.register_late_lint_pass(box map_clone::Pass);
330332
reg.register_late_lint_pass(box shadow::Pass);
331333
reg.register_late_lint_pass(box types::LetPass);
332334
reg.register_late_lint_pass(box types::UnitCmp);
@@ -583,6 +585,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
583585
loops::WHILE_IMMUTABLE_CONDITION,
584586
loops::WHILE_LET_LOOP,
585587
loops::WHILE_LET_ON_ITERATOR,
588+
map_clone::MAP_CLONE,
586589
map_unit_fn::OPTION_MAP_UNIT_FN,
587590
map_unit_fn::RESULT_MAP_UNIT_FN,
588591
matches::MATCH_AS_REF,
@@ -742,6 +745,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
742745
loops::FOR_KV_MAP,
743746
loops::NEEDLESS_RANGE_LOOP,
744747
loops::WHILE_LET_ON_ITERATOR,
748+
map_clone::MAP_CLONE,
745749
matches::MATCH_BOOL,
746750
matches::MATCH_OVERLAPPING_ARM,
747751
matches::MATCH_REF_PATS,

clippy_lints/src/map_clone.rs

+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
use crate::rustc::hir;
2+
use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3+
use crate::rustc::{declare_tool_lint, lint_array};
4+
use crate::syntax::source_map::Span;
5+
use crate::utils::paths;
6+
use crate::utils::{
7+
in_macro, match_trait_method, match_type,
8+
remove_blocks, snippet,
9+
span_lint_and_sugg,
10+
};
11+
use if_chain::if_chain;
12+
use crate::syntax::ast::Ident;
13+
14+
#[derive(Clone)]
15+
pub struct Pass;
16+
17+
/// **What it does:** Checks for usage of `iterator.map(|x| x.clone())` and suggests
18+
/// `iterator.cloned()` instead
19+
///
20+
/// **Why is this bad?** Readability, this can be written more concisely
21+
///
22+
/// **Known problems:** None.
23+
///
24+
/// **Example:**
25+
///
26+
/// ```rust
27+
/// let x = vec![42, 43];
28+
/// let y = x.iter();
29+
/// let z = y.map(|i| *i);
30+
/// ```
31+
///
32+
/// The correct use would be:
33+
///
34+
/// ```rust
35+
/// let x = vec![42, 43];
36+
/// let y = x.iter();
37+
/// let z = y.cloned();
38+
/// ```
39+
declare_clippy_lint! {
40+
pub MAP_CLONE,
41+
style,
42+
"using `iterator.map(|x| x.clone())`, or dereferencing closures for `Copy` types"
43+
}
44+
45+
impl LintPass for Pass {
46+
fn get_lints(&self) -> LintArray {
47+
lint_array!(MAP_CLONE)
48+
}
49+
}
50+
51+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
52+
fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
53+
if in_macro(e.span) {
54+
return;
55+
}
56+
57+
if_chain! {
58+
if let hir::ExprKind::MethodCall(ref method, _, ref args) = e.node;
59+
if args.len() == 2;
60+
if method.ident.as_str() == "map";
61+
let ty = cx.tables.expr_ty(&args[0]);
62+
if match_type(cx, ty, &paths::OPTION) || match_trait_method(cx, e, &paths::ITERATOR);
63+
if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].node;
64+
let closure_body = cx.tcx.hir.body(body_id);
65+
let closure_expr = remove_blocks(&closure_body.value);
66+
then {
67+
match closure_body.arguments[0].pat.node {
68+
hir::PatKind::Ref(ref inner, _) => if let hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) = inner.node {
69+
lint(cx, e.span, args[0].span, name, closure_expr);
70+
},
71+
hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, name, None) => match closure_expr.node {
72+
hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => lint(cx, e.span, args[0].span, name, inner),
73+
hir::ExprKind::MethodCall(ref method, _, ref obj) => if method.ident.as_str() == "clone" {
74+
if match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) {
75+
lint(cx, e.span, args[0].span, name, &obj[0]);
76+
}
77+
}
78+
_ => {},
79+
},
80+
_ => {},
81+
}
82+
}
83+
}
84+
}
85+
}
86+
87+
fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, name: Ident, path: &hir::Expr) {
88+
if let hir::ExprKind::Path(hir::QPath::Resolved(None, ref path)) = path.node {
89+
if path.segments.len() == 1 && path.segments[0].ident == name {
90+
span_lint_and_sugg(
91+
cx,
92+
MAP_CLONE,
93+
replace,
94+
"You are using an explicit closure for cloning elements",
95+
"Consider calling the dedicated `cloned` method",
96+
format!("{}.cloned()", snippet(cx, root, "..")),
97+
)
98+
}
99+
}
100+
}

tests/ui/map_clone.rs

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
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<i8> = vec![5_i8; 6].iter().map(|x| *x).collect();
7+
let _: Vec<String> = vec![String::new()].iter().map(|x| x.clone()).collect();
8+
let _: Vec<u32> = vec![42, 43].iter().map(|&x| x).collect();
9+
}

tests/ui/map_clone.stderr

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error: You are using an explicit closure for cloning elements
2+
--> $DIR/map_clone.rs:6:22
3+
|
4+
6 | let _: Vec<i8> = vec![5_i8; 6].iter().map(|x| *x).collect();
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Consider calling the dedicated `cloned` method: `vec![5_i8; 6].iter().cloned()`
6+
|
7+
= note: `-D clippy::map-clone` implied by `-D warnings`
8+
9+
error: You are using an explicit closure for cloning elements
10+
--> $DIR/map_clone.rs:7:26
11+
|
12+
7 | let _: Vec<String> = vec![String::new()].iter().map(|x| x.clone()).collect();
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Consider calling the dedicated `cloned` method: `vec![String::new()].iter().cloned()`
14+
15+
error: You are using an explicit closure for cloning elements
16+
--> $DIR/map_clone.rs:8:23
17+
|
18+
8 | let _: Vec<u32> = vec![42, 43].iter().map(|&x| x).collect();
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: Consider calling the dedicated `cloned` method: `vec![42, 43].iter().cloned()`
20+
21+
error: aborting due to 3 previous errors
22+

0 commit comments

Comments
 (0)