new rules for merging expected/supplied types in closure signatures

Also, fix numbering in mir-opt tests. We are now anonymizing more
consistently, I think, and hence some of the `TyAnon` indices shifted.
This commit is contained in:
Niko Matsakis 2017-10-06 06:06:38 -04:00
parent ea4db3521e
commit 053383dbef
18 changed files with 649 additions and 71 deletions

View File

@ -13,14 +13,22 @@
use super::{check_fn, Expectation, FnCtxt}; use super::{check_fn, Expectation, FnCtxt};
use astconv::AstConv; use astconv::AstConv;
use rustc::hir::def_id::DefId;
use rustc::infer::LateBoundRegionConversionTime;
use rustc::infer::type_variable::TypeVariableOrigin; use rustc::infer::type_variable::TypeVariableOrigin;
use rustc::ty::{self, ToPolyTraitRef, Ty}; use rustc::ty::{self, ToPolyTraitRef, Ty};
use rustc::ty::subst::Substs; use rustc::ty::subst::Substs;
use rustc::ty::TypeFoldable;
use std::cmp; use std::cmp;
use std::iter; use std::iter;
use syntax::abi::Abi; use syntax::abi::Abi;
use rustc::hir; use rustc::hir;
struct ClosureSignatures<'tcx> {
bound_sig: ty::PolyFnSig<'tcx>,
liberated_sig: ty::FnSig<'tcx>,
}
impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
pub fn check_expr_closure(&self, pub fn check_expr_closure(&self,
expr: &hir::Expr, expr: &hir::Expr,
@ -56,15 +64,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
expected_sig); expected_sig);
let expr_def_id = self.tcx.hir.local_def_id(expr.id); let expr_def_id = self.tcx.hir.local_def_id(expr.id);
let sig = self.ty_of_closure(decl, expected_sig);
debug!("check_closure: ty_of_closure returns {:?}", sig); let ClosureSignatures { bound_sig, liberated_sig } =
self.sig_of_closure(expr_def_id, decl, body, expected_sig);
// `deduce_expectations_from_expected_type` introduces late-bound debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
// lifetimes defined elsewhere, which we need to anonymize away.
let sig = self.tcx.anonymize_late_bound_regions(&sig);
debug!("check_closure: anonymized sig={:?}", sig); let interior = check_fn(self, self.param_env, liberated_sig, decl, expr.id, body, true).1;
// Create type variables (for now) to represent the transformed // Create type variables (for now) to represent the transformed
// types of upvars. These will be unified during the upvar // types of upvars. These will be unified during the upvar
@ -75,14 +81,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
|_, _| span_bug!(expr.span, "closure has region param"), |_, _| span_bug!(expr.span, "closure has region param"),
|_, _| self.infcx.next_ty_var(TypeVariableOrigin::TransformedUpvar(expr.span)) |_, _| self.infcx.next_ty_var(TypeVariableOrigin::TransformedUpvar(expr.span))
); );
let closure_type = self.tcx.mk_closure(expr_def_id, substs);
let fn_sig = self.liberate_late_bound_regions(expr_def_id, &sig);
let fn_sig = self.inh.normalize_associated_types_in(body.value.span,
body.value.id,
self.param_env,
&fn_sig);
let interior = check_fn(self, self.param_env, fn_sig, decl, expr.id, body, true).1;
if let Some(interior) = interior { if let Some(interior) = interior {
let closure_substs = ty::ClosureSubsts { let closure_substs = ty::ClosureSubsts {
@ -91,13 +90,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
return self.tcx.mk_generator(expr_def_id, closure_substs, interior); return self.tcx.mk_generator(expr_def_id, closure_substs, interior);
} }
let closure_type = self.tcx.mk_closure(expr_def_id, substs);
debug!("check_closure: expr.id={:?} closure_type={:?}", expr.id, closure_type); debug!("check_closure: expr.id={:?} closure_type={:?}", expr.id, closure_type);
// Tuple up the arguments and insert the resulting function type into // Tuple up the arguments and insert the resulting function type into
// the `closures` table. // the `closures` table.
let sig = sig.map_bound(|sig| self.tcx.mk_fn_sig( let sig = bound_sig.map_bound(|sig| self.tcx.mk_fn_sig(
iter::once(self.tcx.intern_tup(sig.inputs(), false)), iter::once(self.tcx.intern_tup(sig.inputs(), false)),
sig.output(), sig.output(),
sig.variadic, sig.variadic,
@ -271,71 +268,214 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
} }
} }
fn sig_of_closure(&self,
expr_def_id: DefId,
decl: &hir::FnDecl,
body: &hir::Body,
expected_sig: Option<ty::FnSig<'tcx>>)
-> ClosureSignatures<'tcx>
{
if let Some(e) = expected_sig {
self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
} else {
self.sig_of_closure_no_expectation(expr_def_id, decl, body)
}
}
/// If there is no expected signature, then we will convert the
/// types that the user gave into a signature.
fn sig_of_closure_no_expectation(&self,
expr_def_id: DefId,
decl: &hir::FnDecl,
body: &hir::Body)
-> ClosureSignatures<'tcx>
{
debug!("sig_of_closure_no_expectation()");
let bound_sig = self.supplied_sig_of_closure(decl);
self.closure_sigs(expr_def_id, body, bound_sig)
}
/// Invoked to compute the signature of a closure expression. This /// Invoked to compute the signature of a closure expression. This
/// combines any user-provided type annotations (e.g., `|x: u32| /// combines any user-provided type annotations (e.g., `|x: u32|
/// -> u32 { .. }`) with the expected signature. /// -> u32 { .. }`) with the expected signature.
/// ///
/// The arguments here are a bit odd-ball: /// The approach is as follows:
/// ///
/// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
/// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
/// - If we have no expectation `E`, then the signature of the closure is `S`.
/// - Otherwise, the signature of the closure is E. Moreover:
/// - Skolemize the late-bound regions in `E`, yielding `E'`.
/// - Instantiate all the late-bound regions bound in the closure within `S`
/// with fresh (existential) variables, yielding `S'`
/// - Require that `E' = S'`
/// - We could use some kind of subtyping relationship here,
/// I imagine, but equality is easier and works fine for
/// our purposes.
///
/// The key intuition here is that the user's types must be valid
/// from "the inside" of the closure, but the expectation
/// ultimately drives the overall signature.
///
/// # Examples
///
/// ```
/// fn with_closure<F>(_: F)
/// where F: Fn(&u32) -> &u32 { .. }
///
/// with_closure(|x: &u32| { ... })
/// ```
///
/// Here:
/// - E would be `fn(&u32) -> &u32`.
/// - S would be `fn(&u32) ->
/// - E' is `&'!0 u32 -> &'!0 u32`
/// - S' is `&'?0 u32 -> ?T`
///
/// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
///
/// # Arguments
///
/// - `expr_def_id`: the def-id of the closure expression
/// - `decl`: the HIR declaration of the closure /// - `decl`: the HIR declaration of the closure
/// - `body`: the body of the closure
/// - `expected_sig`: the expected signature (if any). Note that /// - `expected_sig`: the expected signature (if any). Note that
/// this is missing a binder: that is, there may be late-bound /// this is missing a binder: that is, there may be late-bound
/// regions with depth 1, which are bound then by the closure. /// regions with depth 1, which are bound then by the closure.
fn ty_of_closure(&self, fn sig_of_closure_with_expectation(&self,
decl: &hir::FnDecl, expr_def_id: DefId,
expected_sig: Option<ty::FnSig<'tcx>>) decl: &hir::FnDecl,
-> ty::PolyFnSig<'tcx> body: &hir::Body,
expected_sig: ty::FnSig<'tcx>)
-> ClosureSignatures<'tcx>
{
debug!("sig_of_closure_with_expectation(expected_sig={:?})", expected_sig);
// Watch out for some surprises and just ignore the
// expectation if things don't see to match up with what we
// expect.
if expected_sig.variadic != decl.variadic {
return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
} else if expected_sig.inputs_and_output.len() != decl.inputs.len() + 1 {
// we could probably handle this case more gracefully
return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
}
// Create a `PolyFnSig`. Note the oddity that late bound
// regions appearing free in `expected_sig` are now bound up
// in this binder we are creating.
assert!(!expected_sig.has_regions_escaping_depth(1));
let bound_sig =
ty::Binder(self.tcx.mk_fn_sig(
expected_sig.inputs().iter().cloned(),
expected_sig.output(),
decl.variadic,
hir::Unsafety::Normal,
Abi::RustCall));
// `deduce_expectations_from_expected_type` introduces
// late-bound lifetimes defined elsewhere, which we now
// anonymize away, so as not to confuse the user.
let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
// Up till this point, we have ignored the annotations that the user
// gave. This function will check that they unify successfully.
// Along the way, it also writes out entries for types that the user
// wrote into our tables, which are then later used by the privacy
// check.
self.check_supplied_sig_against_expectation(decl, &closure_sigs);
closure_sigs
}
/// Enforce the user's types against the expectation. See
/// `sig_of_closure_with_expectation` for details on the overall
/// strategy.
fn check_supplied_sig_against_expectation(&self,
decl: &hir::FnDecl,
expected_sigs: &ClosureSignatures<'tcx>)
{
// Get the signature S that the user gave.
//
// (See comment on `sig_of_closure_with_expectation` for the
// meaning of these letters.)
let supplied_sig = self.supplied_sig_of_closure(decl);
debug!("check_supplied_sig_against_expectation: supplied_sig={:?}",
supplied_sig);
// The liberated version of this signature should be be a subtype
// of the liberated form of the expectation.
for ((hir_ty, &supplied_ty), expected_ty) in
decl.inputs.iter()
.zip(*supplied_sig.inputs().skip_binder()) // binder moved to (*) below
.zip(expected_sigs.liberated_sig.inputs()) // `liberated_sig` is E'.
{
// Instantiate (this part of..) S to S', i.e., with fresh variables.
let (supplied_ty, _) = self.infcx.replace_late_bound_regions_with_fresh_var(
hir_ty.span,
LateBoundRegionConversionTime::FnCall,
&ty::Binder(supplied_ty)); // recreated from (*) above
// Check that E' = S'.
self.demand_eqtype(hir_ty.span, expected_ty, supplied_ty);
}
let (supplied_output_ty, _) = self.infcx.replace_late_bound_regions_with_fresh_var(
decl.output.span(),
LateBoundRegionConversionTime::FnCall,
&supplied_sig.output());
self.demand_eqtype(decl.output.span(),
expected_sigs.liberated_sig.output(),
supplied_output_ty);
}
/// If there is no expected signature, then we will convert the
/// types that the user gave into a signature.
fn supplied_sig_of_closure(&self,
decl: &hir::FnDecl)
-> ty::PolyFnSig<'tcx>
{ {
let astconv: &AstConv = self; let astconv: &AstConv = self;
debug!("ty_of_closure(expected_sig={:?})", // First, convert the types that the user supplied (if any).
expected_sig); let supplied_arguments =
decl.inputs
let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| { .iter()
let expected_arg_ty = expected_sig.as_ref().and_then(|e| { .map(|a| astconv.ast_ty_to_ty(a));
// no guarantee that the correct number of expected args let supplied_return = match decl.output {
// were supplied hir::Return(ref output) => astconv.ast_ty_to_ty(&output),
if i < e.inputs().len() { hir::DefaultReturn(_) => astconv.ty_infer(decl.output.span()),
Some(e.inputs()[i])
} else {
None
}
});
let input_ty = astconv.ty_of_arg(a, expected_arg_ty);
debug!("ty_of_closure: i={} input_ty={:?} expected_arg_ty={:?}",
i, input_ty, expected_arg_ty);
input_ty
});
let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
let output_ty = match decl.output {
hir::Return(ref output) => {
if let (&hir::TyInfer, Some(expected_ret_ty)) = (&output.node, expected_ret_ty) {
astconv.record_ty(output.hir_id, expected_ret_ty, output.span);
expected_ret_ty
} else {
astconv.ast_ty_to_ty(&output)
}
}
hir::DefaultReturn(span) => {
if let Some(expected_ret_ty) = expected_ret_ty {
expected_ret_ty
} else {
astconv.ty_infer(span)
}
}
}; };
debug!("ty_of_closure: output_ty={:?}", output_ty); let result = ty::Binder(self.tcx.mk_fn_sig(
supplied_arguments,
ty::Binder(self.tcx.mk_fn_sig( supplied_return,
input_tys,
output_ty,
decl.variadic, decl.variadic,
hir::Unsafety::Normal, hir::Unsafety::Normal,
Abi::RustCall)) Abi::RustCall));
debug!("supplied_sig_of_closure: result={:?}", result);
result
}
fn closure_sigs(&self,
expr_def_id: DefId,
body: &hir::Body,
bound_sig: ty::PolyFnSig<'tcx>)
-> ClosureSignatures<'tcx>
{
let liberated_sig = self.liberate_late_bound_regions(expr_def_id, &bound_sig);
let liberated_sig = self.inh.normalize_associated_types_in(body.value.span,
body.value.id,
self.param_env,
&liberated_sig);
ClosureSignatures { bound_sig, liberated_sig }
} }
} }

View File

@ -76,6 +76,7 @@ This API is completely unstable and subject to change.
#![feature(box_patterns)] #![feature(box_patterns)]
#![feature(box_syntax)] #![feature(box_syntax)]
#![feature(conservative_impl_trait)] #![feature(conservative_impl_trait)]
#![feature(match_default_bindings)]
#![feature(never_type)] #![feature(never_type)]
#![feature(quote)] #![feature(quote)]
#![feature(rustc_diagnostic_macros)] #![feature(rustc_diagnostic_macros)]

View File

@ -0,0 +1 @@
See `src/test/run-pass/closure-expected-type`.

View File

@ -0,0 +1,49 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// must-compile-successfully
#![feature(underscore_lifetimes)]
#![allow(warnings)]
type Different<'a, 'b> = &'a mut (&'a (), &'b ());
type Same<'a> = Different<'a, 'a>;
fn with_closure_expecting_different<F>(_: F)
where F: for<'a, 'b> FnOnce(Different<'a, 'b>)
{
}
fn with_closure_expecting_different_anon<F>(_: F)
where F: FnOnce(Different<'_, '_>)
{
}
fn supplying_nothing_expecting_anon() {
with_closure_expecting_different_anon(|x: Different| {
})
}
fn supplying_nothing_expecting_named() {
with_closure_expecting_different(|x: Different| {
})
}
fn supplying_underscore_expecting_anon() {
with_closure_expecting_different_anon(|x: Different<'_, '_>| {
})
}
fn supplying_underscore_expecting_named() {
with_closure_expecting_different(|x: Different<'_, '_>| {
})
}
fn main() { }

View File

@ -0,0 +1,70 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(underscore_lifetimes)]
fn with_closure_expecting_fn_with_free_region<F>(_: F)
where F: for<'a> FnOnce(fn(&'a u32), &i32)
{
}
fn with_closure_expecting_fn_with_bound_region<F>(_: F)
where F: FnOnce(fn(&u32), &i32)
{
}
fn expect_free_supply_free_from_fn<'x>(x: &'x u32) {
// Here, the type given for `'x` "obscures" a region from the
// expected signature that is bound at closure level.
with_closure_expecting_fn_with_free_region(|x: fn(&'x u32), y| {});
//~^ ERROR mismatched types
//~| ERROR mismatched types
}
fn expect_free_supply_free_from_closure() {
// A variant on the previous test. Here, the region `'a` will be
// bound at the closure level, just as is expected, so no error
// results.
type Foo<'a> = fn(&'a u32);
with_closure_expecting_fn_with_free_region(|_x: Foo<'_>, y| {});
}
fn expect_free_supply_bound() {
// Here, we are given a function whose region is bound at closure level,
// but we expect one bound in the argument. Error results.
with_closure_expecting_fn_with_free_region(|x: fn(&u32), y| {});
//~^ ERROR mismatched types
}
fn expect_bound_supply_free_from_fn<'x>(x: &'x u32) {
// Here, we are given a `fn(&u32)` but we expect a `fn(&'x
// u32)`. In principle, this could be ok, but we demand equality.
with_closure_expecting_fn_with_bound_region(|x: fn(&'x u32), y| {});
//~^ ERROR mismatched types
}
fn expect_bound_supply_free_from_closure() {
// A variant on the previous test. Here, the region `'a` will be
// bound at the closure level, but we expect something bound at
// the argument level.
type Foo<'a> = fn(&'a u32);
with_closure_expecting_fn_with_bound_region(|_x: Foo<'_>, y| {});
//~^ ERROR mismatched types
}
fn expect_bound_supply_bound<'x>(x: &'x u32) {
// No error in this case. The supplied type supplies the bound
// regions, and hence we are able to figure out the type of `y`
// from the expected type
with_closure_expecting_fn_with_bound_region(|x: for<'z> fn(&'z u32), y| {
});
}
fn main() { }

View File

@ -0,0 +1,35 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn with_closure<F, A>(_: F)
where F: FnOnce(A, A)
{
}
fn a() {
with_closure(|x: u32, y| {
// We deduce type of `y` from `x`.
});
}
fn b() {
// Here we take the supplied types, resulting in an error later on.
with_closure(|x: u32, y: i32| {
//~^ ERROR mismatched types
});
}
fn c() {
with_closure(|x, y: i32| {
// We deduce type of `x` from `y`.
});
}
fn main() { }

View File

@ -0,0 +1,29 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// must-compile-successfully
fn with_closure<F, A>(_: F)
where F: FnOnce(A, &u32)
{
}
fn foo() {
// This version works; we infer `A` to be `u32`, and take the type
// of `y` to be `&u32`.
with_closure(|x: u32, y| {});
}
fn bar() {
// This version also works.
with_closure(|x: &u32, y| {});
}
fn main() { }

View File

@ -0,0 +1,29 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// must-compile-successfully
fn with_closure<F, A>(_: F)
where F: FnOnce(A, &u32)
{
}
fn foo() {
// This version works; we infer `A` to be `u32`, and take the type
// of `y` to be `&u32`.
with_closure(|x: u32, y| {});
}
fn bar<'x>(x: &'x u32) {
// Same.
with_closure(|x: &'x u32, y| {});
}
fn main() { }

View File

@ -0,0 +1,80 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(warnings)]
fn closure_expecting_bound<F>(_: F)
where F: FnOnce(&u32)
{
}
fn closure_expecting_free<'a, F>(_: F)
where F: FnOnce(&'a u32)
{
}
fn expect_bound_supply_nothing() {
// Because `x` is inferred to have a bound region, we cannot allow
// it to escape into `f`:
let mut f: Option<&u32> = None;
closure_expecting_bound(|x| {
f = Some(x); //~ ERROR E0495
});
}
fn expect_bound_supply_bound() {
// Because `x` is inferred to have a bound region, we cannot allow
// it to escape into `f`, even with an explicit type annotation on
// closure:
let mut f: Option<&u32> = None;
closure_expecting_bound(|x: &u32| {
f = Some(x); //~ ERROR E0495
});
}
fn expect_bound_supply_named<'x>() {
let mut f: Option<&u32> = None;
// Here we give a type annotation that `x` should be free. We get
// an error because of that.
closure_expecting_bound(|x: &'x u32| {
//~^ ERROR mismatched types
//~| ERROR mismatched types
// And we still cannot let `x` escape into `f`.
f = Some(x);
//~^ ERROR cannot infer
});
}
fn expect_free_supply_nothing() {
let mut f: Option<&u32> = None;
closure_expecting_free(|x| f = Some(x)); // OK
}
fn expect_free_supply_bound() {
let mut f: Option<&u32> = None;
// Here, even though the annotation `&u32` could be seen as being
// bound in the closure, we permit it to be defined as a free
// region (which is inferred to something in the fn body).
closure_expecting_free(|x: &u32| f = Some(x)); // OK
}
fn expect_free_supply_named<'x>() {
let mut f: Option<&u32> = None;
// Here, even though the annotation `&u32` could be seen as being
// bound in the closure, we permit it to be defined as a free
// region (which is inferred to something in the fn body).
closure_expecting_free(|x: &'x u32| f = Some(x)); // OK
}
fn main() { }

