Skip to content
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

When needing type annotations in local bindings, account for impl Trait and closures #63507

Merged
merged 7 commits into from
Aug 15, 2019
Merged
Show file tree
Hide file tree
Changes from 4 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: 24 additions & 4 deletions src/librustc/hir/map/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -650,11 +650,31 @@ impl<'hir> Map<'hir> {
}

pub fn is_const_scope(&self, hir_id: HirId) -> bool {
estebank marked this conversation as resolved.
Show resolved Hide resolved
self.walk_parent_nodes(hir_id, |node| match *node {
Node::Item(Item { node: ItemKind::Const(_, _), .. }) => true,
Node::Item(Item { node: ItemKind::Fn(_, header, _, _), .. }) => header.is_const(),
let parent_id = self.get_parent_item(hir_id);
match self.get(parent_id) {
Node::Item(&Item {
node: ItemKind::Const(..),
..
})
| Node::TraitItem(&TraitItem {
node: TraitItemKind::Const(..),
..
})
| Node::ImplItem(&ImplItem {
node: ImplItemKind::Const(..),
..
})
| Node::AnonConst(_)
| Node::Item(&Item {
node: ItemKind::Static(..),
..
}) => true,
Node::Item(&Item {
node: ItemKind::Fn(_, header, ..),
..
}) => header.constness == Constness::Const,
_ => false,
}, |_| false).map(|id| id != CRATE_HIR_ID).unwrap_or(false)
}
}

/// If there is some error when walking the parents (e.g., a node does not
Expand Down
34 changes: 32 additions & 2 deletions src/librustc/infer/error_reporting/need_type_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,22 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
// | the type parameter `E` is specified
// ```
let (ty_msg, suffix) = match &local_visitor.found_ty {
Some(ty) if &ty.to_string() != "_" && name == "_" => {
Some(ty) if &ty.to_string() != "_" &&
name == "_" &&
// FIXME: Remove this check after `impl_trait_in_bindings` is stabilized.
estebank marked this conversation as resolved.
Show resolved Hide resolved
(!ty.is_impl_trait() || self.tcx.features().impl_trait_in_bindings) &&
!ty.is_closure() => // The suggestion doesn't make sense for closures.
{
let ty = ty_to_string(ty);
(format!(" for `{}`", ty),
format!("the explicit type `{}`, with the type parameters specified", ty))
}
Some(ty) if &ty.to_string() != "_" && ty.to_string() != name => {
Some(ty) if &ty.to_string() != "_" &&
ty.to_string() != name &&
// FIXME: Remove this check after `impl_trait_in_bindings` is stabilized.
(!ty.is_impl_trait() || self.tcx.features().impl_trait_in_bindings) &&
!ty.is_closure() => // The suggestion doesn't make sense for closures.
{
let ty = ty_to_string(ty);
(format!(" for `{}`", ty),
format!(
Expand All @@ -165,6 +175,26 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
name,
))
}
Some(ty::TyS { sty: ty::Closure(def_id, substs), .. }) => {
let msg = " for the closure".to_string();
let fn_sig = substs.closure_sig(*def_id, self.tcx);
let args = fn_sig.inputs()
.skip_binder()
.iter()
.next()
.map(|args| args.tuple_fields()
.map(|arg| arg.to_string())
.collect::<Vec<_>>().join(", "))
Centril marked this conversation as resolved.
Show resolved Hide resolved
.unwrap_or_else(String::new);
estebank marked this conversation as resolved.
Show resolved Hide resolved
// This suggestion is incomplete, as the user will get further type inference
// errors due to the `_` placeholders and the introduction of `Box`, but it does
// nudge them in the right direction.
(msg, format!(
"a boxed closure type like `Box<Fn({}) -> {}>`",
estebank marked this conversation as resolved.
Show resolved Hide resolved
args,
fn_sig.output().skip_binder().to_string(),
))
}
_ => (String::new(), "a type".to_owned()),
};
let mut labels = vec![(span, InferCtxt::missing_type_msg(&name))];
Expand Down
3 changes: 3 additions & 0 deletions src/librustc/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2068,6 +2068,9 @@ impl<'tcx> TyS<'tcx> {
Error => { // ignore errors (#54954)
ty::Binder::dummy(FnSig::fake())
}
Closure(..) => bug!(
"to get the signature of a closure, use `closure_sig()` not `fn_sig()`",
),
_ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self)
}
}
Expand Down
1 change: 1 addition & 0 deletions src/librustc_typeck/check/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {

self.suggest_compatible_variants(&mut err, expr, expected, expr_ty);
self.suggest_ref_or_into(&mut err, expr, expected, expr_ty);
self.suggest_boxing_when_appropriate(&mut err, expr, expected, expr_ty);
self.suggest_missing_await(&mut err, expr, expected, expr_ty);

(expected, Some(err))
Expand Down
35 changes: 35 additions & 0 deletions src/librustc_typeck/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3820,6 +3820,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err, &fn_decl, expected, found, can_suggest);
}
self.suggest_ref_or_into(err, expression, expected, found);
self.suggest_boxing_when_appropriate(err, expression, expected, found);
pointing_at_return_type
}

Expand Down Expand Up @@ -3980,6 +3981,40 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}

