Skip to content

Commit bb552dc

Browse files
committed
eta_reduction: fix false positive for unsafe fns (fixes rust-lang#243)
1 parent bb3b47d commit bb552dc

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

src/eta_reduction.rs

+16-6
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use rustc::lint::*;
22
use syntax::ast::*;
3-
use syntax::print::pprust::expr_to_string;
3+
use rustc::middle::ty;
44

5-
use utils::span_lint;
5+
use utils::{snippet, span_lint};
66

77

88
#[allow(missing_copy_implementations)]
@@ -47,7 +47,17 @@ fn check_closure(cx: &Context, expr: &Expr) {
4747
// is no way the closure is the same as the function
4848
return;
4949
}
50-
if args.iter().any(|arg| is_adjusted(cx, arg)) { return; }
50+
if args.iter().any(|arg| is_adjusted(cx, arg)) {
51+
// Are the arguments type-adjusted? Then we need the closure
52+
return;
53+
}
54+
let fn_ty = cx.tcx.expr_ty(caller);
55+
if let ty::TyBareFn(_, fn_ty) = fn_ty.sty {
56+
// Is it an unsafe function? They don't implement the closure traits
57+
if fn_ty.unsafety == Unsafety::Unsafe {
58+
return;
59+
}
60+
}
5161
for (ref a1, ref a2) in decl.inputs.iter().zip(args) {
5262
if let PatIdent(_, ident, _) = a1.pat.node {
5363
// XXXManishearth Should I be checking the binding mode here?
@@ -67,9 +77,9 @@ fn check_closure(cx: &Context, expr: &Expr) {
6777
return
6878
}
6979
}
70-
span_lint(cx, REDUNDANT_CLOSURE, expr.span,
71-
&format!("redundant closure found. Consider using `{}` in its place",
72-
expr_to_string(caller))[..])
80+
span_lint(cx, REDUNDANT_CLOSURE, expr.span, &format!(
81+
"redundant closure found. Consider using `{}` in its place",
82+
snippet(cx, caller.span, "..")));
7383
}
7484
}
7585
}

tests/compile-fail/eta.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,12 @@ fn main() {
99
meta(|a| foo(a));
1010
//~^ ERROR redundant closure found. Consider using `foo` in its place
1111
let c = Some(1u8).map(|a| {1+2; foo}(a));
12-
//~^ ERROR redundant closure found. Consider using `{ 1 + 2; foo }` in its place
12+
//~^ ERROR redundant closure found. Consider using `{1+2; foo}` in its place
1313
let d = Some(1u8).map(|a| foo((|b| foo2(b))(a))); //is adjusted?
1414
all(&[1, 2, 3], &&2, |x, y| below(x, y)); //is adjusted
15+
unsafe {
16+
Some(1u8).map(|a| unsafe_fn(a)); // unsafe fn
17+
}
1518
}
1619

1720
fn meta<F>(f: F) where F: Fn(u8) {
@@ -32,3 +35,5 @@ where F: Fn(&X, &X) -> bool {
3235
}
3336

3437
fn below(x: &u8, y: &u8) -> bool { x < y }
38+
39+
unsafe fn unsafe_fn(_: u8) { }

0 commit comments

Comments
 (0)