View File

@ -0,0 +1,29 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn with_closure<F, A, B>(_: F)
where F: FnOnce(A, B)
{
}
fn a() {
// Type of `y` is unconstrained.
with_closure(|x: u32, y| {}); //~ ERROR E0282
}
fn b() {
with_closure(|x: u32, y: u32| {}); // OK
}
fn c() {
with_closure(|x: u32, y: u32| {}); // OK
}
fn main() { }

View File

@ -62,7 +62,7 @@ fn main() {
// fn main::{{closure}}(_1: &ReErased [closure@NodeId(50)], _2: &ReErased mut i32) -> i32 { // fn main::{{closure}}(_1: &ReErased [closure@NodeId(50)], _2: &ReErased mut i32) -> i32 {
// ... // ...
// bb0: { // bb0: {
// Validate(Acquire, [_1: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:11) => validate_1[317d]::main[0]::{{closure}}[0] }, BrEnv) [closure@NodeId(50)], _2: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:11) => validate_1[317d]::main[0]::{{closure}}[0] }, BrAnon(1)) mut i32]); // Validate(Acquire, [_1: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:11) => validate_1[317d]::main[0]::{{closure}}[0] }, BrEnv) [closure@NodeId(50)], _2: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:11) => validate_1[317d]::main[0]::{{closure}}[0] }, BrAnon(0)) mut i32]);
// StorageLive(_3); // StorageLive(_3);
// Validate(Suspend(ReScope(Remainder(BlockRemainder { block: ItemLocalId(22), first_statement_index: 0 }))), [(*_2): i32]); // Validate(Suspend(ReScope(Remainder(BlockRemainder { block: ItemLocalId(22), first_statement_index: 0 }))), [(*_2): i32]);
// _3 = &ReErased (*_2); // _3 = &ReErased (*_2);

View File

@ -78,8 +78,8 @@ fn main() {
// fn main::{{closure}}(_1: &ReErased [closure@NodeId(60)], _2: &ReErased mut i32) -> bool { // fn main::{{closure}}(_1: &ReErased [closure@NodeId(60)], _2: &ReErased mut i32) -> bool {
// ... // ...
// bb0: { // bb0: {
// Validate(Acquire, [_1: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:10) => validate_4[317d]::main[0]::{{closure}}[0] }, BrEnv) [closure@NodeId(60)], _2: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:10) => validate_4[317d]::main[0]::{{closure}}[0] }, BrAnon(1)) mut i32]); // Validate(Acquire, [_1: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:10) => validate_4[317d]::main[0]::{{closure}}[0] }, BrEnv) [closure@NodeId(60)], _2: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:10) => validate_4[317d]::main[0]::{{closure}}[0] }, BrAnon(0)) mut i32]);
// Validate(Release, [_1: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:10) => validate_4[317d]::main[0]::{{closure}}[0] }, BrEnv) [closure@NodeId(60)], _2: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:10) => validate_4[317d]::main[0]::{{closure}}[0] }, BrAnon(1)) mut i32]); // Validate(Release, [_1: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:10) => validate_4[317d]::main[0]::{{closure}}[0] }, BrEnv) [closure@NodeId(60)], _2: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:10) => validate_4[317d]::main[0]::{{closure}}[0] }, BrAnon(0)) mut i32]);
// StorageLive(_3); // StorageLive(_3);
// ... // ...
// _0 = const write_42(_3) -> bb1; // _0 = const write_42(_3) -> bb1;

View File

@ -49,7 +49,7 @@ fn main() {
// fn main::{{closure}}(_1: &ReErased [closure@NodeId(46)], _2: &ReErased mut i32) -> bool { // fn main::{{closure}}(_1: &ReErased [closure@NodeId(46)], _2: &ReErased mut i32) -> bool {
// ... // ...
// bb0: { // bb0: {
// Validate(Acquire, [_1: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:9) => validate_5[317d]::main[0]::{{closure}}[0] }, BrEnv) [closure@NodeId(46)], _2: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:9) => validate_5[317d]::main[0]::{{closure}}[0] }, BrAnon(1)) mut i32]); // Validate(Acquire, [_1: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:9) => validate_5[317d]::main[0]::{{closure}}[0] }, BrEnv) [closure@NodeId(46)], _2: &ReFree(DefId { krate: CrateNum(0), index: DefIndex(1:9) => validate_5[317d]::main[0]::{{closure}}[0] }, BrAnon(0)) mut i32]);
// StorageLive(_3); // StorageLive(_3);
// StorageLive(_4); // StorageLive(_4);
// Validate(Suspend(ReScope(Node(ItemLocalId(9)))), [(*_2): i32]); // Validate(Suspend(ReScope(Node(ItemLocalId(9)))), [(*_2): i32]);

View File

@ -0,0 +1,8 @@
Some tests targeted at how we deduce the types of closure arguments.
This process is a result of some heuristics aimed at combining the
*expected type* we have with the *actual types* that we get from
inputs. This investigation was kicked off by #38714, which revealed
some pretty deep flaws in the ad-hoc way that we were doing things
before.
See also `src/test/compile-fail/closure-expected-type`.

View File

@ -0,0 +1,26 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn with_closure<A, F>(_: F)
where F: FnOnce(Vec<A>, A)
{
}
fn expect_free_supply_free<'x>(x: &'x u32) {
with_closure(|mut x: Vec<_>, y| {
// Shows that the call to `x.push()` is influencing type of `y`...
x.push(22_u32);
// ...since we now know the type of `y` and can resolve the method call.
y.wrapping_add(1);
});
}
fn main() { }

View File

@ -0,0 +1,26 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct UsizeRef<'a> {
a: &'a usize
}
type RefTo = Box<for<'r> Fn(&'r Vec<usize>) -> UsizeRef<'r>>;
fn ref_to<'a>(vec: &'a Vec<usize>) -> UsizeRef<'a> {
UsizeRef{ a: &vec[0]}
}
fn main() {
// Regression test: this was causing ICEs; it should compile.
let a: RefTo = Box::new(|vec: &Vec<usize>| {
UsizeRef{ a: &vec[0] }
});
}

View File

@ -0,0 +1,35 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn with_closure<F, R>(f: F) -> Result<char, R>
where F: FnOnce(&char) -> Result<char, R>,
{
f(&'a')
}
fn main() {
// Test that supplying the `-> Result<char, ()>` manually here
// (which is needed to constrain `R`) still allows us to figure
// out that the type of `x` is `&'a char` where `'a` is bound in
// the closure (if we didn't, we'd get a type-error because
// `with_closure` requires a bound region).
//
// This pattern was found in the wild.
let z = with_closure(|x| -> Result<char, ()> { Ok(*x) });
assert_eq!(z.unwrap(), 'a');
// It also works with `_`:
let z = with_closure(|x: _| -> Result<char, ()> { Ok(*x) });
assert_eq!(z.unwrap(), 'a');
// It also works with `&_`:
let z = with_closure(|x: &_| -> Result<char, ()> { Ok(*x) });
assert_eq!(z.unwrap(), 'a');
}

View File

@ -0,0 +1,20 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn with_closure<F>(f: F) -> u32
where F: FnOnce(&u32, &u32) -> u32
{
f(&22, &44)
}
fn main() {
let z = with_closure(|x, y| x + y).wrapping_add(1);
assert_eq!(z, 22 + 44 + 1);
}