/// When encountering the expected boxed value allocated in the stack, suggest allocating it
/// in the heap by calling `Box::new()`.
fn suggest_boxing_when_appropriate(
&self,
err: &mut DiagnosticBuilder<'tcx>,
expr: &hir::Expr,
expected: Ty<'tcx>,
found: Ty<'tcx>,
) {
if self.tcx.hir().is_const_scope(expr.hir_id) {
// Do not suggest `Box::new` in const context.
return;
}
if expected.is_box() && !found.is_box() {
estebank marked this conversation as resolved.
Show resolved Hide resolved
let boxed_found = self.tcx.mk_box(found);
if let (true, Ok(snippet)) = (
self.can_coerce(boxed_found, expected),
self.sess().source_map().span_to_snippet(expr.span),
) {
err.span_suggestion(
expr.span,
"you can store this in the heap calling `Box::new`",
estebank marked this conversation as resolved.
Show resolved Hide resolved
format!("Box::new({})", snippet),
Applicability::MachineApplicable,
);
err.note("for more information about the distinction between the stack and the \
estebank marked this conversation as resolved.
Show resolved Hide resolved
heap, read https://doc.rust-lang.org/book/ch15-01-box.html, \
https://doc.rust-lang.org/rust-by-example/std/box.html and \
estebank marked this conversation as resolved.
Show resolved Hide resolved
https://doc.rust-lang.org/std/boxed/index.html");
}
}
}


/// A common error is to forget to add a semicolon at the end of a block, e.g.,
///
/// ```
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// edition:2018
#![feature(async_await)]
#![feature(impl_trait_in_bindings)]
//~^ WARN the feature `impl_trait_in_bindings` is incomplete and may cause the compiler to crash

use std::io::Error;

fn make_unit() -> Result<(), Error> {
Ok(())
}

fn main() {
let fut = async {
make_unit()?; //~ ERROR type annotations needed

Ok(())
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
warning: the feature `impl_trait_in_bindings` is incomplete and may cause the compiler to crash
--> $DIR/cannot-infer-async-enabled-impl-trait-bindings.rs:3:12
|
LL | #![feature(impl_trait_in_bindings)]
| ^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(incomplete_features)]` on by default

error[E0282]: type annotations needed for `impl std::future::Future`
--> $DIR/cannot-infer-async-enabled-impl-trait-bindings.rs:14:9
|
LL | let fut = async {
| --- consider giving `fut` the explicit type `impl std::future::Future`, with the type parameters specified
estebank marked this conversation as resolved.
Show resolved Hide resolved
LL | make_unit()?;
| ^^^^^^^^^^^^ cannot infer type

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.
16 changes: 16 additions & 0 deletions src/test/ui/inference/cannot-infer-async.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// edition:2018
#![feature(async_await)]

use std::io::Error;

fn make_unit() -> Result<(), Error> {
Ok(())
}

fn main() {
let fut = async {
make_unit()?; //~ ERROR type annotations needed

Ok(())
};
}
11 changes: 11 additions & 0 deletions src/test/ui/inference/cannot-infer-async.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
error[E0282]: type annotations needed
--> $DIR/cannot-infer-async.rs:12:9
|
LL | let fut = async {
| --- consider giving `fut` a type
LL | make_unit()?;
| ^^^^^^^^^^^^ cannot infer type

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.
6 changes: 6 additions & 0 deletions src/test/ui/inference/cannot-infer-closure.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
fn main() {
let x = |a: (), b: ()| {
Err(a)?; //~ ERROR type annotations needed for the closure
Ok(b)
};
}
11 changes: 11 additions & 0 deletions src/test/ui/inference/cannot-infer-closure.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
error[E0282]: type annotations needed for the closure
--> $DIR/cannot-infer-closure.rs:3:9
|
LL | let x = |a: (), b: ()| {
| - consider giving `x` a boxed closure type like `Box<Fn((), ()) -> std::result::Result<(), _>>`
LL | Err(a)?;
| ^^^^^^^ cannot infer type

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.
8 changes: 8 additions & 0 deletions src/test/ui/suggestions/suggest-box.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// run-rustfix

fn main() {
let _x: Box<dyn Fn() -> Result<(), ()>> = Box::new(|| { //~ ERROR mismatched types
Err(())?;
Ok(())
});
}
8 changes: 8 additions & 0 deletions src/test/ui/suggestions/suggest-box.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// run-rustfix

fn main() {
let _x: Box<dyn Fn() -> Result<(), ()>> = || { //~ ERROR mismatched types
Err(())?;
Ok(())
};
}
24 changes: 24 additions & 0 deletions src/test/ui/suggestions/suggest-box.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
error[E0308]: mismatched types
--> $DIR/suggest-box.rs:4:47
|
LL | let _x: Box<dyn Fn() -> Result<(), ()>> = || {
| _______________________________________________^
LL | | Err(())?;
LL | | Ok(())
LL | | };
| |_____^ expected struct `std::boxed::Box`, found closure
|
= note: expected type `std::boxed::Box<dyn std::ops::Fn() -> std::result::Result<(), ()>>`
found type `[closure@$DIR/suggest-box.rs:4:47: 7:6]`
= note: for more information about the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html and https://doc.rust-lang.org/std/boxed/index.html
help: you can store this in the heap calling `Box::new`
|
LL | let _x: Box<dyn Fn() -> Result<(), ()>> = Box::new(|| {
LL | Err(())?;
LL | Ok(())
LL | });
|

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.