Skip to content

needless_borrow reported on &&T when only &T implements Trait and &Trait is required #957

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 1 commit into from
May 27, 2016
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
17 changes: 9 additions & 8 deletions src/needless_borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
//! This lint is **warn** by default

use rustc::lint::*;
use rustc::hir::*;
use rustc::hir::{ExprAddrOf, Expr, MutImmutable};
use rustc::ty::TyRef;
use utils::{span_lint, in_macro};
use rustc::ty::adjustment::AutoAdjustment::AdjustDerefRef;

/// **What it does:** This lint checks for address of operations (`&`) that are going to be dereferenced immediately by the compiler
///
Expand Down Expand Up @@ -36,13 +37,13 @@ impl LateLintPass for NeedlessBorrow {
}
if let ExprAddrOf(MutImmutable, ref inner) = e.node {
if let TyRef(..) = cx.tcx.expr_ty(inner).sty {
let ty = cx.tcx.expr_ty(e);
let adj_ty = cx.tcx.expr_ty_adjusted(e);
if ty != adj_ty {
span_lint(cx,
NEEDLESS_BORROW,
e.span,
"this expression borrows a reference that is immediately dereferenced by the compiler");
if let Some(&AdjustDerefRef(ref deref)) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
if deref.autoderefs > 1 && deref.autoref.is_some() {
span_lint(cx,
NEEDLESS_BORROW,
e.span,
"this expression borrows a reference that is immediately dereferenced by the compiler");
}
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions tests/compile-fail/needless_borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ fn main() {
let g_val = g(&Vec::new()); // should not error, because `&Vec<T>` derefs to `&[T]`
let vec = Vec::new();
let vec_val = g(&vec); // should not error, because `&Vec<T>` derefs to `&[T]`
h(&"foo"); // should not error, because the `&&str` is required, due to `&Trait`
}

fn f<T:Copy>(y: &T) -> T {
Expand All @@ -25,3 +26,9 @@ fn f<T:Copy>(y: &T) -> T {
fn g(y: &[u8]) -> u8 {
y[0]
}

trait Trait {}

impl<'a> Trait for &'a str {}

fn h(_: &Trait) {}