提交 f2e1a1b5 编写于 作者: B bors

Auto merge of #23424 - arielb1:ambiguous-project, r=nikomatsakis

r? @nikomatsakis 
...@@ -117,23 +117,71 @@ pub enum MethodMatchedData { ...@@ -117,23 +117,71 @@ pub enum MethodMatchedData {
/// obligation is for `int`. In that case, we drop the impl out of the /// obligation is for `int`. In that case, we drop the impl out of the
/// list. But the other cases are considered *candidates*. /// list. But the other cases are considered *candidates*.
/// ///
/// Candidates can either be definitive or ambiguous. An ambiguous /// For selection to succeed, there must be exactly one matching
/// candidate is one that might match or might not, depending on how /// candidate. If the obligation is fully known, this is guaranteed
/// type variables wind up being resolved. This only occurs during inference. /// by coherence. However, if the obligation contains type parameters
/// or variables, there may be multiple such impls.
/// ///
/// For selection to succeed, there must be exactly one non-ambiguous /// It is not a real problem if multiple matching impls exist because
/// candidate. Usually, it is not possible to have more than one /// of type variables - it just means the obligation isn't sufficiently
/// definitive candidate, due to the coherence rules. However, there is /// elaborated. In that case we report an ambiguity, and the caller can
/// one case where it could occur: if there is a blanket impl for a /// try again after more type information has been gathered or report a
/// trait (that is, an impl applied to all T), and a type parameter /// "type annotations required" error.
/// with a where clause. In that case, we can have a candidate from the ///
/// where clause and a second candidate from the impl. This is not a /// However, with type parameters, this can be a real problem - type
/// problem because coherence guarantees us that the impl which would /// parameters don't unify with regular types, but they *can* unify
/// be used to satisfy the where clause is the same one that we see /// with variables from blanket impls, and (unless we know its bounds
/// now. To resolve this issue, therefore, we ignore impls if we find a /// will always be satisfied) picking the blanket impl will be wrong
/// matching where clause. Part of the reason for this is that where /// for at least *some* substitutions. To make this concrete, if we have
/// clauses can give additional information (like, the types of output ///
/// parameters) that would have to be inferred from the impl. /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
/// impl<T: fmt::Debug> AsDebug for T {
/// type Out = T;
/// fn debug(self) -> fmt::Debug { self }
/// }
/// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
///
/// we can't just use the impl to resolve the <T as AsDebug> obligation
/// - a type from another crate (that doesn't implement fmt::Debug) could
/// implement AsDebug.
///
/// Because where-clauses match the type exactly, multiple clauses can
/// only match if there are unresolved variables, and we can mostly just
/// report this ambiguity in that case. This is still a problem - we can't
/// *do anything* with ambiguities that involve only regions. This is issue
/// #21974.
///
/// If a single where-clause matches and there are no inference
/// variables left, then it definitely matches and we can just select
/// it.
///
/// In fact, we even select the where-clause when the obligation contains
/// inference variables. The can lead to inference making "leaps of logic",
/// for example in this situation:
///
/// pub trait Foo<T> { fn foo(&self) -> T; }
/// impl<T> Foo<()> for T { fn foo(&self) { } }
/// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
///
/// pub fn foo<T>(t: T) where T: Foo<bool> {
/// println!("{:?}", <T as Foo<_>>::foo(&t));
/// }
/// fn main() { foo(false); }
///
/// Here the obligation <T as Foo<$0>> can be matched by both the blanket
/// impl and the where-clause. We select the where-clause and unify $0=bool,
/// so the program prints "false". However, if the where-clause is omitted,
/// the blanket impl is selected, we unify $0=(), and the program prints
/// "()".
///
/// Exactly the same issues apply to projection and object candidates, except
/// that we can have both a projection candidate and a where-clause candidate
/// for the same obligation. In that case either would do (except that
/// different "leaps of logic" would occur if inference variables are
/// present), and we just pick the projection. This is, for example,
/// required for associated types to work in default impls, as the bounds
/// are visible both as projection bounds and as where-clauses from the
/// parameter environment.
#[derive(PartialEq,Eq,Debug,Clone)] #[derive(PartialEq,Eq,Debug,Clone)]
enum SelectionCandidate<'tcx> { enum SelectionCandidate<'tcx> {
PhantomFnCandidate, PhantomFnCandidate,
...@@ -1350,63 +1398,51 @@ fn winnow_selection<'o>(&mut self, ...@@ -1350,63 +1398,51 @@ fn winnow_selection<'o>(&mut self,
/// Returns true if `candidate_i` should be dropped in favor of /// Returns true if `candidate_i` should be dropped in favor of
/// `candidate_j`. Generally speaking we will drop duplicate /// `candidate_j`. Generally speaking we will drop duplicate
/// candidates and prefer where-clause candidates. /// candidates and prefer where-clause candidates.
/// Returns true if `victim` should be dropped in favor of
/// `other`. Generally speaking we will drop duplicate
/// candidates and prefer where-clause candidates.
///
/// See the comment for "SelectionCandidate" for more details.
fn candidate_should_be_dropped_in_favor_of<'o>(&mut self, fn candidate_should_be_dropped_in_favor_of<'o>(&mut self,
candidate_i: &SelectionCandidate<'tcx>, victim: &SelectionCandidate<'tcx>,
candidate_j: &SelectionCandidate<'tcx>) other: &SelectionCandidate<'tcx>)
-> bool -> bool
{ {
if candidate_i == candidate_j { if victim == other {
return true; return true;
} }
match (candidate_i, candidate_j) { match other {
(&ImplCandidate(..), &ParamCandidate(..)) | &ObjectCandidate(..) |
(&ClosureCandidate(..), &ParamCandidate(..)) | &ParamCandidate(_) | &ProjectionCandidate => match victim {
(&FnPointerCandidate(..), &ParamCandidate(..)) | &DefaultImplCandidate(..) => {
(&BuiltinObjectCandidate(..), &ParamCandidate(_)) | self.tcx().sess.bug(
(&BuiltinCandidate(..), &ParamCandidate(..)) => { "default implementations shouldn't be recorded \
// We basically prefer always prefer to use a when there are other valid candidates");
// where-clause over another option. Where clauses }
// impose the burden of finding the exact match onto &PhantomFnCandidate => {
// the caller. Using an impl in preference of a where self.tcx().sess.bug("PhantomFn didn't short-circuit selection");
// clause can also lead us to "overspecialize", as in }
// #18453. &ImplCandidate(..) |
true &ClosureCandidate(..) |
} &FnPointerCandidate(..) |
(&ImplCandidate(..), &ObjectCandidate(..)) => { &BuiltinObjectCandidate(..) |
// This means that we are matching an object of type &DefaultImplObjectCandidate(..) |
// `Trait` against the trait `Trait`. In that case, we &BuiltinCandidate(..) => {
// always prefer to use the object vtable over the // We have a where-clause so don't go around looking
// impl. Like a where clause, the impl may or may not // for impls.
// be the one that is used by the object (because the true
// impl may have additional where-clauses that the }
// object's source might not meet) -- if it is, using &ObjectCandidate(..) |
// the vtable is fine. If it is not, using the vtable &ProjectionCandidate => {
// is good. A win win! // Arbitrarily give param candidates priority
true // over projection and object candidates.
} true
(&DefaultImplCandidate(_), _) => { },
// Prefer other candidates over default implementations. &ParamCandidate(..) => false,
self.tcx().sess.bug( &ErrorCandidate => false // propagate errors
"default implementations shouldn't be recorded \ },
when there are other valid candidates"); _ => false
}
(&ProjectionCandidate, &ParamCandidate(_)) => {
// FIXME(#20297) -- this gives where clauses precedent
// over projections. Really these are just two means
// of deducing information (one based on the where
// clauses on the trait definition; one based on those
// on the enclosing scope), and it'd be better to
// integrate them more intelligently. But for now this
// seems ok. If we DON'T give where clauses
// precedence, we run into trouble in default methods,
// where both the projection bounds for `Self::A` and
// the where clauses are in scope.
true
}
_ => {
false
}
} }
} }
......
// Copyright 2015 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.
pub trait Data { fn doit(&self) {} }
impl<T> Data for T {}
pub trait UnaryLogic { type D: Data; }
impl UnaryLogic for () { type D = i32; }
pub fn crashes<T: UnaryLogic>(t: T::D) {
t.doit();
}
fn main() { crashes::<()>(0); }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册