Skip to content

Lint passing Cow by reference #2493

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 5, 2018
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
28 changes: 28 additions & 0 deletions clippy_lints/src/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::borrow::Cow;
use rustc::hir::*;
use rustc::hir::map::NodeItem;
use rustc::hir::QPath;
use rustc::lint::*;
use rustc::ty;
use syntax::ast::NodeId;
Expand Down Expand Up @@ -213,6 +214,33 @@ fn check_fn(cx: &LateContext, decl: &FnDecl, fn_id: NodeId, opt_body_id: Option<
},
);
}
} else if match_type(cx, ty, &paths::COW) {
if_chain! {
if let TyRptr(_, MutTy { ref ty, ..} ) = arg.node;
if let TyPath(ref path) = ty.node;
if let QPath::Resolved(None, ref pp) = *path;
if let [ref bx] = *pp.segments;
if let Some(ref params) = bx.parameters;
if !params.parenthesized;
if let [ref inner] = *params.types;
then {
let replacement = snippet_opt(cx, inner.span);
match replacement {
Some(r) => {
span_lint_and_then(
cx,
PTR_ARG,
arg.span,
"using a reference to `Cow` is not recommended.",
|db| {
db.span_suggestion(arg.span, "change this to", "&".to_owned() + &r);
},
);
},
None => (),
}
}
}
}
}
}
Expand Down
11 changes: 10 additions & 1 deletion tests/ui/needless_borrow.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

use std::borrow::Cow;


fn x(y: &i32) -> i32 {
Expand Down Expand Up @@ -51,3 +51,12 @@ fn issue_1432() {

let _ = v.iter().filter(|&a| a.is_empty());
}

#[allow(dead_code)]
fn test_cow_with_ref(c: &Cow<[i32]>) {
}

#[allow(dead_code)]
fn test_cow(c: Cow<[i32]>) {
let _c = c;
}
10 changes: 9 additions & 1 deletion tests/ui/needless_borrow.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,13 @@ error: this pattern creates a reference to a reference
50 | let _ = v.iter().filter(|&ref a| a.is_empty());
| ^^^^^ help: change this to: `a`

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

error: aborting due to 7 previous errors