Skip to content

Commit 40ebff8

Browse files
authored
Merge pull request #2493 from bootandy/fix_cow
Lint passing Cow by reference
2 parents 598acba + 6662aa4 commit 40ebff8

File tree

3 files changed

+47
-2
lines changed

3 files changed

+47
-2
lines changed

clippy_lints/src/ptr.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use std::borrow::Cow;
44
use rustc::hir::*;
55
use rustc::hir::map::NodeItem;
6+
use rustc::hir::QPath;
67
use rustc::lint::*;
78
use rustc::ty;
89
use syntax::ast::NodeId;
@@ -213,6 +214,33 @@ fn check_fn(cx: &LateContext, decl: &FnDecl, fn_id: NodeId, opt_body_id: Option<
213214
},
214215
);
215216
}
217+
} else if match_type(cx, ty, &paths::COW) {
218+
if_chain! {
219+
if let TyRptr(_, MutTy { ref ty, ..} ) = arg.node;
220+
if let TyPath(ref path) = ty.node;
221+
if let QPath::Resolved(None, ref pp) = *path;
222+
if let [ref bx] = *pp.segments;
223+
if let Some(ref params) = bx.parameters;
224+
if !params.parenthesized;
225+
if let [ref inner] = *params.types;
226+
then {
227+
let replacement = snippet_opt(cx, inner.span);
228+
match replacement {
229+
Some(r) => {
230+
span_lint_and_then(
231+
cx,
232+
PTR_ARG,
233+
arg.span,
234+
"using a reference to `Cow` is not recommended.",
235+
|db| {
236+
db.span_suggestion(arg.span, "change this to", "&".to_owned() + &r);
237+
},
238+
);
239+
},
240+
None => (),
241+
}
242+
}
243+
}
216244
}
217245
}
218246
}

tests/ui/needless_borrow.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
1+
use std::borrow::Cow;
22

33

44
fn x(y: &i32) -> i32 {
@@ -51,3 +51,12 @@ fn issue_1432() {
5151

5252
let _ = v.iter().filter(|&a| a.is_empty());
5353
}
54+
55+
#[allow(dead_code)]
56+
fn test_cow_with_ref(c: &Cow<[i32]>) {
57+
}
58+
59+
#[allow(dead_code)]
60+
fn test_cow(c: Cow<[i32]>) {
61+
let _c = c;
62+
}

tests/ui/needless_borrow.stderr

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,13 @@ error: this pattern creates a reference to a reference
3838
50 | let _ = v.iter().filter(|&ref a| a.is_empty());
3939
| ^^^^^ help: change this to: `a`
4040

41-
error: aborting due to 6 previous errors
41+
error: using a reference to `Cow` is not recommended.
42+
--> $DIR/needless_borrow.rs:56:25
43+
|
44+
56 | fn test_cow_with_ref(c: &Cow<[i32]>) {
45+
| ^^^^^^^^^^^ help: change this to: `&[i32]`
46+
|
47+
= note: `-D ptr-arg` implied by `-D warnings`
48+
49+
error: aborting due to 7 previous errors
4250

0 commit comments

Comments
 (0)